Browse Source

eslint fixes

pull/4313/head
Artur Arseniev 4 years ago
parent
commit
66ede37f5f
  1. 3
      .eslintrc
  2. 4
      docs/api.js
  3. 126
      index.d.ts
  4. 4
      src/abstract/Collection.ts
  5. 4
      src/abstract/Model.ts
  6. 2
      src/abstract/Module.ts
  7. 8
      src/abstract/View.ts
  8. 2
      src/commands/view/SelectComponent.js
  9. 2
      src/css_composer/view/CssRulesView.js
  10. 2
      src/domain_abstract/model/StyleableModel.js
  11. 2
      src/domain_abstract/ui/InputColor.js
  12. 64
      src/editor/index.ts
  13. 2
      src/i18n/index.js
  14. 46
      src/i18n/locale/bs.js
  15. 54
      src/i18n/locale/de.js
  16. 48
      src/i18n/locale/fr.js
  17. 46
      src/i18n/locale/se.js
  18. 50
      src/selector_manager/model/Selector.ts
  19. 16
      src/selector_manager/model/Selectors.ts
  20. 12
      src/selector_manager/model/State.ts
  21. 44
      src/selector_manager/view/ClassTagView.ts
  22. 2
      src/style_manager/view/LayerView.js
  23. 12
      test/specs/commands/view/Preview.js
  24. 32
      test/specs/css_composer/index.js
  25. 10
      test/specs/css_composer/model/CssModels.js
  26. 4
      test/specs/dom_components/index.js
  27. 8
      test/specs/dom_components/model/Component.js
  28. 25
      test/specs/dom_components/model/ComponentTypes.js
  29. 97
      test/specs/dom_components/model/Symbols.js
  30. 2
      test/specs/editor/index.js
  31. 6
      test/specs/grapesjs/index.js
  32. 8
      test/specs/navigator/view/ItemView.js
  33. 41
      test/specs/pages/index.js
  34. 153
      test/specs/parser/model/ParserCss.js
  35. 4
      test/specs/parser/model/ParserHtml.js
  36. 27
      test/specs/selector_manager/view/ClassTagsView.js
  37. 12
      test/specs/style_manager/index.js
  38. 6
      test/specs/style_manager/model/Properties.js
  39. 2
      webpack.config.js

3
.eslintrc

@ -19,6 +19,7 @@
"parser": "@typescript-eslint/parser" "parser": "@typescript-eslint/parser"
}], }],
"ignorePatterns": [ "ignorePatterns": [
"dist/*" "dist/*",
"private/*",
] ]
} }

4
docs/api.js

@ -56,7 +56,7 @@ async function generateDocs () {
.replace(/<\\\[/g, '<[') .replace(/<\\\[/g, '<[')
.replace(/<\(\\\[/g, '<([') .replace(/<\(\\\[/g, '<([')
.replace(/\| \\\[/g, '| [') .replace(/\| \\\[/g, '| [')
.replace(/\\n```js/g, "```js") .replace(/\\n```js/g, '```js')
.replace('**Extends Model**', ''); .replace('**Extends Model**', '');
fs.writeFileSync(`${docRoot}/api/${file[1]}`, res); fs.writeFileSync(`${docRoot}/api/${file[1]}`, res);
log('Created', file[1]); log('Created', file[1]);
@ -66,4 +66,4 @@ async function generateDocs () {
log('API Reference generation done!'); log('API Reference generation done!');
}; };
generateDocs(); generateDocs();

126
index.d.ts

@ -83,7 +83,7 @@ declare namespace grapesjs {
/** Type of logs to print with the logger (by default is used the devtool console). /** Type of logs to print with the logger (by default is used the devtool console).
* Available by default: debug, info, warning, error * Available by default: debug, info, warning, error
* You can use `false` to disable all of them or `true` to print all of them */ * You can use `false` to disable all of them or `true` to print all of them */
log?: ("debug" | "info" | "warning" | "error")[]; log?: ('debug' | 'info' | 'warning' | 'error')[];
/** By default Grapes injects base CSS into the canvas. For example, it sets body margin to 0 /** By default Grapes injects base CSS into the canvas. For example, it sets body margin to 0
* and sets a default background color of white. This CSS is desired in most cases. * and sets a default background color of white. This CSS is desired in most cases.
@ -442,7 +442,7 @@ declare namespace grapesjs {
getInitValue(): string; getInitValue(): string;
} }
type TraitType = "text" | "number" | "checkbox" | "select" | string; type TraitType = 'text' | 'number' | 'checkbox' | 'select' | string;
interface TraitOptions { interface TraitOptions {
type: TraitType; type: TraitType;
@ -475,7 +475,7 @@ declare namespace grapesjs {
interface ButtonOptions { interface ButtonOptions {
id: string; id: string;
label: string; label: string;
tagName: "span"; tagName: 'span';
className: string; className: string;
command: string | ((editor: Editor, opts?: any) => void); command: string | ((editor: Editor, opts?: any) => void);
context: string; context: string;
@ -1057,83 +1057,83 @@ declare namespace grapesjs {
| GeneralEvent; | GeneralEvent;
type ComponentEvent = type ComponentEvent =
| "component:create" | 'component:create'
| "component:mount" | 'component:mount'
| "component:add" | 'component:add'
| "component:remove" | 'component:remove'
| "component:remove:before" | 'component:remove:before'
| "component:clone" | 'component:clone'
| "component:update" | 'component:update'
| "component:styleUpdate" | 'component:styleUpdate'
| "component:selected" | 'component:selected'
| "component:deselected" | 'component:deselected'
| "component:toggled" | 'component:toggled'
| "component:type:add" | 'component:type:add'
| "component:type:update" | 'component:type:update'
| "component:drag:start" | 'component:drag:start'
| "component:drag" | 'component:drag'
| "component:drag:end"; | 'component:drag:end';
type BlockEvent = type BlockEvent =
| "block:add" | 'block:add'
| "block:remove" | 'block:remove'
| "block:drag:start" | 'block:drag:start'
| "block:drag" | 'block:drag'
| "block:drag:stop"; | 'block:drag:stop';
type AssetEvent = type AssetEvent =
| "asset:add" | 'asset:add'
| "asset:remove" | 'asset:remove'
| "asset:upload:start" | 'asset:upload:start'
| "asset:upload:end" | 'asset:upload:end'
| "asset:upload:error" | 'asset:upload:error'
| "asset:upload:response"; | 'asset:upload:response';
type KeymapEvent = type KeymapEvent =
| "keymap:add" | 'keymap:add'
| "keymap:remove" | 'keymap:remove'
| "keymap:emit" | 'keymap:emit'
| "keymap:emit:{keymapId}"; | 'keymap:emit:{keymapId}';
type StyleManagerEvent = type StyleManagerEvent =
| "styleManager:update:target" | 'styleManager:update:target'
| "styleManager:change" | 'styleManager:change'
| "styleManager:change:{propertyName}"; | 'styleManager:change:{propertyName}';
type StorageEvent = type StorageEvent =
| "storage:start" | 'storage:start'
| "storage:start:store" | 'storage:start:store'
| "storage:start:load" | 'storage:start:load'
| "storage:load" | 'storage:load'
| "storage:store" | 'storage:store'
| "storage:end" | 'storage:end'
| "storage:end:store" | 'storage:end:store'
| "storage:end:load" | 'storage:end:load'
| "storage:error" | 'storage:error'
| "storage:error:store" | 'storage:error:store'
| "storage:error:load"; | 'storage:error:load';
type CanvasEvent = type CanvasEvent =
| "canvas:dragenter" | 'canvas:dragenter'
| "canvas:dragover" | 'canvas:dragover'
| "canvas:drop" | 'canvas:drop'
| "canvas:dragend" | 'canvas:dragend'
| "canvas:dragdata"; | 'canvas:dragdata';
type SelectorEvent = "selector:add"; type SelectorEvent = 'selector:add';
type RichTextEditorEvent = "rte:enable" | "rte:disable"; type RichTextEditorEvent = 'rte:enable' | 'rte:disable';
type ModalEvent = "modal:open" | "modal:close"; type ModalEvent = 'modal:open' | 'modal:close';
type CommandEvent = type CommandEvent =
| "run:{commandName}" | 'run:{commandName}'
| "stop:{commandName}" | 'stop:{commandName}'
| "run:{commandName}:before" | 'run:{commandName}:before'
| "stop:{commandName}:before" | 'stop:{commandName}:before'
| "abort:{commandName}"; | 'abort:{commandName}';
type GeneralEvent = "canvasScroll" | "undo" | "redo" | "load"; type GeneralEvent = 'canvasScroll' | 'undo' | 'redo' | 'load';
/** /**
* You can customize the initial state of the module from the editor initialization, by passing the following [Configuration Object](https://github.com/artf/grapesjs/blob/master/src/asset_manager/config/config.js) * You can customize the initial state of the module from the editor initialization, by passing the following [Configuration Object](https://github.com/artf/grapesjs/blob/master/src/asset_manager/config/config.js)
@ -5369,4 +5369,4 @@ declare namespace grapesjs {
} }
export default grapesjs; export default grapesjs;
export as namespace grapesjs; export as namespace grapesjs;

4
src/abstract/Collection.ts

@ -1,5 +1,5 @@
import Backbone from "backbone"; import Backbone from 'backbone';
import Model from "./Model"; import Model from './Model';
export default class Collection< export default class Collection<
TModel extends Model = Model TModel extends Model = Model

4
src/abstract/Model.ts

@ -1,5 +1,5 @@
import Backbone from "backbone"; import Backbone from 'backbone';
import Module, { IBaseModule } from "./Module"; import Module, { IBaseModule } from './Module';
export default class Model< export default class Model<
TModule extends IBaseModule<any> = Module, TModule extends IBaseModule<any> = Module,

2
src/abstract/Module.ts

@ -1,4 +1,4 @@
import EditorModel from "../editor/model/Editor"; import EditorModel from '../editor/model/Editor';
export interface IModule<TConfig extends any = any> extends IBaseModule<TConfig> { export interface IModule<TConfig extends any = any> extends IBaseModule<TConfig> {
init(cfg: any): void; init(cfg: any): void;

8
src/abstract/View.ts

@ -1,16 +1,16 @@
import Backbone from "backbone"; import Backbone from 'backbone';
import Model from "./Model"; import Model from './Model';
export default class View< export default class View<
TModel extends Model = Model, TModel extends Model = Model,
TElement extends Element = HTMLElement TElement extends Element = HTMLElement
> extends Backbone.View<TModel, TElement> { > extends Backbone.View<TModel, TElement> {
protected get pfx() { protected get pfx() {
return (this.model.module.em.config as any).stylePrefix || ""; return (this.model.module.em.config as any).stylePrefix || '';
} }
protected get ppfx() { protected get ppfx() {
return this.pfx + this.model.module.config.stylePrefix || ""; return this.pfx + this.model.module.config.stylePrefix || '';
} }
protected get em() { protected get em() {

2
src/commands/view/SelectComponent.js

@ -451,7 +451,7 @@ export default {
} }
modelToStyle.addStyle({ ...style, en }, { avoidStore: !store }); modelToStyle.addStyle({ ...style, en }, { avoidStore: !store });
const updateEvent = `update:component:style`; const updateEvent = 'update:component:style';
const eventToListen = `${updateEvent}:${keyHeight} ${updateEvent}:${keyWidth}`; const eventToListen = `${updateEvent}:${keyHeight} ${updateEvent}:${keyWidth}`;
em && em.trigger(eventToListen, null, null, { noEmit: 1 }); em && em.trigger(eventToListen, null, null, { noEmit: 1 });
}, },

2
src/css_composer/view/CssRulesView.js

@ -57,7 +57,7 @@ export default class CssRulesView extends View {
atRuleEl = document.createTextNode(''); atRuleEl = document.createTextNode('');
styleEl.appendChild(document.createTextNode(`${atRule}{`)); styleEl.appendChild(document.createTextNode(`${atRule}{`));
styleEl.appendChild(atRuleEl); styleEl.appendChild(atRuleEl);
styleEl.appendChild(document.createTextNode(`}`)); styleEl.appendChild(document.createTextNode('}'));
this.atRules[atRule] = atRuleEl; this.atRules[atRule] = atRuleEl;
rendered = styleEl; rendered = styleEl;
} }

2
src/domain_abstract/model/StyleableModel.js

@ -55,7 +55,7 @@ export default class StyleableModel extends Model {
if (opts.noEvent) return; if (opts.noEvent) return;
this.trigger(`change:style:${pr}`); this.trigger(`change:style:${pr}`);
if (em) { if (em) {
em.trigger(`styleable:change`, this, pr, opts); em.trigger('styleable:change', this, pr, opts);
em.trigger(`styleable:change:${pr}`, this, pr, opts); em.trigger(`styleable:change:${pr}`, this, pr, opts);
} }
}); });

2
src/domain_abstract/ui/InputColor.js

@ -103,7 +103,7 @@ export default class InputColor extends Input {
let changed = 0; let changed = 0;
let previousColor; let previousColor;
this.$el.find(`[data-colorp-c]`).append(colorEl); this.$el.find('[data-colorp-c]').append(colorEl);
colorEl.spectrum({ colorEl.spectrum({
color: model.getValue() || false, color: model.getValue() || false,
containerClassName: `${ppfx}one-bg ${ppfx}two-color`, containerClassName: `${ppfx}one-bg ${ppfx}two-color`,

64
src/editor/index.ts

@ -82,134 +82,134 @@ export default class EditorModule implements IBaseModule<typeof defaults> {
//@ts-ignore //@ts-ignore
get I18n(): I18nModule { get I18n(): I18nModule {
return this.em.get("I18n"); return this.em.get('I18n');
} }
//@ts-ignore //@ts-ignore
get Utils(): UtilsModule { get Utils(): UtilsModule {
return this.em.get("Utils"); return this.em.get('Utils');
} }
get Config(): any { get Config(): any {
return this.em.config; return this.em.config;
} }
//@ts-ignore //@ts-ignore
get Commands(): CommandsModule { get Commands(): CommandsModule {
return this.em.get("Commands"); return this.em.get('Commands');
} }
//@ts-ignore //@ts-ignore
get Keymaps(): KeymapsModule { get Keymaps(): KeymapsModule {
return this.em.get("Keymaps"); return this.em.get('Keymaps');
} }
//@ts-ignore //@ts-ignore
get Modal(): ModalModule { get Modal(): ModalModule {
return this.em.get("Modal"); return this.em.get('Modal');
} }
//@ts-ignore //@ts-ignore
get Panels(): PanelsModule { get Panels(): PanelsModule {
return this.em.get("Panels"); return this.em.get('Panels');
} }
//@ts-ignore //@ts-ignore
get Canvas(): CanvasModule { get Canvas(): CanvasModule {
return this.em.get("Canvas"); return this.em.get('Canvas');
} }
//@ts-ignore //@ts-ignore
get Parser(): ParserModule { get Parser(): ParserModule {
return this.em.get("Parser"); return this.em.get('Parser');
} }
//@ts-ignore //@ts-ignore
get CodeManager(): CodeManagerModule { get CodeManager(): CodeManagerModule {
return this.em.get("CodeManager"); return this.em.get('CodeManager');
} }
//@ts-ignore //@ts-ignore
get UndoManager(): UndoManagerModule { get UndoManager(): UndoManagerModule {
return this.em.get("UndoManager"); return this.em.get('UndoManager');
} }
//@ts-ignore //@ts-ignore
get RichTextEditor(): RichTextEditorModule { get RichTextEditor(): RichTextEditorModule {
return this.em.get("RichTextEditor"); return this.em.get('RichTextEditor');
} }
//@ts-ignore //@ts-ignore
get Pages(): PageManagerModule { get Pages(): PageManagerModule {
return this.em.get("PageManager"); return this.em.get('PageManager');
} }
//@ts-ignore //@ts-ignore
get Components(): DomComponentsModule { get Components(): DomComponentsModule {
return this.em.get("DomComponents"); return this.em.get('DomComponents');
} }
//@ts-ignore //@ts-ignore
get DomComponents(): DomComponentsModule { get DomComponents(): DomComponentsModule {
return this.em.get("DomComponents"); return this.em.get('DomComponents');
} }
//@ts-ignore //@ts-ignore
get Layers(): LayerManagerModule { get Layers(): LayerManagerModule {
return this.em.get("LayerManager"); return this.em.get('LayerManager');
} }
//@ts-ignore //@ts-ignore
get LayerManager(): LayerManagerModule { get LayerManager(): LayerManagerModule {
return this.em.get("LayerManager"); return this.em.get('LayerManager');
} }
//@ts-ignore //@ts-ignore
get Css(): CssComposerModule { get Css(): CssComposerModule {
return this.em.get("CssComposer"); return this.em.get('CssComposer');
} }
//@ts-ignore //@ts-ignore
get CssComposer(): CssComposerModule { get CssComposer(): CssComposerModule {
return this.em.get("CssComposer"); return this.em.get('CssComposer');
} }
//@ts-ignore //@ts-ignore
get Storage(): StorageManagerModule { get Storage(): StorageManagerModule {
return this.em.get("StorageManager"); return this.em.get('StorageManager');
} }
//@ts-ignore //@ts-ignore
get StorageManager(): StorageManagerModule { get StorageManager(): StorageManagerModule {
return this.em.get("StorageManager"); return this.em.get('StorageManager');
} }
//@ts-ignore //@ts-ignore
get Assets(): AssetManagerModule { get Assets(): AssetManagerModule {
return this.em.get("AssetManager"); return this.em.get('AssetManager');
} }
//@ts-ignore //@ts-ignore
get AssetManager(): AssetManagerModule { get AssetManager(): AssetManagerModule {
return this.em.get("AssetManager"); return this.em.get('AssetManager');
} }
//@ts-ignore //@ts-ignore
get Blocks(): BlockManagerModule { get Blocks(): BlockManagerModule {
return this.em.get("BlockManager"); return this.em.get('BlockManager');
} }
//@ts-ignore //@ts-ignore
get BlockManager(): BlockManagerModule { get BlockManager(): BlockManagerModule {
return this.em.get("BlockManager"); return this.em.get('BlockManager');
} }
//@ts-ignore //@ts-ignore
get Traits(): TraitManagerModule { get Traits(): TraitManagerModule {
return this.em.get("TraitManager"); return this.em.get('TraitManager');
} }
//@ts-ignore //@ts-ignore
get TraitManager(): TraitManagerModule { get TraitManager(): TraitManagerModule {
return this.em.get("TraitManager"); return this.em.get('TraitManager');
} }
//@ts-ignore //@ts-ignore
get Selectors(): SelectorManagerCollectionModule { get Selectors(): SelectorManagerCollectionModule {
return this.em.get("SelectorManager"); return this.em.get('SelectorManager');
} }
//@ts-ignore //@ts-ignore
get SelectorManager(): SelectorManagerCollectionModule { get SelectorManager(): SelectorManagerCollectionModule {
return this.em.get("SelectorManager"); return this.em.get('SelectorManager');
} }
//@ts-ignore //@ts-ignore
get Styles(): StyleManagerModule { get Styles(): StyleManagerModule {
return this.em.get("StyleManager"); return this.em.get('StyleManager');
} }
//@ts-ignore //@ts-ignore
get StyleManager(): StyleManagerModule { get StyleManager(): StyleManagerModule {
return this.em.get("StyleManager"); return this.em.get('StyleManager');
} }
//@ts-ignore //@ts-ignore
get Devices(): DeviceManagerModule { get Devices(): DeviceManagerModule {
return this.em.get("DeviceManager"); return this.em.get('DeviceManager');
} }
//@ts-ignore //@ts-ignore
get DeviceManager(): DeviceManagerModule { get DeviceManager(): DeviceManagerModule {
return this.em.get("DeviceManager"); return this.em.get('DeviceManager');
} }
//@deprecated //@deprecated

2
src/i18n/index.js

@ -191,7 +191,7 @@ export default class I18nModule {
} }
_addParams(str, params) { _addParams(str, params) {
const reg = new RegExp(`\{([\\w\\d-]*)\}`, 'g'); const reg = new RegExp('{([\\w\\d-]*)}', 'g');
return str.replace(reg, (m, val) => params[val] || '').trim(); return str.replace(reg, (m, val) => params[val] || '').trim();
} }

46
src/i18n/locale/bs.js

@ -5,7 +5,7 @@ export default {
addButton: 'Dodaj sliku', addButton: 'Dodaj sliku',
inputPlh: 'http://putanja/url/do/slike.jpg', inputPlh: 'http://putanja/url/do/slike.jpg',
modalTitle: 'Odaberi sliku', modalTitle: 'Odaberi sliku',
uploadTitle: 'Ubaci datoteke ovdje ili klikni za Upload' uploadTitle: 'Ubaci datoteke ovdje ili klikni za Upload',
}, },
// Here just as a reference, GrapesJS core doesn't contain any block, // Here just as a reference, GrapesJS core doesn't contain any block,
// so this should be omitted from other local files // so this should be omitted from other local files
@ -15,7 +15,7 @@ export default {
}, },
categories: { categories: {
// 'category-id': 'Category Label', // 'category-id': 'Category Label',
} },
}, },
domComponents: { domComponents: {
names: { names: {
@ -33,8 +33,8 @@ export default {
thead: 'Zaglavlje tabele', thead: 'Zaglavlje tabele',
table: 'Tabela', table: 'Tabela',
row: 'Red tabele', row: 'Red tabele',
cell: 'Ćelija tabele' cell: 'Ćelija tabele',
} },
}, },
deviceManager: { deviceManager: {
device: 'Uređaj', device: 'Uređaj',
@ -42,8 +42,8 @@ export default {
desktop: 'Računar', desktop: 'Računar',
tablet: 'Tablet', tablet: 'Tablet',
mobileLandscape: 'Mobitel vodoravno', mobileLandscape: 'Mobitel vodoravno',
mobilePortrait: 'Mobitel uspravno' mobilePortrait: 'Mobitel uspravno',
} },
}, },
panels: { panels: {
buttons: { buttons: {
@ -55,9 +55,9 @@ export default {
'open-sm': 'Otvori postavke izgleda', 'open-sm': 'Otvori postavke izgleda',
'open-tm': 'Postavke', 'open-tm': 'Postavke',
'open-layers': 'Otvori postavke slojeva', 'open-layers': 'Otvori postavke slojeva',
'open-blocks': 'Otvori blokove' 'open-blocks': 'Otvori blokove',
} },
} },
}, },
selectorManager: { selectorManager: {
label: 'Klase', label: 'Klase',
@ -66,8 +66,8 @@ export default {
states: { states: {
hover: 'Miš preko', hover: 'Miš preko',
active: 'Kliknuto', active: 'Kliknuto',
'nth-of-type(2n)': 'Parno/Neparno' 'nth-of-type(2n)': 'Parno/Neparno',
} },
}, },
styleManager: { styleManager: {
empty: 'Odaberi element prije korištenja Postavki Izgleda', empty: 'Odaberi element prije korištenja Postavki Izgleda',
@ -80,7 +80,7 @@ export default {
decorations: 'Dekoracije', decorations: 'Dekoracije',
extra: 'Dodatno', extra: 'Dodatno',
flex: 'Flex', flex: 'Flex',
dimension: 'Dimenzije' dimension: 'Dimenzije',
}, },
// The core library generates the name by their `property` name // The core library generates the name by their `property` name
properties: { properties: {
@ -134,9 +134,9 @@ export default {
'box-shadow-h': 'Sjena: horizontalno', 'box-shadow-h': 'Sjena: horizontalno',
'box-shadow-v': 'Sjena: vertikalno', 'box-shadow-v': 'Sjena: vertikalno',
'box-shadow-blur': 'Sjena: zamagljenost', 'box-shadow-blur': 'Sjena: zamagljenost',
'box-shadow-spread': "Sjena: širenje", 'box-shadow-spread': 'Sjena: širenje',
'box-shadow-color': "Sjena: boja", 'box-shadow-color': 'Sjena: boja',
'box-shadow-type': "Sjena: tip", 'box-shadow-type': 'Sjena: tip',
background: 'Pozadina', background: 'Pozadina',
'background-image': 'Pozadinska slika', 'background-image': 'Pozadinska slika',
'background-repeat': 'Ponavljanje pozadine', 'background-repeat': 'Ponavljanje pozadine',
@ -165,8 +165,8 @@ export default {
'flex-basis': 'Flex Basis', 'flex-basis': 'Flex Basis',
'flex-grow': 'Flex Rast', 'flex-grow': 'Flex Rast',
'flex-shrink': 'Flex Smanjenje', 'flex-shrink': 'Flex Smanjenje',
'align-self': 'Poravnaj sebe' 'align-self': 'Poravnaj sebe',
} },
}, },
traitManager: { traitManager: {
empty: 'Odaberi element prije korištenja Postavki Osobina', empty: 'Odaberi element prije korištenja Postavki Osobina',
@ -184,15 +184,15 @@ export default {
id: traitInputAttr, id: traitInputAttr,
alt: traitInputAttr, alt: traitInputAttr,
title: traitInputAttr, title: traitInputAttr,
href: { placeholder: 'npr. https://google.com' } href: { placeholder: 'npr. https://google.com' },
}, },
// In a trait like select, these are used to translate option names // In a trait like select, these are used to translate option names
options: { options: {
target: { target: {
false: 'Ovaj prozor', false: 'Ovaj prozor',
_blank: 'Novi prozor' _blank: 'Novi prozor',
} },
} },
} },
} },
}; };

54
src/i18n/locale/de.js

@ -5,7 +5,7 @@ export default {
addButton: 'Bild hinzufügen', addButton: 'Bild hinzufügen',
inputPlh: 'http://chemin/vers/image.jpg', inputPlh: 'http://chemin/vers/image.jpg',
modalTitle: 'Bild auswählen', modalTitle: 'Bild auswählen',
uploadTitle: 'Ziehen Sie eine Datei hierher oder klicken Sie auf Upload' uploadTitle: 'Ziehen Sie eine Datei hierher oder klicken Sie auf Upload',
}, },
// Here just as a reference, GrapesJS core doesn't contain any block, // Here just as a reference, GrapesJS core doesn't contain any block,
// so this should be omitted from other local files // so this should be omitted from other local files
@ -15,7 +15,7 @@ export default {
}, },
categories: { categories: {
// 'category-id': 'Kategorie Label', // 'category-id': 'Kategorie Label',
} },
}, },
domComponents: { domComponents: {
names: { names: {
@ -33,8 +33,8 @@ export default {
thead: 'Tabellen Kopf', thead: 'Tabellen Kopf',
table: 'Tabelle', table: 'Tabelle',
row: 'Zeile', row: 'Zeile',
cell: 'Zelle' cell: 'Zelle',
} },
}, },
deviceManager: { deviceManager: {
device: 'Gerät', device: 'Gerät',
@ -42,8 +42,8 @@ export default {
desktop: 'Desktop', desktop: 'Desktop',
tablet: 'Tablet', tablet: 'Tablet',
mobileLandscape: 'Mobile Landscape', mobileLandscape: 'Mobile Landscape',
mobilePortrait: 'Mobile Portrait' mobilePortrait: 'Mobile Portrait',
} },
}, },
panels: { panels: {
buttons: { buttons: {
@ -55,9 +55,9 @@ export default {
'open-sm': 'Stil Manager öffnen', 'open-sm': 'Stil Manager öffnen',
'open-tm': 'Parameter', 'open-tm': 'Parameter',
'open-layers': 'Layer Manager öffnen', 'open-layers': 'Layer Manager öffnen',
'open-blocks': 'Block öffnen' 'open-blocks': 'Block öffnen',
} },
} },
}, },
selectorManager: { selectorManager: {
label: 'Klassen', label: 'Klassen',
@ -66,12 +66,11 @@ export default {
states: { states: {
hover: 'Hover', hover: 'Hover',
active: 'Klick', active: 'Klick',
'nth-of-type(2n)': 'Gerade/Ungerade' 'nth-of-type(2n)': 'Gerade/Ungerade',
} },
}, },
styleManager: { styleManager: {
empty: empty: 'Wählen Sie ein Element aus bevor Sie den Stil Manager nutzen',
"Wählen Sie ein Element aus bevor Sie den Stil Manager nutzen",
layer: 'Ebene', layer: 'Ebene',
fileButton: 'Bilder', fileButton: 'Bilder',
sectors: { sectors: {
@ -81,7 +80,7 @@ export default {
decorations: 'Dekorationen', decorations: 'Dekorationen',
extra: 'Extra', extra: 'Extra',
flex: 'Flex', flex: 'Flex',
dimension: 'Dimension' dimension: 'Dimension',
}, },
// The core library generates the name by their `property` name // The core library generates the name by their `property` name
properties: { properties: {
@ -135,9 +134,9 @@ export default {
'box-shadow-h': 'Boxschatten: horizontal', 'box-shadow-h': 'Boxschatten: horizontal',
'box-shadow-v': 'Boxschatten: vertikal', 'box-shadow-v': 'Boxschatten: vertikal',
'box-shadow-blur': 'Boxschatten: Unschärfe', 'box-shadow-blur': 'Boxschatten: Unschärfe',
'box-shadow-spread': "Boxschatten: Streuung", 'box-shadow-spread': 'Boxschatten: Streuung',
'box-shadow-color': "Boxschatten: Farbe", 'box-shadow-color': 'Boxschatten: Farbe',
'box-shadow-type': "Boxschatten: Typ", 'box-shadow-type': 'Boxschatten: Typ',
background: 'Hintergrund', background: 'Hintergrund',
'background-image': 'Hintergrundbild', 'background-image': 'Hintergrundbild',
'background-repeat': 'Hintergrund wiederholen', 'background-repeat': 'Hintergrund wiederholen',
@ -166,12 +165,11 @@ export default {
'flex-basis': 'Flex Basis', 'flex-basis': 'Flex Basis',
'flex-grow': 'Flex Wachsen', 'flex-grow': 'Flex Wachsen',
'flex-shrink': 'Flex Schrumpfen', 'flex-shrink': 'Flex Schrumpfen',
'align-self': 'Eigene Ausrichtung' 'align-self': 'Eigene Ausrichtung',
} },
}, },
traitManager: { traitManager: {
empty: empty: 'Wählen Sie ein Element aus bevor Sie den Komponenten Manager nutzen',
"Wählen Sie ein Element aus bevor Sie den Komponenten Manager nutzen",
label: 'Komponenteneinstellungen', label: 'Komponenteneinstellungen',
traits: { traits: {
// The core library generates the name by their `name` property // The core library generates the name by their `name` property
@ -179,22 +177,22 @@ export default {
id: 'ID', id: 'ID',
alt: 'Alternativtext', alt: 'Alternativtext',
title: 'Titel', title: 'Titel',
href: 'Link' href: 'Link',
}, },
// In a simple trait, like text input, these are used on input attributes // In a simple trait, like text input, these are used on input attributes
attributes: { attributes: {
id: traitInputAttr, id: traitInputAttr,
alt: traitInputAttr, alt: traitInputAttr,
title: traitInputAttr, title: traitInputAttr,
href: { placeholder: 'z.B. https://google.com' } href: { placeholder: 'z.B. https://google.com' },
}, },
// In a trait like select, these are used to translate option names // In a trait like select, these are used to translate option names
options: { options: {
target: { target: {
false: 'Dieses Fenster', false: 'Dieses Fenster',
_blank: 'Neues Fenster' _blank: 'Neues Fenster',
} },
} },
} },
} },
}; };

48
src/i18n/locale/fr.js

@ -5,7 +5,7 @@ export default {
addButton: 'Ajouter image', addButton: 'Ajouter image',
inputPlh: 'http://chemin/vers/image.jpg', inputPlh: 'http://chemin/vers/image.jpg',
modalTitle: 'Sélectionner une image', modalTitle: 'Sélectionner une image',
uploadTitle: 'Déposez des fichiers ici ou cliquez pour envoyer des fichiers' uploadTitle: 'Déposez des fichiers ici ou cliquez pour envoyer des fichiers',
}, },
blockManager: { blockManager: {
labels: { labels: {
@ -13,7 +13,7 @@ export default {
}, },
categories: { categories: {
// 'category-id': 'Identifiant de la catégorie', // 'category-id': 'Identifiant de la catégorie',
} },
}, },
domComponents: { domComponents: {
names: { names: {
@ -31,8 +31,8 @@ export default {
thead: 'En-tête de tableau', thead: 'En-tête de tableau',
table: 'Tableau', table: 'Tableau',
row: 'Ligne tableau', row: 'Ligne tableau',
cell: 'Cellule tableau' cell: 'Cellule tableau',
} },
}, },
deviceManager: { deviceManager: {
device: 'Appareil', device: 'Appareil',
@ -40,8 +40,8 @@ export default {
desktop: 'Ordinateur de bureau', desktop: 'Ordinateur de bureau',
tablet: 'Tablette', tablet: 'Tablette',
mobileLandscape: 'Mobile format paysage', mobileLandscape: 'Mobile format paysage',
mobilePortrait: 'Mobile format portrait' mobilePortrait: 'Mobile format portrait',
} },
}, },
panels: { panels: {
buttons: { buttons: {
@ -53,9 +53,9 @@ export default {
'open-sm': 'Ouvrir le gestionnaire de style', 'open-sm': 'Ouvrir le gestionnaire de style',
'open-tm': 'Paramètres', 'open-tm': 'Paramètres',
'open-layers': 'Ouvrir le gestionnaire de calques', 'open-layers': 'Ouvrir le gestionnaire de calques',
'open-blocks': 'Ouvrir le gestionnaire de blocs' 'open-blocks': 'Ouvrir le gestionnaire de blocs',
} },
} },
}, },
selectorManager: { selectorManager: {
label: 'Classes', label: 'Classes',
@ -64,12 +64,11 @@ export default {
states: { states: {
hover: 'Survol', hover: 'Survol',
active: 'Clic', active: 'Clic',
'nth-of-type(2n)': 'Paire/Impaire' 'nth-of-type(2n)': 'Paire/Impaire',
} },
}, },
styleManager: { styleManager: {
empty: empty: "Veuillez sélectionner un élément avant d'utiliser le gestionnaire de style",
"Veuillez sélectionner un élément avant d'utiliser le gestionnaire de style",
layer: 'Calque', layer: 'Calque',
fileButton: 'Images', fileButton: 'Images',
sectors: { sectors: {
@ -79,7 +78,7 @@ export default {
decorations: 'Décorations', decorations: 'Décorations',
extra: 'Extra', extra: 'Extra',
flex: 'Flex', flex: 'Flex',
dimension: 'Dimension' dimension: 'Dimension',
}, },
// The core library generates the name by their `property` name // The core library generates the name by their `property` name
properties: { properties: {
@ -164,12 +163,11 @@ export default {
'flex-basis': 'Base Flex', 'flex-basis': 'Base Flex',
'flex-grow': 'Flex grow', 'flex-grow': 'Flex grow',
'flex-shrink': 'Flex shrink', 'flex-shrink': 'Flex shrink',
'align-self': 'Aligner' 'align-self': 'Aligner',
} },
}, },
traitManager: { traitManager: {
empty: empty: 'Veuillez sélectionner un élément pour modifier les paramètres de cet élément',
'Veuillez sélectionner un élément pour modifier les paramètres de cet élément',
label: 'Paramètres composant', label: 'Paramètres composant',
traits: { traits: {
// The core library generates the name by their `name` property // The core library generates the name by their `name` property
@ -177,22 +175,22 @@ export default {
id: 'Identifiant', id: 'Identifiant',
alt: 'Texte alternatif', alt: 'Texte alternatif',
title: 'Titre', title: 'Titre',
href: 'Source lien' href: 'Source lien',
}, },
// In a simple trait, like text input, these are used on input attributes // In a simple trait, like text input, these are used on input attributes
attributes: { attributes: {
id: traitInputAttr, id: traitInputAttr,
alt: traitInputAttr, alt: traitInputAttr,
title: traitInputAttr, title: traitInputAttr,
href: { placeholder: 'eg. https://google.com' } href: { placeholder: 'eg. https://google.com' },
}, },
// In a trait like select, these are used to translate option names // In a trait like select, these are used to translate option names
options: { options: {
target: { target: {
false: 'Cette fenêtre', false: 'Cette fenêtre',
_blank: 'Nouvelle fenêtre' _blank: 'Nouvelle fenêtre',
} },
} },
} },
} },
}; };

46
src/i18n/locale/se.js

@ -5,7 +5,7 @@ export default {
addButton: 'Lägg till bild', addButton: 'Lägg till bild',
inputPlh: 'http://adress/till/bilden.jpg', inputPlh: 'http://adress/till/bilden.jpg',
modalTitle: 'Välj bild', modalTitle: 'Välj bild',
uploadTitle: 'Dra och släpp filer här eller klicka för att ladda upp' uploadTitle: 'Dra och släpp filer här eller klicka för att ladda upp',
}, },
// Here just as a reference, GrapesJS core doesn't contain any block, // Here just as a reference, GrapesJS core doesn't contain any block,
// so this should be omitted from other local files // so this should be omitted from other local files
@ -15,7 +15,7 @@ export default {
}, },
categories: { categories: {
// 'category-id': 'Category Label', // 'category-id': 'Category Label',
} },
}, },
domComponents: { domComponents: {
names: { names: {
@ -33,8 +33,8 @@ export default {
thead: 'Tabellhuvud', thead: 'Tabellhuvud',
table: 'Tabell', table: 'Tabell',
row: 'Tabellrad', row: 'Tabellrad',
cell: 'Tabellcell' cell: 'Tabellcell',
} },
}, },
deviceManager: { deviceManager: {
device: 'Enhet', device: 'Enhet',
@ -42,8 +42,8 @@ export default {
desktop: 'Dator', desktop: 'Dator',
tablet: 'Surfplatta', tablet: 'Surfplatta',
mobileLandscape: 'Mobil liggande', mobileLandscape: 'Mobil liggande',
mobilePortrait: 'Mobil stående' mobilePortrait: 'Mobil stående',
} },
}, },
panels: { panels: {
buttons: { buttons: {
@ -55,9 +55,9 @@ export default {
'open-sm': 'Öppna stilhanterare', 'open-sm': 'Öppna stilhanterare',
'open-tm': 'Inställningar', 'open-tm': 'Inställningar',
'open-layers': 'Öppna lagerhanterare', 'open-layers': 'Öppna lagerhanterare',
'open-blocks': 'Öppna block' 'open-blocks': 'Öppna block',
} },
} },
}, },
selectorManager: { selectorManager: {
label: 'Klasser', label: 'Klasser',
@ -66,8 +66,8 @@ export default {
states: { states: {
hover: 'Mus över', hover: 'Mus över',
active: 'Klick', active: 'Klick',
'nth-of-type(2n)': 'Jämn/udda' 'nth-of-type(2n)': 'Jämn/udda',
} },
}, },
styleManager: { styleManager: {
empty: 'Markera ett element innan du använder stilhanteraren', empty: 'Markera ett element innan du använder stilhanteraren',
@ -80,7 +80,7 @@ export default {
decorations: 'Dekoration', decorations: 'Dekoration',
extra: 'Extra', extra: 'Extra',
flex: 'Flex', flex: 'Flex',
dimension: 'Dimension' dimension: 'Dimension',
}, },
// The core library generates the name by their `property` name // The core library generates the name by their `property` name
properties: { properties: {
@ -138,9 +138,9 @@ export default {
'box-shadow-h': 'Horisontell skugga', 'box-shadow-h': 'Horisontell skugga',
'box-shadow-v': 'Vertikal skugga', 'box-shadow-v': 'Vertikal skugga',
'box-shadow-blur': 'Skuggans luddighet', 'box-shadow-blur': 'Skuggans luddighet',
'box-shadow-spread': "Skuggans spridning", 'box-shadow-spread': 'Skuggans spridning',
'box-shadow-color': "Skuggans färg", 'box-shadow-color': 'Skuggans färg',
'box-shadow-type': "Typ av skugga", 'box-shadow-type': 'Typ av skugga',
background: 'Bakgrund', background: 'Bakgrund',
'background-image': 'Bakgrundsbild', 'background-image': 'Bakgrundsbild',
'background-repeat': 'Upprepa bakgrund', 'background-repeat': 'Upprepa bakgrund',
@ -169,8 +169,8 @@ export default {
'flex-basis': 'Flexbas', 'flex-basis': 'Flexbas',
'flex-grow': 'Flex väx', 'flex-grow': 'Flex väx',
'flex-shrink': 'Flex krymp', 'flex-shrink': 'Flex krymp',
'align-self': 'Självjustering' 'align-self': 'Självjustering',
} },
}, },
traitManager: { traitManager: {
empty: 'Markera ett element innan du använder egenskapshanteraren', empty: 'Markera ett element innan du använder egenskapshanteraren',
@ -196,15 +196,15 @@ export default {
id: traitInputAttr, id: traitInputAttr,
alt: traitInputAttr, alt: traitInputAttr,
title: traitInputAttr, title: traitInputAttr,
href: { placeholder: 't.ex. https://google.com' } href: { placeholder: 't.ex. https://google.com' },
}, },
// In a trait like select, these are used to translate option names // In a trait like select, these are used to translate option names
options: { options: {
target: { target: {
false: 'Detta fönster', false: 'Detta fönster',
_blank: 'Nytt fönster' _blank: 'Nytt fönster',
} },
} },
} },
} },
}; };

50
src/selector_manager/model/Selector.ts

@ -1,6 +1,6 @@
import { result, forEach, keys } from "underscore"; import { result, forEach, keys } from 'underscore';
import { Model } from "../../common"; import { Model } from '../../common';
import EditorModel from "../../editor/model/Editor"; import EditorModel from '../../editor/model/Editor';
const TYPE_CLASS = 1; const TYPE_CLASS = 1;
const TYPE_ID = 2; const TYPE_ID = 2;
@ -17,8 +17,8 @@ const TYPE_ID = 2;
export default class Selector extends Model { export default class Selector extends Model {
defaults() { defaults() {
return { return {
name: "", name: '',
label: "", label: '',
type: TYPE_CLASS, type: TYPE_CLASS,
active: true, active: true,
private: false, private: false,
@ -36,43 +36,43 @@ export default class Selector extends Model {
constructor(props: any, opts: any = {}) { constructor(props: any, opts: any = {}) {
super(props, opts); super(props, opts);
const { config = {} } = opts; const { config = {} } = opts;
const name = this.get("name"); const name = this.get('name');
const label = this.get("label"); const label = this.get('label');
if (!name) { if (!name) {
this.set("name", label); this.set('name', label);
} else if (!label) { } else if (!label) {
this.set("label", name); this.set('label', name);
} }
const namePreEsc = this.get("name"); const namePreEsc = this.get('name');
const { escapeName } = config; const { escapeName } = config;
const nameEsc = escapeName const nameEsc = escapeName
? escapeName(namePreEsc) ? escapeName(namePreEsc)
: Selector.escapeName(namePreEsc); : Selector.escapeName(namePreEsc);
this.set("name", nameEsc); this.set('name', nameEsc);
this.em = opts.em; this.em = opts.em;
} }
isId() { isId() {
return this.get("type") === TYPE_ID; return this.get('type') === TYPE_ID;
} }
isClass() { isClass() {
return this.get("type") === TYPE_CLASS; return this.get('type') === TYPE_CLASS;
} }
getFullName(opts: any = {}) { getFullName(opts: any = {}) {
const { escape } = opts; const { escape } = opts;
const name = this.get("name"); const name = this.get('name');
let pfx = ""; let pfx = '';
switch (this.get("type")) { switch (this.get('type')) {
case TYPE_CLASS: case TYPE_CLASS:
pfx = "."; pfx = '.';
break; break;
case TYPE_ID: case TYPE_ID:
pfx = "#"; pfx = '#';
break; break;
} }
@ -100,7 +100,7 @@ export default class Selector extends Model {
* // -> `My selector` * // -> `My selector`
*/ */
getLabel() { getLabel() {
return this.get("label"); return this.get('label');
} }
/** /**
@ -113,7 +113,7 @@ export default class Selector extends Model {
* // -> `New Label` * // -> `New Label`
*/ */
setLabel(label: string) { setLabel(label: string) {
return this.set("label", label); return this.set('label', label);
} }
/** /**
@ -121,7 +121,7 @@ export default class Selector extends Model {
* @returns {Boolean} * @returns {Boolean}
*/ */
getActive(): boolean { getActive(): boolean {
return this.get("active"); return this.get('active');
} }
/** /**
@ -129,13 +129,13 @@ export default class Selector extends Model {
* @param {Boolean} value New active state * @param {Boolean} value New active state
*/ */
setActive(value: boolean) { setActive(value: boolean) {
return this.set("active", value); return this.set('active', value);
} }
toJSON(opts = {}) { toJSON(opts = {}) {
const { em } = this; const { em } = this;
let obj = Model.prototype.toJSON.call(this, [opts]); let obj = Model.prototype.toJSON.call(this, [opts]);
const defaults = result(this, "defaults"); const defaults = result(this, 'defaults');
if (em && em.getConfig().avoidDefaults) { if (em && em.getConfig().avoidDefaults) {
forEach(defaults, (value, key) => { forEach(defaults, (value, key) => {
@ -169,8 +169,8 @@ export default class Selector extends Model {
* @public * @public
*/ */
static escapeName(name: string) { static escapeName(name: string) {
return `${name}`.trim().replace(/([^a-z0-9\w-\:]+)/gi, "-"); return `${name}`.trim().replace(/([^a-z0-9\w-\:]+)/gi, '-');
} }
} }
Selector.prototype.idAttribute = "name"; Selector.prototype.idAttribute = 'name';

16
src/selector_manager/model/Selectors.ts

@ -1,6 +1,6 @@
import { filter } from "underscore"; import { filter } from 'underscore';
import { Collection } from "../../common"; import { Collection } from '../../common';
import Selector from "./Selector"; import Selector from './Selector';
const combine = (tail: string[], curr: string): string[] => { const combine = (tail: string[], curr: string): string[] => {
return tail.reduce( return tail.reduce(
@ -19,13 +19,13 @@ export default class Selectors extends Collection<Selector> {
getStyleable() { getStyleable() {
return filter( return filter(
this.models, this.models,
(item) => item.get("active") && !item.get("private") (item) => item.get('active') && !item.get('private')
); );
} }
getValid({ noDisabled }: any = {}) { getValid({ noDisabled }: any = {}) {
return filter(this.models, (item) => !item.get("private")).filter((item) => return filter(this.models, (item) => !item.get('private')).filter((item) =>
noDisabled ? item.get("active") : 1 noDisabled ? item.get('active') : 1
); );
} }
@ -33,7 +33,7 @@ export default class Selectors extends Collection<Selector> {
const result: string[] = []; const result: string[] = [];
const coll = collection || this; const coll = collection || this;
coll.forEach((selector) => result.push(selector.getFullName(opts))); coll.forEach((selector) => result.push(selector.getFullName(opts)));
return result.join("").trim(); return result.join('').trim();
} }
getFullName(opts: any = {}) { getFullName(opts: any = {}) {
@ -49,7 +49,7 @@ export default class Selectors extends Collection<Selector> {
result = sels; result = sels;
} }
return array ? result : combination ? result.join(",") : result.join(""); return array ? result : combination ? result.join(',') : result.join('');
} }
} }

12
src/selector_manager/model/State.ts

@ -1,4 +1,4 @@
import { Model } from "../../common"; import { Model } from '../../common';
/** /**
* @typedef State * @typedef State
@ -8,8 +8,8 @@ import { Model } from "../../common";
export default class State extends Model { export default class State extends Model {
defaults() { defaults() {
return { return {
name: "", name: '',
label: "", label: '',
}; };
} }
@ -18,7 +18,7 @@ export default class State extends Model {
* @returns {String} * @returns {String}
*/ */
getName(): string { getName(): string {
return this.get("name"); return this.get('name');
} }
/** /**
@ -26,7 +26,7 @@ export default class State extends Model {
* @returns {String} * @returns {String}
*/ */
getLabel(): string { getLabel(): string {
return this.get("label") || this.getName(); return this.get('label') || this.getName();
} }
} }
State.prototype.idAttribute = "name"; State.prototype.idAttribute = 'name';

44
src/selector_manager/view/ClassTagView.ts

@ -1,12 +1,12 @@
import { View } from "../../common"; import { View } from '../../common';
import State from "../model/State"; import State from '../model/State';
const inputProp = "contentEditable"; const inputProp = 'contentEditable';
export default class ClassTagView extends View<State> { export default class ClassTagView extends View<State> {
template() { template() {
const { pfx, model, config } = this; const { pfx, model, config } = this;
const label = model.get("label") || ""; const label = model.get('label') || '';
return ` return `
<span id="${pfx}checkbox" class="${pfx}tag-status" data-tag-status></span> <span id="${pfx}checkbox" class="${pfx}tag-status" data-tag-status></span>
@ -19,10 +19,10 @@ export default class ClassTagView extends View<State> {
events() { events() {
return { return {
"click [data-tag-remove]": "removeTag", 'click [data-tag-remove]': 'removeTag',
"click [data-tag-status]": "changeStatus", 'click [data-tag-status]': 'changeStatus',
"dblclick [data-tag-name]": "startEditTag", 'dblclick [data-tag-name]': 'startEditTag',
"focusout [data-tag-name]": "endEditTag", 'focusout [data-tag-name]': 'endEditTag',
}; };
} }
config: any; config: any;
@ -39,10 +39,10 @@ export default class ClassTagView extends View<State> {
this.config = config; this.config = config;
this.module = o.module; this.module = o.module;
this.coll = o.coll || null; this.coll = o.coll || null;
this.pfx = config.stylePrefix || ""; this.pfx = config.stylePrefix || '';
this.ppfx = config.pStylePrefix || ""; this.ppfx = config.pStylePrefix || '';
this.em = config.em; this.em = config.em;
this.listenTo(this.model, "change:active", this.updateStatus); this.listenTo(this.model, 'change:active', this.updateStatus);
} }
/** /**
@ -51,7 +51,7 @@ export default class ClassTagView extends View<State> {
*/ */
getInputEl() { getInputEl() {
if (!this.inputEl) { if (!this.inputEl) {
this.inputEl = this.el.querySelector("[data-tag-name]") as HTMLElement; this.inputEl = this.el.querySelector('[data-tag-name]') as HTMLElement;
} }
return this.inputEl; return this.inputEl;
@ -65,7 +65,7 @@ export default class ClassTagView extends View<State> {
const { em } = this; const { em } = this;
const inputEl = this.getInputEl(); const inputEl = this.getInputEl();
inputEl; inputEl;
inputEl[inputProp] = "true"; inputEl[inputProp] = 'true';
inputEl.focus(); inputEl.focus();
em && em.setEditing(1); em && em.setEditing(1);
} }
@ -80,15 +80,15 @@ export default class ClassTagView extends View<State> {
const inputEl = this.getInputEl(); const inputEl = this.getInputEl();
const label = inputEl.textContent; const label = inputEl.textContent;
const em = this.em; const em = this.em;
const sm = em && em.get("SelectorManager"); const sm = em && em.get('SelectorManager');
inputEl[inputProp] = "false"; inputEl[inputProp] = 'false';
em && em.setEditing(0); em && em.setEditing(0);
if (sm) { if (sm) {
const name = sm.escapeName(label); const name = sm.escapeName(label);
if (sm.get(name)) { if (sm.get(name)) {
inputEl.innerText = model.get("label"); inputEl.innerText = model.get('label');
} else { } else {
model.set({ name, label }); model.set({ name, label });
} }
@ -101,7 +101,7 @@ export default class ClassTagView extends View<State> {
*/ */
changeStatus() { changeStatus() {
const { model } = this; const { model } = this;
model.set("active", !model.get("active")); model.set('active', !model.get('active'));
} }
/** /**
@ -120,14 +120,14 @@ export default class ClassTagView extends View<State> {
updateStatus() { updateStatus() {
const { model, $el, config } = this; const { model, $el, config } = this;
const { iconTagOn, iconTagOff } = config; const { iconTagOn, iconTagOff } = config;
const $chk = $el.find("[data-tag-status]"); const $chk = $el.find('[data-tag-status]');
if (model.get("active")) { if (model.get('active')) {
$chk.html(iconTagOn); $chk.html(iconTagOn);
$el.removeClass("opac50"); $el.removeClass('opac50');
} else { } else {
$chk.html(iconTagOff); $chk.html(iconTagOff);
$el.addClass("opac50"); $el.addClass('opac50');
} }
} }
@ -135,7 +135,7 @@ export default class ClassTagView extends View<State> {
const pfx = this.pfx; const pfx = this.pfx;
const ppfx = this.ppfx; const ppfx = this.ppfx;
this.$el.html(this.template()); this.$el.html(this.template());
this.$el.attr("class", `${pfx}tag ${ppfx}three-bg`); this.$el.attr('class', `${pfx}tag ${ppfx}three-bg`);
this.updateStatus(); this.updateStatus();
return this; return this;
} }

2
src/style_manager/view/LayerView.js

@ -111,7 +111,7 @@ export default class LayerView extends View {
el.innerHTML = this.template(); el.innerHTML = this.template();
el.className = `${pfx}layer`; el.className = `${pfx}layer`;
if (model.hasPreview()) { if (model.hasPreview()) {
el.querySelector(`[data-preview-box]`).style.display = ''; el.querySelector('[data-preview-box]').style.display = '';
} }
this.updateLabel(); this.updateLabel();
this.updateVisibility(); this.updateVisibility();

12
test/specs/commands/view/Preview.js

@ -16,7 +16,7 @@ describe('Preview command', () => {
getModel: jest.fn().mockReturnValue({ getModel: jest.fn().mockReturnValue({
runDefault: jest.fn(), runDefault: jest.fn(),
stopDefault: jest.fn() stopDefault: jest.fn(),
}), }),
Config: {}, Config: {},
@ -24,8 +24,8 @@ describe('Preview command', () => {
Canvas: { Canvas: {
getElement: jest.fn().mockReturnValue({ getElement: jest.fn().mockReturnValue({
style: {}, style: {},
setAttribute: jest.fn() setAttribute: jest.fn(),
}) }),
}, },
select: jest.fn(), select: jest.fn(),
@ -33,12 +33,12 @@ describe('Preview command', () => {
getSelectedAll: jest.fn().mockReturnValue([]), getSelectedAll: jest.fn().mockReturnValue([]),
Commands: { Commands: {
isActive: jest.fn(() => fakeIsActive) isActive: jest.fn(() => fakeIsActive),
}, },
Panels: { Panels: {
getPanels: jest.fn(() => fakePanels) getPanels: jest.fn(() => fakePanels),
} },
}; };
Preview.panels = undefined; Preview.panels = undefined;

32
test/specs/css_composer/index.js

@ -161,9 +161,9 @@ describe('Css Composer', () => {
expect(obj.getAll().length).toEqual(1); expect(obj.getAll().length).toEqual(1);
const rule = obj.getIdRule(name); const rule = obj.getIdRule(name);
expect(rule.selectorsToString()).toEqual(`#${name}`); expect(rule.selectorsToString()).toEqual(`#${name}`);
expect(rule.styleToString()).toEqual(`color:red;`); expect(rule.styleToString()).toEqual('color:red;');
expect(rule.styleToString({ important: 1 })).toEqual(`color:red !important;`); expect(rule.styleToString({ important: 1 })).toEqual('color:red !important;');
expect(rule.styleToString({ important: ['color'] })).toEqual(`color:red !important;`); expect(rule.styleToString({ important: ['color'] })).toEqual('color:red !important;');
}); });
test('Create a rule with id selector and state by using setIdRule()', () => { test('Create a rule with id selector and state by using setIdRule()', () => {
@ -181,7 +181,7 @@ describe('Css Composer', () => {
expect(obj.getAll().length).toEqual(1); expect(obj.getAll().length).toEqual(1);
const rule = obj.getClassRule(name); const rule = obj.getClassRule(name);
expect(rule.selectorsToString()).toEqual(`.${name}`); expect(rule.selectorsToString()).toEqual(`.${name}`);
expect(rule.styleToString()).toEqual(`color:red;`); expect(rule.styleToString()).toEqual('color:red;');
}); });
test('Create a rule with class selector and state by using setClassRule()', () => { test('Create a rule with class selector and state by using setClassRule()', () => {
@ -199,7 +199,7 @@ describe('Css Composer', () => {
expect(obj.getAll().length).toEqual(1); expect(obj.getAll().length).toEqual(1);
const rule = obj.getRule(selector); const rule = obj.getRule(selector);
expect(rule.selectorsToString()).toEqual(selector); expect(rule.selectorsToString()).toEqual(selector);
expect(rule.styleToString()).toEqual(`color:red;`); expect(rule.styleToString()).toEqual('color:red;');
}); });
test('Avoid creating multiple rules with the same selector', () => { test('Avoid creating multiple rules with the same selector', () => {
@ -209,7 +209,7 @@ describe('Css Composer', () => {
expect(obj.getAll().length).toEqual(1); expect(obj.getAll().length).toEqual(1);
const rule = obj.getRule(selector); const rule = obj.getRule(selector);
expect(rule.selectorsToString()).toEqual(selector); expect(rule.selectorsToString()).toEqual(selector);
expect(rule.styleToString()).toEqual(`color:blue;`); expect(rule.styleToString()).toEqual('color:blue;');
}); });
test('Create a class-based rule with setRule', () => { test('Create a class-based rule with setRule', () => {
@ -218,7 +218,7 @@ describe('Css Composer', () => {
expect(obj.getAll().length).toEqual(1); expect(obj.getAll().length).toEqual(1);
const rule = obj.getRule(selector); const rule = obj.getRule(selector);
expect(rule.selectorsToString()).toEqual(selector); expect(rule.selectorsToString()).toEqual(selector);
expect(rule.styleToString()).toEqual(`color:red;`); expect(rule.styleToString()).toEqual('color:red;');
}); });
test('Create a class-based rule with a state, by using setRule', () => { test('Create a class-based rule with a state, by using setRule', () => {
@ -227,7 +227,7 @@ describe('Css Composer', () => {
expect(obj.getAll().length).toEqual(1); expect(obj.getAll().length).toEqual(1);
const rule = obj.getRule(selector); const rule = obj.getRule(selector);
expect(rule.selectorsToString()).toEqual(selector); expect(rule.selectorsToString()).toEqual(selector);
expect(rule.styleToString()).toEqual(`color:red;`); expect(rule.styleToString()).toEqual('color:red;');
}); });
test('Create a rule with class-based and mixed selectors', () => { test('Create a rule with class-based and mixed selectors', () => {
@ -236,7 +236,7 @@ describe('Css Composer', () => {
expect(obj.getAll().length).toEqual(1); expect(obj.getAll().length).toEqual(1);
const rule = obj.getRule(selector); const rule = obj.getRule(selector);
expect(rule.selectorsToString()).toEqual(selector); expect(rule.selectorsToString()).toEqual(selector);
expect(rule.styleToString()).toEqual(`color:red;`); expect(rule.styleToString()).toEqual('color:red;');
}); });
test('Create a rule with only mixed selectors', () => { test('Create a rule with only mixed selectors', () => {
@ -246,7 +246,7 @@ describe('Css Composer', () => {
const rule = obj.getRule(selector); const rule = obj.getRule(selector);
expect(rule.get('selectors').length).toEqual(0); expect(rule.get('selectors').length).toEqual(0);
expect(rule.selectorsToString()).toEqual(selector); expect(rule.selectorsToString()).toEqual(selector);
expect(rule.styleToString()).toEqual(`color:red;`); expect(rule.styleToString()).toEqual('color:red;');
}); });
test('Create a rule with atRule', () => { test('Create a rule with atRule', () => {
@ -309,7 +309,7 @@ describe('Css Composer', () => {
const name = 'rule-test'; const name = 'rule-test';
const selClass = `.${name}`; const selClass = `.${name}`;
const selId = `#${name}`; const selId = `#${name}`;
const decl = `{colore:red;}`; const decl = '{colore:red;}';
all.add(`${selClass}${decl} ${selId}${decl}`); all.add(`${selClass}${decl} ${selId}${decl}`);
expect(all.length).toBe(2); expect(all.length).toBe(2);
const ruleClass = all.at(0); const ruleClass = all.at(0);
@ -326,17 +326,17 @@ describe('Css Composer', () => {
describe('Collections', () => { describe('Collections', () => {
test('Add a single rule as CSS string', () => { test('Add a single rule as CSS string', () => {
const cssRule = `.test-rule{color:red;}`; const cssRule = '.test-rule{color:red;}';
obj.addCollection(cssRule); obj.addCollection(cssRule);
expect(obj.getAll().length).toEqual(1); expect(obj.getAll().length).toEqual(1);
expect(getCSS(obj)).toEqual(cssRule); expect(getCSS(obj)).toEqual(cssRule);
}); });
test('Add multiple rules as CSS string', () => { test('Add multiple rules as CSS string', () => {
const cssRules = [ const cssRules = [
`.test-rule{color:red;}`, '.test-rule{color:red;}',
`.test-rule:hover{color:blue;}`, '.test-rule:hover{color:blue;}',
`@media (max-width: 992px){.test-rule{color:darkred;}}`, '@media (max-width: 992px){.test-rule{color:darkred;}}',
`@media (max-width: 992px){.test-rule:hover{color:darkblue;}}`, '@media (max-width: 992px){.test-rule:hover{color:darkblue;}}',
]; ];
const cssString = cssRules.join(''); const cssString = cssRules.join('');
obj.addCollection(cssString); obj.addCollection(cssString);

10
test/specs/css_composer/model/CssModels.js

@ -68,7 +68,7 @@ describe('CssRule', () => {
test('toCSS returns simple CSS', () => { test('toCSS returns simple CSS', () => {
obj.get('selectors').add({ name: 'test1' }); obj.get('selectors').add({ name: 'test1' });
obj.setStyle({ color: 'red' }); obj.setStyle({ color: 'red' });
expect(obj.toCSS()).toEqual(`.test1{color:red;}`); expect(obj.toCSS()).toEqual('.test1{color:red;}');
}); });
test('toCSS wraps correctly inside media rule', () => { test('toCSS wraps correctly inside media rule', () => {
@ -84,14 +84,14 @@ describe('CssRule', () => {
obj.set('atRuleType', 'supports'); obj.set('atRuleType', 'supports');
obj.get('selectors').add({ name: 'test1' }); obj.get('selectors').add({ name: 'test1' });
obj.setStyle({ 'font-family': 'Open Sans' }); obj.setStyle({ 'font-family': 'Open Sans' });
expect(obj.toCSS()).toEqual(`@supports{.test1{font-family:Open Sans;}}`); expect(obj.toCSS()).toEqual('@supports{.test1{font-family:Open Sans;}}');
}); });
test('toCSS with a generic single at-rule', () => { test('toCSS with a generic single at-rule', () => {
obj.set('atRuleType', 'font-face'); obj.set('atRuleType', 'font-face');
obj.set('singleAtRule', 1); obj.set('singleAtRule', 1);
obj.setStyle({ 'font-family': 'Sans' }); obj.setStyle({ 'font-family': 'Sans' });
expect(obj.toCSS()).toEqual(`@font-face{font-family:Sans;}`); expect(obj.toCSS()).toEqual('@font-face{font-family:Sans;}');
}); });
test('toCSS with a generic at-rule and condition', () => { test('toCSS with a generic at-rule and condition', () => {
@ -99,9 +99,7 @@ describe('CssRule', () => {
obj.set('mediaText', 'some-condition'); obj.set('mediaText', 'some-condition');
obj.get('selectors').add({ name: 'test1' }); obj.get('selectors').add({ name: 'test1' });
obj.setStyle({ 'font-family': 'Open Sans' }); obj.setStyle({ 'font-family': 'Open Sans' });
expect(obj.toCSS()).toEqual( expect(obj.toCSS()).toEqual('@font-face some-condition{.test1{font-family:Open Sans;}}');
`@font-face some-condition{.test1{font-family:Open Sans;}}`
);
}); });
}); });

4
test/specs/dom_components/index.js

@ -193,7 +193,7 @@ describe('DOM Components', () => {
}, },
}); });
expect(obj.getTypes().length).toBe(initialTypes); expect(obj.getTypes().length).toBe(initialTypes);
obj.addComponent(`<img src="##"/>`); obj.addComponent('<img src="##"/>');
const comp = obj.getComponents().at(0); const comp = obj.getComponents().at(0);
expect(comp.get('type')).toBe(id); expect(comp.get('type')).toBe(id);
expect(comp.get('testProp')).toBe(testProp); expect(comp.get('testProp')).toBe(testProp);
@ -212,7 +212,7 @@ describe('DOM Components', () => {
}, },
}, },
}); });
obj.addComponent(`<img src="##"/>`); obj.addComponent('<img src="##"/>');
expect(obj.getTypes()[0].id).toEqual(id); expect(obj.getTypes()[0].id).toEqual(id);
const comp = obj.getComponents().at(0); const comp = obj.getComponents().at(0);
// I'm not specifying the isComponent // I'm not specifying the isComponent

8
test/specs/dom_components/model/Component.js

@ -149,7 +149,7 @@ describe('Component', () => {
obj.set({ obj.set({
bool: true, bool: true,
boolf: false, boolf: false,
string: `st'ri"ng`, string: 'st\'ri"ng',
array: [1, 'string', true], array: [1, 'string', true],
object: { a: 1, b: 'string', c: true }, object: { a: 1, b: 'string', c: true },
null: null, null: null,
@ -158,12 +158,12 @@ describe('Component', () => {
zero: 0, zero: 0,
_private: 'value', _private: 'value',
}); });
let resStr = `st'ri&quot;ng`; let resStr = "st'ri&quot;ng";
let resArr = '[1,&quot;string&quot;,true]'; let resArr = '[1,&quot;string&quot;,true]';
let resObj = '{&quot;a&quot;:1,&quot;b&quot;:&quot;string&quot;,&quot;c&quot;:true}'; let resObj = '{&quot;a&quot;:1,&quot;b&quot;:&quot;string&quot;,&quot;c&quot;:true}';
let res = `<div data-gjs-bool data-gjs-string="${resStr}" data-gjs-array="${resArr}" data-gjs-object="${resObj}" data-gjs-empty="" data-gjs-zero="0"></div>`; let res = `<div data-gjs-bool data-gjs-string="${resStr}" data-gjs-array="${resArr}" data-gjs-object="${resObj}" data-gjs-empty="" data-gjs-zero="0"></div>`;
expect(obj.toHTML({ withProps: true })).toEqual(res); expect(obj.toHTML({ withProps: true })).toEqual(res);
resStr = `st&apos;ri"ng`; resStr = 'st&apos;ri"ng';
resArr = '[1,"string",true]'; resArr = '[1,"string",true]';
resObj = '{"a":1,"b":"string","c":true}'; resObj = '{"a":1,"b":"string","c":true}';
res = `<div data-gjs-bool data-gjs-string='${resStr}' data-gjs-array='${resArr}' data-gjs-object='${resObj}' data-gjs-empty="" data-gjs-zero="0"></div>`; res = `<div data-gjs-bool data-gjs-string='${resStr}' data-gjs-array='${resArr}' data-gjs-object='${resObj}' data-gjs-empty="" data-gjs-zero="0"></div>`;
@ -516,7 +516,7 @@ describe('Text Node Component', () => {
test('Component toHTML with attributes', () => { test('Component toHTML with attributes', () => {
obj = new ComponentTextNode({ obj = new ComponentTextNode({
attributes: { 'data-test': 'value' }, attributes: { 'data-test': 'value' },
content: `test content &<>"'`, content: 'test content &<>"\'',
}); });
expect(obj.toHTML()).toEqual('test content &amp;&lt;&gt;&quot;&#039;'); expect(obj.toHTML()).toEqual('test content &amp;&lt;&gt;&quot;&#039;');
}); });

25
test/specs/dom_components/model/ComponentTypes.js

@ -14,10 +14,7 @@ describe('Component Types', () => {
beforeAll(() => { beforeAll(() => {
editor = new Editor({ allowScripts: 1 }); editor = new Editor({ allowScripts: 1 });
editor editor.getModel().get('PageManager').onLoad();
.getModel()
.get('PageManager')
.onLoad();
wrapper = editor.getWrapper(); wrapper = editor.getWrapper();
}); });
@ -55,7 +52,7 @@ describe('Component Types', () => {
test('<tr> is correctly recognized', () => { test('<tr> is correctly recognized', () => {
expectedType('<table><tbody><tr> </tr></tbody></table>', 'row', { expectedType('<table><tbody><tr> </tr></tbody></table>', 'row', {
getType: 1 getType: 1,
}); });
}); });
@ -65,11 +62,11 @@ describe('Component Types', () => {
test('<td> & <th> are correctly recognized', () => { test('<td> & <th> are correctly recognized', () => {
expectedType('<table><tbody><tr><td></td></tr></tbody></table>', 'cell', { expectedType('<table><tbody><tr><td></td></tr></tbody></table>', 'cell', {
getType: 1 getType: 1,
}); });
expectedType('<table><tbody><tr><th></th></tr></tbody></table>', 'cell', { expectedType('<table><tbody><tr><th></th></tr></tbody></table>', 'cell', {
total: 2, total: 2,
getType: 1 getType: 1,
}); });
}); });
@ -79,15 +76,12 @@ describe('Component Types', () => {
test('<script> is correctly recognized', () => { test('<script> is correctly recognized', () => {
// const scr = 'console.log("Inline script");'; // issues with jsdom parser // const scr = 'console.log("Inline script");'; // issues with jsdom parser
const scr = ``; const scr = '';
expectedType(`<script attr-test="value">${scr}</script>`, 'script'); expectedType(`<script attr-test="value">${scr}</script>`, 'script');
}); });
test('<iframe> is correctly recognized', () => { test('<iframe> is correctly recognized', () => {
expectedType( expectedType('<iframe frameborder="0" src="/somewhere" attr-test="value"></iframe>', 'iframe');
`<iframe frameborder="0" src="/somewhere" attr-test="value"></iframe>`,
'iframe'
);
}); });
test('<svg> is correctly recognized', () => { test('<svg> is correctly recognized', () => {
@ -96,11 +90,6 @@ describe('Component Types', () => {
`)[0]; `)[0];
expect(wrapper.components().length).toBe(1); expect(wrapper.components().length).toBe(1);
expect(cmp.is('svg')).toBe(true); expect(cmp.is('svg')).toBe(true);
expect( expect(cmp.components().at(0).is('svg-in')).toBe(true);
cmp
.components()
.at(0)
.is('svg-in')
).toBe(true);
}); });
}); });

97
test/specs/dom_components/model/Symbols.js

@ -1,9 +1,5 @@
import Editor from 'editor'; import Editor from 'editor';
import { import { keySymbol, keySymbols, keySymbolOvrd } from 'dom_components/model/Component';
keySymbol,
keySymbols,
keySymbolOvrd
} from 'dom_components/model/Component';
describe('Symbols', () => { describe('Symbols', () => {
let editor; let editor;
@ -20,7 +16,7 @@ describe('Symbols', () => {
}; };
const simpleCompDef = { const simpleCompDef = {
type: 'text', type: 'text',
components: [{ type: 'textnode', content: 'Component' }] components: [{ type: 'textnode', content: 'Component' }],
}; };
const simpleComp = '<div data-a="b">Component</div>'; const simpleComp = '<div data-a="b">Component</div>';
const simpleComp2 = '<div data-b="c">Component 3</div>'; const simpleComp2 = '<div data-b="c">Component 3</div>';
@ -36,7 +32,7 @@ describe('Symbols', () => {
attributes: (m, attr) => { attributes: (m, attr) => {
delete attr.id; delete attr.id;
return attr; return attr;
} },
}); });
const getUm = cmp => cmp.em.get('UndoManager'); const getUm = cmp => cmp.em.get('UndoManager');
const getInnerComp = (cmp, i = 0) => cmp.components().at(i); const getInnerComp = (cmp, i = 0) => cmp.components().at(i);
@ -55,10 +51,7 @@ describe('Symbols', () => {
beforeAll(() => { beforeAll(() => {
editor = new Editor({ symbols: 1 }); editor = new Editor({ symbols: 1 });
editor editor.getModel().get('PageManager').onLoad();
.getModel()
.get('PageManager')
.onLoad();
wrapper = editor.getWrapper(); wrapper = editor.getWrapper();
}); });
@ -148,12 +141,12 @@ describe('Symbols', () => {
const defComp = { const defComp = {
...simpleCompDef, ...simpleCompDef,
[keySymbol]: idSymb, [keySymbol]: idSymb,
attributes: { id: idComp } attributes: { id: idComp },
}; };
const defSymb = { const defSymb = {
...simpleCompDef, ...simpleCompDef,
[keySymbols]: [idComp], [keySymbols]: [idComp],
attributes: { id: idSymb } attributes: { id: idSymb },
}; };
const [comp, symbol] = wrapper.append([defComp, defSymb]); const [comp, symbol] = wrapper.append([defComp, defSymb]);
expect(comp.__getSymbol()).toBe(symbol); expect(comp.__getSymbol()).toBe(symbol);
@ -193,14 +186,7 @@ describe('Symbols', () => {
const addedSymb = added.__getSymbol(); const addedSymb = added.__getSymbol();
const symbAdded = symbol.components().at(0); const symbAdded = symbol.components().at(0);
expect(addedSymb).toBe(symbAdded); expect(addedSymb).toBe(symbAdded);
allInst.forEach(cmp => allInst.forEach(cmp => expect(cmp.components().at(0).__getSymbol()).toBe(symbAdded));
expect(
cmp
.components()
.at(0)
.__getSymbol()
).toBe(symbAdded)
);
// The new main Symbol should keep the track of all instances // The new main Symbol should keep the track of all instances
expect(symbAdded.__getSymbols().length).toBe(allInst.length); expect(symbAdded.__getSymbols().length).toBe(allInst.length);
}); });
@ -247,9 +233,7 @@ describe('Symbols', () => {
test('Adding a new component to a symbol, it will be propogated to all instances', () => { test('Adding a new component to a symbol, it will be propogated to all instances', () => {
const added = symbol.append(simpleComp, { at: 0 })[0]; const added = symbol.append(simpleComp, { at: 0 })[0];
all.forEach(cmp => all.forEach(cmp => expect(cmp.components().length).toBe(compInitChild + 1));
expect(cmp.components().length).toBe(compInitChild + 1)
);
// Check symbol references // Check symbol references
expect(added.__getSymbols().length).toBe(allInst.length); expect(added.__getSymbols().length).toBe(allInst.length);
allInst.forEach(cmp => expect(getFirstInnSymbol(cmp)).toBe(added)); allInst.forEach(cmp => expect(getFirstInnSymbol(cmp)).toBe(added));
@ -257,9 +241,7 @@ describe('Symbols', () => {
test('Adding a new component to an instance of the symbol, it will be propogated to all symbols', () => { test('Adding a new component to an instance of the symbol, it will be propogated to all symbols', () => {
const added = comp.append(simpleComp, { at: 0 })[0]; const added = comp.append(simpleComp, { at: 0 })[0];
all.forEach(cmp => all.forEach(cmp => expect(cmp.components().length).toBe(compInitChild + 1));
expect(cmp.components().length).toBe(compInitChild + 1)
);
// Check symbol references // Check symbol references
const addSymb = added.__getSymbol(); const addSymb = added.__getSymbol();
expect(symbol.components().at(0)).toBe(addSymb); expect(symbol.components().at(0)).toBe(addSymb);
@ -274,9 +256,7 @@ describe('Symbols', () => {
um.redo(); um.redo();
um.undo(); um.undo();
um.redo(); // check multiple undo/redo um.redo(); // check multiple undo/redo
all.forEach(cmp => all.forEach(cmp => expect(cmp.components().length).toBe(compInitChild + 1));
expect(cmp.components().length).toBe(compInitChild + 1)
);
// Check symbol references // Check symbol references
const addSymbs = added.__getSymbol().__getSymbols(); const addSymbs = added.__getSymbol().__getSymbols();
expect(addSymbs.length).toBe(allInst.length); expect(addSymbs.length).toBe(allInst.length);
@ -395,22 +375,14 @@ describe('Symbols', () => {
expect(symbol.__getSymbToUp({ changed: 'anything' }).length).toBe(0); expect(symbol.__getSymbToUp({ changed: 'anything' }).length).toBe(0);
// With override as an array with props, changed option will count // With override as an array with props, changed option will count
symbol.set(keySymbolOvrd, ['components']); symbol.set(keySymbolOvrd, ['components']);
expect(symbol.__getSymbToUp({ changed: 'anything' }).length).toBe( expect(symbol.__getSymbToUp({ changed: 'anything' }).length).toBe(allInst.length);
allInst.length
);
symbol.set(keySymbolOvrd, ['components']); symbol.set(keySymbolOvrd, ['components']);
expect(symbol.__getSymbToUp({ changed: 'components' }).length).toBe(0); expect(symbol.__getSymbToUp({ changed: 'components' }).length).toBe(0);
expect( expect(symbol.__getSymbToUp({ changed: 'components:reset' }).length).toBe(0);
symbol.__getSymbToUp({ changed: 'components:reset' }).length
).toBe(0);
// Support also overrides with type of actions // Support also overrides with type of actions
symbol.set(keySymbolOvrd, ['components:change']); // specific change symbol.set(keySymbolOvrd, ['components:change']); // specific change
expect(symbol.__getSymbToUp({ changed: 'components' }).length).toBe( expect(symbol.__getSymbToUp({ changed: 'components' }).length).toBe(allInst.length);
allInst.length expect(symbol.__getSymbToUp({ changed: 'components:change' }).length).toBe(0);
);
expect(
symbol.__getSymbToUp({ changed: 'components:change' }).length
).toBe(0);
}); });
test('Symbol is not propagating props data if override is set', () => { test('Symbol is not propagating props data if override is set', () => {
@ -470,42 +442,26 @@ describe('Symbols', () => {
// The symbol has changed, but istances should remain the same // The symbol has changed, but istances should remain the same
expect(symbol.components().length).toBe(1); expect(symbol.components().length).toBe(1);
allInst.forEach(cmp => expect(toHTML(cmp)).toBe(toHTML(comp))); allInst.forEach(cmp => expect(toHTML(cmp)).toBe(toHTML(comp)));
allInst.forEach(cmp => allInst.forEach(cmp => expect(cmp.components().length).toBe(innCompsLen));
expect(cmp.components().length).toBe(innCompsLen)
);
// Check for add action // Check for add action
symbol.append('<div>B</div><div>C</div>'); symbol.append('<div>B</div><div>C</div>');
expect(symbol.components().length).toBe(3); expect(symbol.components().length).toBe(3);
allInst.forEach(cmp => allInst.forEach(cmp => expect(cmp.components().length).toBe(innCompsLen));
expect(cmp.components().length).toBe(innCompsLen)
);
}); });
test('Symbol is not removing components data if override is set', () => { test('Symbol is not removing components data if override is set', () => {
symbol.set(keySymbolOvrd, ['components']); symbol.set(keySymbolOvrd, ['components']);
const innCompsLen = symbol.components().length; const innCompsLen = symbol.components().length;
symbol symbol.components().at(0).remove();
.components()
.at(0)
.remove();
expect(symbol.components().length).toBe(innCompsLen - 1); expect(symbol.components().length).toBe(innCompsLen - 1);
allInst.forEach(cmp => allInst.forEach(cmp => expect(cmp.components().length).toBe(innCompsLen));
expect(cmp.components().length).toBe(innCompsLen)
);
}); });
test('Symbol is not propagating remove on instances with ovverride', () => { test('Symbol is not propagating remove on instances with ovverride', () => {
comp.set(keySymbolOvrd, ['components']); comp.set(keySymbolOvrd, ['components']);
const innCompsLen = symbol.components().length; const innCompsLen = symbol.components().length;
symbol symbol.components().at(0).remove();
.components() all.forEach(cmp => expect(cmp.components().length).toBe(cmp === comp ? innCompsLen : innCompsLen - 1));
.at(0)
.remove();
all.forEach(cmp =>
expect(cmp.components().length).toBe(
cmp === comp ? innCompsLen : innCompsLen - 1
)
);
}); });
test('On symbol components update, those having override are ignored', () => { test('On symbol components update, those having override are ignored', () => {
@ -530,10 +486,7 @@ describe('Symbols', () => {
all.forEach(cmp => expect(cmp.components().length).toBe(2)); all.forEach(cmp => expect(cmp.components().length).toBe(2));
// Check remove action // Check remove action
symbol symbol.components().at(0).remove();
.components()
.at(0)
.remove();
all.forEach(cmp => { all.forEach(cmp => {
expect(cmp.components().length).toBe(cmp === comp ? 2 : 1); expect(cmp.components().length).toBe(cmp === comp ? 2 : 1);
}); });
@ -579,9 +532,7 @@ describe('Symbols', () => {
const secInstans = secSymbol.__getSymbols(); const secInstans = secSymbol.__getSymbols();
expect(secInstans.length).toBe(all.length); expect(secInstans.length).toBe(all.length);
// All instances still refer to the second symbol // All instances still refer to the second symbol
secInstans.forEach(secInst => secInstans.forEach(secInst => expect(secInst.__getSymbol()).toBe(secSymbol));
expect(secInst.__getSymbol()).toBe(secSymbol)
);
}); });
test('Adding the instance, of the second symbol, inside one of the first instances, propagates correctly to all first symbols', () => { test('Adding the instance, of the second symbol, inside one of the first instances, propagates correctly to all first symbols', () => {
@ -594,9 +545,7 @@ describe('Symbols', () => {
const secInstans = secSymbol.__getSymbols(); const secInstans = secSymbol.__getSymbols();
expect(secInstans.length).toBe(all.length); expect(secInstans.length).toBe(all.length);
// All instances still refer to the second symbol // All instances still refer to the second symbol
secInstans.forEach(secInst => secInstans.forEach(secInst => expect(secInst.__getSymbol()).toBe(secSymbol));
expect(secInst.__getSymbol()).toBe(secSymbol)
);
}); });
test('Adding the instance, of the second symbol, inside one of the first instances, and then removing it, will not affect second instances outside', () => { test('Adding the instance, of the second symbol, inside one of the first instances, and then removing it, will not affect second instances outside', () => {

2
test/specs/editor/index.js

@ -77,7 +77,7 @@ describe('Editor', () => {
const umStack = um.getStack(); const umStack = um.getStack();
const wrapper = editor.getWrapper(); const wrapper = editor.getWrapper();
expect(umStack.length).toBe(0); expect(umStack.length).toBe(0);
const comp = wrapper.append(`<div>Component 1</div>`)[0]; const comp = wrapper.append('<div>Component 1</div>')[0];
expect(umStack.length).toBe(1); expect(umStack.length).toBe(1);
wrapper.empty(); wrapper.empty();
expect(umStack.length).toBe(2); expect(umStack.length).toBe(2);

6
test/specs/grapesjs/index.js

@ -93,15 +93,15 @@ describe('GrapesJS', () => {
const body = editor.Canvas.getBody(); const body = editor.Canvas.getBody();
expect(body.outerHTML).toContain(config.baseCss); expect(body.outerHTML).toContain(config.baseCss);
expect(body.outerHTML.replace(/\s+/g, ` `)).not.toContain(`body { margin: 0;`); expect(body.outerHTML.replace(/\s+/g, ' ')).not.toContain('body { margin: 0;');
}); });
test('Editor canvas baseCSS defaults to sensible values if not defined', () => { test('Editor canvas baseCSS defaults to sensible values if not defined', () => {
config.components = htmlString; config.components = htmlString;
config.protectedCss = ''; config.protectedCss = '';
obj.init(config); obj.init(config);
expect(window.frames[0].document.documentElement.outerHTML.replace(/\s+/g, ` `)).toContain( expect(window.frames[0].document.documentElement.outerHTML.replace(/\s+/g, ' ')).toContain(
`body { background-color: #fff` 'body { background-color: #fff'
); );
}); });

8
test/specs/navigator/view/ItemView.js

@ -10,7 +10,7 @@ describe('ItemView', () => {
fakeModel = { fakeModel = {
get: jest.fn(), get: jest.fn(),
set: jest.fn(), set: jest.fn(),
getStyle: jest.fn(() => fakeModelStyle) getStyle: jest.fn(() => fakeModelStyle),
}; };
itemView = new ItemView({ itemView = new ItemView({
@ -18,9 +18,9 @@ describe('ItemView', () => {
config: { config: {
...config, ...config,
em: { em: {
get: jest.fn(() => ({ stylePrefix: '' })) get: jest.fn(() => ({ stylePrefix: '' })),
} },
} },
}); });
}); });

41
test/specs/pages/index.js

@ -43,19 +43,13 @@ describe('Pages', () => {
}); });
test('The default frame has the wrapper component', () => { test('The default frame has the wrapper component', () => {
const frame = pm const frame = pm.getMain().getFrames().at(0);
.getMain()
.getFrames()
.at(0);
const frameCmp = frame.getComponent(); const frameCmp = frame.getComponent();
expect(frameCmp.is('wrapper')).toBe(true); expect(frameCmp.is('wrapper')).toBe(true);
}); });
test('The default wrapper has no content', () => { test('The default wrapper has no content', () => {
const frame = pm const frame = pm.getMain().getFrames().at(0);
.getMain()
.getFrames()
.at(0);
const frameCmp = frame.getComponent(); const frameCmp = frame.getComponent();
expect(frameCmp.components().length).toBe(0); expect(frameCmp.components().length).toBe(0);
expect(frame.getStyles().length).toBe(0); expect(frame.getStyles().length).toBe(0);
@ -80,9 +74,9 @@ describe('Pages', () => {
attributes: { attributes: {
id, id,
class: id, class: id,
customattr: id customattr: id,
}, },
components: `Component ${id}` components: `Component ${id}`,
}); });
beforeAll(() => { beforeAll(() => {
idPage1 = 'page-1'; idPage1 = 'page-1';
@ -94,31 +88,31 @@ describe('Pages', () => {
{ {
id: idPage1, id: idPage1,
component: [comp1], component: [comp1],
styles: `#${idComp1} { color: red }` styles: `#${idComp1} { color: red }`,
}, },
{ {
id: 'page-2', id: 'page-2',
frames: [ frames: [
{ {
component: [comp2], component: [comp2],
styles: `#${idComp2} { color: blue }` styles: `#${idComp2} { color: blue }`,
} },
] ],
}, },
{ {
id: 'page-3', id: 'page-3',
frames: [ frames: [
{ {
component: '<div id="comp3">Component 3</div>', component: '<div id="comp3">Component 3</div>',
styles: `#comp3 { color: green }` styles: '#comp3 { color: green }',
} },
] ],
} },
]; ];
editor = new Editor({ editor = new Editor({
pageManager: { pageManager: {
pages: initPages pages: initPages,
} },
}); });
em = editor.getModel(); em = editor.getModel();
domc = em.get('DomComponents'); domc = em.get('DomComponents');
@ -142,12 +136,7 @@ describe('Pages', () => {
// All pages should have an ID // All pages should have an ID
expect(page.get('id')).toBeTruthy(); expect(page.get('id')).toBeTruthy();
// The main component is always a wrapper // The main component is always a wrapper
expect( expect(page.getMainFrame().getComponent().is('wrapper')).toBe(true);
page
.getMainFrame()
.getComponent()
.is('wrapper')
).toBe(true);
}); });
// Components container should contain the same amount of wrappers as pages // Components container should contain the same amount of wrappers as pages
const wrappers = Object.keys(allbyId) const wrappers = Object.keys(allbyId)

153
test/specs/parser/model/ParserCss.js

@ -10,8 +10,8 @@ describe('ParserCss', () => {
config = { config = {
em: { em: {
getCustomParserCss: () => customParser, getCustomParserCss: () => customParser,
trigger: () => {} trigger: () => {},
} },
}; };
obj = new ParserCss(config); obj = new ParserCss(config);
}); });
@ -50,8 +50,8 @@ describe('ParserCss', () => {
selectors: ['test1'], selectors: ['test1'],
style: { style: {
color: 'red', color: 'red',
width: '50px' width: '50px',
} },
}; };
expect(obj.parse(str)).toEqual([result]); expect(obj.parse(str)).toEqual([result]);
}); });
@ -60,7 +60,7 @@ describe('ParserCss', () => {
var str = ' .test1.test2 {color:red; test: value}'; var str = ' .test1.test2 {color:red; test: value}';
var result = { var result = {
selectors: ['test1', 'test2'], selectors: ['test1', 'test2'],
style: { color: 'red', test: 'value' } style: { color: 'red', test: 'value' },
}; };
expect(obj.parse(str)).toEqual([result]); expect(obj.parse(str)).toEqual([result]);
}); });
@ -70,36 +70,35 @@ describe('ParserCss', () => {
var result = [ var result = [
{ {
selectors: ['test1', 'test2'], selectors: ['test1', 'test2'],
style: { color: 'red' } style: { color: 'red' },
}, },
{ {
selectors: ['test3'], selectors: ['test3'],
style: { color: 'red' } style: { color: 'red' },
} },
]; ];
expect(obj.parse(str)).toEqual(result); expect(obj.parse(str)).toEqual(result);
}); });
test('Parse more rules', () => { test('Parse more rules', () => {
var str = var str = ' .test1.test2, .test3{ color:red } .test4, .test5.test6{ width:10px }';
' .test1.test2, .test3{ color:red } .test4, .test5.test6{ width:10px }';
var result = [ var result = [
{ {
selectors: ['test1', 'test2'], selectors: ['test1', 'test2'],
style: { color: 'red' } style: { color: 'red' },
}, },
{ {
selectors: ['test3'], selectors: ['test3'],
style: { color: 'red' } style: { color: 'red' },
}, },
{ {
selectors: ['test4'], selectors: ['test4'],
style: { width: '10px' } style: { width: '10px' },
}, },
{ {
selectors: ['test5', 'test6'], selectors: ['test5', 'test6'],
style: { width: '10px' } style: { width: '10px' },
} },
]; ];
expect(obj.parse(str)).toEqual(result); expect(obj.parse(str)).toEqual(result);
}); });
@ -109,7 +108,7 @@ describe('ParserCss', () => {
var result = { var result = {
selectors: ['test1', 'test2'], selectors: ['test1', 'test2'],
style: { color: 'red' }, style: { color: 'red' },
state: 'hover' state: 'hover',
}; };
expect(obj.parse(str)).toEqual([result]); expect(obj.parse(str)).toEqual([result]);
}); });
@ -119,7 +118,7 @@ describe('ParserCss', () => {
var result = { var result = {
selectors: ['test1', 'test2'], selectors: ['test1', 'test2'],
style: { color: 'red' }, style: { color: 'red' },
state: ':after' state: ':after',
}; };
expect(obj.parse(str)).toEqual([result]); expect(obj.parse(str)).toEqual([result]);
}); });
@ -129,21 +128,20 @@ describe('ParserCss', () => {
var result = { var result = {
selectors: ['test1', 'test2'], selectors: ['test1', 'test2'],
style: { color: 'red' }, style: { color: 'red' },
state: 'nth-of-type(2n)' state: 'nth-of-type(2n)',
}; };
expect(obj.parse(str)).toEqual([result]); expect(obj.parse(str)).toEqual([result]);
}); });
// Phantom don't find 'node.conditionText' so will skip it // Phantom don't find 'node.conditionText' so will skip it
test('Parse rule inside media query', () => { test('Parse rule inside media query', () => {
var str = var str = '@media only screen and (max-width: 992px){ .test1.test2:hover{ color:red }}';
'@media only screen and (max-width: 992px){ .test1.test2:hover{ color:red }}';
var result = { var result = {
atRuleType: 'media', atRuleType: 'media',
selectors: ['test1', 'test2'], selectors: ['test1', 'test2'],
style: { color: 'red' }, style: { color: 'red' },
state: 'hover', state: 'hover',
mediaText: 'only screen and (max-width: 992px)' mediaText: 'only screen and (max-width: 992px)',
}; };
expect(obj.parse(str)).toEqual([result]); expect(obj.parse(str)).toEqual([result]);
}); });
@ -156,7 +154,7 @@ describe('ParserCss', () => {
selectors: ['test1', 'test2'], selectors: ['test1', 'test2'],
style: { color: 'red' }, style: { color: 'red' },
state: 'hover', state: 'hover',
mediaText: '(max-width: 992px)' mediaText: '(max-width: 992px)',
}; };
expect(obj.parse(str)).toEqual([result]); expect(obj.parse(str)).toEqual([result]);
}); });
@ -169,21 +167,21 @@ describe('ParserCss', () => {
{ {
selectors: ['test1'], selectors: ['test1'],
style: { color: 'white' }, style: { color: 'white' },
state: 'hover' state: 'hover',
}, },
{ {
selectors: ['test1', 'test2'], selectors: ['test1', 'test2'],
style: { color: 'red' }, style: { color: 'red' },
state: 'hover', state: 'hover',
atRuleType: 'media', atRuleType: 'media',
mediaText: '(max-width: 992px)' mediaText: '(max-width: 992px)',
}, },
{ {
selectors: ['test2'], selectors: ['test2'],
style: { color: 'blue' }, style: { color: 'blue' },
atRuleType: 'media', atRuleType: 'media',
mediaText: '(max-width: 992px)' mediaText: '(max-width: 992px)',
} },
]; ];
expect(obj.parse(str)).toEqual(result); expect(obj.parse(str)).toEqual(result);
}); });
@ -193,38 +191,36 @@ describe('ParserCss', () => {
var result = { var result = {
selectors: [], selectors: [],
selectorsAdd: '.class1 .class2, div > .class3', selectorsAdd: '.class1 .class2, div > .class3',
style: { color: 'red' } style: { color: 'red' },
}; };
expect(obj.parse(str)).toEqual([result]); expect(obj.parse(str)).toEqual([result]);
}); });
test('Parse rule with mixed selectors', () => { test('Parse rule with mixed selectors', () => {
var str = var str = ' .class1 .class2, .class3, div > .class4, .class5.class6 { color:red }';
' .class1 .class2, .class3, div > .class4, .class5.class6 { color:red }';
var result = [ var result = [
{ {
selectors: ['class3'], selectors: ['class3'],
style: { color: 'red' } style: { color: 'red' },
}, },
{ {
selectors: ['class5', 'class6'], selectors: ['class5', 'class6'],
selectorsAdd: '.class1 .class2, div > .class4', selectorsAdd: '.class1 .class2, div > .class4',
style: { color: 'red' } style: { color: 'red' },
} },
]; ];
expect(obj.parse(str)).toEqual(result); expect(obj.parse(str)).toEqual(result);
}); });
test('Parse rule with important styles', () => { test('Parse rule with important styles', () => {
var str = var str = ' .test1 {color:red !important; width: 100px; height: 10px !important}';
' .test1 {color:red !important; width: 100px; height: 10px !important}';
var result = { var result = {
selectors: ['test1'], selectors: ['test1'],
style: { style: {
color: 'red !important', color: 'red !important',
height: '10px !important', height: '10px !important',
width: '100px' width: '100px',
} },
}; };
expect(obj.parse(str)).toEqual([result]); expect(obj.parse(str)).toEqual([result]);
}); });
@ -239,8 +235,8 @@ describe('ParserCss', () => {
selectorsAdd: ':root', selectorsAdd: ':root',
style: { style: {
'--some-color': 'red', '--some-color': 'red',
'--some-width': '55px' '--some-width': '55px',
} },
}; };
expect(obj.parse(str)).toEqual([result]); expect(obj.parse(str)).toEqual([result]);
}); });
@ -256,14 +252,14 @@ describe('ParserCss', () => {
selectors: [], selectors: [],
atRuleType: 'keyframes', atRuleType: 'keyframes',
selectorsAdd: 'from', selectorsAdd: 'from',
style: { opacity: '0' } style: { opacity: '0' },
}, },
{ {
selectors: [], selectors: [],
atRuleType: 'keyframes', atRuleType: 'keyframes',
selectorsAdd: 'to', selectorsAdd: 'to',
style: { opacity: '1' } style: { opacity: '1' },
} },
]; ];
expect(obj.parse(str)).toEqual(result); expect(obj.parse(str)).toEqual(result);
}); });
@ -277,7 +273,7 @@ describe('ParserCss', () => {
selectorsAdd: '', selectorsAdd: '',
atRuleType: 'font-face', atRuleType: 'font-face',
singleAtRule: 1, singleAtRule: 1,
style: { 'font-family': '"Open Sans"' } style: { 'font-family': '"Open Sans"' },
}; };
expect(obj.parse(str)).toEqual([result]); expect(obj.parse(str)).toEqual([result]);
}); });
@ -297,49 +293,48 @@ describe('ParserCss', () => {
selectorsAdd: '', selectorsAdd: '',
style: { 'font-family': '"Open Sans"' }, style: { 'font-family': '"Open Sans"' },
singleAtRule: 1, singleAtRule: 1,
atRuleType: 'font-face' atRuleType: 'font-face',
}, },
{ {
selectors: [], selectors: [],
selectorsAdd: '', selectorsAdd: '',
style: { style: {
'font-family': "'Glyphicons Halflings'", 'font-family': "'Glyphicons Halflings'",
src: src: 'url(https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/fonts/glyphicons-halflings-regular.eot)',
'url(https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/fonts/glyphicons-halflings-regular.eot)'
}, },
singleAtRule: 1, singleAtRule: 1,
atRuleType: 'font-face' atRuleType: 'font-face',
} },
]; ];
const parsed = obj.parse(str); const parsed = obj.parse(str);
expect(parsed).toEqual(result); expect(parsed).toEqual(result);
}); });
test('Parse ID rule', () => { test('Parse ID rule', () => {
var str = `#test { color: red }`; var str = '#test { color: red }';
var result = { var result = {
selectors: ['#test'], selectors: ['#test'],
style: { color: 'red' } style: { color: 'red' },
}; };
expect(obj.parse(str)).toEqual([result]); expect(obj.parse(str)).toEqual([result]);
}); });
test('Parse ID rule with state', () => { test('Parse ID rule with state', () => {
var str = `#test:hover { color: red }`; var str = '#test:hover { color: red }';
var result = { var result = {
selectors: ['#test'], selectors: ['#test'],
state: 'hover', state: 'hover',
style: { color: 'red' } style: { color: 'red' },
}; };
expect(obj.parse(str)).toEqual([result]); expect(obj.parse(str)).toEqual([result]);
}); });
test('Avoid composed selectors with ID', () => { test('Avoid composed selectors with ID', () => {
var str = `#test.class, #test.class:hover, .class { color: red }`; var str = '#test.class, #test.class:hover, .class { color: red }';
var result = { var result = {
selectors: ['class'], selectors: ['class'],
selectorsAdd: '#test.class, #test.class:hover', selectorsAdd: '#test.class, #test.class:hover',
style: { color: 'red' } style: { color: 'red' },
}; };
expect(obj.parse(str)).toEqual([result]); expect(obj.parse(str)).toEqual([result]);
}); });
@ -348,10 +343,10 @@ describe('ParserCss', () => {
var str = '.test1 { color:red }'; var str = '.test1 { color:red }';
var result = { var result = {
selectors: ['test1'], selectors: ['test1'],
style: { color: 'blue' } style: { color: 'blue' },
}; };
obj = new ParserCss({ obj = new ParserCss({
parserCss: () => [result] parserCss: () => [result],
}); });
expect(obj.parse(str)).toEqual([result]); expect(obj.parse(str)).toEqual([result]);
}); });
@ -372,22 +367,21 @@ describe('ParserCss', () => {
test('Check node with font-face rule', () => { test('Check node with font-face rule', () => {
const style = { const style = {
'font-family': '"Glyphicons Halflings"', 'font-family': '"Glyphicons Halflings"',
src: src: 'url("https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/fonts/glyphicons-halflings-regular.eot")',
'url("https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/fonts/glyphicons-halflings-regular.eot")'
}; };
expect( expect(
obj.checkNode({ obj.checkNode({
atRule: 'font-face', atRule: 'font-face',
selectors: '', selectors: '',
style: style style: style,
}) })
).toEqual([ ).toEqual([
{ {
style: style, style: style,
atRuleType: 'font-face', atRuleType: 'font-face',
singleAtRule: 1, singleAtRule: 1,
selectors: [] selectors: [],
} },
]); ]);
}); });
@ -398,7 +392,7 @@ describe('ParserCss', () => {
atRule: 'keyframes', atRule: 'keyframes',
params: 'name', params: 'name',
selectors: 'from', selectors: 'from',
style: style style: style,
}) })
).toEqual([ ).toEqual([
{ {
@ -406,8 +400,8 @@ describe('ParserCss', () => {
atRuleType: 'keyframes', atRuleType: 'keyframes',
selectorsAdd: 'from', selectorsAdd: 'from',
style: style, style: style,
mediaText: 'name' mediaText: 'name',
} },
]); ]);
}); });
@ -418,7 +412,7 @@ describe('ParserCss', () => {
atRule: 'media', atRule: 'media',
params: 'screen and (min-width: 480px)', params: 'screen and (min-width: 480px)',
selectors: '.class-test.class2:hover, div > span ', selectors: '.class-test.class2:hover, div > span ',
style style,
}) })
).toEqual([ ).toEqual([
{ {
@ -427,8 +421,8 @@ describe('ParserCss', () => {
selectorsAdd: 'div > span', selectorsAdd: 'div > span',
style: style, style: style,
state: 'hover', state: 'hover',
mediaText: 'screen and (min-width: 480px)' mediaText: 'screen and (min-width: 480px)',
} },
]); ]);
}); });
@ -437,58 +431,57 @@ describe('ParserCss', () => {
expect( expect(
obj.checkNode({ obj.checkNode({
selectors: '#main:hover', selectors: '#main:hover',
style style,
}) })
).toEqual([ ).toEqual([
{ {
selectors: ['#main'], selectors: ['#main'],
state: 'hover', state: 'hover',
style: style style: style,
} },
]); ]);
}); });
test('Check node with multiple class selectors', () => { test('Check node with multiple class selectors', () => {
const style = { const style = {
border: '1px solid black !important', border: '1px solid black !important',
'background-repeat': 'repeat-y, no-repeat' 'background-repeat': 'repeat-y, no-repeat',
}; };
expect( expect(
obj.checkNode({ obj.checkNode({
selectors: selectors: '.class1, .class1.class2:hover, div > .test:hover, span.test2',
'.class1, .class1.class2:hover, div > .test:hover, span.test2', style,
style
}) })
).toEqual([ ).toEqual([
{ {
selectors: ['class1'], selectors: ['class1'],
style: style style: style,
}, },
{ {
selectors: ['class1', 'class2'], selectors: ['class1', 'class2'],
state: 'hover', state: 'hover',
selectorsAdd: 'div > .test:hover, span.test2', selectorsAdd: 'div > .test:hover, span.test2',
style: style style: style,
} },
]); ]);
}); });
test('Check node with a rule containing CSS variables', () => { test('Check node with a rule containing CSS variables', () => {
const style = { const style = {
'--some-color': 'red', '--some-color': 'red',
'--some-width': '55px' '--some-width': '55px',
}; };
expect( expect(
obj.checkNode({ obj.checkNode({
selectors: ':root', selectors: ':root',
style style,
}) })
).toEqual([ ).toEqual([
{ {
selectors: [], selectors: [],
selectorsAdd: ':root', selectorsAdd: ':root',
style: style style: style,
} },
]); ]);
}); });
}); });

4
test/specs/parser/model/ParserHtml.js

@ -492,7 +492,7 @@ describe('ParserHtml', () => {
}); });
test('Parse attributes with object inside', () => { test('Parse attributes with object inside', () => {
var str = `<div data-gjs-test='{ "prop1": "value1", "prop2": 10, "prop3": true}'>test2 </div>`; var str = '<div data-gjs-test=\'{ "prop1": "value1", "prop2": 10, "prop3": true}\'>test2 </div>';
var result = [ var result = [
{ {
tagName: 'div', tagName: 'div',
@ -510,7 +510,7 @@ describe('ParserHtml', () => {
}); });
test('Parse attributes with arrays inside', () => { test('Parse attributes with arrays inside', () => {
var str = `<div data-gjs-test='["value1", "value2"]'>test2 </div>`; var str = '<div data-gjs-test=\'["value1", "value2"]\'>test2 </div>';
var result = [ var result = [
{ {
tagName: 'div', tagName: 'div',

27
test/specs/selector_manager/view/ClassTagsView.js

@ -39,13 +39,13 @@ describe('ClassTagsView', () => {
view = new ClassTagsView({ view = new ClassTagsView({
config: { em }, config: { em },
collection: coll, collection: coll,
module: em.get('SelectorManager') module: em.get('SelectorManager'),
}); });
testContext.targetStub = { testContext.targetStub = {
add(v) { add(v) {
return { name: v }; return { name: v };
} },
}; };
compTest = new Component(); compTest = new Component();
@ -94,22 +94,22 @@ describe('ClassTagsView', () => {
expect(testContext.input.val()).toBeFalsy(); expect(testContext.input.val()).toBeFalsy();
}); });
test.skip('Check keyup of ESC on input', function() { test.skip('Check keyup of ESC on input', function () {
this.btnAdd.click(); this.btnAdd.click();
sinon.stub(view, 'addNewTag'); sinon.stub(view, 'addNewTag');
this.input.trigger({ this.input.trigger({
type: 'keyup', type: 'keyup',
keyCode: 13 keyCode: 13,
}); });
expect(view.addNewTag.calledOnce).toEqual(true); expect(view.addNewTag.calledOnce).toEqual(true);
}); });
test.skip('Check keyup on ENTER on input', function() { test.skip('Check keyup on ENTER on input', function () {
this.btnAdd.click(); this.btnAdd.click();
sinon.stub(view, 'endNewTag'); sinon.stub(view, 'endNewTag');
this.input.trigger({ this.input.trigger({
type: 'keyup', type: 'keyup',
keyCode: 27 keyCode: 27,
}); });
expect(view.endNewTag.calledOnce).toEqual(true); expect(view.endNewTag.calledOnce).toEqual(true);
}); });
@ -147,13 +147,7 @@ describe('ClassTagsView', () => {
test('New tag correctly added', () => { test('New tag correctly added', () => {
coll.add({ label: 'test' }); coll.add({ label: 'test' });
expect( expect(testContext.$tags.children().first().find('[data-tag-name]').text()).toEqual('test');
testContext.$tags
.children()
.first()
.find('[data-tag-name]')
.text()
).toEqual('test');
}); });
test('States are hidden in case no tags', () => { test('States are hidden in case no tags', () => {
@ -189,12 +183,9 @@ describe('ClassTagsView', () => {
}); });
test('Output correctly state options', done => { test('Output correctly state options', done => {
target target.get('SelectorManager').setStates([{ name: 'testName', label: 'testLabel' }]);
.get('SelectorManager')
.setStates([{ name: 'testName', label: 'testLabel' }]);
setTimeout(() => { setTimeout(() => {
const res = const res = '<option value="">- State -</option><option value="testName">testLabel</option>';
'<option value="">- State -</option><option value="testName">testLabel</option>';
expect(view.getStates()[0].innerHTML).toEqual(res); expect(view.getStates()[0].innerHTML).toEqual(res);
done(); done();
}); });

12
test/specs/style_manager/index.js

@ -130,7 +130,7 @@ describe('StyleManager', () => {
}); });
test('Single class, multiple devices', done => { test('Single class, multiple devices', done => {
const cmp = domc.addComponent(`<div class="cls"></div>`); const cmp = domc.addComponent('<div class="cls"></div>');
const [rule1, rule2] = cssc.addRules(` const [rule1, rule2] = cssc.addRules(`
.cls { color: red; } .cls { color: red; }
@media (max-width: 992px) { @media (max-width: 992px) {
@ -148,7 +148,7 @@ describe('StyleManager', () => {
test('With ID, multiple devices', () => { test('With ID, multiple devices', () => {
sm.setComponentFirst(true); sm.setComponentFirst(true);
const cmp = domc.addComponent(`<div class="cls" id="id-test"></div>`); const cmp = domc.addComponent('<div class="cls" id="id-test"></div>');
const [rule1, rule2] = cssc.addRules(` const [rule1, rule2] = cssc.addRules(`
#id-test { color: red; } #id-test { color: red; }
@media (max-width: 992px) { @media (max-width: 992px) {
@ -163,7 +163,7 @@ describe('StyleManager', () => {
}); });
test('With ID + class, class first', () => { test('With ID + class, class first', () => {
const cmp = domc.addComponent(`<div class="cls" id="id-test"></div>`); const cmp = domc.addComponent('<div class="cls" id="id-test"></div>');
const [rule1, rule2] = cssc.addRules(` const [rule1, rule2] = cssc.addRules(`
.cls { color: red; } .cls { color: red; }
#id-test { color: blue; } #id-test { color: blue; }
@ -176,7 +176,7 @@ describe('StyleManager', () => {
test('With ID + class, component first', () => { test('With ID + class, component first', () => {
sm.setComponentFirst(true); sm.setComponentFirst(true);
const cmp = domc.addComponent(`<div class="cls" id="id-test"></div>`); const cmp = domc.addComponent('<div class="cls" id="id-test"></div>');
const [rule1, rule2] = cssc.addRules(` const [rule1, rule2] = cssc.addRules(`
.cls { color: red; } .cls { color: red; }
#id-test { color: blue; } #id-test { color: blue; }
@ -189,7 +189,7 @@ describe('StyleManager', () => {
test('With ID + class, multiple devices', () => { test('With ID + class, multiple devices', () => {
sm.setComponentFirst(true); sm.setComponentFirst(true);
const cmp = domc.addComponent(`<div class="cls" id="id-test"></div>`); const cmp = domc.addComponent('<div class="cls" id="id-test"></div>');
const [rule1, rule2] = cssc.addRules(` const [rule1, rule2] = cssc.addRules(`
.cls { color: red; } .cls { color: red; }
@media (max-width: 992px) { @media (max-width: 992px) {
@ -204,7 +204,7 @@ describe('StyleManager', () => {
}); });
test('Mixed classes', () => { test('Mixed classes', () => {
const cmp = domc.addComponent(`<div class="cls1 cls2"></div>`); const cmp = domc.addComponent('<div class="cls1 cls2"></div>');
const [rule1, rule2] = cssc.addRules(` const [rule1, rule2] = cssc.addRules(`
.cls1 { color: red; } .cls1 { color: red; }
.cls1.cls2 { color: blue; } .cls1.cls2 { color: blue; }

6
test/specs/style_manager/model/Properties.js

@ -24,7 +24,7 @@ describe('StyleManager properties logic', () => {
sm = em.get('SelectorManager'); sm = em.get('SelectorManager');
obj = em.get('StyleManager'); obj = em.get('StyleManager');
em.get('PageManager').onLoad(); em.get('PageManager').onLoad();
cmp = domc.addComponent(`<div class="cls"></div>`); cmp = domc.addComponent('<div class="cls"></div>');
}); });
afterEach(() => { afterEach(() => {
@ -46,7 +46,7 @@ describe('StyleManager properties logic', () => {
let compTypePropInn; let compTypePropInn;
beforeEach(() => { beforeEach(() => {
rule1 = cssc.addRules(`.cls { color: red; }`)[0]; rule1 = cssc.addRules('.cls { color: red; }')[0];
obj.addSector(sectorTest, { obj.addSector(sectorTest, {
properties: [ properties: [
{ {
@ -708,7 +708,7 @@ describe('StyleManager properties logic', () => {
); );
expect(rule1.getStyle()).toEqual({ expect(rule1.getStyle()).toEqual({
__p: false, __p: false,
[propTest]: `valueA-new valueB-new valueC-new, valueA-1 valueB-1 valueC-1-ext, valueA-2 valueB-2 valueC-2-ext`, [propTest]: 'valueA-new valueB-new valueC-new, valueA-1 valueB-1 valueC-1-ext, valueA-2 valueB-2 valueC-2-ext',
}); });
}); });

2
webpack.config.js

@ -47,4 +47,4 @@ export default ({ config }) => ({
new webpack.DefinePlugin({ __GJS_VERSION__: `'${pkg.version}'` }), new webpack.DefinePlugin({ __GJS_VERSION__: `'${pkg.version}'` }),
...config.plugins, ...config.plugins,
] ]
}); });

Loading…
Cancel
Save