This repository has been archived by the owner on Dec 2, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 63
/
VisualFormat.js
653 lines (630 loc) · 27.1 KB
/
VisualFormat.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
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
import parser from './parser/parser';
import parserExt from './parser/parserExt';
import Attribute from './Attribute';
import Relation from './Relation';
const Orientation = {
HORIZONTAL: 1,
VERTICAL: 2,
ZINDEX: 4
};
/**
* Helper function that inserts equal spacers (~).
* @private
*/
function _processEqualSpacer(context, stackView) {
// Determine unique name for the spacer
context.equalSpacerIndex = context.equalSpacerIndex || 1;
const name = '_~' + context.lineIndex + ':' + context.equalSpacerIndex + '~';
if (context.equalSpacerIndex > 1) {
// Ensure that all spacers have the same width/height
context.constraints.push({
view1: '_~' + context.lineIndex + ':1~',
attr1: context.horizontal ? Attribute.WIDTH : Attribute.HEIGHT,
relation: context.relation.relation || Relation.EQU,
view2: name,
attr2: context.horizontal ? Attribute.WIDTH : Attribute.HEIGHT,
priority: context.relation.priority
});
}
context.equalSpacerIndex++;
// Enforce view/proportional width/height
if (context.relation.view || (context.relation.multiplier && (context.relation.multiplier !== 1))) {
context.constraints.push({
view1: name,
attr1: context.horizontal ? Attribute.WIDTH : Attribute.HEIGHT,
relation: context.relation.relation || Relation.EQU,
view2: context.relation.view,
attr2: context.horizontal ? Attribute.WIDTH : Attribute.HEIGHT,
priority: context.relation.priority,
multiplier: context.relation.multiplier
});
context.relation.multiplier = undefined;
}
else if (context.relation.constant) {
context.constraints.push({
view1: name,
attr1: context.horizontal ? Attribute.WIDTH : Attribute.HEIGHT,
relation: Relation.EQU,
view2: null,
attr2: Attribute.CONST,
priority: context.relation.priority,
constant: context.relation.constant
});
context.relation.constant = undefined;
}
// Add constraint
for (var i = 0; i < context.prevViews.length; i++) {
const prevView = context.prevViews[i];
switch (context.orientation) {
case Orientation.HORIZONTAL:
context.prevAttr = (prevView !== stackView) ? Attribute.RIGHT : Attribute.LEFT;
context.curAttr = Attribute.LEFT;
break;
case Orientation.VERTICAL:
context.prevAttr = (prevView !== stackView) ? Attribute.BOTTOM : Attribute.TOP;
context.curAttr = Attribute.TOP;
break;
case Orientation.ZINDEX:
context.prevAttr = Attribute.ZINDEX;
context.curAttr = Attribute.ZINDEX;
context.relation.constant = (prevView !== stackView) ? 'default' : 0;
break;
}
context.constraints.push({
view1: prevView,
attr1: context.prevAttr,
relation: context.relation.relation,
view2: name,
attr2: context.curAttr,
priority: context.relation.priority
});
}
context.prevViews = [name];
}
/**
* Helper function that inserts proportional spacers (-12%-).
* @private
*/
function _processProportionalSpacer(context, stackView) {
context.proportionalSpacerIndex = context.proportionalSpacerIndex || 1;
const name = '_-' + context.lineIndex + ':' + context.proportionalSpacerIndex + '-';
context.proportionalSpacerIndex++;
context.constraints.push({
view1: name,
attr1: context.horizontal ? Attribute.WIDTH : Attribute.HEIGHT,
relation: context.relation.relation || Relation.EQU,
view2: context.relation.view, // or relative to the stackView... food for thought
attr2: context.horizontal ? Attribute.WIDTH : Attribute.HEIGHT,
priority: context.relation.priority,
multiplier: context.relation.multiplier
});
context.relation.multiplier = undefined;
// Add constraint
for (var i = 0; i < context.prevViews.length; i++) {
const prevView = context.prevViews[i];
switch (context.orientation) {
case Orientation.HORIZONTAL:
context.prevAttr = (prevView !== stackView) ? Attribute.RIGHT : Attribute.LEFT;
context.curAttr = Attribute.LEFT;
break;
case Orientation.VERTICAL:
context.prevAttr = (prevView !== stackView) ? Attribute.BOTTOM : Attribute.TOP;
context.curAttr = Attribute.TOP;
break;
case Orientation.ZINDEX:
context.prevAttr = Attribute.ZINDEX;
context.curAttr = Attribute.ZINDEX;
context.relation.constant = (prevView !== stackView) ? 'default' : 0;
break;
}
context.constraints.push({
view1: prevView,
attr1: context.prevAttr,
relation: context.relation.relation,
view2: name,
attr2: context.curAttr,
priority: context.relation.priority
});
}
context.prevViews = [name];
}
/**
* In case of a stack-view, set constraints for opposite orientations
* @private
*/
function _processStackView(context, name, subView) {
let viewName;
for (var orientation = 1; orientation <= 4; orientation *= 2) {
if ((subView.orientations & orientation) &&
(subView.stack.orientation !== orientation) &&
!(subView.stack.processedOrientations & orientation)) {
subView.stack.processedOrientations = subView.stack.processedOrientations | orientation;
viewName = viewName || {
name: name,
type: 'stack'
};
for (var i = 0, j = subView.stack.subViews.length; i < j; i++) {
if (orientation === Orientation.ZINDEX) {
context.constraints.push({
view1: viewName,
attr1: Attribute.ZINDEX,
relation: Relation.EQU,
view2: subView.stack.subViews[i],
attr2: Attribute.ZINDEX
});
}
else {
context.constraints.push({
view1: viewName,
attr1: (orientation === Orientation.VERTICAL) ? Attribute.HEIGHT : Attribute.WIDTH,
relation: Relation.EQU,
view2: subView.stack.subViews[i],
attr2: (orientation === Orientation.VERTICAL) ? Attribute.HEIGHT : Attribute.WIDTH
});
context.constraints.push({
view1: viewName,
attr1: (orientation === Orientation.VERTICAL) ? Attribute.TOP : Attribute.LEFT,
relation: Relation.EQU,
view2: subView.stack.subViews[i],
attr2: (orientation === Orientation.VERTICAL) ? Attribute.TOP : Attribute.LEFT
});
}
}
}
}
}
/**
* Recursive helper function converts a view-name and a range to a series
* of view-names (e.g. [child1, child2, child3, ...]).
* @private
*/
function _getRange(name, range) {
if (range === true) {
range = name.match(/\.\.\d+$/);
if (range) {
name = name.substring(0, name.length - range[0].length);
range = parseInt(range[0].substring(2));
}
}
if (!range) {
return [name];
}
var start = name.match(/\d+$/);
var res = [];
var i;
if (start) {
name = name.substring(0, name.length - start[0].length);
for (i = parseInt(start); i <= range; i++) {
res.push(name + i);
}
}
else {
res.push(name);
for (i = 2; i <= range; i++) {
res.push(name + i);
}
}
return res;
}
/**
* Recursive helper function that processes the cascaded data.
* @private
*/
function _processCascade(context, cascade, parentItem) {
const stackView = parentItem ? parentItem.view : null;
const subViews = [];
let curViews = [];
let subView;
if (stackView) {
cascade.push({view: stackView});
curViews.push(stackView);
}
for (var i = 0; i < cascade.length; i++) {
let item = cascade[i];
if ((!Array.isArray(item) && item.hasOwnProperty('view')) ||
(Array.isArray(item) && item[0].view && !item[0].relation)) {
const items = Array.isArray(item) ? item : [item];
for (var z = 0; z < items.length; z++) {
item = items[z];
const viewRange = (item === ',') ? [] : item.view ? _getRange(item.view, item.range) : [null];
for (var r = 0; r < viewRange.length; r++) {
const curView = viewRange[r];
curViews.push(curView);
//
// Add this view to the collection of subViews
//
if (curView !== stackView) {
subViews.push(curView);
subView = context.subViews[curView];
if (!subView) {
subView = {orientations: 0};
context.subViews[curView] = subView;
}
subView.orientations = subView.orientations | context.orientation;
if (subView.stack) {
_processStackView(context, curView, subView);
}
}
//
// Process the relationship between this and the previous views
//
if ((context.prevViews !== undefined) && (curView !== undefined) && context.relation) {
if (context.relation.relation !== 'none') {
for (var p = 0; p < context.prevViews.length; p++) {
const prevView = context.prevViews[p];
switch (context.orientation) {
case Orientation.HORIZONTAL:
context.prevAttr = (prevView !== stackView) ? Attribute.RIGHT : Attribute.LEFT;
context.curAttr = (curView !== stackView) ? Attribute.LEFT : Attribute.RIGHT;
break;
case Orientation.VERTICAL:
context.prevAttr = (prevView !== stackView) ? Attribute.BOTTOM : Attribute.TOP;
context.curAttr = (curView !== stackView) ? Attribute.TOP : Attribute.BOTTOM;
break;
case Orientation.ZINDEX:
context.prevAttr = Attribute.ZINDEX;
context.curAttr = Attribute.ZINDEX;
context.relation.constant = !prevView ? 0 : (context.relation.constant || 'default');
break;
}
context.constraints.push({
view1: prevView,
attr1: context.prevAttr,
relation: context.relation.relation,
view2: curView,
attr2: context.curAttr,
multiplier: context.relation.multiplier,
constant: ((context.relation.constant === 'default') || !context.relation.constant) ? context.relation.constant : -context.relation.constant,
priority: context.relation.priority
});
}
}
}
//
// Process view size constraints
//
const constraints = item.constraints;
if (constraints) {
for (var n = 0; n < constraints.length; n++) {
context.prevAttr = context.horizontal ? Attribute.WIDTH : Attribute.HEIGHT;
context.curAttr = (constraints[n].view || constraints[n].multiplier) ?
(constraints[n].attribute || context.prevAttr) :
(constraints[n].variable ? Attribute.VARIABLE : Attribute.CONST);
context.constraints.push({
view1: curView,
attr1: context.prevAttr,
relation: constraints[n].relation,
view2: constraints[n].view,
attr2: context.curAttr,
multiplier: constraints[n].multiplier,
constant: constraints[n].constant,
priority: constraints[n].priority
});
}
}
//
// Process cascaded data (child stack-views)
//
if (item.cascade) {
_processCascade(context, item.cascade, item);
}
}
}
}
else if (item !== ',') {
context.prevViews = curViews;
curViews = [];
context.relation = item[0];
if (context.prevViews !== undefined) {
if (context.relation.equalSpacing) {
_processEqualSpacer(context, stackView);
}
if (context.relation.multiplier) {
_processProportionalSpacer(context, stackView);
}
}
}
}
if (stackView) {
subView = context.subViews[stackView];
if (!subView) {
subView = {orientations: context.orientation};
context.subViews[stackView] = subView;
}
else if (subView.stack) {
const err = new Error('A stack named "' + stackView + '" has already been created');
err.column = parentItem.$parserOffset + 1;
throw err;
}
subView.stack = {
orientation: context.orientation,
processedOrientations: context.orientation,
subViews: subViews
};
_processStackView(context, stackView, subView);
}
}
const metaInfoCategories = [
'viewport',
'spacing',
'colors',
'shapes',
'widths',
'heights'
];
/**
* VisualFormat
*
* @namespace VisualFormat
*/
class VisualFormat {
/**
* Parses a single line of vfl into an array of constraint definitions.
*
* When the visual-format could not be succesfully parsed an exception is thrown containing
* additional info about the parse error and column position.
*
* @param {String} visualFormat Visual format string (cannot contain line-endings!).
* @param {Object} [options] Configuration options.
* @param {Boolean} [options.extended] When set to true uses the extended syntax (default: false).
* @param {String} [options.outFormat] Output format (`constraints` or `raw`) (default: `constraints`).
* @param {Number} [options.lineIndex] Line-index used when auto generating equal-spacing constraints.
* @return {Array} Array of constraint definitions.
*/
static parseLine(visualFormat, options) {
if ((visualFormat.length === 0) ||
(options && options.extended && (visualFormat.indexOf('//') === 0))) {
return [];
}
const res = (options && options.extended) ? parserExt.parse(visualFormat) : parser.parse(visualFormat);
if (options && options.outFormat === 'raw') {
return [res];
}
let context = {
constraints: [],
lineIndex: (options ? options.lineIndex : undefined) || 1,
subViews: (options ? options.subViews : undefined) || {}
};
if (res.type === 'attribute') {
for (let n = 0; n < res.attributes.length; n++) {
const attr = res.attributes[n];
for (let m = 0; m < attr.predicates.length; m++) {
const predicate = attr.predicates[m];
context.constraints.push({
view1: res.view,
attr1: attr.attr,
relation: predicate.relation,
view2: predicate.view,
attr2: predicate.attribute || attr.attr,
multiplier: predicate.multiplier,
constant: predicate.constant,
priority: predicate.priority
});
}
}
} else {
switch (res.orientation) {
case 'horizontal':
context.orientation = Orientation.HORIZONTAL;
context.horizontal = true;
_processCascade(context, res.cascade, null);
break;
case 'vertical':
context.orientation = Orientation.VERTICAL;
_processCascade(context, res.cascade, null);
break;
case 'horzvert':
context.orientation = Orientation.HORIZONTAL;
context.horizontal = true;
_processCascade(context, res.cascade, null);
context = {
constraints: context.constraints,
lineIndex: context.lineIndex,
subViews: context.subViews,
orientation: Orientation.VERTICAL
};
_processCascade(context, res.cascade, null);
break;
case 'zIndex':
context.orientation = Orientation.ZINDEX;
_processCascade(context, res.cascade, null);
break;
}
}
return context.constraints;
}
/**
* Parses one or more visual format strings into an array of constraint definitions.
*
* When the visual-format could not be succesfully parsed an exception is thrown containing
* additional info about the parse error and column position.
*
* @param {String|Array} visualFormat One or more visual format strings.
* @param {Object} [options] Configuration options.
* @param {Boolean} [options.extended] When set to true uses the extended syntax (default: false).
* @param {Boolean} [options.strict] When set to false trims any leading/trailing spaces and ignores empty lines (default: true).
* @param {String} [options.lineSeparator] String that defines the end of a line (default `\n`).
* @param {String} [options.outFormat] Output format (`constraints` or `raw`) (default: `constraints`).
* @return {Array} Array of constraint definitions.
*/
static parse(visualFormat, options) {
const lineSeparator = (options && options.lineSeparator) ? options.lineSeparator : '\n';
if (!Array.isArray(visualFormat) && (visualFormat.indexOf(lineSeparator) < 0)) {
try {
return this.parseLine(visualFormat, options);
}
catch (err) {
err.source = visualFormat;
throw err;
}
}
// Decompose visual-format into an array of strings, and within those strings
// search for line-endings, and treat each line as a seperate visual-format.
visualFormat = Array.isArray(visualFormat) ? visualFormat : [visualFormat];
let lines;
let constraints = [];
let lineIndex = 0;
let line;
const parseOptions = {
lineIndex: lineIndex,
extended: (options && options.extended),
strict: (options && (options.strict !== undefined)) ? options.strict : true,
outFormat: options ? options.outFormat : undefined,
subViews: {}
};
try {
for (var i = 0; i < visualFormat.length; i++) {
lines = visualFormat[i].split(lineSeparator);
for (var j = 0; j < lines.length; j++) {
line = lines[j];
lineIndex++;
parseOptions.lineIndex = lineIndex;
if (!parseOptions.strict) {
line = line.trim();
}
if (parseOptions.strict || line.length) {
constraints = constraints.concat(this.parseLine(line, parseOptions));
}
}
}
}
catch (err) {
err.source = line;
err.line = lineIndex;
throw err;
}
return constraints;
}
/**
* Parses meta information from the comments in the VFL.
*
* Additional meta information can be specified in the comments
* for previewing and rendering purposes. For instance, the view-port
* aspect-ratio, sub-view widths and colors, can be specified. The
* following example renders three colored circles in the visual-format editor:
*
* ```vfl
* //viewport aspect-ratio:3/1 max-height:300
* //colors red:#FF0000 green:#00FF00 blue:#0000FF
* //shapes red:circle green:circle blue:circle
* H:|-[row:[red(green,blue)]-[green]-[blue]]-|
* V:|[row]|
* ```
*
* Supported categories and properties:
*
* |Category|Property|Example|
* |--------|--------|-------|
* |`viewport`|`aspect-ratio:{width}/{height}`|`//viewport aspect-ratio:16/9`|
* ||`width:[{number}/intrinsic]`|`//viewport width:10`|
* ||`height:[{number}/intrinsic]`|`//viewport height:intrinsic`|
* ||`min-width:{number}`|
* ||`max-width:{number}`|
* ||`min-height:{number}`|
* ||`max-height:{number}`|
* |`spacing`|`[{number}/array]`|`//spacing:8` or `//spacing:[10, 20, 5]`|
* |`widths`|`{view-name}:[{number}/intrinsic]`|`//widths subview1:100`|
* |`heights`|`{view-name}:[{number}/intrinsic]`|`//heights subview1:intrinsic`|
* |`colors`|`{view-name}:{color}`|`//colors redview:#FF0000 blueview:#00FF00`|
* |`shapes`|`{view-name}:[circle/square]`|`//shapes avatar:circle`|
*
* @param {String|Array} visualFormat One or more visual format strings.
* @param {Object} [options] Configuration options.
* @param {String} [options.lineSeparator] String that defines the end of a line (default `\n`).
* @param {String} [options.prefix] When specified, also processes the categories using that prefix (e.g. "-dev-viewport max-height:10").
* @return {Object} meta-info
*/
static parseMetaInfo(visualFormat, options) {
const lineSeparator = (options && options.lineSeparator) ? options.lineSeparator : '\n';
const prefix = options ? options.prefix : undefined;
visualFormat = Array.isArray(visualFormat) ? visualFormat : [visualFormat];
const metaInfo = {};
var key;
for (var k = 0; k < visualFormat.length; k++) {
const lines = visualFormat[k].split(lineSeparator);
for (var i = 0; i < lines.length; i++) {
const line = lines[i];
for (var c = 0; c < metaInfoCategories.length; c++) {
for (var s = 0; s < (prefix ? 2 : 1); s++) {
const category = metaInfoCategories[c];
const prefixedCategory = ((s === 0) ? '' : prefix) + category;
if (line.indexOf('//' + prefixedCategory + ' ') === 0) {
const items = line.substring(3 + prefixedCategory.length).split(' ');
for (var j = 0; j < items.length; j++) {
metaInfo[category] = metaInfo[category] || {};
const item = items[j].split(':');
const names = _getRange(item[0], true);
for (var r = 0; r < names.length; r++) {
metaInfo[category][names[r]] = (item.length > 1) ? item[1] : '';
}
}
}
else if (line.indexOf('//' + prefixedCategory + ':') === 0) {
metaInfo[category] = line.substring(3 + prefixedCategory.length);
}
}
}
}
}
if (metaInfo.viewport) {
const viewport = metaInfo.viewport;
var aspectRatio = viewport['aspect-ratio'];
if (aspectRatio) {
aspectRatio = aspectRatio.split('/');
viewport['aspect-ratio'] = parseInt(aspectRatio[0]) / parseInt(aspectRatio[1]);
}
if (viewport.height !== undefined) {
viewport.height = (viewport.height === 'intrinsic') ? true : parseInt(viewport.height);
}
if (viewport.width !== undefined) {
viewport.width = (viewport.width === 'intrinsic') ? true : parseInt(viewport.width);
}
if (viewport['max-height'] !== undefined) {
viewport['max-height'] = parseInt(viewport['max-height']);
}
if (viewport['max-width'] !== undefined) {
viewport['max-width'] = parseInt(viewport['max-width']);
}
if (viewport['min-height'] !== undefined) {
viewport['min-height'] = parseInt(viewport['min-height']);
}
if (viewport['min-width'] !== undefined) {
viewport['min-width'] = parseInt(viewport['min-width']);
}
}
if (metaInfo.widths) {
for (key in metaInfo.widths) {
const width = (metaInfo.widths[key] === 'intrinsic') ? true : parseInt(metaInfo.widths[key]);
metaInfo.widths[key] = width;
if ((width === undefined) || isNaN(width)) {
delete metaInfo.widths[key];
}
}
}
if (metaInfo.heights) {
for (key in metaInfo.heights) {
const height = (metaInfo.heights[key] === 'intrinsic') ? true : parseInt(metaInfo.heights[key]);
metaInfo.heights[key] = height;
if ((height === undefined) || isNaN(height)) {
delete metaInfo.heights[key];
}
}
}
if (metaInfo.spacing) {
const value = JSON.parse(metaInfo.spacing);
metaInfo.spacing = value;
if (Array.isArray(value)){
for (var sIdx = 0, len = value.length; sIdx < len; sIdx++) {
if (isNaN(value[sIdx])){
delete metaInfo.spacing;
break;
}
}
} else if (value === undefined || isNaN(value)){
delete metaInfo.spacing;
}
}
return metaInfo;
}
}
export default VisualFormat;