forked from riot/riot
-
Notifications
You must be signed in to change notification settings - Fork 0
/
riot+compiler.js
3960 lines (3285 loc) · 104 KB
/
riot+compiler.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
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
/* Riot v3.7.3, @license MIT */
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
typeof define === 'function' && define.amd ? define(factory) :
(global.riot = factory());
}(this, (function () { 'use strict';
var __TAGS_CACHE = [];
var __TAG_IMPL = {};
var YIELD_TAG = 'yield';
var GLOBAL_MIXIN = '__global_mixin';
var ATTRS_PREFIX = 'riot-';
var REF_DIRECTIVES = ['ref', 'data-ref'];
var IS_DIRECTIVE = 'data-is';
var CONDITIONAL_DIRECTIVE = 'if';
var LOOP_DIRECTIVE = 'each';
var LOOP_NO_REORDER_DIRECTIVE = 'no-reorder';
var SHOW_DIRECTIVE = 'show';
var HIDE_DIRECTIVE = 'hide';
var KEY_DIRECTIVE = 'key';
var RIOT_EVENTS_KEY = '__riot-events__';
var T_STRING = 'string';
var T_OBJECT = 'object';
var T_UNDEF = 'undefined';
var T_FUNCTION = 'function';
var XLINK_NS = 'http://www.w3.org/1999/xlink';
var SVG_NS = 'http://www.w3.org/2000/svg';
var XLINK_REGEX = /^xlink:(\w+)/;
var WIN = typeof window === T_UNDEF ? undefined : window;
var RE_SPECIAL_TAGS = /^(?:t(?:body|head|foot|[rhd])|caption|col(?:group)?|opt(?:ion|group))$/;
var RE_SPECIAL_TAGS_NO_OPTION = /^(?:t(?:body|head|foot|[rhd])|caption|col(?:group)?)$/;
var RE_EVENTS_PREFIX = /^on/;
var RE_HTML_ATTRS = /([-\w]+) ?= ?(?:"([^"]*)|'([^']*)|({[^}]*}))/g;
var CASE_SENSITIVE_ATTRIBUTES = {
'viewbox': 'viewBox',
'preserveaspectratio': 'preserveAspectRatio'
};
var RE_BOOL_ATTRS = /^(?:disabled|checked|readonly|required|allowfullscreen|auto(?:focus|play)|compact|controls|default|formnovalidate|hidden|ismap|itemscope|loop|multiple|muted|no(?:resize|shade|validate|wrap)?|open|reversed|seamless|selected|sortable|truespeed|typemustmatch)$/;
var IE_VERSION = (WIN && WIN.document || {}).documentMode | 0;
/**
* Specialized function for looping an array-like collection with `each={}`
* @param { Array } list - collection of items
* @param {Function} fn - callback function
* @returns { Array } the array looped
*/
function each(list, fn) {
var len = list ? list.length : 0;
var i = 0;
for (; i < len; i++) { fn(list[i], i); }
return list
}
/**
* Check whether an array contains an item
* @param { Array } array - target array
* @param { * } item - item to test
* @returns { Boolean } -
*/
function contains(array, item) {
return array.indexOf(item) !== -1
}
/**
* Convert a string containing dashes to camel case
* @param { String } str - input string
* @returns { String } my-string -> myString
*/
function toCamel(str) {
return str.replace(/-(\w)/g, function (_, c) { return c.toUpperCase(); })
}
/**
* Faster String startsWith alternative
* @param { String } str - source string
* @param { String } value - test string
* @returns { Boolean } -
*/
function startsWith(str, value) {
return str.slice(0, value.length) === value
}
/**
* Helper function to set an immutable property
* @param { Object } el - object where the new property will be set
* @param { String } key - object key where the new property will be stored
* @param { * } value - value of the new property
* @param { Object } options - set the propery overriding the default options
* @returns { Object } - the initial object
*/
function defineProperty(el, key, value, options) {
Object.defineProperty(el, key, extend({
value: value,
enumerable: false,
writable: false,
configurable: true
}, options));
return el
}
/**
* Function returning always a unique identifier
* @returns { Number } - number from 0...n
*/
var uid = (function() {
var i = 0;
return function () { return ++i; }
})();
/**
* Short alias for Object.getOwnPropertyDescriptor
*/
var getPropDescriptor = function (o, k) { return Object.getOwnPropertyDescriptor(o, k); };
/**
* Extend any object with other properties
* @param { Object } src - source object
* @returns { Object } the resulting extended object
*
* var obj = { foo: 'baz' }
* extend(obj, {bar: 'bar', foo: 'bar'})
* console.log(obj) => {bar: 'bar', foo: 'bar'}
*
*/
function extend(src) {
var obj;
var i = 1;
var args = arguments;
var l = args.length;
for (; i < l; i++) {
if (obj = args[i]) {
for (var key in obj) {
// check if this property of the source object could be overridden
if (isWritable(src, key))
{ src[key] = obj[key]; }
}
}
}
return src
}
var misc = Object.freeze({
each: each,
contains: contains,
toCamel: toCamel,
startsWith: startsWith,
defineProperty: defineProperty,
uid: uid,
getPropDescriptor: getPropDescriptor,
extend: extend
});
/**
* Check if the passed argument is a boolean attribute
* @param { String } value -
* @returns { Boolean } -
*/
function isBoolAttr(value) {
return RE_BOOL_ATTRS.test(value)
}
/**
* Check if passed argument is a function
* @param { * } value -
* @returns { Boolean } -
*/
function isFunction(value) {
return typeof value === T_FUNCTION
}
/**
* Check if passed argument is an object, exclude null
* NOTE: use isObject(x) && !isArray(x) to excludes arrays.
* @param { * } value -
* @returns { Boolean } -
*/
function isObject(value) {
return value && typeof value === T_OBJECT // typeof null is 'object'
}
/**
* Check if passed argument is undefined
* @param { * } value -
* @returns { Boolean } -
*/
function isUndefined(value) {
return typeof value === T_UNDEF
}
/**
* Check if passed argument is a string
* @param { * } value -
* @returns { Boolean } -
*/
function isString(value) {
return typeof value === T_STRING
}
/**
* Check if passed argument is empty. Different from falsy, because we dont consider 0 or false to be blank
* @param { * } value -
* @returns { Boolean } -
*/
function isBlank(value) {
return isNil(value) || value === ''
}
/**
* Check against the null and undefined values
* @param { * } value -
* @returns {Boolean} -
*/
function isNil(value) {
return isUndefined(value) || value === null
}
/**
* Check if passed argument is a kind of array
* @param { * } value -
* @returns { Boolean } -
*/
function isArray(value) {
return Array.isArray(value) || value instanceof Array
}
/**
* Check whether object's property could be overridden
* @param { Object } obj - source object
* @param { String } key - object property
* @returns { Boolean } true if writable
*/
function isWritable(obj, key) {
var descriptor = getPropDescriptor(obj, key);
return isUndefined(obj[key]) || descriptor && descriptor.writable
}
var check = Object.freeze({
isBoolAttr: isBoolAttr,
isFunction: isFunction,
isObject: isObject,
isUndefined: isUndefined,
isString: isString,
isBlank: isBlank,
isNil: isNil,
isArray: isArray,
isWritable: isWritable
});
/**
* Shorter and fast way to select multiple nodes in the DOM
* @param { String } selector - DOM selector
* @param { Object } ctx - DOM node where the targets of our search will is located
* @returns { Object } dom nodes found
*/
function $$(selector, ctx) {
return Array.prototype.slice.call((ctx || document).querySelectorAll(selector))
}
/**
* Shorter and fast way to select a single node in the DOM
* @param { String } selector - unique dom selector
* @param { Object } ctx - DOM node where the target of our search will is located
* @returns { Object } dom node found
*/
function $(selector, ctx) {
return (ctx || document).querySelector(selector)
}
/**
* Create a document fragment
* @returns { Object } document fragment
*/
function createFrag() {
return document.createDocumentFragment()
}
/**
* Create a document text node
* @returns { Object } create a text node to use as placeholder
*/
function createDOMPlaceholder() {
return document.createTextNode('')
}
/**
* Check if a DOM node is an svg tag
* @param { HTMLElement } el - node we want to test
* @returns {Boolean} true if it's an svg node
*/
function isSvg(el) {
return !!el.ownerSVGElement
}
/**
* Create a generic DOM node
* @param { String } name - name of the DOM node we want to create
* @param { Boolean } isSvg - true if we need to use an svg node
* @returns { Object } DOM node just created
*/
function mkEl(name) {
return name === 'svg' ? document.createElementNS(SVG_NS, name) : document.createElement(name)
}
/**
* Set the inner html of any DOM node SVGs included
* @param { Object } container - DOM node where we'll inject new html
* @param { String } html - html to inject
*/
/* istanbul ignore next */
function setInnerHTML(container, html) {
if (!isUndefined(container.innerHTML))
{ container.innerHTML = html; }
// some browsers do not support innerHTML on the SVGs tags
else {
var doc = new DOMParser().parseFromString(html, 'application/xml');
var node = container.ownerDocument.importNode(doc.documentElement, true);
container.appendChild(node);
}
}
/**
* Toggle the visibility of any DOM node
* @param { Object } dom - DOM node we want to hide
* @param { Boolean } show - do we want to show it?
*/
function toggleVisibility(dom, show) {
dom.style.display = show ? '' : 'none';
dom.hidden = show ? false : true;
}
/**
* Remove any DOM attribute from a node
* @param { Object } dom - DOM node we want to update
* @param { String } name - name of the property we want to remove
*/
function remAttr(dom, name) {
dom.removeAttribute(name);
}
/**
* Convert a style object to a string
* @param { Object } style - style object we need to parse
* @returns { String } resulting css string
* @example
* styleObjectToString({ color: 'red', height: '10px'}) // => 'color: red; height: 10px'
*/
function styleObjectToString(style) {
return Object.keys(style).reduce(function (acc, prop) {
return (acc + " " + prop + ": " + (style[prop]) + ";")
}, '')
}
/**
* Get the value of any DOM attribute on a node
* @param { Object } dom - DOM node we want to parse
* @param { String } name - name of the attribute we want to get
* @returns { String | undefined } name of the node attribute whether it exists
*/
function getAttr(dom, name) {
return dom.getAttribute(name)
}
/**
* Set any DOM attribute
* @param { Object } dom - DOM node we want to update
* @param { String } name - name of the property we want to set
* @param { String } val - value of the property we want to set
*/
function setAttr(dom, name, val) {
var xlink = XLINK_REGEX.exec(name);
if (xlink && xlink[1])
{ dom.setAttributeNS(XLINK_NS, xlink[1], val); }
else
{ dom.setAttribute(name, val); }
}
/**
* Insert safely a tag to fix #1962 #1649
* @param { HTMLElement } root - children container
* @param { HTMLElement } curr - node to insert
* @param { HTMLElement } next - node that should preceed the current node inserted
*/
function safeInsert(root, curr, next) {
root.insertBefore(curr, next.parentNode && next);
}
/**
* Minimize risk: only zero or one _space_ between attr & value
* @param { String } html - html string we want to parse
* @param { Function } fn - callback function to apply on any attribute found
*/
function walkAttrs(html, fn) {
if (!html) { return }
var m;
while (m = RE_HTML_ATTRS.exec(html))
{ fn(m[1].toLowerCase(), m[2] || m[3] || m[4]); }
}
/**
* Walk down recursively all the children tags starting dom node
* @param { Object } dom - starting node where we will start the recursion
* @param { Function } fn - callback to transform the child node just found
* @param { Object } context - fn can optionally return an object, which is passed to children
*/
function walkNodes(dom, fn, context) {
if (dom) {
var res = fn(dom, context);
var next;
// stop the recursion
if (res === false) { return }
dom = dom.firstChild;
while (dom) {
next = dom.nextSibling;
walkNodes(dom, fn, res);
dom = next;
}
}
}
var dom = Object.freeze({
$$: $$,
$: $,
createFrag: createFrag,
createDOMPlaceholder: createDOMPlaceholder,
isSvg: isSvg,
mkEl: mkEl,
setInnerHTML: setInnerHTML,
toggleVisibility: toggleVisibility,
remAttr: remAttr,
styleObjectToString: styleObjectToString,
getAttr: getAttr,
setAttr: setAttr,
safeInsert: safeInsert,
walkAttrs: walkAttrs,
walkNodes: walkNodes
});
var styleNode;
// Create cache and shortcut to the correct property
var cssTextProp;
var byName = {};
var remainder = [];
var needsInject = false;
// skip the following code on the server
if (WIN) {
styleNode = ((function () {
// create a new style element with the correct type
var newNode = mkEl('style');
// replace any user node or insert the new one into the head
var userNode = $('style[type=riot]');
setAttr(newNode, 'type', 'text/css');
/* istanbul ignore next */
if (userNode) {
if (userNode.id) { newNode.id = userNode.id; }
userNode.parentNode.replaceChild(newNode, userNode);
} else { document.getElementsByTagName('head')[0].appendChild(newNode); }
return newNode
}))();
cssTextProp = styleNode.styleSheet;
}
/**
* Object that will be used to inject and manage the css of every tag instance
*/
var styleManager = {
styleNode: styleNode,
/**
* Save a tag style to be later injected into DOM
* @param { String } css - css string
* @param { String } name - if it's passed we will map the css to a tagname
*/
add: function add(css, name) {
if (name) { byName[name] = css; }
else { remainder.push(css); }
needsInject = true;
},
/**
* Inject all previously saved tag styles into DOM
* innerHTML seems slow: http://jsperf.com/riot-insert-style
*/
inject: function inject() {
if (!WIN || !needsInject) { return }
needsInject = false;
var style = Object.keys(byName)
.map(function (k) { return byName[k]; })
.concat(remainder).join('\n');
/* istanbul ignore next */
if (cssTextProp) { cssTextProp.cssText = style; }
else { styleNode.innerHTML = style; }
}
};
/**
* The riot template engine
* @version v3.0.8
*/
var skipRegex = (function () { //eslint-disable-line no-unused-vars
var beforeReChars = '[{(,;:?=|&!^~>%*/';
var beforeReWords = [
'case',
'default',
'do',
'else',
'in',
'instanceof',
'prefix',
'return',
'typeof',
'void',
'yield'
];
var wordsLastChar = beforeReWords.reduce(function (s, w) {
return s + w.slice(-1)
}, '');
var RE_REGEX = /^\/(?=[^*>/])[^[/\\]*(?:(?:\\.|\[(?:\\.|[^\]\\]*)*\])[^[\\/]*)*?\/[gimuy]*/;
var RE_VN_CHAR = /[$\w]/;
function prev (code, pos) {
while (--pos >= 0 && /\s/.test(code[pos])){ }
return pos
}
function _skipRegex (code, start) {
var re = /.*/g;
var pos = re.lastIndex = start++;
var match = re.exec(code)[0].match(RE_REGEX);
if (match) {
var next = pos + match[0].length;
pos = prev(code, pos);
var c = code[pos];
if (pos < 0 || ~beforeReChars.indexOf(c)) {
return next
}
if (c === '.') {
if (code[pos - 1] === '.') {
start = next;
}
} else if (c === '+' || c === '-') {
if (code[--pos] !== c ||
(pos = prev(code, pos)) < 0 ||
!RE_VN_CHAR.test(code[pos])) {
start = next;
}
} else if (~wordsLastChar.indexOf(c)) {
var end = pos + 1;
while (--pos >= 0 && RE_VN_CHAR.test(code[pos])){ }
if (~beforeReWords.indexOf(code.slice(pos + 1, end))) {
start = next;
}
}
}
return start
}
return _skipRegex
})();
/**
* riot.util.brackets
*
* - `brackets ` - Returns a string or regex based on its parameter
* - `brackets.set` - Change the current riot brackets
*
* @module
*/
/* global riot */
/* istanbul ignore next */
var brackets = (function (UNDEF) {
var
REGLOB = 'g',
R_MLCOMMS = /\/\*[^*]*\*+(?:[^*\/][^*]*\*+)*\//g,
R_STRINGS = /"[^"\\]*(?:\\[\S\s][^"\\]*)*"|'[^'\\]*(?:\\[\S\s][^'\\]*)*'|`[^`\\]*(?:\\[\S\s][^`\\]*)*`/g,
S_QBLOCKS = R_STRINGS.source + '|' +
/(?:\breturn\s+|(?:[$\w\)\]]|\+\+|--)\s*(\/)(?![*\/]))/.source + '|' +
/\/(?=[^*\/])[^[\/\\]*(?:(?:\[(?:\\.|[^\]\\]*)*\]|\\.)[^[\/\\]*)*?([^<]\/)[gim]*/.source,
UNSUPPORTED = RegExp('[\\' + 'x00-\\x1F<>a-zA-Z0-9\'",;\\\\]'),
NEED_ESCAPE = /(?=[[\]()*+?.^$|])/g,
S_QBLOCK2 = R_STRINGS.source + '|' + /(\/)(?![*\/])/.source,
FINDBRACES = {
'(': RegExp('([()])|' + S_QBLOCK2, REGLOB),
'[': RegExp('([[\\]])|' + S_QBLOCK2, REGLOB),
'{': RegExp('([{}])|' + S_QBLOCK2, REGLOB)
},
DEFAULT = '{ }';
var _pairs = [
'{', '}',
'{', '}',
/{[^}]*}/,
/\\([{}])/g,
/\\({)|{/g,
RegExp('\\\\(})|([[({])|(})|' + S_QBLOCK2, REGLOB),
DEFAULT,
/^\s*{\^?\s*([$\w]+)(?:\s*,\s*(\S+))?\s+in\s+(\S.*)\s*}/,
/(^|[^\\]){=[\S\s]*?}/
];
var
cachedBrackets = UNDEF,
_regex,
_cache = [],
_settings;
function _loopback (re) { return re }
function _rewrite (re, bp) {
if (!bp) { bp = _cache; }
return new RegExp(
re.source.replace(/{/g, bp[2]).replace(/}/g, bp[3]), re.global ? REGLOB : ''
)
}
function _create (pair) {
if (pair === DEFAULT) { return _pairs }
var arr = pair.split(' ');
if (arr.length !== 2 || UNSUPPORTED.test(pair)) {
throw new Error('Unsupported brackets "' + pair + '"')
}
arr = arr.concat(pair.replace(NEED_ESCAPE, '\\').split(' '));
arr[4] = _rewrite(arr[1].length > 1 ? /{[\S\s]*?}/ : _pairs[4], arr);
arr[5] = _rewrite(pair.length > 3 ? /\\({|})/g : _pairs[5], arr);
arr[6] = _rewrite(_pairs[6], arr);
arr[7] = RegExp('\\\\(' + arr[3] + ')|([[({])|(' + arr[3] + ')|' + S_QBLOCK2, REGLOB);
arr[8] = pair;
return arr
}
function _brackets (reOrIdx) {
return reOrIdx instanceof RegExp ? _regex(reOrIdx) : _cache[reOrIdx]
}
_brackets.split = function split (str, tmpl, _bp) {
// istanbul ignore next: _bp is for the compiler
if (!_bp) { _bp = _cache; }
var
parts = [],
match,
isexpr,
start,
pos,
re = _bp[6];
var qblocks = [];
var prevStr = '';
var mark, lastIndex;
isexpr = start = re.lastIndex = 0;
while ((match = re.exec(str))) {
lastIndex = re.lastIndex;
pos = match.index;
if (isexpr) {
if (match[2]) {
var ch = match[2];
var rech = FINDBRACES[ch];
var ix = 1;
rech.lastIndex = lastIndex;
while ((match = rech.exec(str))) {
if (match[1]) {
if (match[1] === ch) { ++ix; }
else if (!--ix) { break }
} else {
rech.lastIndex = pushQBlock(match.index, rech.lastIndex, match[2]);
}
}
re.lastIndex = ix ? str.length : rech.lastIndex;
continue
}
if (!match[3]) {
re.lastIndex = pushQBlock(pos, lastIndex, match[4]);
continue
}
}
if (!match[1]) {
unescapeStr(str.slice(start, pos));
start = re.lastIndex;
re = _bp[6 + (isexpr ^= 1)];
re.lastIndex = start;
}
}
if (str && start < str.length) {
unescapeStr(str.slice(start));
}
parts.qblocks = qblocks;
return parts
function unescapeStr (s) {
if (prevStr) {
s = prevStr + s;
prevStr = '';
}
if (tmpl || isexpr) {
parts.push(s && s.replace(_bp[5], '$1'));
} else {
parts.push(s);
}
}
function pushQBlock(_pos, _lastIndex, slash) { //eslint-disable-line
if (slash) {
_lastIndex = skipRegex(str, _pos);
}
if (tmpl && _lastIndex > _pos + 2) {
mark = '\u2057' + qblocks.length + '~';
qblocks.push(str.slice(_pos, _lastIndex));
prevStr += str.slice(start, _pos) + mark;
start = _lastIndex;
}
return _lastIndex
}
};
_brackets.hasExpr = function hasExpr (str) {
return _cache[4].test(str)
};
_brackets.loopKeys = function loopKeys (expr) {
var m = expr.match(_cache[9]);
return m
? { key: m[1], pos: m[2], val: _cache[0] + m[3].trim() + _cache[1] }
: { val: expr.trim() }
};
_brackets.array = function array (pair) {
return pair ? _create(pair) : _cache
};
function _reset (pair) {
if ((pair || (pair = DEFAULT)) !== _cache[8]) {
_cache = _create(pair);
_regex = pair === DEFAULT ? _loopback : _rewrite;
_cache[9] = _regex(_pairs[9]);
}
cachedBrackets = pair;
}
function _setSettings (o) {
var b;
o = o || {};
b = o.brackets;
Object.defineProperty(o, 'brackets', {
set: _reset,
get: function () { return cachedBrackets },
enumerable: true
});
_settings = o;
_reset(b);
}
Object.defineProperty(_brackets, 'settings', {
set: _setSettings,
get: function () { return _settings }
});
/* istanbul ignore next: in the browser riot is always in the scope */
_brackets.settings = typeof riot !== 'undefined' && riot.settings || {};
_brackets.set = _reset;
_brackets.skipRegex = skipRegex;
_brackets.R_STRINGS = R_STRINGS;
_brackets.R_MLCOMMS = R_MLCOMMS;
_brackets.S_QBLOCKS = S_QBLOCKS;
_brackets.S_QBLOCK2 = S_QBLOCK2;
return _brackets
})();
/**
* @module tmpl
*
* tmpl - Root function, returns the template value, render with data
* tmpl.hasExpr - Test the existence of a expression inside a string
* tmpl.loopKeys - Get the keys for an 'each' loop (used by `_each`)
*/
/* istanbul ignore next */
var tmpl = (function () {
var _cache = {};
function _tmpl (str, data) {
if (!str) { return str }
return (_cache[str] || (_cache[str] = _create(str))).call(
data, _logErr.bind({
data: data,
tmpl: str
})
)
}
_tmpl.hasExpr = brackets.hasExpr;
_tmpl.loopKeys = brackets.loopKeys;
// istanbul ignore next
_tmpl.clearCache = function () { _cache = {}; };
_tmpl.errorHandler = null;
function _logErr (err, ctx) {
err.riotData = {
tagName: ctx && ctx.__ && ctx.__.tagName,
_riot_id: ctx && ctx._riot_id //eslint-disable-line camelcase
};
if (_tmpl.errorHandler) { _tmpl.errorHandler(err); }
else if (
typeof console !== 'undefined' &&
typeof console.error === 'function'
) {
console.error(err.message);
console.log('<%s> %s', err.riotData.tagName || 'Unknown tag', this.tmpl); // eslint-disable-line
console.log(this.data); // eslint-disable-line
}
}
function _create (str) {
var expr = _getTmpl(str);
if (expr.slice(0, 11) !== 'try{return ') { expr = 'return ' + expr; }
return new Function('E', expr + ';') // eslint-disable-line no-new-func
}
var RE_DQUOTE = /\u2057/g;
var RE_QBMARK = /\u2057(\d+)~/g;
function _getTmpl (str) {
var parts = brackets.split(str.replace(RE_DQUOTE, '"'), 1);
var qstr = parts.qblocks;
var expr;
if (parts.length > 2 || parts[0]) {
var i, j, list = [];
for (i = j = 0; i < parts.length; ++i) {
expr = parts[i];
if (expr && (expr = i & 1
? _parseExpr(expr, 1, qstr)
: '"' + expr
.replace(/\\/g, '\\\\')
.replace(/\r\n?|\n/g, '\\n')
.replace(/"/g, '\\"') +
'"'
)) { list[j++] = expr; }
}
expr = j < 2 ? list[0]
: '[' + list.join(',') + '].join("")';
} else {
expr = _parseExpr(parts[1], 0, qstr);
}
if (qstr.length) {
expr = expr.replace(RE_QBMARK, function (_, pos) {
return qstr[pos]
.replace(/\r/g, '\\r')
.replace(/\n/g, '\\n')
});
}
return expr
}
var RE_CSNAME = /^(?:(-?[_A-Za-z\xA0-\xFF][-\w\xA0-\xFF]*)|\u2057(\d+)~):/;
var
RE_BREND = {
'(': /[()]/g,
'[': /[[\]]/g,
'{': /[{}]/g
};
function _parseExpr (expr, asText, qstr) {
expr = expr
.replace(/\s+/g, ' ').trim()
.replace(/\ ?([[\({},?\.:])\ ?/g, '$1');
if (expr) {
var
list = [],
cnt = 0,
match;
while (expr &&
(match = expr.match(RE_CSNAME)) &&
!match.index
) {
var
key,
jsb,
re = /,|([[{(])|$/g;
expr = RegExp.rightContext;
key = match[2] ? qstr[match[2]].slice(1, -1).trim().replace(/\s+/g, ' ') : match[1];
while (jsb = (match = re.exec(expr))[1]) { skipBraces(jsb, re); }
jsb = expr.slice(0, match.index);
expr = RegExp.rightContext;
list[cnt++] = _wrapExpr(jsb, 1, key);
}
expr = !cnt ? _wrapExpr(expr, asText)
: cnt > 1 ? '[' + list.join(',') + '].join(" ").trim()' : list[0];
}
return expr
function skipBraces (ch, re) {
var
mm,
lv = 1,
ir = RE_BREND[ch];
ir.lastIndex = re.lastIndex;
while (mm = ir.exec(expr)) {
if (mm[0] === ch) { ++lv; }
else if (!--lv) { break }
}
re.lastIndex = lv ? expr.length : ir.lastIndex;
}
}
// istanbul ignore next: not both
var // eslint-disable-next-line max-len
JS_CONTEXT = '"in this?this:' + (typeof window !== 'object' ? 'global' : 'window') + ').',
JS_VARNAME = /[,{][\$\w]+(?=:)|(^ *|[^$\w\.{])(?!(?:typeof|true|false|null|undefined|in|instanceof|is(?:Finite|NaN)|void|NaN|new|Date|RegExp|Math)(?![$\w]))([$_A-Za-z][$\w]*)/g,
JS_NOPROPS = /^(?=(\.[$\w]+))\1(?:[^.[(]|$)/;
function _wrapExpr (expr, asText, key) {
var tb;
expr = expr.replace(JS_VARNAME, function (match, p, mvar, pos, s) {
if (mvar) {
pos = tb ? 0 : pos + match.length;