forked from riot/riot
-
Notifications
You must be signed in to change notification settings - Fork 0
/
riot+compiler.js
1727 lines (1330 loc) · 42.4 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.2.2, @license MIT, (c) 2015 Muut Inc. + contributors */
;(function(window, undefined) {
'use strict'
var riot = { version: 'v2.2.2', settings: {} }
// This globals 'const' helps code size reduction
// for typeof == '' comparisons
var T_STRING = 'string',
T_OBJECT = 'object',
T_UNDEF = 'undefined'
// for IE8 and rest of the world
/* istanbul ignore next */
var isArray = Array.isArray || (function () {
var _ts = Object.prototype.toString
return function (v) { return _ts.call(v) === '[object Array]' }
})()
// Version# for IE 8-11, 0 for others
var ieVersion = (function (win) {
return (window && window.document || {}).documentMode | 0
})()
riot.observable = function(el) {
el = el || {}
var callbacks = {},
_id = 0
el.on = function(events, fn) {
if (isFunction(fn)) {
if (typeof fn.id === T_UNDEF) fn._id = _id++
events.replace(/\S+/g, function(name, pos) {
(callbacks[name] = callbacks[name] || []).push(fn)
fn.typed = pos > 0
})
}
return el
}
el.off = function(events, fn) {
if (events == '*') callbacks = {}
else {
events.replace(/\S+/g, function(name) {
if (fn) {
var arr = callbacks[name]
for (var i = 0, cb; (cb = arr && arr[i]); ++i) {
if (cb._id == fn._id) arr.splice(i--, 1)
}
} else {
callbacks[name] = []
}
})
}
return el
}
// only single event supported
el.one = function(name, fn) {
function on() {
el.off(name, on)
fn.apply(el, arguments)
}
return el.on(name, on)
}
el.trigger = function(name) {
var args = [].slice.call(arguments, 1),
fns = callbacks[name] || []
for (var i = 0, fn; (fn = fns[i]); ++i) {
if (!fn.busy) {
fn.busy = 1
fn.apply(el, fn.typed ? [name].concat(args) : args)
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
}
riot.mixin = (function() {
var mixins = {}
return function(name, mixin) {
if (!mixin) return mixins[name]
mixins[name] = mixin
}
})()
;(function(riot, evt, win) {
// browsers only
if (!win) return
var loc = win.location,
fns = riot.observable(),
started = false,
current
function hash() {
return loc.href.split('#')[1] || ''
}
function parser(path) {
return path.split('/')
}
function emit(path) {
if (path.type) path = hash()
if (path != current) {
fns.trigger.apply(null, ['H'].concat(parser(path)))
current = path
}
}
var r = riot.route = function(arg) {
// string
if (arg[0]) {
loc.hash = arg
emit(arg)
// function
} else {
fns.on('H', arg)
}
}
r.exec = function(fn) {
fn.apply(null, parser(hash()))
}
r.parser = function(fn) {
parser = fn
}
r.stop = function () {
if (!started) return
win.removeEventListener ? win.removeEventListener(evt, emit, false) : win.detachEvent('on' + evt, emit)
fns.off('*')
started = false
}
r.start = function () {
if (started) return
win.addEventListener ? win.addEventListener(evt, emit, false) : win.attachEvent('on' + evt, emit)
started = true
}
// autostart the router
r.start()
})(riot, 'hashchange', window)
/*
//// How it works?
Three ways:
1. Expressions: tmpl('{ value }', data).
Returns the result of evaluated expression as a raw object.
2. Templates: tmpl('Hi { name } { surname }', data).
Returns a string with evaluated expressions.
3. Filters: tmpl('{ show: !done, highlight: active }', data).
Returns a space separated list of trueish keys (mainly
used for setting html classes), e.g. "show highlight".
// Template examples
tmpl('{ title || "Untitled" }', data)
tmpl('Results are { results ? "ready" : "loading" }', data)
tmpl('Today is { new Date() }', data)
tmpl('{ message.length > 140 && "Message is too long" }', data)
tmpl('This item got { Math.round(rating) } stars', data)
tmpl('<h1>{ title }</h1>{ body }', data)
// Falsy expressions in templates
In templates (as opposed to single expressions) all falsy values
except zero (undefined/null/false) will default to empty string:
tmpl('{ undefined } - { false } - { null } - { 0 }', {})
// will return: " - - - 0"
*/
var brackets = (function(orig) {
var cachedBrackets,
r,
b,
re = /[{}]/g
return function(x) {
// make sure we use the current setting
var s = riot.settings.brackets || orig
// recreate cached vars if needed
if (cachedBrackets !== s) {
cachedBrackets = s
b = s.split(' ')
r = b.map(function (e) { return e.replace(/(?=.)/g, '\\') })
}
// if regexp given, rewrite it with current brackets (only if differ from default)
return x instanceof RegExp ? (
s === orig ? x :
new RegExp(x.source.replace(re, function(b) { return r[~~(b === '}')] }), x.global ? 'g' : '')
) :
// else, get specific bracket
b[x]
}
})('{ }')
var tmpl = (function() {
var cache = {},
reVars = /(['"\/]).*?[^\\]\1|\.\w*|\w*:|\b(?:(?:new|typeof|in|instanceof) |(?:this|true|false|null|undefined)\b|function *\()|([a-z_$]\w*)/gi
// [ 1 ][ 2 ][ 3 ][ 4 ][ 5 ]
// find variable names:
// 1. skip quoted strings and regexps: "a b", 'a b', 'a \'b\'', /a b/
// 2. skip object properties: .name
// 3. skip object literals: name:
// 4. skip javascript keywords
// 5. match var name
// build a template (or get it from cache), render with data
return function(str, data) {
return str && (cache[str] = cache[str] || tmpl(str))(data)
}
// create a template instance
function tmpl(s, p) {
// default template string to {}
s = (s || (brackets(0) + brackets(1)))
// temporarily convert \{ and \} to a non-character
.replace(brackets(/\\{/g), '\uFFF0')
.replace(brackets(/\\}/g), '\uFFF1')
// split string to expression and non-expresion parts
p = split(s, extract(s, brackets(/{/), brackets(/}/)))
return new Function('d', 'return ' + (
// is it a single expression or a template? i.e. {x} or <b>{x}</b>
!p[0] && !p[2] && !p[3]
// if expression, evaluate it
? expr(p[1])
// if template, evaluate all expressions in it
: '[' + p.map(function(s, i) {
// is it an expression or a string (every second part is an expression)
return i % 2
// evaluate the expressions
? expr(s, true)
// process string parts of the template:
: '"' + s
// preserve new lines
.replace(/\n/g, '\\n')
// escape quotes
.replace(/"/g, '\\"')
+ '"'
}).join(',') + '].join("")'
)
// bring escaped { and } back
.replace(/\uFFF0/g, brackets(0))
.replace(/\uFFF1/g, brackets(1))
+ ';')
}
// parse { ... } expression
function expr(s, n) {
s = s
// convert new lines to spaces
.replace(/\n/g, ' ')
// trim whitespace, brackets, strip comments
.replace(brackets(/^[{ ]+|[ }]+$|\/\*.+?\*\//g), '')
// is it an object literal? i.e. { key : value }
return /^\s*[\w- "']+ *:/.test(s)
// if object literal, return trueish keys
// e.g.: { show: isOpen(), done: item.done } -> "show done"
? '[' +
// extract key:val pairs, ignoring any nested objects
extract(s,
// name part: name:, "name":, 'name':, name :
/["' ]*[\w- ]+["' ]*:/,
// expression part: everything upto a comma followed by a name (see above) or end of line
/,(?=["' ]*[\w- ]+["' ]*:)|}|$/
).map(function(pair) {
// get key, val parts
return pair.replace(/^[ "']*(.+?)[ "']*: *(.+?),? *$/, function(_, k, v) {
// wrap all conditional parts to ignore errors
return v.replace(/[^&|=!><]+/g, wrap) + '?"' + k + '":"",'
})
}).join('')
+ '].join(" ").trim()'
// if js expression, evaluate as javascript
: wrap(s, n)
}
// execute js w/o breaking on errors or undefined vars
function wrap(s, nonull) {
s = s.trim()
return !s ? '' : '(function(v){try{v='
// prefix vars (name => data.name)
+ (s.replace(reVars, function(s, _, v) { return v ? '(d.'+v+'===undefined?'+(typeof window == 'undefined' ? 'global.' : 'window.')+v+':d.'+v+')' : s })
// break the expression if its empty (resulting in undefined value)
|| 'x')
+ '}catch(e){'
+ '}finally{return '
// default to empty string for falsy values except zero
+ (nonull === true ? '!v&&v!==0?"":v' : 'v')
+ '}}).call(d)'
}
// split string by an array of substrings
function split(str, substrings) {
var parts = []
substrings.map(function(sub, i) {
// push matched expression and part before it
i = str.indexOf(sub)
parts.push(str.slice(0, i), sub)
str = str.slice(i + sub.length)
})
// push the remaining part
return parts.concat(str)
}
// match strings between opening and closing regexp, skipping any inner/nested matches
function extract(str, open, close) {
var start,
level = 0,
matches = [],
re = new RegExp('('+open.source+')|('+close.source+')', 'g')
str.replace(re, function(_, open, close, pos) {
// if outer inner bracket, mark position
if (!level && open) start = pos
// in(de)crease bracket level
level += open ? 1 : -1
// if outer closing bracket, grab the match
if (!level && close != null) matches.push(str.slice(start, pos+close.length))
})
return matches
}
})()
// { key, i in items} -> { key, i, items }
function loopKeys(expr) {
var b0 = brackets(0),
els = expr.slice(b0.length).match(/^\s*(\S+?)\s*(?:,\s*(\S+))?\s+in\s+(.+)$/)
return els ? { key: els[1], pos: els[2], val: b0 + els[3] } : { val: expr }
}
function mkitem(expr, key, val) {
var item = {}
item[expr.key] = key
if (expr.pos) item[expr.pos] = val
return item
}
/* Beware: heavy stuff */
function _each(dom, parent, expr) {
remAttr(dom, 'each')
var tagName = getTagName(dom),
template = dom.outerHTML,
hasImpl = !!tagImpl[tagName],
impl = tagImpl[tagName] || {
tmpl: template
},
root = dom.parentNode,
placeholder = document.createComment('riot placeholder'),
tags = [],
child = getTag(dom),
checksum
root.insertBefore(placeholder, dom)
expr = loopKeys(expr)
// clean template code
parent
.one('premount', function () {
if (root.stub) root = parent.root
// remove the original DOM node
dom.parentNode.removeChild(dom)
})
.on('update', function () {
var items = tmpl(expr.val, parent)
// object loop. any changes cause full redraw
if (!isArray(items)) {
checksum = items ? JSON.stringify(items) : ''
items = !items ? [] :
Object.keys(items).map(function (key) {
return mkitem(expr, key, items[key])
})
}
var frag = document.createDocumentFragment(),
i = tags.length,
j = items.length
// unmount leftover items
while (i > j) {
tags[--i].unmount()
tags.splice(i, 1)
}
for (i = 0; i < j; ++i) {
var _item = !checksum && !!expr.key ? mkitem(expr, items[i], i) : items[i]
if (!tags[i]) {
// mount new
(tags[i] = new Tag(impl, {
parent: parent,
isLoop: true,
hasImpl: hasImpl,
root: hasImpl ? dom.cloneNode() : root,
item: _item
}, dom.innerHTML)
).mount()
frag.appendChild(tags[i].root)
} else
tags[i].update(_item)
tags[i]._item = _item
}
root.insertBefore(frag, placeholder)
if (child) parent.tags[tagName] = tags
}).one('updated', function() {
var keys = Object.keys(parent)// only set new values
walk(root, function(node) {
// only set element node and not isLoop
if (node.nodeType == 1 && !node.isLoop && !node._looped) {
node._visited = false // reset _visited for loop node
node._looped = true // avoid set multiple each
setNamed(node, parent, keys)
}
})
})
}
function parseNamedElements(root, parent, childTags) {
walk(root, function(dom) {
if (dom.nodeType == 1) {
dom.isLoop = dom.isLoop || (dom.parentNode && dom.parentNode.isLoop || dom.getAttribute('each')) ? 1 : 0
// custom child tag
var child = getTag(dom)
if (child && !dom.isLoop) {
var tag = new Tag(child, { root: dom, parent: parent }, dom.innerHTML),
tagName = getTagName(dom),
ptag = parent,
cachedTag
while (!getTag(ptag.root)) {
if (!ptag.parent) break
ptag = ptag.parent
}
// fix for the parent attribute in the looped elements
tag.parent = ptag
cachedTag = ptag.tags[tagName]
// if there are multiple children tags having the same name
if (cachedTag) {
// if the parent tags property is not yet an array
// create it adding the first cached tag
if (!isArray(cachedTag))
ptag.tags[tagName] = [cachedTag]
// add the new nested tag to the array
ptag.tags[tagName].push(tag)
} else {
ptag.tags[tagName] = tag
}
// empty the child node once we got its template
// to avoid that its children get compiled multiple times
dom.innerHTML = ''
childTags.push(tag)
}
if (!dom.isLoop)
setNamed(dom, parent, [])
}
})
}
function parseExpressions(root, tag, expressions) {
function addExpr(dom, val, extra) {
if (val.indexOf(brackets(0)) >= 0) {
var expr = { dom: dom, expr: val }
expressions.push(extend(expr, extra))
}
}
walk(root, function(dom) {
var type = dom.nodeType
// text node
if (type == 3 && dom.parentNode.tagName != 'STYLE') addExpr(dom, dom.nodeValue)
if (type != 1) return
/* element */
// loop
var attr = dom.getAttribute('each')
if (attr) { _each(dom, tag, attr); return false }
// attribute expressions
each(dom.attributes, function(attr) {
var name = attr.name,
bool = name.split('__')[1]
addExpr(dom, attr.value, { attr: bool || name, bool: bool })
if (bool) { remAttr(dom, name); return false }
})
// skip custom tags
if (getTag(dom)) return false
})
}
function Tag(impl, conf, innerHTML) {
var self = riot.observable(this),
opts = inherit(conf.opts) || {},
dom = mkdom(impl.tmpl),
parent = conf.parent,
isLoop = conf.isLoop,
hasImpl = conf.hasImpl,
item = cleanUpData(conf.item),
expressions = [],
childTags = [],
root = conf.root,
fn = impl.fn,
tagName = root.tagName.toLowerCase(),
attr = {},
propsInSyncWithParent = [],
loopDom,
TAG_ATTRIBUTES = /([\w\-]+)\s?=\s?['"]([^'"]+)["']/gim
if (fn && root._tag) {
root._tag.unmount(true)
}
// not yet mounted
this.isMounted = false
root.isLoop = isLoop
if (impl.attrs) {
var attrs = impl.attrs.match(TAG_ATTRIBUTES)
each(attrs, function(a) {
var kv = a.split(/\s?=\s?/)
root.setAttribute(kv[0], kv[1].replace(/['"]/g, ''))
})
}
// keep a reference to the tag just created
// so we will be able to mount this tag multiple times
root._tag = this
// create a unique id to this tag
// it could be handy to use it also to improve the virtual dom rendering speed
this._id = fastAbs(~~(new Date().getTime() * Math.random()))
extend(this, { parent: parent, root: root, opts: opts, tags: {} }, item)
// grab attributes
each(root.attributes, function(el) {
var val = el.value
// remember attributes with expressions only
if (brackets(/\{.*\}/).test(val)) attr[el.name] = val
})
if (dom.innerHTML && !/select|select|optgroup|tbody|tr/.test(tagName))
// replace all the yield tags with the tag inner html
dom.innerHTML = replaceYield(dom.innerHTML, innerHTML)
// options
function updateOpts() {
var ctx = hasImpl && isLoop ? self : parent || self
// update opts from current DOM attributes
each(root.attributes, function(el) {
opts[el.name] = tmpl(el.value, ctx)
})
// recover those with expressions
each(Object.keys(attr), function(name) {
opts[name] = tmpl(attr[name], ctx)
})
}
function normalizeData(data) {
for (var key in item) {
if (typeof self[key] !== T_UNDEF)
self[key] = data[key]
}
}
function inheritFromParent () {
if (!self.parent || !isLoop) return
each(Object.keys(self.parent), function(k) {
// some properties must be always in sync with the parent tag
var mustSync = ~propsInSyncWithParent.indexOf(k)
if (typeof self[k] === T_UNDEF || mustSync) {
// track the property to keep in sync
// so we can keep it updated
if (!mustSync) propsInSyncWithParent.push(k)
self[k] = self.parent[k]
}
})
}
this.update = function(data) {
// make sure the data passed will not override
// the component core methods
data = cleanUpData(data)
// inherit properties from the parent
inheritFromParent()
// normalize the tag properties in case an item object was initially passed
if (typeof item === T_OBJECT || isArray(item)) {
normalizeData(data)
item = data
}
extend(self, data)
updateOpts()
self.trigger('update', data)
update(expressions, self)
self.trigger('updated')
}
this.mixin = function() {
each(arguments, function(mix) {
mix = typeof mix === T_STRING ? riot.mixin(mix) : mix
each(Object.keys(mix), function(key) {
// bind methods to self
if (key != 'init')
self[key] = isFunction(mix[key]) ? mix[key].bind(self) : mix[key]
})
// init method will be called automatically
if (mix.init) mix.init.bind(self)()
})
}
this.mount = function() {
updateOpts()
// initialiation
fn && fn.call(self, opts)
toggle(true)
// parse layout after init. fn may calculate args for nested custom tags
parseExpressions(dom, self, expressions)
if (!self.parent || hasImpl) parseExpressions(self.root, self, expressions) // top level before update, empty root
if (!self.parent || isLoop) self.update(item)
// internal use only, fixes #403
self.trigger('premount')
if (isLoop && !hasImpl) {
// update the root attribute for the looped elements
self.root = root = loopDom = dom.firstChild
} else {
while (dom.firstChild) root.appendChild(dom.firstChild)
if (root.stub) self.root = root = parent.root
}
// if it's not a child tag we can trigger its mount event
if (!self.parent || self.parent.isMounted) {
self.isMounted = true
self.trigger('mount')
}
// otherwise we need to wait that the parent event gets triggered
else self.parent.one('mount', function() {
// avoid to trigger the `mount` event for the tags
// not visible included in an if statement
if (!isInStub(self.root)) {
self.parent.isMounted = self.isMounted = true
self.trigger('mount')
}
})
}
this.unmount = function(keepRootTag) {
var el = loopDom || root,
p = el.parentNode
if (p) {
if (parent)
// remove this tag from the parent tags object
// if there are multiple nested tags with same name..
// remove this element form the array
if (isArray(parent.tags[tagName]))
each(parent.tags[tagName], function(tag, i) {
if (tag._id == self._id)
parent.tags[tagName].splice(i, 1)
})
else
// otherwise just delete the tag instance
parent.tags[tagName] = undefined
else
while (el.firstChild) el.removeChild(el.firstChild)
if (!keepRootTag)
p.removeChild(el)
}
self.trigger('unmount')
toggle()
self.off('*')
// somehow ie8 does not like `delete root._tag`
root._tag = null
}
function toggle(isMount) {
// mount/unmount children
each(childTags, function(child) { child[isMount ? 'mount' : 'unmount']() })
// listen/unlisten parent (events flow one way from parent to children)
if (parent) {
var evt = isMount ? 'on' : 'off'
// the loop tags will be always in sync with the parent automatically
if (isLoop)
parent[evt]('unmount', self.unmount)
else
parent[evt]('update', self.update)[evt]('unmount', self.unmount)
}
}
// named elements available for fn
parseNamedElements(dom, this, childTags)
}
function setEventHandler(name, handler, dom, tag) {
dom[name] = function(e) {
var item = tag._item,
ptag = tag.parent
if (!item)
while (ptag) {
item = ptag._item
ptag = item ? false : ptag.parent
}
// cross browser event fix
e = e || window.event
// ignore error on some browsers
try {
e.currentTarget = dom
if (!e.target) e.target = e.srcElement
if (!e.which) e.which = e.charCode || e.keyCode
} catch (ignored) { '' }
e.item = item
// prevent default behaviour (by default)
if (handler.call(tag, e) !== true && !/radio|check/.test(dom.type)) {
e.preventDefault && e.preventDefault()
e.returnValue = false
}
if (!e.preventUpdate) {
var el = item ? tag.parent : tag
el.update()
}
}
}
// used by if- attribute
function insertTo(root, node, before) {
if (root) {
root.insertBefore(before, node)
root.removeChild(node)
}
}
function update(expressions, tag) {
each(expressions, function(expr, i) {
var dom = expr.dom,
attrName = expr.attr,
value = tmpl(expr.expr, tag),
parent = expr.dom.parentNode
if (value == null) value = ''
// leave out riot- prefixes from strings inside textarea
if (parent && parent.tagName == 'TEXTAREA') value = value.replace(/riot-/g, '')
// no change
if (expr.value === value) return
expr.value = value
// text node
if (!attrName) return dom.nodeValue = value.toString()
// remove original attribute
remAttr(dom, attrName)
// event handler
if (isFunction(value)) {
setEventHandler(attrName, value, dom, tag)
// if- conditional
} else if (attrName == 'if') {
var stub = expr.stub
// add to DOM
if (value) {
if (stub) {
insertTo(stub.parentNode, stub, dom)
dom.inStub = false
// avoid to trigger the mount event if the tags is not visible yet
// maybe we can optimize this avoiding to mount the tag at all
if (!isInStub(dom)) {
walk(dom, function(el) {
if (el._tag && !el._tag.isMounted) el._tag.isMounted = !!el._tag.trigger('mount')
})
}
}
// remove from DOM
} else {
stub = expr.stub = stub || document.createTextNode('')
insertTo(dom.parentNode, dom, stub)
dom.inStub = true
}
// show / hide
} else if (/^(show|hide)$/.test(attrName)) {
if (attrName == 'hide') value = !value
dom.style.display = value ? '' : 'none'
// field value
} else if (attrName == 'value') {
dom.value = value
// <img src="{ expr }">
} else if (attrName.slice(0, 5) == 'riot-' && attrName != 'riot-tag') {
attrName = attrName.slice(5)
value ? dom.setAttribute(attrName, value) : remAttr(dom, attrName)
} else {
if (expr.bool) {
dom[attrName] = value
if (!value) return
value = attrName
}
if (typeof value !== T_OBJECT) dom.setAttribute(attrName, value)
}
})
}
function each(els, fn) {
for (var i = 0, len = (els || []).length, el; i < len; i++) {
el = els[i]
// return false -> remove current item during loop
if (el != null && fn(el, i) === false) i--
}
return els
}
function isFunction(v) {
return typeof v === 'function' || false // avoid IE problems
}
function remAttr(dom, name) {
dom.removeAttribute(name)
}
function fastAbs(nr) {
return (nr ^ (nr >> 31)) - (nr >> 31)
}
function getTag(dom) {
var tagName = dom.tagName.toLowerCase()
return tagImpl[dom.getAttribute(RIOT_TAG) || tagName]
}
function getTagName(dom) {
var child = getTag(dom),
namedTag = dom.getAttribute('name'),