Skip to content

Commit

Permalink
Cleanup Component models
Browse files Browse the repository at this point in the history
  • Loading branch information
xQwexx committed Apr 25, 2024
1 parent 717e429 commit 4c61b0f
Show file tree
Hide file tree
Showing 16 changed files with 76 additions and 85 deletions.
15 changes: 7 additions & 8 deletions src/dom_components/model/Component.ts
Original file line number Diff line number Diff line change
Expand Up @@ -226,7 +226,8 @@ export default class Component extends StyleableModel<ComponentProperties> {
* @ts-ignore */
collection!: Components;

initialize(props = {}, opt: ComponentOptions = {}) {
constructor(props: ComponentProperties = {}, opt: ComponentOptions) {
super(props, opt);
bindAll(this, '__upSymbProps', '__upSymbCls', '__upSymbComps');
const em = opt.em;

Expand Down Expand Up @@ -519,12 +520,12 @@ export default class Component extends StyleableModel<ComponentProperties> {
* const result = component.replaceWith('<div>Some new content</div>');
* // result -> [Component]
*/
replaceWith<C extends Component = Component>(el: ComponentAdd, opts: AddOptions = {}): C[] {
replaceWith<C extends Component = Component>(el: ComponentAdd, opts: AddOptions = {}): C {
const coll = this.collection;
const at = coll.indexOf(this);
coll.remove(this);
const result = coll.add(el, { ...opts, at });
return isArray(result) ? result : [result];
return result as C;
}

/**
Expand Down Expand Up @@ -2105,11 +2106,9 @@ export default class Component extends StyleableModel<ComponentProperties> {
}

static getList(model: Component) {
const { opt = {} } = model;
// @ts-ignore
const { domc, em } = opt;
const dm = domc || em?.Components;
return dm ? dm.componentsById : {};
const { em } = model;
const dm = em?.Components;
return dm?.componentsById ?? {};
}

static checkId(
Expand Down
5 changes: 3 additions & 2 deletions src/dom_components/model/ComponentImage.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import { result } from 'underscore';
import Component from './Component';
import { toLowerCase, buildBase64UrlFromSvg, hasWin } from '../../utils/mixins';
import { ObjectStrings } from '../../common';
import { ComponentOptions, ComponentProperties } from './types';

const svgAttrs =
'xmlns="http://www.w3.org/2000/svg" width="100" viewBox="0 0 24 24" style="fill: rgba(0,0,0,0.15); transform: scale(0.75)"';
Expand Down Expand Up @@ -35,8 +36,8 @@ export default class ComponentImage extends Component {
};
}

initialize(props: any, opts: any) {
super.initialize(props, opts);
constructor(props: ComponentProperties = {}, opt: ComponentOptions) {
super(props, opt);
const { src } = this.get('attributes')!;
if (src && buildBase64UrlFromSvg(result(this, 'defaults').src) !== src) {
this.set('src', src, { silent: true });
Expand Down
6 changes: 4 additions & 2 deletions src/dom_components/model/ComponentMap.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import ComponentImage from './ComponentImage';
import { toLowerCase } from '../../utils/mixins';
import { ComponentOptions, ComponentProperties } from './types';

export default class ComponentMap extends ComponentImage {
/** @ts-ignore */
Expand Down Expand Up @@ -49,10 +50,11 @@ export default class ComponentMap extends ComponentImage {
};
}

initialize(props: any, opts: any) {
constructor(props: ComponentProperties = {}, opt: ComponentOptions) {
super(props, opt);
if (this.get('src')) this.parseFromSrc();
else this.updateSrc();
super.initialize(props, opts);

this.listenTo(this, 'change:address change:zoom change:mapType', this.updateSrc);
}

Expand Down
5 changes: 3 additions & 2 deletions src/dom_components/model/ComponentTable.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import Component from './Component';
import { toLowerCase } from '../../utils/mixins';
import { ComponentOptions, ComponentProperties } from './types';

const type = 'table';

Expand All @@ -14,8 +15,8 @@ export default class ComponentTable extends Component {
};
}

initialize(props: any, opts: any) {
super.initialize(props, opts);
constructor(props: ComponentProperties = {}, opt: ComponentOptions) {
super(props, opt);
const components = this.get('components')!;
!components.length && components.add({ type: 'tbody' });
}
Expand Down
5 changes: 3 additions & 2 deletions src/dom_components/model/ComponentTableBody.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import Component from './Component';
import { toLowerCase } from '../../utils/mixins';
import { ComponentOptions, ComponentProperties } from './types';

const type = 'tbody';

Expand All @@ -17,8 +18,8 @@ export default class ComponentTableBody extends Component {
};
}

initialize(props: any, opts: any) {
super.initialize(props, opts);
constructor(props: ComponentProperties = {}, opt: ComponentOptions) {
super(props, opt);
const components = this.get('components')!;
let columns = this.get('columns');
let rows = this.get('rows');
Expand Down
5 changes: 3 additions & 2 deletions src/dom_components/model/ComponentText.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { isFunction } from 'underscore';
import Component from './Component';
import { ComponentOptions, ComponentProperties } from './types';

export default class ComponentText extends Component {
get defaults() {
Expand All @@ -12,8 +13,8 @@ export default class ComponentText extends Component {
};
}

initialize(props: any, opts: any) {
super.initialize(props, opts);
constructor(props: ComponentProperties = {}, opt: ComponentOptions) {
super(props, opt);
this.__checkInnerChilds();
}

Expand Down
6 changes: 3 additions & 3 deletions src/dom_components/model/ComponentVideo.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { ObjectAny } from '../../common';
import { isDef, isEmptyObj, toLowerCase } from '../../utils/mixins';
import ComponentImage from './ComponentImage';
import { ComponentOptions, ComponentProperties } from './types';

const type = 'video';
const yt = 'yt';
Expand Down Expand Up @@ -38,14 +39,13 @@ export default class ComponentVideo extends ComponentImage {
};
}

initialize(props: any, opts: any) {
this.em = opts.em;
constructor(props: ComponentProperties = {}, opt: ComponentOptions) {
super(props, opt);
if (this.get('src')) this.parseFromSrc();
this.updatePropsFromAttr();
this.updateTraits();
this.on('change:provider', this.updateTraits);
this.on('change:videoId change:provider', this.updateSrc);
super.initialize(props, opts);
}

updatePropsFromAttr() {
Expand Down
77 changes: 28 additions & 49 deletions src/dom_components/model/Components.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,13 @@ import { DomComponentsConfig } from '../config/config';
import EditorModel from '../../editor/model/Editor';
import ComponentManager from '..';
import CssRule from '../../css_composer/model/CssRule';
import { ComponentAdd, ComponentProperties } from './types';
import {
ComponentAdd,
ComponentAddType,
ComponentDefinition,
ComponentDefinitionDefined,
ComponentProperties,
} from './types';
import ComponentText from './ComponentText';

export const getComponentIds = (cmp?: Component | Component[] | Components, res: string[] = []) => {
Expand Down Expand Up @@ -69,7 +75,7 @@ const getComponentsFromDefs = (
};

export interface ComponentsOptions {
em?: EditorModel;
em: EditorModel;
config?: DomComponentsConfig;
domc?: ComponentManager;
}
Expand All @@ -80,19 +86,19 @@ export default class Components extends Collection</**
Component> {
opt!: ComponentsOptions;
config?: DomComponentsConfig;
em!: EditorModel;
em: EditorModel;
domc?: ComponentManager;
parent?: Component;
__firstAdd?: any;

initialize(models: any, opt: ComponentsOptions = {}) {
constructor(models: any, opt: ComponentsOptions) {
super(models, opt);
this.opt = opt;
this.listenTo(this, 'add', this.onAdd);
this.listenTo(this, 'remove', this.removeChildren);
this.listenTo(this, 'reset', this.resetChildren);
const { em, config } = opt;
this.config = config;
this.em = em!;
this.em = em;
this.domc = opt.domc || em?.Components;
}

Expand Down Expand Up @@ -246,14 +252,16 @@ Component> {
return parsed.html;
}

/** @ts-ignore */
add(models: ComponentAdd, opt: AddOptions & { previousModels?: Component[]; keepIds?: string[] } = {}) {
add(model: ComponentAddType, opt?: AddOptions & { previousModels?: Component[]; keepIds?: string[] }): Component;
add(models: ComponentAddType[], opt?: AddOptions & { previousModels?: Component[]; keepIds?: string[] }): Component[];
add(models: unknown, opt: AddOptions & { previousModels?: Component[]; keepIds?: string[] } = {}): unknown {
if (models == undefined) return;

opt.keepIds = [...(opt.keepIds || []), ...getComponentIds(opt.previousModels)];

if (isString(models)) {
models = this.parseString(models, opt)!;
} else if (isArray(models)) {
models = [...models];
models.forEach((item: string, index: number) => {
if (isString(item)) {
const nodes = this.parseString(item, opt);
Expand All @@ -262,21 +270,19 @@ Component> {
});
}

const isMult = isArray(models);
// @ts-ignore
models = (isMult ? models : [models]).filter(Boolean).map((model: any) => this.processDef(model));
// @ts-ignore
models = isMult ? flatten(models as any, 1) : models[0];
const processedModels = (isArray(models) ? models : [models])
.filter(Boolean)
.map((model: any) => this.processDef(model));

const result = Collection.prototype.add.apply(this, [models as any, opt]);
this.__firstAdd = result;
return result;
models = isArray(models) ? flatten(processedModels as any, 1) : processedModels[0];

return super.add(models as any, opt);
}

/**
* Process component definition.
*/
processDef(mdl: any) {
processDef(mdl: Component | ComponentDefinition | ComponentDefinitionDefined) {
// Avoid processing Models
if (mdl.cid && mdl.ccid) return mdl;
const { em, config = {} } = this;
Expand All @@ -287,12 +293,14 @@ Component> {
model = { ...model }; // Avoid 'Cannot delete property ...'
const modelPr = processor(model);
if (modelPr) {
//@ts-ignore
each(model, (val, key) => delete model[key]);
extend(model, modelPr);
}
}

// React JSX preset
//@ts-ignore
if (model.$$typeof && typeof model.props == 'object') {
model = { ...model };
model.props = { ...model.props };
Expand All @@ -301,6 +309,7 @@ Component> {
const { parserHtml } = parser;

each(model, (value, key) => {
//@ts-ignore
if (!includes(['props', 'type'], key)) delete model[key];
});
const { props } = model;
Expand Down Expand Up @@ -332,43 +341,13 @@ Component> {
const avoidInline = em && em.getConfig().avoidInlineStyle;
domc && domc.Component.ensureInList(model);

// @ts-ignore
if (!isEmpty(style) && !avoidInline && em && em.get && em.getConfig().forceClass && !opts.temporary) {
if (!isEmpty(style) && !avoidInline && em && em.getConfig().forceClass && !opts.temporary) {
const name = model.cid;
em.Css.setClassRule(name, style);
model.setStyle({});
model.addClass(name);
}

model.__postAdd({ recursive: true });
// this.__onAddEnd();
}

// __onAddEnd = debounce(function () {
// // TODO to check symbols on load, probably this might be removed as symbols
// // are always recovered from the model
// // const { domc } = this;
// // const allComp = (domc && domc.allById()) || {};
// // const firstAdd = this.__firstAdd;
// // const toCheck = isArray(firstAdd) ? firstAdd : [firstAdd];
// // const silent = { silent: true };
// // const onAll = comps => {
// // comps.forEach(comp => {
// // const symbol = comp.get(keySymbols);
// // const symbolOf = comp.get(keySymbol);
// // if (symbol && isArray(symbol) && isString(symbol[0])) {
// // comp.set(
// // keySymbols,
// // symbol.map(smb => allComp[smb]).filter(i => i),
// // silent
// // );
// // }
// // if (isString(symbolOf)) {
// // comp.set(keySymbol, allComp[symbolOf], silent);
// // }
// // onAll(comp.components());
// // });
// // };
// // onAll(toCheck);
// });
}
12 changes: 6 additions & 6 deletions src/dom_components/model/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,10 +15,10 @@ export type DragMode = 'translate' | 'absolute' | '';

export type DraggableDroppableFn = (source: Component, target: Component, index?: number) => boolean | void;

export interface ComponentStackItem {
export interface ComponentStackItem<C extends Component = Component, CV extends ComponentView<C> = ComponentView<C>> {
id: string;
model: typeof Component;
view: typeof ComponentView<any>;
model: new (props: any, opt: ComponentOptions) => C;
view: new (opt: any) => CV;
}

/**
Expand Down Expand Up @@ -260,7 +260,7 @@ export interface ComponentModelProperties extends ComponentProperties {
[key: string]: any;
}

type ComponentAddType = Component | ComponentDefinition | ComponentDefinitionDefined | string;
export type ComponentAddType = Component | ComponentDefinition | ComponentDefinitionDefined | string;

export type ComponentAdd = ComponentAddType | ComponentAddType[];

Expand Down Expand Up @@ -288,8 +288,8 @@ export type ToHTMLOptions = {
};

export interface ComponentOptions {
em?: EditorModel;
config?: DomComponentsConfig;
em: EditorModel;
config: DomComponentsConfig;
frame?: Frame;
temporary?: boolean;
avoidChildren?: boolean;
Expand Down
8 changes: 7 additions & 1 deletion test/specs/dom_components/model/Component.ts
Original file line number Diff line number Diff line change
Expand Up @@ -328,8 +328,9 @@ describe('Component', () => {
obj.append([{}, {}]);
const comps = obj.components();
expect(comps.length).toEqual(2);
obj.append({});
const result = obj.append({});
expect(comps.length).toEqual(3);
expect(result[0].em).toEqual(em);
});

test('components() set new collection', () => {
Expand All @@ -338,6 +339,8 @@ describe('Component', () => {
const result = obj.components();
expect(result.length).toEqual(1);
expect(result.models[0].get('tagName')).toEqual('span');

expect(result.em).toEqual(em);
});

test('Propagate properties to children', () => {
Expand Down Expand Up @@ -664,18 +667,21 @@ describe('Components', () => {
var c = new Components([], compOpts);
var m = c.add({});
expect(m instanceof Component).toEqual(true);
expect(m.em).toEqual(em);
});

test('Creates image component correctly', () => {
var c = new Components([], compOpts);
var m = c.add({ type: 'image' });
expect(m instanceof ComponentImage).toEqual(true);
expect(m.em).toEqual(em);
});

test('Creates text component correctly', () => {
var c = new Components([], compOpts);
var m = c.add({ type: 'text' });
expect(m instanceof ComponentText).toEqual(true);
expect(m.em).toEqual(em);
});

test('Avoid conflicting components with the same ID', () => {
Expand Down
Loading

0 comments on commit 4c61b0f

Please sign in to comment.