-
Notifications
You must be signed in to change notification settings - Fork 1
/
riot+compiler.js
2859 lines (2340 loc) · 73.9 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 v2.3.1, @license MIT, (c) 2015 Muut Inc. + contributors */
;(function(window, undefined) {
'use strict';
var riot = { version: 'v2.3.1', settings: {} },
// be aware, internal usage
// ATTENTION: prefix the global dynamic variables with `__`
// counter to give a unique id to all the Tag instances
__uid = 0,
// tags instances cache
__virtualDom = [],
// tags implementation cache
__tagImpl = {},
/**
* Const
*/
// riot specific prefixes
RIOT_PREFIX = 'riot-',
RIOT_TAG = RIOT_PREFIX + 'tag',
// for typeof == '' comparisons
T_STRING = 'string',
T_OBJECT = 'object',
T_UNDEF = 'undefined',
T_FUNCTION = 'function',
// special native tags that cannot be treated like the others
SPECIAL_TAGS_REGEX = /^(?:opt(ion|group)|tbody|col|t[rhd])$/,
RESERVED_WORDS_BLACKLIST = ['_item', '_id', '_parent', 'update', 'root', 'mount', 'unmount', 'mixin', 'isMounted', 'isLoop', 'tags', 'parent', 'opts', 'trigger', 'on', 'off', 'one'],
// version# for IE 8-11, 0 for others
IE_VERSION = (window && window.document || {}).documentMode | 0
/* istanbul ignore next */
riot.observable = function(el) {
/**
* Extend the original object or create a new empty one
* @type { Object }
*/
el = el || {}
/**
* Private variables and methods
*/
var callbacks = {},
onEachEvent = function(e, fn) { e.replace(/\S+/g, fn) },
defineProperty = function (key, value) {
Object.defineProperty(el, key, {
value: value,
enumerable: false,
writable: false,
configurable: false
})
}
/**
* Listen to the given space separated list of `events` and execute the `callback` each time an event is triggered.
* @param { String } events - events ids
* @param { Function } fn - callback function
* @returns { Object } el
*/
defineProperty('on', function(events, fn) {
if (typeof fn != 'function') return el
onEachEvent(events, function(name, pos) {
(callbacks[name] = callbacks[name] || []).push(fn)
fn.typed = pos > 0
})
return el
})
/**
* Removes the given space separated list of `events` listeners
* @param { String } events - events ids
* @param { Function } fn - callback function
* @returns { Object } el
*/
defineProperty('off', function(events, fn) {
if (events == '*') callbacks = {}
else {
onEachEvent(events, function(name) {
if (fn) {
var arr = callbacks[name]
for (var i = 0, cb; cb = arr && arr[i]; ++i) {
if (cb == fn) arr.splice(i--, 1)
}
} else delete callbacks[name]
})
}
return el
})
/**
* Listen to the given space separated list of `events` and execute the `callback` at most once
* @param { String } events - events ids
* @param { Function } fn - callback function
* @returns { Object } el
*/
defineProperty('one', function(events, fn) {
function on() {
el.off(events, on)
fn.apply(el, arguments)
}
return el.on(events, on)
})
/**
* Execute all callback functions that listen to the given space separated list of `events`
* @param { String } events - events ids
* @returns { Object } el
*/
defineProperty('trigger', function(events) {
// getting the arguments
// skipping the first one
var arglen = arguments.length - 1,
args = new Array(arglen)
for (var i = 0; i < arglen; i++) {
args[i] = arguments[i + 1]
}
onEachEvent(events, function(name) {
var fns = (callbacks[name] || []).slice(0)
for (var i = 0, fn; fn = fns[i]; ++i) {
if (fn.busy) return
fn.busy = 1
try {
fn.apply(el, fn.typed ? [name].concat(args) : args)
} catch (e) { /* error */}
if (fns[i] !== fn) { i-- }
fn.busy = 0
}
if (callbacks.all && name != 'all')
el.trigger.apply(el, ['all', name].concat(args))
})
return el
})
return el
}
/* istanbul ignore next */
;(function(riot) { if (!window) return;
/**
* Simple client-side router
* @module riot-route
*/
var RE_ORIGIN = /^.+?\/+[^\/]+/,
EVENT_LISTENER = 'EventListener',
REMOVE_EVENT_LISTENER = 'remove' + EVENT_LISTENER,
ADD_EVENT_LISTENER = 'add' + EVENT_LISTENER,
HAS_ATTRIBUTE = 'hasAttribute',
REPLACE = 'replace',
POPSTATE = 'popstate',
TRIGGER = 'trigger',
MAX_EMIT_STACK_LEVEL = 3,
win = window,
doc = document,
loc = win.history.location || win.location, // see html5-history-api
prot = Router.prototype, // to minify more
clickEvent = doc && doc.ontouchstart ? 'touchstart' : 'click',
started = false,
central = riot.observable(),
base, current, parser, secondParser, emitStack = [], emitStackLevel = 0
/**
* Default parser. You can replace it via router.parser method.
* @param {string} path - current path (normalized)
* @returns {array} array
*/
function DEFAULT_PARSER(path) {
return path.split(/[/?#]/)
}
/**
* Default parser (second). You can replace it via router.parser method.
* @param {string} path - current path (normalized)
* @param {string} filter - filter string (normalized)
* @returns {array} array
*/
function DEFAULT_SECOND_PARSER(path, filter) {
var re = new RegExp('^' + filter[REPLACE](/\*/g, '([^/?#]+?)')[REPLACE](/\.\./, '.*') + '$'),
args = path.match(re)
if (args) return args.slice(1)
}
/**
* Router class
*/
function Router() {
this.$ = []
riot.observable(this) // make it observable
central.on('stop', this.s.bind(this))
central.on('emit', this.e.bind(this))
}
function normalize(path) {
return path[REPLACE](/^\/|\/$/, '')
}
function isString(str) {
return typeof str == 'string'
}
/**
* Get the part after domain name
* @param {string} href - fullpath
* @returns {string} path from root
*/
function getPathFromRoot(href) {
return (href || loc.href)[REPLACE](RE_ORIGIN, '')
}
/**
* Get the part after base
* @param {string} href - fullpath
* @returns {string} path from base
*/
function getPathFromBase(href) {
return base[0] == '#'
? (href || loc.href).split(base)[1] || ''
: getPathFromRoot(href)[REPLACE](base, '')
}
function emit(force) {
// the stack is needed for redirections
var isRoot = emitStackLevel == 0
if (MAX_EMIT_STACK_LEVEL <= emitStackLevel) return
emitStackLevel++
emitStack.push(function() {
var path = getPathFromBase()
if (force || path != current) {
central[TRIGGER]('emit', path)
current = path
}
})
if (isRoot) {
while (emitStack.length) {
emitStack[0]()
emitStack.shift()
}
emitStackLevel = 0
}
}
function click(e) {
if (
e.which != 1 // not left click
|| e.metaKey || e.ctrlKey || e.shiftKey // or meta keys
|| e.defaultPrevented // or default prevented
) return
var el = e.target
while (el && el.nodeName != 'A') el = el.parentNode
if (
!el || el.nodeName != 'A' // not A tag
|| el[HAS_ATTRIBUTE]('download') // has download attr
|| !el[HAS_ATTRIBUTE]('href') // has no href attr
|| el.target && el.target != '_self' // another window or frame
|| el.href.indexOf(loc.href.match(RE_ORIGIN)[0]) == -1 // cross origin
) return
if (el.href != loc.href) {
if (el.href.split('#')[0] == loc.href.split('#')[0]) return // internal jump
go(getPathFromBase(el.href), el.title || doc.title)
}
e.preventDefault()
}
/**
* Go to the path
* @param {string} path - destination path
* @param {string} title - page title
*/
function go(path, title) {
title = title || doc.title
// browsers ignores the second parameter `title`
history.pushState(null, title, base + normalize(path))
// so we need to set it manually
doc.title = title
emit()
}
/**
* Go to path or set action
* a single string: go there
* two strings: go there with setting a title
* a single function: set an action on the default route
* a string/RegExp and a function: set an action on the route
* @param {(string|function)} first - path / action / filter
* @param {(string|RegExp|function)} second - title / action
*/
prot.m = function(first, second) {
if (isString(first) && (!second || isString(second))) go(first, second)
else if (second) this.r(first, second)
else this.r('@', first)
}
/**
* Stop routing
*/
prot.s = function() {
this.off('*')
this.$ = []
}
/**
* Emit
* @param {string} path - path
*/
prot.e = function(path) {
this.$.concat('@').some(function(filter) {
var args = (filter == '@' ? parser : secondParser)(normalize(path), normalize(filter))
if (args) {
this[TRIGGER].apply(null, [filter].concat(args))
return true // exit from loop
}
}, this)
}
/**
* Register route
* @param {string} filter - filter for matching to url
* @param {function} action - action to register
*/
prot.r = function(filter, action) {
if (filter != '@') {
filter = '/' + normalize(filter)
this.$.push(filter)
}
this.on(filter, action)
}
var mainRouter = new Router()
var route = mainRouter.m.bind(mainRouter)
/**
* Create a sub router
* @returns {function} the method of a new Router object
*/
route.create = function() {
var newSubRouter = new Router()
// stop only this sub-router
newSubRouter.m.stop = newSubRouter.s.bind(newSubRouter)
// return sub-router's main method
return newSubRouter.m.bind(newSubRouter)
}
/**
* Set the base of url
* @param {(str|RegExp)} arg - a new base or '#' or '#!'
*/
route.base = function(arg) {
base = arg || '#'
current = getPathFromBase() // recalculate current path
}
/** Exec routing right now **/
route.exec = function() {
emit(true)
}
/**
* Replace the default router to yours
* @param {function} fn - your parser function
* @param {function} fn2 - your secondParser function
*/
route.parser = function(fn, fn2) {
if (!fn && !fn2) {
// reset parser for testing...
parser = DEFAULT_PARSER
secondParser = DEFAULT_SECOND_PARSER
}
if (fn) parser = fn
if (fn2) secondParser = fn2
}
/**
* Helper function to get url query as an object
* @returns {object} parsed query
*/
route.query = function() {
var q = {}
loc.href[REPLACE](/[?&](.+?)=([^&]*)/g, function(_, k, v) { q[k] = v })
return q
}
/** Stop routing **/
route.stop = function () {
if (started) {
win[REMOVE_EVENT_LISTENER](POPSTATE, emit)
doc[REMOVE_EVENT_LISTENER](clickEvent, click)
central[TRIGGER]('stop')
started = false
}
}
/**
* Start routing
* @param {boolean} autoExec - automatically exec after starting if true
*/
route.start = function (autoExec) {
if (!started) {
win[ADD_EVENT_LISTENER](POPSTATE, emit)
doc[ADD_EVENT_LISTENER](clickEvent, click)
started = true
}
if (autoExec) emit(true)
}
/** Prepare the router **/
route.base()
route.parser()
riot.route = route
})(riot)
/* istanbul ignore next */
/**
* The riot template engine
* @version 2.3.0
*/
/**
* @module brackets
*
* `brackets ` Returns a string or regex based on its parameter:
* With a number returns the current left (0) or right (1) brackets.
* With a regex, returns the original regex if the current brackets
* are the default, or a new one with the default brackets replaced
* by the current custom brackets.
* WARNING: recreated regexes discards the `/i` and `/m` flags.
* `brackets.settings` This object mirrors the `riot.settings` object, you can assign this
* if riot is not in context.
* `brackets.set ` The recommended option to change the current tiot brackets, check
* its parameter and reconfigures the internal state immediately.
*/
var brackets = (function (UNDEF) {
var
REGLOB = 'g',
MLCOMMS = /\/\*[^*]*\*+(?:[^*\/][^*]*\*+)*\//g,
STRINGS = /"[^"\\]*(?:\\[\S\s][^"\\]*)*"|'[^'\\]*(?:\\[\S\s][^'\\]*)*'/g,
S_QBSRC = STRINGS.source + '|' +
/(?:[$\w\)\]]|\+\+|--)\s*(\/)(?![*\/])/.source + '|' +
/\/(?=[^*\/])[^[\/\\]*(?:(?:\[(?:\\.|[^\]\\]*)*\]|\\.)[^[\/\\]*)*?(\/)[gim]*/.source,
DEFAULT = '{ }',
FINDBRACES = {
'(': _regExp('([()])|' + S_QBSRC, REGLOB),
'[': _regExp('([[\\]])|' + S_QBSRC, REGLOB),
'{': _regExp('([{}])|' + S_QBSRC, REGLOB)
}
var
cachedBrackets = UNDEF,
_regex,
_pairs = []
function _regExp(source, flags) { return new RegExp(source, flags) }
function _loopback(re) { return re }
function _rewrite(re) {
return new RegExp(
re.source.replace(/{/g, _pairs[2]).replace(/}/g, _pairs[3]), re.global ? REGLOB : ''
)
}
function _reset(pair) {
pair = pair || DEFAULT
if (pair !== _pairs[8]) {
var bp = pair.split(' ')
if (pair === DEFAULT) {
_pairs = bp.concat(bp)
_regex = _loopback
}
else {
if (bp.length !== 2 || /[\x00-\x1F<>a-zA-Z0-9'",;\\]/.test(pair)) {
throw new Error('Unsupported brackets "' + pair + '"')
}
_pairs = bp.concat(pair.replace(/(?=[[\]()*+?.^$|])/g, '\\').split(' '))
_regex = _rewrite
}
_pairs[4] = _regex(_pairs[1].length > 1 ? /(?:^|[^\\]){[\S\s]*?}/ : /(?:^|[^\\]){[^}]*}/)
_pairs[5] = _regex(/\\({|})/g)
_pairs[6] = _regex(/(\\?)({)/g)
_pairs[7] = _regExp('(\\\\?)(?:([[({])|(' + _pairs[3] + '))|' + S_QBSRC, REGLOB)
_pairs[9] = _regExp(/^\s*{\^?\s*([$\w]+)(?:\s*,\s*(\S+))?\s+in\s+(\S+)\s*}/)
_pairs[8] = pair
}
_brackets.settings.brackets = cachedBrackets = pair
}
function _set(pair) {
if (cachedBrackets !== pair) {
_reset(pair)
}
}
function _brackets(reOrIdx) {
_set(_brackets.settings.brackets)
return reOrIdx instanceof RegExp ? _regex(reOrIdx) : _pairs[reOrIdx]
}
_brackets.split = function split(str, tmpl) {
var
parts = [],
match,
isexpr,
start,
pos,
re = _brackets(6)
isexpr = start = re.lastIndex = 0
while (match = re.exec(str)) {
pos = match.index
if (isexpr) {
if (match[2]) {
re.lastIndex = skipBraces(match[2], re.lastIndex)
continue
}
if (!match[3])
continue
}
if (!match[1]) {
unescapeStr(str.slice(start, pos))
start = re.lastIndex
re = _pairs[6 + (isexpr ^= 1)]
re.lastIndex = start
}
}
if (str && start < str.length) {
unescapeStr(str.slice(start))
}
return parts
function unescapeStr(str) {
if (tmpl || isexpr)
parts.push(str && str.replace(_pairs[5], '$1'))
else
parts.push(str)
}
function skipBraces(ch, pos) {
var
match,
recch = FINDBRACES[ch],
level = 1
recch.lastIndex = pos
while (match = recch.exec(str)) {
if (match[1] &&
!(match[1] === ch ? ++level : --level)) break
}
return match ? recch.lastIndex : str.length
}
}
_brackets.hasExpr = function hasExpr(str) {
return _brackets(4).test(str)
}
_brackets.loopKeys = function loopKeys(expr) {
var m = expr.match(_brackets(9))
return m ?
{ key: m[1], pos: m[2], val: _pairs[0] + m[3] + _pairs[1] } : { val: expr.trim() }
}
_brackets.array = function array(pair) {
if (pair != null) _reset(pair)
return _pairs
}
/* istanbul ignore next: in the node version riot is not in the scope */
_brackets.settings = typeof riot !== 'undefined' && riot.settings || {}
_brackets.set = _set
_brackets.R_STRINGS = STRINGS
_brackets.R_MLCOMMS = MLCOMMS
_brackets.S_QBLOCKS = S_QBSRC
_reset(_brackets.settings.brackets)
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`)
*/
var tmpl = (function () {
var
FALSE = !1,
_cache = {}
function _tmpl(str, data) {
if (!str) return str
return (_cache[str] || (_cache[str] = _create(str))).call(data, _logErr)
}
_tmpl.hasExpr = brackets.hasExpr
_tmpl.loopKeys = brackets.loopKeys
_tmpl.errorHandler = FALSE
function _logErr(err, ctx) {
if (_tmpl.errorHandler) {
err.riotData = {
tagName: ctx && ctx.root && ctx.root.tagName,
_riot_id: ctx && ctx._riot_id //eslint-disable-line camelcase
}
_tmpl.errorHandler(err)
}
}
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 indent
}
var
RE_QBLOCK = new RegExp(brackets.S_QBLOCKS, 'g'),
RE_QBMARK = /\x01(\d+)~/g
function _getTmpl(str) {
var
qstr = [],
expr,
parts = brackets.split(str, 1)
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[0])
expr = expr.replace(RE_QBMARK, function (_, pos) {
return qstr[pos]
.replace(/\r/g, '\\r')
.replace(/\n/g, '\\n')
})
return expr
}
var
CS_IDENT = /^(?:(-?[_A-Za-z\xA0-\xFF][-\w\xA0-\xFF]*)|\x01(\d+)~):/,
RE_BRACE = /,|([[{(])|$/g
function _parseExpr(expr, asText, qstr) {
expr = expr
.replace(RE_QBLOCK, function (s, div) {
return s.length > 2 && !div ? '\x01' + (qstr.push(s) - 1) + '~' : s
})
.replace(/\s+/g, ' ').trim()
.replace(/\ ?([[\({},?\.:])\ ?/g, '$1')
if (expr) {
var
list = [],
cnt = 0,
match
while (expr &&
(match = expr.match(CS_IDENT)) &&
!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(jsb, re) {
var
match,
lv = 1,
ir = jsb === '(' ? /[()]/g : jsb === '[' ? /[[\]]/g : /[{}]/g
ir.lastIndex = re.lastIndex
while (match = ir.exec(expr)) {
if (match[0] === jsb) ++lv
else if (!--lv) break
}
re.lastIndex = lv ? expr.length : ir.lastIndex
}
}
// istanbul ignore next: not both
var JS_CONTEXT = '"in this?this:' + (typeof window !== 'object' ? 'global' : 'window') + ').'
var 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
function _wrapExpr(expr, asText, key) {
var tb = FALSE
expr = expr.replace(JS_VARNAME, function (match, p, mvar, pos, s) {
if (mvar) {
pos = tb ? 0 : pos + match.length
if (mvar !== 'this' && mvar !== 'global' && mvar !== 'window') {
match = p + '("' + mvar + JS_CONTEXT + mvar
if (pos) tb = (s = s[pos]) === '.' || s === '(' || s === '['
}
else if (pos)
tb = !/^(?=(\.[$\w]+))\1(?:[^.[(]|$)/.test(s.slice(pos))
}
return match
})
if (tb) {
expr = "try{return " + expr + '}catch(e){E(e,this)}'
}
if (key) {
expr = (tb ?
'function(){' + expr + '}.call(this)' : '(' + expr + ')'
) + '?"' + key + '":""'
}
else if (asText) {
expr = 'function(v){' + (tb ?
expr.replace('return ', 'v=') : 'v=(' + expr + ')'
) + ';return v||v===0?v:""}.call(this)'
}
return expr
}
// istanbul ignore next: compatibility fix for beta versions
_tmpl.parse = function (s) { return s }
return _tmpl
})()
/*
lib/browser/tag/mkdom.js
Includes hacks needed for the Internet Explorer version 9 and bellow
*/
// http://kangax.github.io/compat-table/es5/#ie8
// http://codeplanet.io/dropping-ie8/
var mkdom = (function (checkIE) {
var rootEls = {
'tr': 'tbody',
'th': 'tr',
'td': 'tr',
'tbody': 'table',
'col': 'colgroup'
},
GENERIC = 'div'
checkIE = checkIE && checkIE < 10
// creates any dom element in a div, table, or colgroup container
function _mkdom(html) {
var match = html && html.match(/^\s*<([-\w]+)/),
tagName = match && match[1].toLowerCase(),
rootTag = rootEls[tagName] || GENERIC,
el = mkEl(rootTag)
el.stub = true
/* istanbul ignore next */
if (checkIE && tagName && (match = tagName.match(SPECIAL_TAGS_REGEX)))
ie9elem(el, html, tagName, !!match[1])
else
el.innerHTML = html
return el
}
// creates tr, th, td, option, optgroup element for IE8-9
/* istanbul ignore next */
function ie9elem(el, html, tagName, select) {
var div = mkEl(GENERIC),
tag = select ? 'select>' : 'table>',
child
div.innerHTML = '<' + tag + html + '</' + tag
child = $(tagName, div)
if (child)
el.appendChild(child)
}
// end ie9elem()
return _mkdom
})(IE_VERSION)
/**
* Convert the item looped into an object used to extend the child tag properties
* @param { Object } expr - object containing the keys used to extend the children tags
* @param { * } key - value to assign to the new object returned
* @param { * } val - value containing the position of the item in the array
* @returns { Object } - new object containing the values of the original item
*
* The variables 'key' and 'val' are arbitrary.
* They depend on the collection type looped (Array, Object)
* and on the expression used on the each tag
*
*/
function mkitem(expr, key, val) {
var item = {}
item[expr.key] = key
if (expr.pos) item[expr.pos] = val
return item
}
/**
* Unmount the redundant tags
* @param { Array } items - array containing the current items to loop
* @param { Array } tags - array containing all the children tags
*/
function unmountRedundant(items, tags) {
var i = tags.length,
j = items.length
while (i > j) {
var t = tags[--i]
tags.splice(i, 1)
t.unmount()
}
}
/**
* Move the nested custom tags in non custom loop tags
* @param { Object } child - non custom loop tag
* @param { Number } i - current position of the loop tag
*/
function moveNestedTags(child, i) {
Object.keys(child.tags).forEach(function(tagName) {
var tag = child.tags[tagName]
if (isArray(tag))
each(tag, function (t) {
moveChildTag(t, tagName, i)
})
else
moveChildTag(tag, tagName, i)
})
}
/**
* Adds the elements for a virtual tag
* @param { Tag } tag - the tag whose root's children will be inserted or appended
* @param { Node } src - the node that will do the inserting or appending
* @param { Tag } target - only if inserting, insert before this tag's first child
*/
function addVirtual(tag, src, target) {
var el = tag._root
tag._virts = []
while (el) {
var sib = el.nextSibling
if (target)
src.insertBefore(el, target._root)
else
src.appendChild(el)
tag._virts.push(el) // hold for unmounting
el = sib
}
}
/**
* Move virtual tag and all child nodes
* @param { Tag } tag - first child reference used to start move
* @param { Node } src - the node that will do the inserting
* @param { Tag } target - insert before this tag's first child
* @param { Number } len - how many child nodes to move
*/
function moveVirtual(tag, src, target, len) {
var el = tag._root
for (var i = 0; i < len; i++) {
var sib = el.nextSibling
src.insertBefore(el, target._root)
el = sib
}
}
/**
* Manage tags having the 'each'
* @param { Object } dom - DOM node we need to loop
* @param { Tag } parent - parent tag instance where the dom node is contained
* @param { String } expr - string contained in the 'each' attribute
*/
function _each(dom, parent, expr) {
// remove the each property from the original tag
remAttr(dom, 'each')
var mustReorder = typeof getAttr(dom, 'no-reorder') !== T_STRING || remAttr(dom, 'no-reorder'),
tagName = getTagName(dom),
impl = __tagImpl[tagName] || { tmpl: dom.outerHTML },
useRoot = SPECIAL_TAGS_REGEX.test(tagName),
root = dom.parentNode,
isSpecialTag = SPECIAL_TAGS_REGEX.test(tagName),
ref = document.createTextNode(''),
child = getTag(dom),
tags = [],
oldItems = [],
checksum,