-
-
Notifications
You must be signed in to change notification settings - Fork 3.8k
/
Component.js
444 lines (369 loc) · 10.5 KB
/
Component.js
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
import Styleable from 'domain_abstract/model/Styleable';
var Backbone = require('backbone');
var Components = require('./Components');
var Selectors = require('selector_manager/model/Selectors');
var Traits = require('trait_manager/model/Traits');
const escapeRegExp = (str) => {
return str.replace(/[|\\{}()[\]^$+*?.]/g, '\\$&');
}
module.exports = Backbone.Model.extend(Styleable).extend({
defaults: {
// HTML tag of the component
tagName: 'div',
// Component type, eg. 'text', 'image', 'video', etc.
type: '',
// True if the component is removable from the canvas
removable: true,
// Indicates if it's possible to drag the component inside other
// Tip: Indicate an array of selectors where it could be dropped inside
draggable: true,
// Indicates if it's possible to drop other components inside
// Tip: Indicate an array of selectors which could be dropped inside
droppable: true,
// Set false if don't want to see the badge (with the name) over the component
badgable: true,
// True if it's possible to style it
// Tip: Indicate an array of CSS properties which is possible to style
stylable: true,
// Highlightable with 'dotted' style if true
highlightable: true,
// True if it's possible to clone the component
copyable: true,
// Indicates if it's possible to resize the component (at the moment implemented only on Image Components)
// It's also possible to pass an object as options for the Resizer
resizable: false,
// Allow to edit the content of the component (used on Text components)
editable: false,
// Hide the component inside Layers
layerable: true,
// This property is used by the HTML exporter as void elements do not
// have closing tag, eg. <br/>, <hr/>, etc.
void: false,
// Indicates if the component is in some CSS state like ':hover', ':active', etc.
state: '',
// State, eg. 'selected'
status: '',
// Content of the component (not escaped) which will be appended before children rendering
content: '',
// Component icon, this string will be inserted before the name, eg. '<i class="fa fa-square-o"></i>'
icon: '',
// Component related style
style: {},
// Key-value object of the component's attributes
attributes: '',
// Array of classes
classes: '',
// Component's javascript
script: '',
// Traits
traits: ['id', 'title'],
/**
* Set an array of items to show up inside the toolbar (eg. move, clone, delete)
* when the component is selected
* toolbar: [{
* attributes: {class: 'fa fa-arrows'},
* command: 'tlb-move',
* },{
* attributes: {class: 'fa fa-clone'},
* command: 'tlb-clone',
* }]
*/
toolbar: null,
},
initialize(props = {}, opt = {}) {
const em = opt.sm || {};
// Check void elements
if(opt && opt.config &&
opt.config.voidElements.indexOf(this.get('tagName')) >= 0) {
this.set('void', true);
}
this.opt = opt;
this.sm = em;
this.config = props;
this.set('attributes', this.get('attributes') || {});
this.listenTo(this, 'change:script', this.scriptUpdated);
this.listenTo(this, 'change:traits', this.traitsUpdated);
//this.defaultCl = this.normalizeClasses(this.get('classes') || this.config.classes || []);
//this.set('classes', new Selectors(this.defaultCl));
this.loadTraits(this.get('traits'));
this.initClasses();
this.initComponents();
this.initToolbar();
// Normalize few properties from strings to arrays
var toNormalize = ['stylable'];
toNormalize.forEach(function(name) {
var value = this.get(name);
if (typeof value == 'string') {
var newValue = value.split(',').map(prop => prop.trim());
this.set(name, newValue);
}
}, this);
this.set('status', '');
this.init();
},
initClasses() {
const classes = this.normalizeClasses(this.get('classes') || this.config.classes || []);
this.set('classes', new Selectors(classes));
return this;
},
initComponents() {
let comps = new Components(this.get('components'), this.opt);
comps.parent = this;
this.set('components', comps);
return this;
},
/**
* Initialize callback
*/
init() {},
/**
* Script updated
*/
scriptUpdated() {
this.set('scriptUpdated', 1);
},
/**
* Once traits are updated I have to populates model's attributes
*/
traitsUpdated() {
let found = 0;
const attrs = Object.assign({}, this.get('attributes'));
this.loadTraits(this.get('traits'), {silent: 1});
this.get('traits').each((trait) => {
found = 1;
if (!trait.get('changeProp')) {
const value = trait.getInitValue();
if (value) {
attrs[trait.get('name')] = value;
}
}
});
found && this.set('attributes', attrs);
},
/**
* Init toolbar
*/
initToolbar() {
var model = this;
if(!model.get('toolbar')) {
var tb = [];
if(model.get('draggable')) {
tb.push({
attributes: {class: 'fa fa-arrows'},
command: 'tlb-move',
});
}
if(model.get('copyable')) {
tb.push({
attributes: {class: 'fa fa-clone'},
command: 'tlb-clone',
});
}
if(model.get('removable')) {
tb.push({
attributes: {class: 'fa fa-trash-o'},
command: 'tlb-delete',
});
}
model.set('toolbar', tb);
}
},
/**
* Load traits
* @param {Array} traits
* @private
*/
loadTraits(traits, opts = {}) {
var trt = new Traits();
trt.setTarget(this);
trt.add(traits);
this.set('traits', trt, opts);
},
/**
* Normalize input classes from array to array of objects
* @param {Array} arr
* @return {Array}
* @private
*/
normalizeClasses(arr) {
var res = [];
if(!this.sm.get)
return;
var clm = this.sm.get('SelectorManager');
if(!clm)
return;
arr.forEach(val => {
var name = '';
if(typeof val === 'string')
name = val;
else
name = val.name;
var model = clm.add(name);
res.push(model);
});
return res;
},
/**
* Override original clone method
* @private
*/
clone(reset) {
var attr = _.clone(this.attributes),
comp = this.get('components'),
traits = this.get('traits'),
cls = this.get('classes');
attr.components = [];
attr.classes = [];
attr.traits = [];
comp.each((md, i) => {
attr.components[i] = md.clone(1);
});
traits.each((md, i) => {
attr.traits[i] = md.clone();
});
cls.each((md, i) => {
attr.classes[i] = md.get('name');
});
attr.status = '';
attr.view = '';
if(reset){
this.opt.collection = null;
}
return new this.constructor(attr, this.opt);
},
/**
* Get the name of the component
* @return {string}
* */
getName() {
let customName = this.get('custom-name');
let tag = this.get('tagName');
tag = tag == 'div' ? 'box' : tag;
let name = this.get('type') || tag;
name = name.charAt(0).toUpperCase() + name.slice(1);
return customName || name;
},
/**
* Get the icon string
* @return {string}
*/
getIcon() {
let icon = this.get('icon');
return icon ? icon + ' ' : '';
},
/**
* Return HTML string of the component
* @param {Object} opts Options
* @return {string} HTML string
* @private
*/
toHTML(opts) {
var code = '';
var m = this;
var tag = m.get('tagName');
var idFound = 0;
var sTag = m.get('void');
var attrId = '';
var strAttr = '';
var attr = this.getAttrToHTML();
for (var prop in attr) {
if (prop == 'id') {
idFound = 1;
}
var val = attr[prop];
strAttr += typeof val !== undefined && val !== '' ?
' ' + prop + '="' + val + '"' : '';
}
// Build the string of classes
var strCls = '';
m.get('classes').each(m => {
strCls += ' ' + m.get('name');
});
strCls = strCls !== '' ? ' class="' + strCls.trim() + '"' : '';
// If style is not empty I need an ID attached to the component
if(!_.isEmpty(m.get('style')) && !idFound)
attrId = ' id="' + m.getId() + '" ';
code += '<' + tag + strCls + attrId + strAttr + (sTag ? '/' : '') + '>' + m.get('content');
m.get('components').each(m => {
code += m.toHTML();
});
if(!sTag)
code += '</'+tag+'>';
return code;
},
/**
* Returns object of attributes for HTML
* @return {Object}
* @private
*/
getAttrToHTML() {
var attr = this.get('attributes') || {};
delete attr.style;
return attr;
},
/**
* Return a shallow copy of the model's attributes for JSON
* stringification.
* @return {Object}
* @private
*/
toJSON(...args) {
var obj = Backbone.Model.prototype.toJSON.apply(this, args);
var scriptStr = this.getScriptString();
delete obj.toolbar;
if (scriptStr) {
obj.script = scriptStr;
}
return obj;
},
/**
* Return model id
* @return {string}
*/
getId() {
let attrs = this.get('attributes') || {};
return attrs.id || this.cid;
},
/**
* Return script in string format, cleans 'function() {..' from scripts
* if it's a function
* @param {string|Function} script
* @return {string}
* @private
*/
getScriptString(script) {
var scr = script || this.get('script');
if (!scr) {
return scr;
}
// Need to convert script functions to strings
if (typeof scr == 'function') {
var scrStr = scr.toString().trim();
scrStr = scrStr.replace(/^function[\s\w]*\(\)\s?\{/, '').replace(/\}$/, '');
scr = scrStr.trim();
}
var config = this.sm.config || {};
var tagVarStart = escapeRegExp(config.tagVarStart || '{[ ');
var tagVarEnd = escapeRegExp(config.tagVarEnd || ' ]}');
var reg = new RegExp(`${tagVarStart}(\\w+)${tagVarEnd}`, 'g');
scr = scr.replace(reg, (match, v) => {
// If at least one match is found I have to track this change for a
// better optimization inside JS generator
this.scriptUpdated();
return this.attributes[v];
})
return scr;
}
},{
/**
* Detect if the passed element is a valid component.
* In case the element is valid an object abstracted
* from the element will be returned
* @param {HTMLElement}
* @return {Object}
* @private
*/
isComponent(el) {
return {tagName: el.tagName ? el.tagName.toLowerCase() : ''};
},
});