-
-
Notifications
You must be signed in to change notification settings - Fork 4.2k
/
Copy pathComponent.ts
2025 lines (1812 loc) · 62.4 KB
/
Component.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import {
isUndefined,
isFunction,
isArray,
isEmpty,
isBoolean,
has,
isString,
forEach,
result,
bindAll,
keys,
} from 'underscore';
import { shallowDiff, capitalize, isEmptyObj, isObject, toLowerCase } from '../../utils/mixins';
import StyleableModel, { StyleProps, UpdateStyleOptions } from '../../domain_abstract/model/StyleableModel';
import { Model } from 'backbone';
import Components from './Components';
import Selector from '../../selector_manager/model/Selector';
import Selectors from '../../selector_manager/model/Selectors';
import Traits from '../../trait_manager/model/Traits';
import EditorModel from '../../editor/model/Editor';
import {
ComponentAdd,
ComponentDefinition,
ComponentDefinitionDefined,
ComponentOptions,
ComponentProperties,
DragMode,
ResetComponentsOptions,
SymbolToUpOptions,
ToHTMLOptions,
} from './types';
import Frame from '../../canvas/model/Frame';
import { DomComponentsConfig } from '../config/config';
import ComponentView from '../view/ComponentView';
import { AddOptions, ExtractMethods, ObjectAny, PrevToNewIdMap, SetOptions } from '../../common';
import CssRule, { CssRuleJSON } from '../../css_composer/model/CssRule';
import Trait from '../../trait_manager/model/Trait';
import { ToolbarButtonProps } from './ToolbarButton';
import { TraitProperties } from '../../trait_manager/types';
import { ActionLabelComponents, ComponentsEvents } from '../types';
import ItemView from '../../navigator/view/ItemView';
import {
getSymbolMain,
getSymbolInstances,
initSymbol,
isSymbol,
isSymbolMain,
isSymbolRoot,
updateSymbolCls,
updateSymbolComps,
updateSymbolProps,
} from './SymbolUtils';
import TraitDataVariable from '../../data_sources/model/TraitDataVariable';
export interface IComponent extends ExtractMethods<Component> {}
export interface SetAttrOptions extends SetOptions, UpdateStyleOptions {}
const escapeRegExp = (str: string) => {
return str.replace(/[|\\{}()[\]^$+*?.]/g, '\\$&');
};
export const avoidInline = (em: EditorModel) => !!em?.getConfig().avoidInlineStyle;
export const eventDrag = 'component:drag';
export const keySymbols = '__symbols';
export const keySymbol = '__symbol';
export const keySymbolOvrd = '__symbol_ovrd';
export const keyUpdate = ComponentsEvents.update;
export const keyUpdateInside = ComponentsEvents.updateInside;
/**
* The Component object represents a single node of our template structure, so when you update its properties the changes are
* immediately reflected on the canvas and in the code to export (indeed, when you ask to export the code we just go through all
* the tree of nodes).
* An example on how to update properties:
* ```js
* component.set({
* tagName: 'span',
* attributes: { ... },
* removable: false,
* });
* component.get('tagName');
* // -> 'span'
* ```
*
* [Component]: component.html
*
* @property {String} [type=''] Component type, eg. `text`, `image`, `video`, etc.
* @property {String} [tagName='div'] HTML tag of the component, eg. `span`. Default: `div`
* @property {Object} [attributes={}] Key-value object of the component's attributes, eg. `{ title: 'Hello' }` Default: `{}`
* @property {String} [name=''] Name of the component. Will be used, for example, in Layers and badges
* @property {Boolean} [removable=true] When `true` the component is removable from the canvas, default: `true`
* @property {Boolean|String|Function} [draggable=true] Indicates if it's possible to drag the component inside others.
* You can also specify a query string to indentify elements,
* eg. `'.some-class[title=Hello], [data-gjs-type=column]'` means you can drag the component only inside elements
* containing `some-class` class and `Hello` title, and `column` components. In the case of a function, target and destination components are passed as arguments, return a Boolean to indicate if the drag is possible. Default: `true`
* @property {Boolean|String|Function} [droppable=true] Indicates if it's possible to drop other components inside. You can use
* a query string as with `draggable`. In the case of a function, target and destination components are passed as arguments, return a Boolean to indicate if the drop is possible. Default: `true`
* @property {Boolean} [badgable=true] Set to false if you don't want to see the badge (with the name) over the component. Default: `true`
* @property {Boolean|Array<String>} [stylable=true] True if it's possible to style the component.
* You can also indicate an array of CSS properties which is possible to style, eg. `['color', 'width']`, all other properties
* will be hidden from the style manager. Default: `true`
* @property {Array<String>} [stylable-require=[]] Indicate an array of style properties to show up which has been marked as `toRequire`. Default: `[]`
* @property {Array<String>} [unstylable=[]] Indicate an array of style properties which should be hidden from the style manager. Default: `[]`
* @property {Boolean} [highlightable=true] It can be highlighted with 'dotted' borders if true. Default: `true`
* @property {Boolean} [copyable=true] True if it's possible to clone the component. Default: `true`
* @property {Boolean} [resizable=false] Indicates if it's possible to resize the component. It's also possible to pass an object as [options for the Resizer](https://github.com/GrapesJS/grapesjs/blob/master/src/utils/Resizer.ts). Default: `false`
* @property {Boolean} [editable=false] Allow to edit the content of the component (used on Text components). Default: `false`
* @property {Boolean} [layerable=true] Set to `false` if you need to hide the component inside Layers. Default: `true`
* @property {Boolean} [selectable=true] Allow component to be selected when clicked. Default: `true`
* @property {Boolean} [hoverable=true] Shows a highlight outline when hovering on the element if `true`. Default: `true`
* @property {Boolean} [locked] Disable the selection of the component and its children in the canvas. You can unlock a children by setting its locked property to `false`. Default: `undefined`
* @property {Boolean} [void=false] This property is used by the HTML exporter as void elements don't have closing tags, eg. `<br/>`, `<hr/>`, etc. Default: `false`
* @property {Object} [style={}] Component default style, eg. `{ width: '100px', height: '100px', 'background-color': 'red' }`
* @property {String} [styles=''] Component related styles, eg. `.my-component-class { color: red }`
* @property {String} [content=''] Content of the component (not escaped) which will be appended before children rendering. Default: `''`
* @property {String} [icon=''] Component's icon, this string will be inserted before the name (in Layers and badge), eg. it can be an HTML string '<i class="fa fa-square-o"></i>'. Default: `''`
* @property {String|Function} [script=''] Component's javascript. More about it [here](/modules/Components-js.html). Default: `''`
* @property {String|Function} [script-export=''] You can specify javascript available only in export functions (eg. when you get the HTML).
* If this property is defined it will overwrite the `script` one (in export functions). Default: `''`
* @property {Array<Object|String>} [traits=''] Component's traits. More about it [here](/modules/Traits.html). Default: `['id', 'title']`
* @property {Array<String>} [propagate=[]] Indicates an array of properties which will be inhereted by all NEW appended children.
* For example if you create a component likes this: `{ removable: false, draggable: false, propagate: ['removable', 'draggable'] }`
* and append some new component inside, the new added component will get the exact same properties indicated in the `propagate` array (and the `propagate` property itself). Default: `[]`
* @property {Array<Object>} [toolbar=null] Set an array of items to show up inside the toolbar when the component is selected (move, clone, delete).
* Eg. `toolbar: [ { attributes: {class: 'fa fa-arrows'}, command: 'tlb-move' }, ... ]`.
* By default, when `toolbar` property is falsy the editor will add automatically commands `core:component-exit` (select parent component, added if there is one), `tlb-move` (added if `draggable`) , `tlb-clone` (added if `copyable`), `tlb-delete` (added if `removable`).
* @property {Collection<Component>} [components=null] Children components. Default: `null`
* @property {Object} [delegate=null] Delegate commands to other components. Available commands `remove` | `move` | `copy` | `select`. eg. `{ remove: (cmp) => cmp.closestType('other-type') }`
*
* @module docsjs.Component
*/
export default class Component extends StyleableModel<ComponentProperties> {
/**
* @private
* @ts-ignore */
get defaults(): ComponentDefinitionDefined {
return {
tagName: 'div',
type: '',
name: '',
removable: true,
draggable: true,
droppable: true,
badgable: true,
stylable: true,
'stylable-require': '',
'style-signature': '',
unstylable: '',
highlightable: true,
copyable: true,
resizable: false,
editable: false,
layerable: true,
selectable: true,
hoverable: true,
void: false,
state: '', // Indicates if the component is in some CSS state like ':hover', ':active', etc.
status: '', // State, eg. 'selected'
content: '',
icon: '',
style: '',
styles: '', // Component related styles
classes: '', // Array of classes
script: '',
'script-props': '',
'script-export': '',
attributes: {},
traits: ['id', 'title'],
propagate: '',
dmode: '',
toolbar: null,
delegate: null,
[keySymbol]: 0,
[keySymbols]: 0,
[keySymbolOvrd]: 0,
_undo: true,
_undoexc: ['status', 'open'],
};
}
get tagName() {
return this.get('tagName')!;
}
get classes() {
return this.get('classes')!;
}
get traits() {
return this.get('traits')!;
}
get content() {
return this.get('content') ?? '';
}
get toolbar() {
return this.get('toolbar') || [];
}
get resizable() {
return this.get('resizable')!;
}
get delegate() {
return this.get('delegate');
}
get locked() {
return this.get('locked');
}
get frame() {
return this.opt.frame;
}
get page() {
return this.frame?.getPage();
}
preInit() {}
/**
* Hook method, called once the model is created
*/
init() {}
/**
* Hook method, called when the model has been updated (eg. updated some model's property)
* @param {String} property Property name, if triggered after some property update
* @param {*} value Property value, if triggered after some property update
* @param {*} previous Property previous value, if triggered after some property update
*/
updated(property: string, value: any, previous: any) {}
/**
* Hook method, called once the model has been removed
*/
removed() {}
em!: EditorModel;
opt!: ComponentOptions;
config!: DomComponentsConfig;
ccid!: string;
views!: ComponentView[];
view?: ComponentView;
viewLayer?: ItemView;
rule?: CssRule;
prevColl?: Components;
__hasUm?: boolean;
__symbReady?: boolean;
/**
* @private
* @ts-ignore */
collection!: Components;
constructor(props: ComponentProperties = {}, opt: ComponentOptions) {
super(props, opt);
bindAll(this, '__upSymbProps', '__upSymbCls', '__upSymbComps');
const em = opt.em;
// Propagate properties from parent if indicated
const parent = this.parent();
const parentAttr = parent?.attributes;
const propagate = this.get('propagate');
propagate && this.set('propagate', isArray(propagate) ? propagate : [propagate]);
if (parentAttr && parentAttr.propagate && !propagate) {
const newAttr: Partial<ComponentProperties> = {};
const toPropagate = parentAttr.propagate;
toPropagate.forEach((prop) => (newAttr[prop] = parent.get(prop as string)));
newAttr.propagate = toPropagate;
this.set({ ...newAttr, ...props });
}
// Check void elements
if (opt && opt.config && opt.config.voidElements!.indexOf(this.get('tagName')!) >= 0) {
this.set('void', true);
}
opt.em = em;
this.opt = opt;
this.em = em!;
this.config = opt.config || {};
this.set('attributes', {
...(result(this, 'defaults').attributes || {}),
...(this.get('attributes') || {}),
});
this.ccid = Component.createId(this, opt);
this.preInit();
this.initClasses();
this.initComponents();
this.initTraits();
this.initToolbar();
this.initScriptProps();
this.listenTo(this, 'change:script', this.scriptUpdated);
this.listenTo(this, 'change:tagName', this.tagUpdated);
this.listenTo(this, 'change:attributes', this.attrUpdated);
this.listenTo(this, 'change:attributes:id', this._idUpdated);
this.on('change:toolbar', this.__emitUpdateTlb);
this.on('change', this.__onChange);
this.on(keyUpdateInside, this.__propToParent);
this.set('status', '');
this.views = [];
// Register global updates for collection properties
['classes', 'traits', 'components'].forEach((name) => {
const events = `add remove ${name !== 'components' ? 'change' : ''}`;
this.listenTo(this.get(name), events.trim(), (...args) => this.emitUpdate(name, ...args));
});
if (!opt.temporary) {
// Add component styles
const cssc = em && em.Css;
const { styles, type } = this.attributes;
if (styles && cssc) {
cssc.addCollection(styles, { avoidUpdateStyle: true }, { group: `cmp:${type}` });
}
this.__postAdd();
this.init();
isSymbol(this) && initSymbol(this);
em?.trigger(ComponentsEvents.create, this, opt);
}
}
__postAdd(opts: { recursive?: boolean } = {}) {
const { em } = this;
const um = em?.UndoManager;
const comps = this.components();
if (um && !this.__hasUm) {
um.add(comps);
um.add(this.getSelectors());
this.__hasUm = true;
}
opts.recursive && comps.map((c) => c.__postAdd(opts));
}
__postRemove() {
const { em } = this;
const um = em?.UndoManager;
if (um) {
um.remove(this.components());
um.remove(this.getSelectors());
delete this.__hasUm;
}
}
__onChange(m: any, opts: any) {
const changed = this.changedAttributes() || {};
keys(changed).forEach((prop) => this.emitUpdate(prop));
['status', 'open', 'toolbar', 'traits'].forEach((name) => delete changed[name]);
// Propagate component prop changes
if (!isEmptyObj(changed)) {
this.__changesUp(opts);
this.__propSelfToParent({ component: this, changed, options: opts });
}
}
__onStyleChange(newStyles: StyleProps) {
const { em } = this;
if (!em) return;
const event = 'component:styleUpdate';
const styleKeys = keys(newStyles);
const pros = { style: newStyles };
em.trigger(event, this, pros);
styleKeys.forEach((key) => em.trigger(`${event}:${key}`, this, pros));
}
__changesUp(opts: any) {
const { em, frame } = this;
[frame, em].forEach((md) => md && md.changesUp(opts));
}
__propSelfToParent(props: any) {
this.trigger(keyUpdate, props);
this.__propToParent(props);
}
__propToParent(props: any) {
const parent = this.parent();
parent && parent.trigger(keyUpdateInside, props);
}
__emitUpdateTlb() {
this.emitUpdate('toolbar');
}
__getAllById() {
const { em } = this;
return em ? em.Components.allById() : {};
}
__upSymbProps(m: any, opts: SymbolToUpOptions = {}) {
updateSymbolProps(this, opts);
}
__upSymbCls(m: any, c: any, opts = {}) {
updateSymbolCls(this, opts);
}
__upSymbComps(m: Component, c: Components, o: any) {
updateSymbolComps(this, m, c, o);
}
/**
* Check component's type
* @param {string} type Component type
* @return {Boolean}
* @example
* component.is('image')
* // -> false
*/
is(type: string) {
return !!(this.get('type') == type);
}
/**
* Return all the propeties
* @returns {Object}
*/
props() {
return this.attributes;
}
/**
* Get the index of the component in the parent collection.
* @return {Number}
*/
index() {
const { collection } = this;
return collection ? collection.indexOf(this) : 0;
}
/**
* Change the drag mode of the component.
* To get more about this feature read: https://github.com/GrapesJS/grapesjs/issues/1936
* @param {String} value Drag mode, options: `'absolute'` | `'translate'` | `''`
* @returns {this}
*/
setDragMode(value?: DragMode) {
return this.set('dmode', value);
}
/**
* Get the drag mode of the component.
* @returns {String} Drag mode value, options: `'absolute'` | `'translate'` | `''`
*/
getDragMode(): DragMode {
return this.get('dmode') || '';
}
/**
* Set symbol override.
* By setting override to `true`, none of its property changes will be propagated to relative symbols.
* By setting override to specific properties, changes of those properties will be skipped from propagation.
* @param {Boolean|String|Array<String>} value
* @example
* component.setSymbolOverride(['children', 'classes']);
*/
setSymbolOverride(value?: boolean | string | string[]) {
this.set(keySymbolOvrd, (isString(value) ? [value] : value) ?? 0);
}
/**
* Get symbol override value.
* @returns {Boolean|Array<String>}
*/
getSymbolOverride(): boolean | string[] | undefined {
return this.get(keySymbolOvrd);
}
/**
* Find inner components by query string.
* **ATTENTION**: this method works only with already rendered component
* @param {String} query Query string
* @return {Array} Array of components
* @example
* component.find('div > .class');
* // -> [Component, Component, ...]
*/
find(query: string) {
const result: Component[] = [];
const $els = this.view?.$el.find(query);
$els?.each((i) => {
const $el = $els.eq(i);
const model = $el.data('model');
model && result.push(model);
});
return result;
}
/**
* Find all inner components by component type.
* The advantage of this method over `find` is that you can use it
* also before rendering the component
* @param {String} type Component type
* @returns {Array<Component>}
* @example
* const allImages = component.findType('image');
* console.log(allImages[0]) // prints the first found component
*/
findType(type: string) {
const result: Component[] = [];
const find = (components: Components) =>
components.forEach((item) => {
item.is(type) && result.push(item);
find(item.components());
});
find(this.components());
return result;
}
/**
* Find the first inner component by component type.
* If no component is found, it returns `undefined`.
* @param {String} type Component type
* @returns {Component|undefined}
* @example
* const image = component.findFirstType('image');
* if (image) {
* console.log(image);
* }
*/
findFirstType(type: string): Component | undefined {
return this.findType(type).at(0);
}
/**
* Find the closest parent component by query string.
* **ATTENTION**: this method works only with already rendered component
* @param {string} query Query string
* @return {Component}
* @example
* component.closest('div.some-class');
* // -> Component
*/
closest(query: string) {
const result = this.view?.$el.closest(query);
return result?.length ? (result.data('model') as Component) : undefined;
}
/**
* Find the closest parent component by its type.
* The advantage of this method over `closest` is that you can use it
* also before rendering the component
* @param {String} type Component type
* @returns {Component} Found component, otherwise `undefined`
* @example
* const Section = component.closestType('section');
* console.log(Section);
*/
closestType(type: string) {
let parent = this.parent();
while (parent && !parent.is(type)) {
parent = parent.parent();
}
return parent;
}
/**
* The method returns a Boolean value indicating whether the passed
* component is a descendant of a given component
* @param {Component} component Component to check
* @returns {Boolean}
*/
contains(component: Component) {
let result = !1;
if (!component) return result;
const contains = (components: Components) => {
!result &&
components.forEach((item) => {
if (item === component) result = !0;
!result && contains(item.components());
});
};
contains(this.components());
return result;
}
/**
* Once the tag is updated I have to rerender the element
* @private
*/
tagUpdated() {
this.trigger('rerender');
}
/**
* Replace a component with another one
* @param {String|Component} el Component or HTML string
* @param {Object} [opts={}] Options for the append action
* @returns {Array<Component>} New replaced components
* @example
* const result = component.replaceWith('<div>Some new content</div>');
* // result -> [Component]
*/
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 }) as C | C[];
return isArray(result) ? result : [result];
}
/**
* Emit changes for each updated attribute
* @private
*/
attrUpdated(m: any, v: any, opts: SetAttrOptions = {}) {
const attrs = this.get('attributes')!;
// Handle classes
const classes = attrs.class;
classes && this.setClass(classes);
delete attrs.class;
// Handle style
const style = attrs.style;
style && this.setStyle(style, opts);
delete attrs.style;
const attrPrev = { ...this.previous('attributes') };
const diff = shallowDiff(attrPrev, this.get('attributes')!);
keys(diff).forEach((pr) => {
const attrKey = `attributes:${pr}`;
this.trigger(`change:${attrKey}`, this, diff[pr], opts);
this.em?.trigger(`${keyUpdate}:${attrKey}`, this, diff[pr], opts);
});
}
/**
* Update attributes of the component
* @param {Object} attrs Key value attributes
* @param {Object} options Options for the model update
* @return {this}
* @example
* component.setAttributes({ id: 'test', 'data-key': 'value' });
*/
setAttributes(attrs: ObjectAny, opts: SetAttrOptions = {}) {
this.set('attributes', { ...attrs }, opts);
return this;
}
/**
* Add attributes to the component
* @param {Object} attrs Key value attributes
* @param {Object} options Options for the model update
* @return {this}
* @example
* component.addAttributes({ 'data-key': 'value' });
*/
addAttributes(attrs: ObjectAny, opts: SetAttrOptions = {}) {
return this.setAttributes(
{
...this.getAttributes({ noClass: true }),
...attrs,
},
opts,
);
}
/**
* Remove attributes from the component
* @param {String|Array<String>} attrs Array of attributes to remove
* @param {Object} options Options for the model update
* @return {this}
* @example
* component.removeAttributes('some-attr');
* component.removeAttributes(['some-attr1', 'some-attr2']);
*/
removeAttributes(attrs: string | string[] = [], opts: SetOptions = {}) {
const attrArr = Array.isArray(attrs) ? attrs : [attrs];
const compAttr = this.getAttributes();
attrArr.map((i) => delete compAttr[i]);
return this.setAttributes(compAttr, opts);
}
/**
* Get the style of the component
* @return {Object}
*/
getStyle(options: any = {}, optsAdd: any = {}) {
const { em } = this;
const prop = isString(options) ? options : '';
const opts = prop ? optsAdd : options;
if (avoidInline(em) && !opts.inline) {
const state = em.get('state');
const cc = em.Css;
const rule = cc.getIdRule(this.getId(), { state, ...opts });
this.rule = rule;
if (rule) {
return rule.getStyle(prop);
}
// Return empty style if not rule have been found. We cannot return inline style with the next return
// because else on load inline style is set a #id or .class style
return {};
}
return super.getStyle.call(this, prop);
}
/**
* Set the style on the component
* @param {Object} prop Key value style object
* @return {Object}
* @example
* component.setStyle({ color: 'red' });
*/
setStyle(prop: StyleProps = {}, opts: UpdateStyleOptions = {}) {
const { opt, em } = this;
if (avoidInline(em) && !opt.temporary && !opts.inline) {
const style = this.get('style') || {};
prop = isString(prop) ? this.parseStyle(prop) : prop;
prop = { ...prop, ...(style as any) };
const state = em.get('state');
const cc = em.Css;
const propOrig = this.getStyle(opts);
this.rule = cc.setIdRule(this.getId(), prop, { state, ...opts });
const diff = shallowDiff(propOrig, prop);
this.set('style', '', { silent: true });
keys(diff).forEach((pr) => this.trigger(`change:style:${pr}`));
} else {
prop = super.setStyle.apply(this, arguments as any);
}
if (!opt.temporary) {
this.__onStyleChange(opts.addStyle || prop);
}
return prop;
}
/**
* Return all component's attributes
* @return {Object}
*/
getAttributes(opts: { noClass?: boolean; noStyle?: boolean } = {}) {
const { em } = this;
const classes: string[] = [];
const attributes = { ...this.get('attributes') };
const sm = em?.Selectors;
const id = this.getId();
// Add classes
if (opts.noClass) {
delete attributes.class;
} else {
this.classes.forEach((cls) => classes.push(isString(cls) ? cls : cls.getName()));
classes.length && (attributes.class = classes.join(' '));
}
// Add style
if (!opts.noStyle) {
const style = this.getStyle({ inline: true });
if (isObject(style) && !isEmptyObj(style)) {
attributes.style = this.styleToString({ inline: true });
}
}
const attrDataVariable = this.get('attributes-data-variable');
if (attrDataVariable) {
Object.entries(attrDataVariable).forEach(([key, value]) => {
const dataVariable = value instanceof TraitDataVariable ? value : new TraitDataVariable(value, { em });
attributes[key] = dataVariable.getDataValue();
});
}
// Check if we need an ID on the component
if (!has(attributes, 'id')) {
let addId = false;
// If we don't rely on inline styling we have to check
// for the ID selector
if (avoidInline(em) || !isEmpty(this.getStyle())) {
addId = !!sm?.get(id, sm.Selector.TYPE_ID);
}
if (
// Symbols should always have an id
isSymbol(this) ||
// Components with script should always have an id
this.get('script-export') ||
this.get('script')
) {
addId = true;
}
if (addId) {
attributes.id = id;
}
}
return attributes;
}
/**
* Add classes
* @param {Array<String>|String} classes Array or string of classes
* @return {Array} Array of added selectors
* @example
* model.addClass('class1');
* model.addClass('class1 class2');
* model.addClass(['class1', 'class2']);
* // -> [SelectorObject, ...]
*/
addClass(classes: string | string[]) {
const added = this.em.Selectors.addClass(classes);
return this.classes.add(added);
}
/**
* Set classes (resets current collection)
* @param {Array<String>|String} classes Array or string of classes
* @return {Array} Array of added selectors
* @example
* model.setClass('class1');
* model.setClass('class1 class2');
* model.setClass(['class1', 'class2']);
* // -> [SelectorObject, ...]
*/
setClass(classes: string | string[]) {
this.classes.reset();
return this.addClass(classes);
}
/**
* Remove classes
* @param {Array<String>|String} classes Array or string of classes
* @return {Array} Array of removed selectors
* @example
* model.removeClass('class1');
* model.removeClass('class1 class2');
* model.removeClass(['class1', 'class2']);
* // -> [SelectorObject, ...]
*/
removeClass(classes: string | string[]) {
const removed: Selector[] = [];
classes = isArray(classes) ? classes : [classes];
const selectors = this.classes;
const type = Selector.TYPE_CLASS;
classes.forEach((classe) => {
const classes = classe.split(' ');
classes.forEach((name) => {
const selector = selectors.where({ name, type })[0];
selector && removed.push(selectors.remove(selector));
});
});
return removed;
}
/**
* Returns component's classes as an array of strings
* @return {Array}
*/
getClasses() {
const attr = this.getAttributes();
const classStr = attr.class;
return classStr ? classStr.split(' ') : [];
}
initClasses(m?: any, c?: any, opts: any = {}) {
const event = 'change:classes';
const { class: attrCls, ...restAttr } = this.get('attributes') || {};
const toListen = [this, event, this.initClasses];
const cls = this.get('classes') || attrCls || [];
const clsArr = isString(cls) ? cls.split(' ') : cls;
this.stopListening(...toListen);
const classes = this.normalizeClasses(clsArr);
const selectors = new Selectors([]);
this.set('classes', selectors, opts);
selectors.add(classes);
selectors.on('add remove reset', this.__upSymbCls);
// Clear attributes from classes
attrCls && classes.length && this.set('attributes', restAttr);
// @ts-ignore
this.listenTo(...toListen);
return this;
}
initComponents() {
const event = 'change:components';
const toListen = [this, event, this.initComponents];
this.stopListening(...toListen);
// Have to add components after the init, otherwise the parent
// is not visible
const comps = new Components([], this.opt);
comps.parent = this;
const components = this.get('components');
const addChild = !this.opt.avoidChildren;
this.set('components', comps);
addChild && components && comps.add(isFunction(components) ? components(this) : components, this.opt as any);
comps.on('add remove reset', this.__upSymbComps);
// @ts-ignore
this.listenTo(...toListen);
return this;
}
initTraits(changed?: any) {
const { em } = this;
const event = 'change:traits';
this.off(event, this.initTraits);
this.__loadTraits();
const attrs = { ...this.get('attributes') };
const traitDataVariableAttr: ObjectAny = {};
const traits = this.traits;
traits.each((trait) => {
const name = trait.getName();
const value = trait.getInitValue();
if (trait.changeProp) {
this.set(name, value);
} else {
if (name && value) attrs[name] = value;
}
if (trait.dynamicVariable) {
traitDataVariableAttr[name] = trait.dynamicVariable;
}
});
traits.length && this.set('attributes', attrs);
Object.keys(traitDataVariableAttr).length && this.set('attributes-data-variable', traitDataVariableAttr);
this.on(event, this.initTraits);
changed && em && em.trigger('component:toggled');
return this;
}
initScriptProps() {
if (this.opt.temporary) return;
const prop = 'script-props';
const toListen: any = [`change:${prop}`, this.initScriptProps];
this.off(...toListen);
const prevProps = this.previous(prop) || [];
const newProps = this.get(prop) || [];
const prevPropsEv = prevProps.map((e) => `change:${e}`).join(' ');
const newPropsEv = newProps.map((e) => `change:${e}`).join(' ');
prevPropsEv && this.off(prevPropsEv, this.__scriptPropsChange);
newPropsEv && this.on(newPropsEv, this.__scriptPropsChange);
// @ts-ignore
this.on(...toListen);
}
__scriptPropsChange(m: any, v: any, opts: any = {}) {
if (opts.avoidStore) return;
this.trigger('rerender');
}
/**
* Add new component children
* @param {Component|String} components Component to add
* @param {Object} [opts={}] Options for the append action
* @return {Array} Array of appended components
* @example
* someComponent.get('components').length // -> 0
* const videoComponent = someComponent.append('<video></video><div></div>')[0];
* // This will add 2 components (`video` and `div`) to your `someComponent`
* someComponent.get('components').length // -> 2
* // You can pass components directly
* otherComponent.append(otherComponent2);
* otherComponent.append([otherComponent3, otherComponent4]);
* // append at specific index (eg. at the beginning)
* someComponent.append(otherComponent, { at: 0 });
*/
append<T extends Component = Component>(components: ComponentAdd, opts: AddOptions = {}): T[] {
const compArr = isArray(components) ? [...components] : [components];
const toAppend = compArr.map((comp) => {
if (isString(comp)) {
return comp;
} else {
// I have to remove components from the old container before adding them to a new one
comp.collection && (comp as Component).collection.remove(comp, { temporary: true } as any);
return comp;
}
});
const result = this.components().add(toAppend, {
action: ActionLabelComponents.add,
...opts,
});
return result as T[];
}
/**
* Set new collection if `components` are provided, otherwise the
* current collection is returned
* @param {Component|Component[]|String} [components] Component Definitions or HTML string
* @param {Object} [opts={}] Options, same as in `Component.append()`
* @returns {Collection|Array<[Component]>}