Browse Source

Convert Canvas to ts

pull/4302/head
Alex 4 years ago
parent
commit
f993a8a4ba
  1. 62
      src/canvas/model/Canvas.js
  2. 72
      src/canvas/model/Canvas.ts
  3. 390
      src/editor/model/Editor.ts

62
src/canvas/model/Canvas.js

@ -1,62 +0,0 @@
import { Model } from '../../common';
import { evPageSelect } from '../../pages';
import Frames from './Frames';
export default class Canvas extends Model {
defaults() {
return {
frame: '',
frames: '',
rulers: false,
zoom: 100,
x: 0,
y: 0,
// Scripts to apply on all frames
scripts: [],
// Styles to apply on all frames
styles: [],
};
}
initialize(props, config = {}) {
const { em } = config;
this.config = config;
this.em = em;
this.set('frames', new Frames());
this.listenTo(this, 'change:zoom', this.onZoomChange);
this.listenTo(em, 'change:device', this.updateDevice);
this.listenTo(em, evPageSelect, this._pageUpdated);
}
init() {
const { em } = this;
const mainPage = em.get('PageManager').getMain();
const frame = mainPage.getMainFrame();
this.set('frames', mainPage.getFrames());
this.updateDevice({ frame });
}
_pageUpdated(page, prev) {
const { em } = this;
em.setSelected();
em.get('readyCanvas') && em.stopDefault(); // We have to stop before changing current frames
prev && prev.getFrames().map(frame => frame.disable());
this.set('frames', page.getFrames());
}
updateDevice(opts = {}) {
const { em } = this;
const device = em.getDeviceModel();
const model = opts.frame || em.getCurrentFrameModel();
if (model && device) {
const { width, height } = device.attributes;
model.set({ width, height }, { noUndo: 1 });
}
}
onZoomChange() {
const zoom = this.get('zoom');
zoom < 1 && this.set('zoom', 1);
}
}

72
src/canvas/model/Canvas.ts

@ -0,0 +1,72 @@
import { Model } from "../../common";
import Backbone from "backbone";
import { evPageSelect } from "../../pages";
import Frames from "./Frames";
import EditorModel from "../../editor/model/Editor";
import Page from "../../pages/model/Page";
export default class Canvas extends Backbone.Model {
defaults() {
return {
frame: "",
frames: "",
rulers: false,
zoom: 100,
x: 0,
y: 0,
// Scripts to apply on all frames
scripts: [],
// Styles to apply on all frames
styles: [],
};
}
em: EditorModel;
config: any;
constructor(props: any, config: any = {}) {
super(props);
const { em } = config;
this.config = config;
this.em = em;
this.set("frames", new Frames());
this.listenTo(this, "change:zoom", this.onZoomChange);
this.listenTo(em, "change:device", this.updateDevice);
this.listenTo(em, evPageSelect, this._pageUpdated);
}
get frames(): Frames {
return this.get("frames");
}
init() {
const { em } = this;
const mainPage = em.get("PageManager").getMain();
const frame = mainPage.getMainFrame();
this.set("frames", mainPage.getFrames());
this.updateDevice({ frame });
}
_pageUpdated(page: Page, prev?: Page) {
const { em } = this;
em.setSelected();
em.get("readyCanvas") && em.stopDefault(); // We have to stop before changing current frames
//@ts-ignore
prev?.getFrames().map((frame) => frame.disable());
this.set("frames", page.getFrames());
}
updateDevice(opts: any = {}) {
const { em } = this;
const device = em.getDeviceModel();
const model = opts.frame || em.getCurrentFrameModel();
if (model && device) {
const { width, height } = device.attributes;
model.set({ width, height }, { noUndo: 1 });
}
}
onZoomChange() {
const zoom = this.get("zoom");
zoom < 1 && this.set("zoom", 1);
}
}

390
src/editor/model/Editor.ts

@ -1,45 +1,51 @@
import { isUndefined, isArray, contains, toArray, keys, bindAll } from 'underscore'; import {
import Backbone from 'backbone'; isUndefined,
import $ from '../../utils/cash-dom'; isArray,
import Extender from '../../utils/extender'; contains,
import { getModel, hasWin, isEmptyObj } from '../../utils/mixins'; toArray,
import { Model } from '../../common'; keys,
import Selected from './Selected'; bindAll,
import FrameView from '../../canvas/view/FrameView'; } from "underscore";
import EditorModule from '..'; import Backbone from "backbone";
import EditorView from '../view/EditorView'; import $ from "../../utils/cash-dom";
import { IModule } from '../../abstract/Module'; import Extender from "../../utils/extender";
import { getModel, hasWin, isEmptyObj } from "../../utils/mixins";
import { Model } from "../../common";
import Selected from "./Selected";
import FrameView from "../../canvas/view/FrameView";
import EditorModule from "..";
import EditorView from "../view/EditorView";
import { IModule } from "../../abstract/Module";
//@ts-ignore //@ts-ignore
Backbone.$ = $; Backbone.$ = $;
const deps = [ const deps = [
require('utils'), require("utils"),
require('i18n'), require("i18n"),
require('keymaps'), require("keymaps"),
require('undo_manager'), require("undo_manager"),
require('storage_manager'), require("storage_manager"),
require('device_manager'), require("device_manager"),
require('parser'), require("parser"),
require('style_manager'), require("style_manager"),
require('selector_manager'), require("selector_manager"),
require('modal_dialog'), require("modal_dialog"),
require('code_manager'), require("code_manager"),
require('panels'), require("panels"),
require('rich_text_editor'), require("rich_text_editor"),
require('asset_manager'), require("asset_manager"),
require('css_composer'), require("css_composer"),
require('pages'), require("pages"),
require('trait_manager'), require("trait_manager"),
require('dom_components'), require("dom_components"),
require('navigator'), require("navigator"),
require('canvas'), require("canvas"),
require('commands'), require("commands"),
require('block_manager'), require("block_manager"),
]; ];
const ts_deps: any[] = [ const ts_deps: any[] = [];
];
Extender({ Extender({
//@ts-ignore //@ts-ignore
@ -68,7 +74,7 @@ export default class EditorModel extends Model {
modules: [], modules: [],
toLoad: [], toLoad: [],
opened: {}, opened: {},
device: '', device: "",
}; };
} }
@ -77,36 +83,35 @@ export default class EditorModel extends Model {
destroyed = false; destroyed = false;
_config: any; _config: any;
attrsOrig: any; attrsOrig: any;
timedInterval?: number; timedInterval?: number;
updateItr?: number; updateItr?: number;
view?: EditorView view?: EditorView;
get storables(): any[]{ get storables(): any[] {
return this.get('storables') return this.get("storables");
} }
get modules(): IModule[]{ get modules(): IModule[] {
return this.get('modules') return this.get("modules");
} }
get toLoad(): any[]{ get toLoad(): any[] {
return this.get('toLoad') return this.get("toLoad");
} }
constructor(conf = {}) { constructor(conf = {}) {
super() super();
this._config = conf; this._config = conf;
const { config } = this; const { config } = this;
this.set('Config', conf); this.set("Config", conf);
this.set('modules', []); this.set("modules", []);
this.set('toLoad', []); this.set("toLoad", []);
this.set('storables', []); this.set("storables", []);
this.set('selected', new Selected()); this.set("selected", new Selected());
this.set('dmode', config.dragMode); this.set("dmode", config.dragMode);
const { el, log } = config; const { el, log } = config;
const toLog = log === true ? keys(logs) : isArray(log) ? log : []; const toLog = log === true ? keys(logs) : isArray(log) ? log : [];
bindAll(this, 'initBaseColorPicker'); bindAll(this, "initBaseColorPicker");
if (el && config.fromElement) { if (el && config.fromElement) {
config.components = el.innerHTML; config.components = el.innerHTML;
@ -117,7 +122,7 @@ timedInterval?: number;
res[next.nodeName] = next.nodeValue; res[next.nodeName] = next.nodeValue;
return res; return res;
}, {}) }, {})
: ''; : "";
// Move components to pages // Move components to pages
if (config.components && !config.pageManager) { if (config.components && !config.pageManager) {
@ -125,27 +130,35 @@ timedInterval?: number;
} }
// Load modules // Load modules
deps.forEach(name => this.loadModule(name)); deps.forEach((name) => this.loadModule(name));
ts_deps.forEach(name => this.tsLoadModule(name)); ts_deps.forEach((name) => this.tsLoadModule(name));
this.on('change:componentHovered', this.componentHovered, this); this.on("change:componentHovered", this.componentHovered, this);
this.on('change:changesCount', this.updateChanges, this); this.on("change:changesCount", this.updateChanges, this);
this.on('change:readyLoad change:readyCanvas', this._checkReady, this); this.on("change:readyLoad change:readyCanvas", this._checkReady, this);
toLog.forEach(e => this.listenLog(e)); toLog.forEach((e) => this.listenLog(e));
// Deprecations // Deprecations
[{ from: 'change:selectedComponent', to: 'component:toggled' }].forEach(event => { [{ from: "change:selectedComponent", to: "component:toggled" }].forEach(
const eventFrom = event.from; (event) => {
const eventTo = event.to; const eventFrom = event.from;
this.listenTo(this, eventFrom, (...args) => { const eventTo = event.to;
this.trigger(eventTo, ...args); this.listenTo(this, eventFrom, (...args) => {
this.logWarning(`The event '${eventFrom}' is deprecated, replace it with '${eventTo}'`); this.trigger(eventTo, ...args);
}); this.logWarning(
}); `The event '${eventFrom}' is deprecated, replace it with '${eventTo}'`
);
});
}
);
} }
_checkReady() { _checkReady() {
if (this.get('readyLoad') && this.get('readyCanvas') && !this.get('ready')) { if (
this.set('ready', true); this.get("readyLoad") &&
this.get("readyCanvas") &&
!this.get("ready")
) {
this.set("ready", true);
} }
} }
@ -179,15 +192,15 @@ timedInterval?: number;
*/ */
loadOnStart() { loadOnStart() {
const { projectData, headless } = this.config; const { projectData, headless } = this.config;
const sm = this.get('StorageManager'); const sm = this.get("StorageManager");
// In `onLoad`, the module will try to load the data from its configurations. // In `onLoad`, the module will try to load the data from its configurations.
this.toLoad.forEach(mdl => mdl.onLoad()); this.toLoad.forEach((mdl) => mdl.onLoad());
// Stuff to do post load // Stuff to do post load
const postLoad = () => { const postLoad = () => {
this.modules.forEach(mdl => mdl.postLoad && mdl.postLoad(this)); this.modules.forEach((mdl) => mdl.postLoad && mdl.postLoad(this));
this.set('readyLoad', 1); this.set("readyLoad", 1);
}; };
if (headless) { if (headless) {
@ -217,8 +230,8 @@ timedInterval?: number;
undoManager: false, undoManager: false,
}); });
// We only need to load a few modules // We only need to load a few modules
['PageManager', 'Canvas'].forEach(key => shallow.get(key).onLoad()); ["PageManager", "Canvas"].forEach((key) => shallow.get(key).onLoad());
this.set('shallow', shallow); this.set("shallow", shallow);
} }
/** /**
@ -227,18 +240,18 @@ timedInterval?: number;
* @private * @private
*/ */
updateChanges() { updateChanges() {
const stm = this.get('StorageManager'); const stm = this.get("StorageManager");
const changes = this.getDirtyCount(); const changes = this.getDirtyCount();
this.updateItr && clearTimeout(this.updateItr); this.updateItr && clearTimeout(this.updateItr);
//@ts-ignore //@ts-ignore
this.updateItr = setTimeout(() => this.trigger('update')); this.updateItr = setTimeout(() => this.trigger("update"));
if (this.config.noticeOnUnload) { if (this.config.noticeOnUnload) {
window.onbeforeunload = changes ? e => 1 : null; window.onbeforeunload = changes ? (e: any) => 1 : null;
} }
if (stm.isAutosave() && changes >= stm.getStepsBeforeSave()) { if (stm.isAutosave() && changes >= stm.getStepsBeforeSave()) {
this.store().catch(err => this.logError(err)); this.store().catch((err) => this.logError(err));
} }
} }
@ -253,9 +266,11 @@ timedInterval?: number;
const Module = moduleName.default || moduleName; const Module = moduleName.default || moduleName;
const Mod = new Module(); const Mod = new Module();
const name = Mod.name.charAt(0).toLowerCase() + Mod.name.slice(1); const name = Mod.name.charAt(0).toLowerCase() + Mod.name.slice(1);
const cfgParent = !isUndefined(config[name]) ? config[name] : config[Mod.name]; const cfgParent = !isUndefined(config[name])
? config[name]
: config[Mod.name];
const cfg = cfgParent === true ? {} : cfgParent || {}; const cfg = cfgParent === true ? {} : cfgParent || {};
cfg.pStylePrefix = config.pStylePrefix || ''; cfg.pStylePrefix = config.pStylePrefix || "";
if (!isUndefined(cfgParent) && !cfgParent) { if (!isUndefined(cfgParent) && !cfgParent) {
cfg._disable = 1; cfg._disable = 1;
@ -281,7 +296,7 @@ timedInterval?: number;
* @return {this} * @return {this}
* @private * @private
*/ */
tsLoadModule(moduleName: any) { tsLoadModule(moduleName: any) {
const Module = moduleName.default || moduleName; const Module = moduleName.default || moduleName;
const Mod = new Module(this); const Mod = new Module(this);
@ -306,11 +321,11 @@ timedInterval?: number;
this.initialize(opts); this.initialize(opts);
this.destroyed = false; this.destroyed = false;
} }
this.set('Editor', editor); this.set("Editor", editor);
} }
getEditor() { getEditor() {
return this.get('Editor'); return this.get("Editor");
} }
/** /**
@ -323,7 +338,13 @@ timedInterval?: number;
* */ * */
handleUpdates(model: any, val: any, opt: any = {}) { handleUpdates(model: any, val: any, opt: any = {}) {
// Component has been added temporarily - do not update storage or record changes // Component has been added temporarily - do not update storage or record changes
if (this.__skip || opt.temporary || opt.noCount || opt.avoidStore || !this.get('ready')) { if (
this.__skip ||
opt.temporary ||
opt.noCount ||
opt.avoidStore ||
!this.get("ready")
) {
return; return;
} }
@ -332,7 +353,7 @@ timedInterval?: number;
this.timedInterval = setTimeout(() => { this.timedInterval = setTimeout(() => {
const curr = this.getDirtyCount() || 0; const curr = this.getDirtyCount() || 0;
const { unset, ...opts } = opt; const { unset, ...opts } = opt;
this.set('changesCount', curr + 1, opts); this.set("changesCount", curr + 1, opts);
}, 0); }, 0);
} }
@ -348,9 +369,9 @@ timedInterval?: number;
* @private * @private
* */ * */
componentHovered(editor: any, component: any, options: any) { componentHovered(editor: any, component: any, options: any) {
const prev = this.previous('componentHovered'); const prev = this.previous("componentHovered");
prev && this.trigger('component:unhovered', prev, options); prev && this.trigger("component:unhovered", prev, options);
component && this.trigger('component:hovered', component, options); component && this.trigger("component:hovered", component, options);
} }
/** /**
@ -359,7 +380,7 @@ timedInterval?: number;
* @public * @public
*/ */
getSelected() { getSelected() {
return this.get('selected').lastComponent(); return this.get("selected").lastComponent();
} }
/** /**
@ -368,7 +389,7 @@ timedInterval?: number;
* @public * @public
*/ */
getSelectedAll(): any[] { getSelectedAll(): any[] {
return this.get('selected').allComponents(); return this.get("selected").allComponents();
} }
/** /**
@ -377,31 +398,32 @@ timedInterval?: number;
* @param {Object} [opts={}] Options, optional * @param {Object} [opts={}] Options, optional
* @public * @public
*/ */
setSelected(el: any, opts: any = {}) { setSelected(el?: any, opts: any = {}) {
const { event } = opts; const { event } = opts;
const ctrlKey = event && (event.ctrlKey || event.metaKey); const ctrlKey = event && (event.ctrlKey || event.metaKey);
const { shiftKey } = event || {}; const { shiftKey } = event || {};
const multiple = isArray(el); const multiple = isArray(el);
const els = (multiple ? el : [el]).map(el => getModel(el, $)); const els = (isArray(el) ? el : [el]).map((el) => getModel(el, $));
const selected = this.getSelectedAll(); const selected = this.getSelectedAll();
const mltSel = this.getConfig().multipleSelection; const mltSel = this.getConfig().multipleSelection;
let added; let added;
// If an array is passed remove all selected // If an array is passed remove all selected
// expect those yet to be selected // expect those yet to be selected
multiple && this.removeSelected(selected.filter(s => !contains(els, s))); multiple && this.removeSelected(selected.filter((s) => !contains(els, s)));
els.forEach(el => { els.forEach((el) => {
let model = getModel(el, undefined); let model = getModel(el, undefined);
if (model) { if (model) {
this.trigger('component:select:before', model, opts); this.trigger("component:select:before", model, opts);
// Check for valid selectable // Check for valid selectable
if (!model.get('selectable') || opts.abort) { if (!model.get("selectable") || opts.abort) {
if (opts.useValid) { if (opts.useValid) {
let parent = model.parent(); let parent = model.parent();
while (parent && !parent.get('selectable')) parent = parent.parent(); while (parent && !parent.get("selectable"))
parent = parent.parent();
model = parent; model = parent;
} else { } else {
return; return;
@ -413,13 +435,13 @@ timedInterval?: number;
if (ctrlKey && mltSel) { if (ctrlKey && mltSel) {
return this.toggleSelected(model); return this.toggleSelected(model);
} else if (shiftKey && mltSel) { } else if (shiftKey && mltSel) {
this.clearSelection(this.get('Canvas').getWindow()); this.clearSelection(this.get("Canvas").getWindow());
const coll = model.collection; const coll = model.collection;
const index = model.index(); const index = model.index();
let min: number|undefined, max: number|undefined; let min: number | undefined, max: number | undefined;
// Fin min and max siblings // Fin min and max siblings
this.getSelectedAll().forEach(sel => { this.getSelectedAll().forEach((sel) => {
const selColl = sel.collection; const selColl = sel.collection;
const selIndex = sel.index(); const selIndex = sel.index();
if (selColl === coll) { if (selColl === coll) {
@ -450,7 +472,7 @@ timedInterval?: number;
return this.addSelected(model); return this.addSelected(model);
} }
!multiple && this.removeSelected(selected.filter(s => s !== model)); !multiple && this.removeSelected(selected.filter((s) => s !== model));
this.addSelected(model, opts); this.addSelected(model, opts);
added = model; added = model;
}); });
@ -466,12 +488,12 @@ timedInterval?: number;
const model = getModel(el, $); const model = getModel(el, $);
const models = isArray(model) ? model : [model]; const models = isArray(model) ? model : [model];
models.forEach(model => { models.forEach((model) => {
if (model && !model.get('selectable')) return; if (model && !model.get("selectable")) return;
const selected = this.get('selected'); const selected = this.get("selected");
opts.forceChange && this.removeSelected(model, opts); opts.forceChange && this.removeSelected(model, opts);
selected.addComponent(model, opts); selected.addComponent(model, opts);
model && this.trigger('component:select', model, opts); model && this.trigger("component:select", model, opts);
}); });
} }
@ -482,7 +504,7 @@ timedInterval?: number;
* @public * @public
*/ */
removeSelected(el: any, opts = {}) { removeSelected(el: any, opts = {}) {
this.get('selected').removeComponent(getModel(el, $), opts); this.get("selected").removeComponent(getModel(el, $), opts);
} }
/** /**
@ -495,8 +517,8 @@ timedInterval?: number;
const model = getModel(el, $); const model = getModel(el, $);
const models = isArray(model) ? model : [model]; const models = isArray(model) ? model : [model];
models.forEach(model => { models.forEach((model) => {
if (this.get('selected').hasComponent(model)) { if (this.get("selected").hasComponent(model)) {
this.removeSelected(model, opts); this.removeSelected(model, opts);
} else { } else {
this.addSelected(model, opts); this.addSelected(model, opts);
@ -511,21 +533,21 @@ timedInterval?: number;
* @private * @private
*/ */
setHovered(el: any, opts: any = {}) { setHovered(el: any, opts: any = {}) {
if (!el) return this.set('componentHovered', ''); if (!el) return this.set("componentHovered", "");
const ev = 'component:hover'; const ev = "component:hover";
let model = getModel(el, undefined); let model = getModel(el, undefined);
if (!model) return; if (!model) return;
opts.forceChange && this.set('componentHovered', ''); opts.forceChange && this.set("componentHovered", "");
this.trigger(`${ev}:before`, model, opts); this.trigger(`${ev}:before`, model, opts);
// Check for valid hoverable // Check for valid hoverable
if (!model.get('hoverable')) { if (!model.get("hoverable")) {
if (opts.useValid && !opts.abort) { if (opts.useValid && !opts.abort) {
let parent = model && model.parent(); let parent = model && model.parent();
while (parent && !parent.get('hoverable')) parent = parent.parent(); while (parent && !parent.get("hoverable")) parent = parent.parent();
model = parent; model = parent;
} else { } else {
return; return;
@ -533,13 +555,13 @@ timedInterval?: number;
} }
if (!opts.abort) { if (!opts.abort) {
this.set('componentHovered', model, opts); this.set("componentHovered", model, opts);
this.trigger(ev, model, opts); this.trigger(ev, model, opts);
} }
} }
getHovered() { getHovered() {
return this.get('componentHovered'); return this.get("componentHovered");
} }
/** /**
@ -550,7 +572,7 @@ timedInterval?: number;
* @public * @public
*/ */
setComponents(components: any, opt = {}) { setComponents(components: any, opt = {}) {
return this.get('DomComponents').setComponents(components, opt); return this.get("DomComponents").setComponents(components, opt);
} }
/** /**
@ -559,13 +581,13 @@ timedInterval?: number;
* @private * @private
*/ */
getComponents() { getComponents() {
var cmp = this.get('DomComponents'); var cmp = this.get("DomComponents");
var cm = this.get('CodeManager'); var cm = this.get("CodeManager");
if (!cmp || !cm) return; if (!cmp || !cm) return;
var wrp = cmp.getComponents(); var wrp = cmp.getComponents();
return cm.getCode(wrp, 'json'); return cm.getCode(wrp, "json");
} }
/** /**
@ -576,7 +598,7 @@ timedInterval?: number;
* @public * @public
*/ */
setStyle(style: any, opt = {}) { setStyle(style: any, opt = {}) {
const cssc = this.get('CssComposer'); const cssc = this.get("CssComposer");
cssc.clear(opt); cssc.clear(opt);
cssc.getAll().add(style, opt); cssc.getAll().add(style, opt);
return this; return this;
@ -599,7 +621,7 @@ timedInterval?: number;
* @private * @private
*/ */
getStyle() { getStyle() {
return this.get('CssComposer').getAll(); return this.get("CssComposer").getAll();
} }
/** /**
@ -608,7 +630,7 @@ timedInterval?: number;
* @returns {this} * @returns {this}
*/ */
setState(value: string) { setState(value: string) {
this.set('state', value); this.set("state", value);
return this; return this;
} }
@ -617,7 +639,7 @@ timedInterval?: number;
* @returns {String} * @returns {String}
*/ */
getState() { getState() {
return this.get('state') || ''; return this.get("state") || "";
} }
/** /**
@ -629,15 +651,15 @@ timedInterval?: number;
getHtml(opts: any = {}) { getHtml(opts: any = {}) {
const { config } = this; const { config } = this;
const { optsHtml } = config; const { optsHtml } = config;
const js = config.jsInHtml ? this.getJs(opts) : ''; const js = config.jsInHtml ? this.getJs(opts) : "";
const cmp = opts.component || this.get('DomComponents').getComponent(); const cmp = opts.component || this.get("DomComponents").getComponent();
let html = cmp let html = cmp
? this.get('CodeManager').getCode(cmp, 'html', { ? this.get("CodeManager").getCode(cmp, "html", {
...optsHtml, ...optsHtml,
...opts, ...opts,
}) })
: ''; : "";
html += js ? `<script>${js}</script>` : ''; html += js ? `<script>${js}</script>` : "";
return html; return html;
} }
@ -651,19 +673,21 @@ timedInterval?: number;
const config = this.config; const config = this.config;
const { optsCss } = config; const { optsCss } = config;
const avoidProt = opts.avoidProtected; const avoidProt = opts.avoidProtected;
const keepUnusedStyles = !isUndefined(opts.keepUnusedStyles) ? opts.keepUnusedStyles : config.keepUnusedStyles; const keepUnusedStyles = !isUndefined(opts.keepUnusedStyles)
const cssc = this.get('CssComposer'); ? opts.keepUnusedStyles
const wrp = opts.component || this.get('DomComponents').getComponent(); : config.keepUnusedStyles;
const protCss = !avoidProt ? config.protectedCss : ''; const cssc = this.get("CssComposer");
const wrp = opts.component || this.get("DomComponents").getComponent();
const protCss = !avoidProt ? config.protectedCss : "";
const css = const css =
wrp && wrp &&
this.get('CodeManager').getCode(wrp, 'css', { this.get("CodeManager").getCode(wrp, "css", {
cssc, cssc,
keepUnusedStyles, keepUnusedStyles,
...optsCss, ...optsCss,
...opts, ...opts,
}); });
return wrp ? (opts.json ? css : protCss + css) : ''; return wrp ? (opts.json ? css : protCss + css) : "";
} }
/** /**
@ -672,8 +696,8 @@ timedInterval?: number;
* @public * @public
*/ */
getJs(opts: any = {}) { getJs(opts: any = {}) {
var wrp = opts.component || this.get('DomComponents').getWrapper(); var wrp = opts.component || this.get("DomComponents").getWrapper();
return wrp ? this.get('CodeManager').getCode(wrp, 'js').trim() : ''; return wrp ? this.get("CodeManager").getCode(wrp, "js").trim() : "";
} }
/** /**
@ -682,7 +706,7 @@ timedInterval?: number;
*/ */
async store(options?: any) { async store(options?: any) {
const data = this.storeData(); const data = this.storeData();
await this.get('StorageManager').store(data, options); await this.get("StorageManager").store(data, options);
this.clearDirtyCount(); this.clearDirtyCount();
return data; return data;
} }
@ -692,7 +716,7 @@ timedInterval?: number;
* @public * @public
*/ */
async load(options?: any) { async load(options?: any) {
const result = await this.get('StorageManager').load(options); const result = await this.get("StorageManager").load(options);
this.loadData(result); this.loadData(result);
return result; return result;
} }
@ -701,9 +725,9 @@ timedInterval?: number;
let result = {}; let result = {};
// Sync content if there is an active RTE // Sync content if there is an active RTE
const editingCmp = this.getEditing(); const editingCmp = this.getEditing();
editingCmp && editingCmp.trigger('sync:content', { noCount: true }); editingCmp && editingCmp.trigger("sync:content", { noCount: true });
this.storables.forEach(m => { this.storables.forEach((m) => {
result = { ...result, ...m.store(1) }; result = { ...result, ...m.store(1) };
}); });
return JSON.parse(JSON.stringify(result)); return JSON.parse(JSON.stringify(result));
@ -711,8 +735,8 @@ timedInterval?: number;
loadData(data = {}) { loadData(data = {}) {
if (!isEmptyObj(data)) { if (!isEmptyObj(data)) {
this.storables.forEach(module => module.clear()); this.storables.forEach((module) => module.clear());
this.storables.forEach(module => module.load(data)); this.storables.forEach((module) => module.load(data));
} }
return data; return data;
} }
@ -723,8 +747,8 @@ timedInterval?: number;
* @private * @private
*/ */
getDeviceModel() { getDeviceModel() {
var name = this.get('device'); var name = this.get("device");
return this.get('DeviceManager').get(name); return this.get("DeviceManager").get(name);
} }
/** /**
@ -733,7 +757,7 @@ timedInterval?: number;
* @private * @private
*/ */
runDefault(opts = {}) { runDefault(opts = {}) {
var command = this.get('Commands').get(this.config.defaultCommand); var command = this.get("Commands").get(this.config.defaultCommand);
if (!command || this.defaultRunning) return; if (!command || this.defaultRunning) return;
command.stop(this, this, opts); command.stop(this, this, opts);
command.run(this, this, opts); command.run(this, this, opts);
@ -746,7 +770,7 @@ timedInterval?: number;
* @private * @private
*/ */
stopDefault(opts = {}) { stopDefault(opts = {}) {
const commands = this.get('Commands'); const commands = this.get("Commands");
const command = commands.get(this.config.defaultCommand); const command = commands.get(this.config.defaultCommand);
if (!command || !this.defaultRunning) return; if (!command || !this.defaultRunning) return;
command.stop(this, this, opts); command.stop(this, this, opts);
@ -758,9 +782,9 @@ timedInterval?: number;
* @public * @public
*/ */
refreshCanvas(opts: any = {}) { refreshCanvas(opts: any = {}) {
this.set('canvasOffset', null); this.set("canvasOffset", null);
this.set('canvasOffset', this.get('Canvas').getOffset()); this.set("canvasOffset", this.get("Canvas").getOffset());
opts.tools && this.trigger('canvas:updateTools'); opts.tools && this.trigger("canvas:updateTools");
} }
/** /**
@ -783,8 +807,8 @@ timedInterval?: number;
const device = this.getDeviceModel(); const device = this.getDeviceModel();
const condition = config.mediaCondition; const condition = config.mediaCondition;
const preview = config.devicePreviewMode; const preview = config.devicePreviewMode;
const width = device && device.get('widthMedia'); const width = device && device.get("widthMedia");
return device && width && !preview ? `(${condition}: ${width})` : ''; return device && width && !preview ? `(${condition}: ${width})` : "";
} }
/** /**
@ -792,15 +816,15 @@ timedInterval?: number;
* @return {Component} * @return {Component}
*/ */
getWrapper() { getWrapper() {
return this.get('DomComponents').getWrapper(); return this.get("DomComponents").getWrapper();
} }
setCurrentFrame(frameView: FrameView) { setCurrentFrame(frameView: FrameView) {
return this.set('currentFrame', frameView); return this.set("currentFrame", frameView);
} }
getCurrentFrame(): FrameView { getCurrentFrame(): FrameView {
return this.get('currentFrame'); return this.get("currentFrame");
} }
getCurrentFrameModel() { getCurrentFrameModel() {
@ -809,7 +833,7 @@ timedInterval?: number;
getIcon(icon: string) { getIcon(icon: string) {
const icons = this.config.icons || {}; const icons = this.config.icons || {};
return icons[icon] || ''; return icons[icon] || "";
} }
/** /**
@ -818,27 +842,27 @@ timedInterval?: number;
* @return {number} * @return {number}
*/ */
getDirtyCount() { getDirtyCount() {
return this.get('changesCount'); return this.get("changesCount");
} }
clearDirtyCount() { clearDirtyCount() {
return this.set('changesCount', 0); return this.set("changesCount", 0);
} }
getZoomDecimal() { getZoomDecimal() {
return this.get('Canvas').getZoomDecimal(); return this.get("Canvas").getZoomDecimal();
} }
getZoomMultiplier() { getZoomMultiplier() {
return this.get('Canvas').getZoomMultiplier(); return this.get("Canvas").getZoomMultiplier();
} }
setDragMode(value: string) { setDragMode(value: string) {
return this.set('dmode', value); return this.set("dmode", value);
} }
t(...args: any[]) { t(...args: any[]) {
const i18n = this.get('I18n'); const i18n = this.get("I18n");
return i18n?.t(...args); return i18n?.t(...args);
} }
@ -847,7 +871,7 @@ timedInterval?: number;
* @returns {Boolean} * @returns {Boolean}
*/ */
inAbsoluteMode() { inAbsoluteMode() {
return this.get('dmode') === 'absolute'; return this.get("dmode") === "absolute";
} }
/** /**
@ -857,41 +881,43 @@ timedInterval?: number;
const { config, view } = this; const { config, view } = this;
const editor = this.getEditor(); const editor = this.getEditor();
const { editors = [] } = config.grapesjs || {}; const { editors = [] } = config.grapesjs || {};
const shallow = this.get('shallow'); const shallow = this.get("shallow");
shallow?.destroyAll(); shallow?.destroyAll();
this.stopListening(); this.stopListening();
this.stopDefault(); this.stopDefault();
this.modules this.modules
.slice() .slice()
.reverse() .reverse()
.forEach(mod => mod.destroy()); .forEach((mod) => mod.destroy());
view && view.remove(); view && view.remove();
this.clear({ silent: true }); this.clear({ silent: true });
this.destroyed = true; this.destroyed = true;
//@ts-ignore ["_config", "view", "_previousAttributes", "_events", "_listeners"].forEach(
['_config', 'view', '_previousAttributes', '_events', '_listeners'].forEach(i => (this[i] = {})); //@ts-ignore
(i) => (this[i] = {})
);
editors.splice(editors.indexOf(editor), 1); editors.splice(editors.indexOf(editor), 1);
//@ts-ignore //@ts-ignore
hasWin() && $(config.el).empty().attr(this.attrsOrig); hasWin() && $(config.el).empty().attr(this.attrsOrig);
} }
getEditing() { getEditing() {
const res = this.get('editing'); const res = this.get("editing");
return (res && res.model) || null; return (res && res.model) || null;
} }
setEditing(value: boolean) { setEditing(value: boolean) {
this.set('editing', value); this.set("editing", value);
return this; return this;
} }
isEditing() { isEditing() {
return !!this.get('editing'); return !!this.get("editing");
} }
log(msg: string, opts: any = {}) { log(msg: string, opts: any = {}) {
const { ns, level = 'debug' } = opts; const { ns, level = "debug" } = opts;
this.trigger('log', msg, opts); this.trigger("log", msg, opts);
level && this.trigger(`log:${level}`, msg, opts); level && this.trigger(`log:${level}`, msg, opts);
if (ns) { if (ns) {
@ -902,15 +928,15 @@ timedInterval?: number;
} }
logInfo(msg: string, opts?: any) { logInfo(msg: string, opts?: any) {
this.log(msg, { ...opts, level: 'info' }); this.log(msg, { ...opts, level: "info" });
} }
logWarning(msg:string, opts?: any) { logWarning(msg: string, opts?: any) {
this.log(msg, { ...opts, level: 'warning' }); this.log(msg, { ...opts, level: "warning" });
} }
logError(msg: string, opts?: any) { logError(msg: string, opts?: any) {
this.log(msg, { ...opts, level: 'error' }); this.log(msg, { ...opts, level: "error" });
} }
initBaseColorPicker(el: any, opts = {}) { initBaseColorPicker(el: any, opts = {}) {
@ -922,13 +948,13 @@ timedInterval?: number;
//@ts-ignore //@ts-ignore
return $(el).spectrum({ return $(el).spectrum({
containerClassName: `${ppfx}one-bg ${ppfx}two-color`, containerClassName: `${ppfx}one-bg ${ppfx}two-color`,
appendTo: elToAppend || 'body', appendTo: elToAppend || "body",
maxSelectionSize: 8, maxSelectionSize: 8,
showPalette: true, showPalette: true,
palette: [], palette: [],
showAlpha: true, showAlpha: true,
chooseText: 'Ok', chooseText: "Ok",
cancelText: '⨯', cancelText: "⨯",
...opts, ...opts,
...colorPicker, ...colorPicker,
}); });
@ -941,7 +967,7 @@ timedInterval?: number;
*/ */
skip(clb: Function) { skip(clb: Function) {
this.__skip = true; this.__skip = true;
const um = this.get('UndoManager'); const um = this.get("UndoManager");
um ? um.skip(clb) : clb(); um ? um.skip(clb) : clb();
this.__skip = false; this.__skip = false;
} }
@ -955,7 +981,7 @@ timedInterval?: number;
* @private * @private
*/ */
data(el: any, name: string, value: any) { data(el: any, name: string, value: any) {
const varName = '_gjs-data'; const varName = "_gjs-data";
if (!el[varName]) { if (!el[varName]) {
el[varName] = {}; el[varName] = {};

Loading…
Cancel
Save