-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbeard.js
More file actions
1291 lines (1161 loc) · 46.4 KB
/
beard.js
File metadata and controls
1291 lines (1161 loc) · 46.4 KB
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
var Beard = function() {
"use strict";
// some constants
var META_START = ['{{', '__'],
META_END = ['}}', '__'],
BLOCKTAGS = ['Loop', 'If', 'Override',
'Size', 'Image', 'Logo', 'CSS', 'JS', 'Style', 'Variant',
'HTML', 'Colour', 'Boolean', 'Font', 'FontSize',
'Choice'],
TEXTONLYTAGS = ['Size', 'Image', 'Logo', 'CSS', 'JS', 'Variant',
'HTML', 'Colour', 'Boolean', 'Font', 'FontSize',
'Choice'],
SETTINGSTAGS = TEXTONLYTAGS.concat(['Style']), // see more below
TEXTREQUIREDTAGS = ['Size', 'CSS', 'JS', 'Colour', 'Boolean', 'Font',
'FontSize', 'Choice'],
FILETYPETAGS = ['Image', 'Logo', 'CSS', 'JS'],
CLOSETAGS = [], // see below
TAGS = []; // see below
// Variant is the one exception to the rule that all text only tags are
// also settings tags.
SETTINGSTAGS.splice(SETTINGSTAGS.indexOf('Variant'), 1);
for (var i in BLOCKTAGS) {
CLOSETAGS.push('End'+BLOCKTAGS[i]);
}
TAGS = BLOCKTAGS.concat(CLOSETAGS).concat(['Else']);
var stripmeta = function(s) {
var from = META_START[0].length,
length = s.length-(META_START[0].length+META_END[0].length);
return s.substr(from, length).trim();
};
var labelToVariableName = function(label) {
var
stripped = label.replace(/[^\s\w]/g, ''),
first = stripped[0].toLowerCase(),
rest = stripped.slice(1);
rest = rest.replace(/\s+\w/g, function(str) {
return str.replace(/\s+/, '').toUpperCase();
});
return first+rest;
};
var getText = function(token) {
var text = '';
for (var i in token.children) {
var child = token.children[i];
if (child.ttype === 'Text') {
text += child.tvalue;
}
}
return text.trim();
};
var splitSettingsToken = function(stripped) {
var index = stripped.indexOf(' '),
tagAndSubsets = stripped.slice(0, index),
labelAndHelp = stripped.slice(index+1),
subsets = [],
tagSplit = tagAndSubsets.split(':'),
tag = tagSplit[0],
labelIndex = labelAndHelp.indexOf('|'),
label = null,
help = '';
if (tagSplit.length > 1) {
subsets = tagSplit[1].split('');
}
if (labelIndex !== -1) {
label = labelAndHelp.slice(0, labelIndex).trim();
help = labelAndHelp.slice(labelIndex+1).trim();
} else {
label = labelAndHelp;
}
return {
tag: tag, // 'style', 'colour', etc.
subsets: subsets, // ['b', 'f'], [], etc.
label: label, // 'Background', 'Logo', etc.
help: help // '320px wide recommended.' or whatever.
};
};
// Token is a tag or some text plus metadata
function Token(ttype, tvalue, offset, linenum, colnum) {
// Text, Var, If, Loop, EndIf, EndLoop
this.ttype = ttype;
// values include the meta chars
this.tvalue = tvalue;
// lots of stuff so that it is easy to do error reporting later on
this.offset = offset;
this.linenum = linenum;
this.colnum = colnum;
// children only get filled in once we parse
this.children = [];
this.trueTokens = [];
this.falseTokens = [];
// these things only get filled in for relevant tokens once we parse
// Everything that's not a Comment or Text:
//stripped
// Override:
//snippetName
// If, Var, Loop, Settings, Variant:
//variableName
// If:
//not
// Loop:
//itemName
// Var:
//formatterName
//formatter
//parameters
// Settings, Variant:
//label
//help
// Style:
//subsets
}
// split the bits between the meta characters
Token.prototype.parseValue = function(getFormatter) {
var ttype = this.ttype;
if (['Comment', 'Text'].indexOf(ttype) !== -1) {
// these tokens' values don't need parsing
return;
}
var tvalue = this.tvalue,
stripped = this.stripped = stripmeta(tvalue);
if (SETTINGSTAGS.indexOf(ttype) !== -1) {
// for setings, parse subsets (if style), label and help
var parts = splitSettingsToken(stripped),
subsets = parts.subsets,
label = parts.label,
help = parts.help;
if (ttype === 'Style') {
for (var i in subsets) {
if (['b', 'f'].indexOf(subsets[i]) === -1) {
throw {
name: 'InvalidSubsets',
message: "Only b(ackground) and f(oreground) "+
"style subsets are allowed.",
token: this
};
}
}
if (subsets.length === 0) {
subsets = ['b', 'f'];
}
} else {
if (subsets.length) {
throw {
name: 'InvalidSubsets',
message: "Subsets are only for style settings.",
token: this
};
}
}
this.subsets = subsets; // ['b', 'f'], [], etc.
this.label = label; // 'Background', 'Logo', etc.
this.help = help; // '320px wide recommended.' or whatever.
this.variableName = labelToVariableName(label);
this.isFile = FILETYPETAGS.indexOf(ttype) !== -1;
return;
} else if (ttype === 'Variant') {
// Variants are sortof like settings...
var parts = splitSettingsToken(stripped),
label = parts.label,
help = parts.help;
this.label = label; //'Normal', 'Hover', etc.
this.help = help;
this.variableName = labelToVariableName(label);
return;
} else if (ttype === 'Var') {
var vname = stripped,
fname = '',
parameters = '';
if (vname.indexOf('|') !== -1) {
// all this because split(something, 1) behaves... odd.
var vparts = vname.split('|');
vname = vparts[0];
fname = vparts.slice(1).join('|');
if (fname.indexOf(' ') !== -1) {
var fparts = fname.split(' ');
fname = fparts[0];
// Parameters is actually just a string that consists of
// everything that remains. The formatter will have to make
// sense of it itself.
parameters = fparts.slice(1).join(' ');
}
}
if (fname) {
var formatter;
if (getFormatter) {
formatter = getFormatter(fname);
}
if (formatter) {
this.formatter = formatter;
} else {
// getFormatter is null, or getFormatter returned nothing.
// Either way it is an error.
throw {
name: 'FormatterNotFound',
message: "Formatter '"+fname+"' not found.",
formatterName: fname,
token: this
};
}
} else {
this.formatter = null;
}
this.variableName = vname;
this.formatterName = fname || null;
this.parameters = parameters || null;
return;
} else if (ttype === 'If') {
var bits = stripped.substr(stripped.indexOf(' ')+1).split(' ');
if (bits[0].toLowerCase() === 'not') {
bits.shift();
this.not = true;
} else {
this.not = false;
}
this.variableName = bits.shift();
return;
} else if (ttype === 'Loop') {
var lbits = stripped.substr(stripped.indexOf(' ')+1).split(' ');
this.variableName = lbits.shift();
if (lbits.length === 2 && lbits[0].toLowerCase() === 'as') {
this.itemName = lbits[1];
} else {
// hackish way to "drop the s".
var lvname = this.variableName;
if (lvname.indexOf('.') !== -1) {
lvname = lvname.slice(lvname.lastIndexOf('.')+1);
}
var single = lvname.substr(0, lvname.length-1);
// drop 'all' from the front
single = single.replace(/^all[A-Z]/, function(str) {
return str[3].toLowerCase();
});
this.itemName = single;
}
return;
} else if (ttype === 'Override') {
this.snippetName = stripped.substr(stripped.indexOf(' ')+1);
return;
}
};
// wrap context.get so that we can add the token to the error message
Token.prototype.getVariable = function(context, defaultValue) {
var variable;
try {
variable = context.get(this.variableName, defaultValue);
} catch(e) {
if (e.name === 'VariableNotFound') {
throw {
name: e.name,
message: "'"+e.variableName+"' not found.",
variableName: e.variableName,
token: this // we're adding this because the context
// doesn't know which token caused it
// (a bit hackish, I know)
};
} else {
throw e;
}
}
return variable;
};
// Render a token. Only use this on tokens that form part of a parsed tree.
// possible runtime errors: VariableNotFound and VariableNotIterable
Token.prototype.render = function(context, renderSnippet) {
// once-off lookups
var ttype = this.ttype,
tvalue = this.tvalue,
snippetName = this.snippetName,
variableName = this.variableName,
formatterName = this.formatterName,
formatter = this.formatter,
parameters = this.parameters;
if (ttype === "Comment") {
return '';
} else if (ttype === "Text") {
return tvalue;
} else if (ttype === "Var") {
var variable = this.getVariable(context);
if (formatter) {
// apply the formatter function
variable = formatter(variable, context, parameters);
}
if (variable === null) {
variable = '';
}
return variable;
} else if (ttype === "If") {
var ivariable = this.getVariable(context, false),
output = '',
isTrue = (ivariable) ? true : false;
if (isTrue && ivariable instanceof Array) {
// make empty arrays "false-like"
isTrue = (ivariable.length > 0);
}
if (this.not) {
// {{if not blah}}
isTrue = !isTrue;
}
if (isTrue) {
for (var i in this.trueTokens) {
var child = this.trueTokens[i];
output += child.render(context);
}
} else {
for (var i in this.falseTokens) {
var child = this.falseTokens[i];
output += child.render(context);
}
}
return output;
} else if (ttype === "Loop") {
var lvariable = this.getVariable(context);
if (lvariable.length === undefined) {
throw {
name: "VariableNotIterable",
message: "'"+this.variableName+
"' does not look like an array.",
variableName: this.variableName,
token: this
};
}
// Merge all properties of object 'b' into object 'a'.
// 'b.property' overwrites 'a.property'
// Taken from mustache.js
// (by the way - the fact that hasOwnProperty even _exists_...)
var merge = function(a, b) {
var _new = {};
for (var name in a) {
if (a.hasOwnProperty(name)) {
_new[name] = a[name];
}
}
for (var name in b) {
if (b.hasOwnProperty(name)) {
_new[name] = b[name];
}
}
return _new;
};
var loutput = '',
items = lvariable;
for (var i in items) {
i = parseInt(i, 10); // gaah!
var item = items[i],
odd = false,
even = false;
if (i % 2 === 1) {
odd = true;
} else {
even = true;
}
var d = {
odd: odd,
even: even,
counter0: i,
counter1: i-0+1,
first: (i===0),
last: (i===items.length-1),
multipleOf2: ((i+1)%2===0),
multipleOf2n: ((i+1)%2===1),
multipleOf3: ((i+1)%3===0),
multipleOf3n: ((i+1)%3===1),
multipleOf4: ((i+1)%4===0),
multipleOf4n: ((i+1)%4===1),
multipleOf5: ((i+1)%5===0),
multipleOf5n: ((i+1)%5===1),
multipleOf6: ((i+1)%6===0),
multipleOf6n: ((i+1)%6===1),
multipleOf7: ((i+1)%7===0),
multipleOf7n: ((i+1)%7===1),
multipleOf8: ((i+1)%8===0),
multipleOf8n: ((i+1)%8===1),
multipleOf9: ((i+1)%9===0),
multipleOf9n: ((i+1)%9===1),
multipleOf10: ((i+1)%10===0),
multipleOf10n: ((i+1)%10===1)
};
d[this.itemName] = item;
context.push(d);
for (var i in this.children) {
var child = this.children[i];
loutput += child.render(context);
}
context.pop();
}
return loutput;
} else if (ttype === "Override") {
var ooutput = '';
if (renderSnippet) {
for (var i in this.children) {
var child = this.children[i];
ooutput += child.render(context);
}
}
return ooutput;
}
return ''; // by default tokens get skipped
};
// drill down the token tree and call callback with the token for every
// token with a ttype in filter
Token.prototype.traverse = function(callback, filter) {
if (!filter || filter.indexOf(this.ttype) !== -1) {
callback(this);
}
if (this.ttype === 'If') {
// if and ifnot tags use trueTokens and falseTokens
for (var i in this.trueTokens) {
this.trueTokens[i].traverse(callback, filter);
}
for (var i in this.falseTokens) {
this.falseTokens[i].traverse(callback, filter);
}
} else {
for (var i in this.children) {
this.children[i].traverse(callback, filter);
}
}
};
// descendvariable is used by Context to drill down into an
// object hierarchy and return the correct variable/object/attribute
var descendvariable = function(variable, names) {
for (var i in names) {
var name = names[i];
if (variable[name] !== undefined) {
variable = variable[name];
} else {
throw {
name: 'VariableNotFound',
message: "'"+name+"' not found.",
variableName: name
};
}
}
return variable;
};
// Context is really just a stack of data hashes
// plus the available formatters
function Context(template, obj, options) {
this.template = template;
this.stack = [];
this.push(obj);
}
// stack push
Context.prototype.push = function(obj) {
this.stack.push(obj);
};
// stack pop
Context.prototype.pop = function() {
return this.stack.pop();
};
// not to be used directly. use get rather
Context.prototype.getvariable = function(vname) {
var index = this.stack.length - 1;
while (index >= 0) {
var obj = this.stack[index];
if (obj[vname] !== undefined) {
return obj[vname];
}
index -= 1;
}
throw {
name: 'VariableNotFound',
message: "'"+vname+"' not found.",
variableName: vname
};
};
// return the correct variable where name is something like path.to.variable
Context.prototype.get = function(name, defaultValue) {
var names = name.split('.'),
first = names[0],
therest = names.slice(1);
try {
var variable = this.getvariable(first);
if (therest) {
return descendvariable(variable, therest);
} else {
return variable;
}
} catch(e) {
if (e.name === 'VariableNotFound' && defaultValue !== undefined) {
return defaultValue;
} else {
throw e;
}
}
};
// Turn code into a flat list of Tokens.
// Can also be useful for syntax hilighting.
var tokenize = function(code) {
/*
COMMENT TOKENS
{# comments #}
OR OTHER NON-TEXT TOKENS
{{no tabs or linebreaks, no semi-colons or underscores}}
(otherwise tight reset css breaks)
__no tabs or libebreaks, no semi-colons or underscores__
Everything else is allowed between {{ and }} or __ and __ for the moment.
__ style tokens get normalised to {{ style ones
THE REST IS ALL TEXT TOKENS
*/
// . never matches a newline. People often tell you to use [\s\S],
// but I cannot get that to work. [^] is apparently another alternative
// and it appears to work for me
var expression = '({#[^]*?#})';
for (var i=0; i<META_START.length; i++) {
var START = META_START[i],//.replace(/\{/g, '{'),
END = META_END[i];//.replace(/\}/g, '}');
expression = expression+'|('+START+'[^\t\n;_]+?'+END+')';
}
// using the regex literal syntax appears to cache it or do something
// very strange in some rare cases. (on V8, at least)
var regex = new RegExp(expression, 'g'),
// same as above, but the entire thing must match from start to finish
matchExpression = '^'+expression+'$',
// GAAH! Why doesn't Javascript have re.split() like Python?!
// TODO: refactor into a regsplit function
bits = [],
lastIndex = 0;
while (true) {
var match = regex.exec(code);
if (match === null) {
break;
}
var bit = code.slice(lastIndex, match.index);
if (bit.length) {
bits.push(bit);
}
var bit = match[0];
bits.push(bit);
lastIndex = regex.lastIndex;
}
// Add the trailing literal
var bit = code.slice(lastIndex);
if (bit.length) {
bits.push(bit);
}
var tokens = [],
offset = 0,
linenum = 0,
colnum = 0;
for (var i in bits) {
var tvalue = bits[i],
ttype, // gets determined below
// this helps us see if this is a comment
cstart = false,
cend = false,
// More strange behaviour. Looks like you have to compile a new
// one every time you want to use it?
matchRegex = new RegExp(matchExpression);
if (tvalue.length >= 5) {
if (tvalue[1] === '#') {
cstart = true;
}
if (tvalue[tvalue.length-2] === '#') {
cend = true;
}
}
if (tvalue.length >= 5 && cstart && cend) {
ttype = 'Comment';
} else {
// strip meta tags and spaces,
// then normalise to the fist meta tags.
var trimmedValue = tvalue;
for (var i=0; i<META_START.length; i++) {
var sl = META_START[i].length,
el = META_END[i].length;
if (tvalue.slice(0, sl) === META_START[i]) {
if (tvalue.slice(-el) === META_END[i]) {
var from = META_START[i].length,
length = tvalue.length-
(META_START[i].length+META_END[i].length),
stripped = tvalue.substr(from, length).trim();
trimmedValue = META_START[0]+stripped+META_END[0];
break;
}
}
}
if (trimmedValue === META_START[0]+'else'+META_END[0]) {
ttype = 'Else';
} else if (matchRegex.exec(trimmedValue)) {
/*
TODO: this should be optimised to not use a regex match,
but the regex feels safest. Just because something starts
and ends with the meta characters doesn't mean it is non-text.
*/
var found = false;
if (trimmedValue.indexOf(META_START[0]+'style:') === 0) {
// special-case {{style:b Background}}
found = true;
ttype = 'Style';
} else {
for (var i in BLOCKTAGS) {
var tagname = BLOCKTAGS[i],
lowered = tagname.toLowerCase(),
startswith = META_START[0]+lowered+' ',
endtag = META_START[0]+'/'+lowered+META_END[0];
if (trimmedValue.indexOf(startswith) === 0) {
found = true;
ttype = tagname;
break;
}
if (trimmedValue === endtag) {
found = true;
ttype = 'End'+tagname;
break;
}
}
}
if (!found) {
ttype = 'Var';
}
} else {
ttype = 'Text';
}
}
tokens.push(new Token(ttype, tvalue, offset, linenum, colnum));
offset += tvalue.length;
if (tvalue.indexOf('\n') !== -1) {
linenum += tvalue.split('\n').length-1; // poor man's .count()
colnum = tvalue.length - tvalue.lastIndexOf('\n') - 1;
} else {
colnum += tvalue.length;
}
}
return tokens;
};
// Template contains the token tree(s)
// and remembers when it was retrieved (parsed)
function Template(code, options) {
code = code.replace(/\r\n/g, '\n');
this.retrieved = new Date();
this.getFormatter = null;
this.allowedSnippets = [];
if (options) {
if (options.getFormatter) {
// should be a function
this.getFormatter = options.getFormatter;
}
if (options.allowedSnippets) {
// should be an array of strings
this.allowedSnippets = options.allowedSnippets;
}
}
var validateRequiredToken = function(setting) {
var label = setting.stripped.split(' ').slice(1).join(' ');
if (setting.children.length === 0) {
throw {
name: 'MissingDefaultError',
message: label+' requires a default value.',
token: setting
};
}
var valueToken = setting.children[0],
value = valueToken.tvalue;
if (setting.ttype === 'Size') {
var rule = value,
sizeStr = rule.substr(0, rule.length-1),
size = parseInt(sizeStr),
orient = rule[rule.length-1],
orients = ['S', 'W', 'H', 'M'];
if (sizeStr != size ||
!(size>0 && orients.indexOf(orient) !== -1)) {
throw {
name: 'InvalidSizeError',
message: label+' must be a positive integer followed '+
'by S, W, H or M.',
token: valueToken
};
}
} else if (setting.ttype === 'Boolean') {
if (value !== 'true' && value !== 'false') {
throw {
name: 'BooleanDefaultError',
message: label+' must default to either true or false.',
token: valueToken
};
}
} else if (setting.ttype === 'Colour') {
var colourValid = true;
if (value.length !== 4 && value.length !== 7) {
colourValid = false;
}
if (colourValid && value[0] !== '#') {
colourValid = false;
}
// TODO: check that each char after the # is a hex digit
if (!colourValid) {
throw {
name: 'ColourDefaultError',
message: label+' default '+
' must be in #xxx or #xxxxxx format.',
token: valueToken
};
}
} else if (setting.ttype === 'FontSize') {
var size, sizeStr, unit;
if (value[value.length-1] == '%') {
sizeStr = value.substr(0, value.length-1),
size = parseInt(sizeStr, 10),
unit = value.substr(value.length-1);
if (sizeStr != size || !(size >= 50 && size <= 600)) {
throw {
name: 'FontSizeDefaultError',
message: '%-based font size must be an integer '+
'between 50% and 600% (inclusive).',
token: valueToken
};
}
} else {
sizeStr = value.substr(0, value.length-2),
size = parseInt(sizeStr, 10),
unit = value.substr(value.length-2);
if (unit != 'px') {
throw {
name: 'FontSizeDefaultError',
message: 'Font sizes must be specified in '+
'pixels or percentages.',
token: valueToken
};
}
if (sizeStr != size || !(size >= 10 && size <= 100)) {
throw {
name: 'FontSizeDefaultError',
message: 'px-based font size must be an integer '+
'between 10px and 100px (inclusive).',
token: valueToken
};
}
}
}
};
// Take the tokens and turn them into nested Token branches as an Array.
var parseTokens = function(tokens, getFormatter, allowedSnippets) {
// TODO: This function is getting huge.
// Perhaps some of it can be refactored into Token?
var branches = [],
snippetTags = [],
blockstack = [],
untiltype = null,
settingsByType = {};
//imageSizes = {};
var pushToken = function(token) {
// if we have tokens on the stack, add this token to the one
// on the top of the stack. otherwise, start a new branch
if (blockstack.length) {
var children,
last = blockstack[blockstack.length-1];
if (last.ttype === 'If') {
// for If tags, use trueTokens or falseTokens
if (token.ttype === 'Else' || last.falseTokens.length) {
children = last.falseTokens;
} else {
children = last.trueTokens;
}
} else {
// for all other tags, use children
children = last.children;
}
children.push(token);
} else {
branches.push(token);
}
};
for (var i in tokens) {
var token = tokens[i];
// parse what goes on between the meta tags
token.parseValue(getFormatter);
// TODO: check the variable names
// (and remember that images and logos
// share the same namespace)
// use settingsByType
if (SETTINGSTAGS.indexOf(token.ttype) !== -1) {
var ttype = token.ttype;
if (ttype === 'Logo') {
ttype = 'Image';
}
if (!settingsByType[ttype]) {
settingsByType[ttype] = {};
}
if (settingsByType[ttype][token.variableName]) {
// throw error
throw {
name: 'DuplicateNameError',
message: 'This label results in a duplicate '+
'variable name. Settings of the same type '+
'must have unique variable names. Images and '+
'logos count as the same type.',
token: token
};
} else {
settingsByType[ttype][token.variableName] = 1;
}
}
var parent = null;
if (blockstack.length) {
parent = blockstack[blockstack.length-1];
}
if (parent && TEXTONLYTAGS.indexOf(parent.ttype) !== -1) {
// make sure that only Text goes inside text-only tokens
if (CLOSETAGS.indexOf(token.ttype) === -1) {
if (token.ttype !== 'Text') {
throw {
name: 'InvalidNestedTag',
message: 'Only text can go inside '+
parent.ttype+'. '+
'Did you remember to close the tag?',
token: parent // token is the first broken tag
};
}
}
} else if (parent && parent.ttype === 'Style') {
// make sure only Text or Variant tags go inside Style
if (CLOSETAGS.indexOf(token.ttype) === -1) {
if (['Text', 'Variant'].indexOf(token.ttype) === -1) {
throw {
name: 'InvalidNestedTag',
message: 'Only text or variant tags can go '+
'inside '+parent.ttype+'. '+
'Did you remember to close the tag?',
token: parent // token is the first broken tag
};
}
}
} else if (token.ttype === 'Variant') {
if (!parent || parent.ttype !== 'Style') {
throw {
name: 'TemplateSyntaxError',
message: 'Variant tags may only go inside '+
'Style tags.',
token: token
};
}
}
if (token.ttype === 'Comment') {
// ignore comments (they don't appear in the parse tree)
continue;
} if (token.ttype === 'Text') {
pushToken(token);
} else if (token.ttype === 'Var') {
pushToken(token);
} else if (token.ttype === 'Else') {
var last;
if (blockstack.length) {
last = blockstack[blockstack.length-1];
}
if (!last || last.ttype !== 'If') {
throw {
name: 'TemplateSyntaxError',
message: 'Else tags may only go inside '+
'If tags.',
token: token
};
}
pushToken(token);
} else if (token.ttype.indexOf('End') === 0) {
// close block tag
if (CLOSETAGS.indexOf(token.ttype) === -1) {
// technically this can't happen right now, because
// tokenize will just return it as a variable token
throw {
name: 'TemplateSyntaxError',
message: 'Unknown tag '+token.ttype,
token: token
};
}
if (token.ttype === untiltype) {
var opentype = untiltype.slice(3);
if (TEXTREQUIREDTAGS.indexOf(opentype) !== -1) {
// this tag requires a text value
var setting = blockstack[blockstack.length-1],
valueToken, value;
validateRequiredToken(setting);
/*
valueToken = setting.children[0];
value = valueToken.tvalue;
if (setting.ttype === 'Size') {
if (imageSizes[value]) {
throw {
name: 'DuplicateSizeError',
message: 'Images sizes must be unique',
token: valueToken
};
} else {
imageSizes[value] = 1;
}
}
*/
}
blockstack.pop();
if (blockstack.length) {
untiltype = 'End'+
blockstack[blockstack.length-1].ttype;
} else {
untiltype = null;
}
} else {
if (untiltype) {
throw {
name: 'TemplateSyntaxError',