-
Notifications
You must be signed in to change notification settings - Fork 0
/
riot.js
2510 lines (2224 loc) · 77.6 KB
/
riot.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 v9.0.4, @license MIT */
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
typeof define === 'function' && define.amd ? define(['exports'], factory) :
(global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.riot = {}));
})(this, (function (exports) { 'use strict';
const EACH = 0;
const IF = 1;
const SIMPLE = 2;
const TAG = 3;
const SLOT = 4;
const bindingTypes = {
EACH,
IF,
SIMPLE,
TAG,
SLOT,
};
/**
* Quick type checking
* @param {*} element - anything
* @param {string} type - type definition
* @returns {boolean} true if the type corresponds
*/
function checkType(element, type) {
return typeof element === type
}
/**
* Check if an element is part of an svg
* @param {HTMLElement} el - element to check
* @returns {boolean} true if we are in an svg context
*/
function isSvg(el) {
const owner = el.ownerSVGElement;
return !!owner || owner === null
}
/**
* Check if an element is a template tag
* @param {HTMLElement} el - element to check
* @returns {boolean} true if it's a <template>
*/
function isTemplate(el) {
return el.tagName.toLowerCase() === 'template'
}
/**
* Check that will be passed if its argument is a function
* @param {*} value - value to check
* @returns {boolean} - true if the value is a function
*/
function isFunction(value) {
return checkType(value, 'function')
}
/**
* Check if a value is a Boolean
* @param {*} value - anything
* @returns {boolean} true only for the value is a boolean
*/
function isBoolean(value) {
return checkType(value, 'boolean')
}
/**
* Check if a value is an Object
* @param {*} value - anything
* @returns {boolean} true only for the value is an object
*/
function isObject(value) {
return !isNil(value) && value.constructor === Object
}
/**
* Check if a value is null or undefined
* @param {*} value - anything
* @returns {boolean} true only for the 'undefined' and 'null' types
*/
function isNil(value) {
return value === null || value === undefined
}
// Riot.js constants that can be used across more modules
const COMPONENTS_IMPLEMENTATION_MAP = new Map(),
DOM_COMPONENT_INSTANCE_PROPERTY = Symbol('riot-component'),
PLUGINS_SET = new Set(),
IS_DIRECTIVE = 'is',
MOUNT_METHOD_KEY = 'mount',
UPDATE_METHOD_KEY = 'update',
UNMOUNT_METHOD_KEY = 'unmount',
SHOULD_UPDATE_KEY = 'shouldUpdate',
ON_BEFORE_MOUNT_KEY = 'onBeforeMount',
ON_MOUNTED_KEY = 'onMounted',
ON_BEFORE_UPDATE_KEY = 'onBeforeUpdate',
ON_UPDATED_KEY = 'onUpdated',
ON_BEFORE_UNMOUNT_KEY = 'onBeforeUnmount',
ON_UNMOUNTED_KEY = 'onUnmounted',
PROPS_KEY = 'props',
STATE_KEY = 'state',
SLOTS_KEY = 'slots',
ROOT_KEY = 'root',
IS_PURE_SYMBOL = Symbol('pure'),
IS_COMPONENT_UPDATING = Symbol('is_updating'),
PARENT_KEY_SYMBOL = Symbol('parent'),
ATTRIBUTES_KEY_SYMBOL = Symbol('attributes'),
TEMPLATE_KEY_SYMBOL = Symbol('template');
/**
* Convert a string from camel case to dash-case
* @param {string} string - probably a component tag name
* @returns {string} component name normalized
*/
function camelToDashCase(string) {
return string.replace(/([a-z])([A-Z])/g, '$1-$2').toLowerCase()
}
/**
* Convert a string containing dashes to camel case
* @param {string} string - input string
* @returns {string} my-string -> myString
*/
function dashToCamelCase(string) {
return string.replace(/-(\w)/g, (_, c) => c.toUpperCase())
}
/**
* Get all the element attributes as object
* @param {HTMLElement} element - DOM node we want to parse
* @returns {Object} all the attributes found as a key value pairs
*/
function DOMattributesToObject(element) {
return Array.from(element.attributes).reduce((acc, attribute) => {
acc[dashToCamelCase(attribute.name)] = attribute.value;
return acc
}, {})
}
/**
* Move all the child nodes from a source tag to another
* @param {HTMLElement} source - source node
* @param {HTMLElement} target - target node
* @returns {undefined} it's a void method ¯\_(ツ)_/¯
*/
// Ignore this helper because it's needed only for svg tags
function moveChildren(source, target) {
// eslint-disable-next-line fp/no-loops
while (source.firstChild) target.appendChild(source.firstChild);
}
/**
* Remove the child nodes from any DOM node
* @param {HTMLElement} node - target node
* @returns {undefined}
*/
function cleanNode(node) {
// eslint-disable-next-line fp/no-loops
while (node.firstChild) node.removeChild(node.firstChild);
}
/**
* Clear multiple children in a node
* @param {HTMLElement[]} children - direct children nodes
* @returns {undefined}
*/
function clearChildren(children) {
// eslint-disable-next-line fp/no-loops,fp/no-let
for (let i = 0; i < children.length; i++) removeChild(children[i]);
}
/**
* Remove a node
* @param {HTMLElement}node - node to remove
* @returns {undefined}
*/
const removeChild = (node) => node.remove();
/**
* Insert before a node
* @param {HTMLElement} newNode - node to insert
* @param {HTMLElement} refNode - ref child
* @returns {undefined}
*/
const insertBefore = (newNode, refNode) =>
refNode &&
refNode.parentNode &&
refNode.parentNode.insertBefore(newNode, refNode);
/**
* Replace a node
* @param {HTMLElement} newNode - new node to add to the DOM
* @param {HTMLElement} replaced - node to replace
* @returns {undefined}
*/
const replaceChild = (newNode, replaced) =>
replaced &&
replaced.parentNode &&
replaced.parentNode.replaceChild(newNode, replaced);
const ATTRIBUTE = 0;
const EVENT = 1;
const TEXT = 2;
const VALUE = 3;
const expressionTypes = {
ATTRIBUTE,
EVENT,
TEXT,
VALUE,
};
// does simply nothing
function noop() {
return this
}
/**
* Autobind the methods of a source object to itself
* @param {Object} source - probably a riot tag instance
* @param {Array<string>} methods - list of the methods to autobind
* @returns {Object} the original object received
*/
function autobindMethods(source, methods) {
methods.forEach((method) => {
source[method] = source[method].bind(source);
});
return source
}
/**
* Call the first argument received only if it's a function otherwise return it as it is
* @param {*} source - anything
* @returns {*} anything
*/
function callOrAssign(source) {
return isFunction(source)
? source.prototype && source.prototype.constructor
? new source()
: source()
: source
}
/**
* Throw an error with a descriptive message
* @param { string } message - error message
* @param { string } cause - optional error cause object
* @returns { undefined } hoppla... at this point the program should stop working
*/
function panic(message, cause) {
throw new Error(message, { cause })
}
/**
* Returns the memoized (cached) function.
* // borrowed from https://www.30secondsofcode.org/js/s/memoize
* @param {Function} fn - function to memoize
* @returns {Function} memoize function
*/
function memoize(fn) {
const cache = new Map();
const cached = (val) => {
return cache.has(val)
? cache.get(val)
: cache.set(val, fn.call(this, val)) && cache.get(val)
};
cached.cache = cache;
return cached
}
/**
* Evaluate a list of attribute expressions
* @param {Array} attributes - attribute expressions generated by the riot compiler
* @returns {Object} key value pairs with the result of the computation
*/
function evaluateAttributeExpressions(attributes) {
return attributes.reduce((acc, attribute) => {
const { value, type } = attribute;
switch (true) {
// spread attribute
case !attribute.name && type === ATTRIBUTE:
return {
...acc,
...value,
}
// value attribute
case type === VALUE:
acc.value = attribute.value;
break
// normal attributes
default:
acc[dashToCamelCase(attribute.name)] = attribute.value;
}
return acc
}, {})
}
/**
* Helper function to set an immutable property
* @param {Object} source - 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 property overriding the default options
* @returns {Object} - the original object modified
*/
function defineProperty(source, key, value, options = {}) {
/* eslint-disable fp/no-mutating-methods */
Object.defineProperty(source, key, {
value,
enumerable: false,
writable: false,
configurable: true,
...options,
});
/* eslint-enable fp/no-mutating-methods */
return source
}
/**
* Define multiple properties on a target object
* @param {Object} source - object where the new properties will be set
* @param {Object} properties - object containing as key pair the key + value properties
* @param {Object} options - set the property overriding the default options
* @returns {Object} the original object modified
*/
function defineProperties(source, properties, options) {
Object.entries(properties).forEach(([key, value]) => {
defineProperty(source, key, value, options);
});
return source
}
/**
* Define default properties if they don't exist on the source object
* @param {Object} source - object that will receive the default properties
* @param {Object} defaults - object containing additional optional keys
* @returns {Object} the original object received enhanced
*/
function defineDefaults(source, defaults) {
Object.entries(defaults).forEach(([key, value]) => {
if (!source[key]) source[key] = value;
});
return source
}
// Components without template use a mocked template interface with some basic functionalities to
// guarantee consistent rendering behaviour see https://github.com/riot/riot/issues/2984
const MOCKED_TEMPLATE_INTERFACE = {
[MOUNT_METHOD_KEY](el) {
this.el = el;
},
[UPDATE_METHOD_KEY]: noop,
[UNMOUNT_METHOD_KEY](_, __, mustRemoveRoot = false) {
if (mustRemoveRoot) removeChild(this.el);
else if (!mustRemoveRoot) cleanNode(this.el);
},
clone: noop,
createDOM: noop,
};
const HEAD_SYMBOL = Symbol();
const TAIL_SYMBOL = Symbol();
/**
* Create the <template> fragments text nodes
* @return {Object} {{head: Text, tail: Text}}
*/
function createHeadTailPlaceholders() {
const head = document.createTextNode('');
const tail = document.createTextNode('');
head[HEAD_SYMBOL] = true;
tail[TAIL_SYMBOL] = true;
return { head, tail }
}
/**
* Create the template meta object in case of <template> fragments
* @param {TemplateChunk} componentTemplate - template chunk object
* @returns {Object} the meta property that will be passed to the mount function of the TemplateChunk
*/
function createTemplateMeta(componentTemplate) {
const fragment = componentTemplate.dom.cloneNode(true);
const { head, tail } = createHeadTailPlaceholders();
return {
avoidDOMInjection: true,
fragment,
head,
tail,
children: [head, ...Array.from(fragment.childNodes), tail],
}
}
/* c8 ignore start */
/**
* ISC License
*
* Copyright (c) 2020, Andrea Giammarchi, @WebReflection
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
* REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
* AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
* INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
* LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE
* OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
* PERFORMANCE OF THIS SOFTWARE.
*/
// fork of https://github.com/WebReflection/udomdiff version 1.1.0
// due to https://github.com/WebReflection/udomdiff/pull/2
/* eslint-disable */
/**
* @param {Node[]} a The list of current/live children
* @param {Node[]} b The list of future children
* @param {(entry: Node, action: number) => Node} get
* The callback invoked per each entry related DOM operation.
* @param {Node} [before] The optional node used as anchor to insert before.
* @returns {Node[]} The same list of future children.
*/
const udomdiff = (a, b, get, before) => {
const bLength = b.length;
let aEnd = a.length;
let bEnd = bLength;
let aStart = 0;
let bStart = 0;
let map = null;
while (aStart < aEnd || bStart < bEnd) {
// append head, tail, or nodes in between: fast path
if (aEnd === aStart) {
// we could be in a situation where the rest of nodes that
// need to be added are not at the end, and in such case
// the node to `insertBefore`, if the index is more than 0
// must be retrieved, otherwise it's gonna be the first item.
const node =
bEnd < bLength
? bStart
? get(b[bStart - 1], -0).nextSibling
: get(b[bEnd - bStart], 0)
: before;
while (bStart < bEnd) insertBefore(get(b[bStart++], 1), node);
}
// remove head or tail: fast path
else if (bEnd === bStart) {
while (aStart < aEnd) {
// remove the node only if it's unknown or not live
if (!map || !map.has(a[aStart])) removeChild(get(a[aStart], -1));
aStart++;
}
}
// same node: fast path
else if (a[aStart] === b[bStart]) {
aStart++;
bStart++;
}
// same tail: fast path
else if (a[aEnd - 1] === b[bEnd - 1]) {
aEnd--;
bEnd--;
}
// The once here single last swap "fast path" has been removed in v1.1.0
// https://github.com/WebReflection/udomdiff/blob/single-final-swap/esm/index.js#L69-L85
// reverse swap: also fast path
else if (a[aStart] === b[bEnd - 1] && b[bStart] === a[aEnd - 1]) {
// this is a "shrink" operation that could happen in these cases:
// [1, 2, 3, 4, 5]
// [1, 4, 3, 2, 5]
// or asymmetric too
// [1, 2, 3, 4, 5]
// [1, 2, 3, 5, 6, 4]
const node = get(a[--aEnd], -1).nextSibling;
insertBefore(get(b[bStart++], 1), get(a[aStart++], -1).nextSibling);
insertBefore(get(b[--bEnd], 1), node);
// mark the future index as identical (yeah, it's dirty, but cheap 👍)
// The main reason to do this, is that when a[aEnd] will be reached,
// the loop will likely be on the fast path, as identical to b[bEnd].
// In the best case scenario, the next loop will skip the tail,
// but in the worst one, this node will be considered as already
// processed, bailing out pretty quickly from the map index check
a[aEnd] = b[bEnd];
}
// map based fallback, "slow" path
else {
// the map requires an O(bEnd - bStart) operation once
// to store all future nodes indexes for later purposes.
// In the worst case scenario, this is a full O(N) cost,
// and such scenario happens at least when all nodes are different,
// but also if both first and last items of the lists are different
if (!map) {
map = new Map();
let i = bStart;
while (i < bEnd) map.set(b[i], i++);
}
// if it's a future node, hence it needs some handling
if (map.has(a[aStart])) {
// grab the index of such node, 'cause it might have been processed
const index = map.get(a[aStart]);
// if it's not already processed, look on demand for the next LCS
if (bStart < index && index < bEnd) {
let i = aStart;
// counts the amount of nodes that are the same in the future
let sequence = 1;
while (++i < aEnd && i < bEnd && map.get(a[i]) === index + sequence)
sequence++;
// effort decision here: if the sequence is longer than replaces
// needed to reach such sequence, which would brings again this loop
// to the fast path, prepend the difference before a sequence,
// and move only the future list index forward, so that aStart
// and bStart will be aligned again, hence on the fast path.
// An example considering aStart and bStart are both 0:
// a: [1, 2, 3, 4]
// b: [7, 1, 2, 3, 6]
// this would place 7 before 1 and, from that time on, 1, 2, and 3
// will be processed at zero cost
if (sequence > index - bStart) {
const node = get(a[aStart], 0);
while (bStart < index) insertBefore(get(b[bStart++], 1), node);
}
// if the effort wasn't good enough, fallback to a replace,
// moving both source and target indexes forward, hoping that some
// similar node will be found later on, to go back to the fast path
else {
replaceChild(get(b[bStart++], 1), get(a[aStart++], -1));
}
}
// otherwise move the source forward, 'cause there's nothing to do
else aStart++;
}
// this node has no meaning in the future list, so it's more than safe
// to remove it, and check the next live node out instead, meaning
// that only the live list index should be forwarded
else removeChild(get(a[aStart++], -1));
}
}
return b
};
const UNMOUNT_SCOPE = Symbol('unmount');
const EachBinding = {
// dynamic binding properties
// childrenMap: null,
// node: null,
// root: null,
// condition: null,
// evaluate: null,
// template: null,
// isTemplateTag: false,
nodes: [],
// getKey: null,
// indexName: null,
// itemName: null,
// afterPlaceholder: null,
// placeholder: null,
// API methods
mount(scope, parentScope) {
return this.update(scope, parentScope)
},
update(scope, parentScope) {
const { placeholder, nodes, childrenMap } = this;
const collection = scope === UNMOUNT_SCOPE ? null : this.evaluate(scope);
const items = collection ? Array.from(collection) : [];
// prepare the diffing
const { newChildrenMap, batches, futureNodes } = createPatch(
items,
scope,
parentScope,
this,
);
// patch the DOM only if there are new nodes
udomdiff(
nodes,
futureNodes,
patch(Array.from(childrenMap.values()), parentScope),
placeholder,
);
// trigger the mounts and the updates
batches.forEach((fn) => fn());
// update the children map
this.childrenMap = newChildrenMap;
this.nodes = futureNodes;
return this
},
unmount(scope, parentScope) {
this.update(UNMOUNT_SCOPE, parentScope);
return this
},
};
/**
* Patch the DOM while diffing
* @param {any[]} redundant - list of all the children (template, nodes, context) added via each
* @param {*} parentScope - scope of the parent template
* @returns {Function} patch function used by domdiff
*/
function patch(redundant, parentScope) {
return (item, info) => {
if (info < 0) {
// get the last element added to the childrenMap saved previously
const element = redundant[redundant.length - 1];
if (element) {
// get the nodes and the template in stored in the last child of the childrenMap
const { template, nodes, context } = element;
// remove the last node (notice <template> tags might have more children nodes)
nodes.pop();
// notice that we pass null as last argument because
// the root node and its children will be removed by domdiff
if (!nodes.length) {
// we have cleared all the children nodes and we can unmount this template
redundant.pop();
template.unmount(context, parentScope, null);
}
}
}
return item
}
}
/**
* Check whether a template must be filtered from a loop
* @param {Function} condition - filter function
* @param {Object} context - argument passed to the filter function
* @returns {boolean} true if this item should be skipped
*/
function mustFilterItem(condition, context) {
return condition ? !condition(context) : false
}
/**
* Extend the scope of the looped template
* @param {Object} scope - current template scope
* @param {Object} options - options
* @param {string} options.itemName - key to identify the looped item in the new context
* @param {string} options.indexName - key to identify the index of the looped item
* @param {number} options.index - current index
* @param {*} options.item - collection item looped
* @returns {Object} enhanced scope object
*/
function extendScope(scope, { itemName, indexName, index, item }) {
defineProperty(scope, itemName, item);
if (indexName) defineProperty(scope, indexName, index);
return scope
}
/**
* Loop the current template items
* @param {Array} items - expression collection value
* @param {*} scope - template scope
* @param {*} parentScope - scope of the parent template
* @param {EachBinding} binding - each binding object instance
* @returns {Object} data
* @returns {Map} data.newChildrenMap - a Map containing the new children template structure
* @returns {Array} data.batches - array containing the template lifecycle functions to trigger
* @returns {Array} data.futureNodes - array containing the nodes we need to diff
*/
function createPatch(items, scope, parentScope, binding) {
const {
condition,
template,
childrenMap,
itemName,
getKey,
indexName,
root,
isTemplateTag,
} = binding;
const newChildrenMap = new Map();
const batches = [];
const futureNodes = [];
items.forEach((item, index) => {
const context = extendScope(Object.create(scope), {
itemName,
indexName,
index,
item,
});
const key = getKey ? getKey(context) : index;
const oldItem = childrenMap.get(key);
const nodes = [];
if (mustFilterItem(condition, context)) {
return
}
const mustMount = !oldItem;
const componentTemplate = oldItem ? oldItem.template : template.clone();
const el = componentTemplate.el || root.cloneNode();
const meta =
isTemplateTag && mustMount
? createTemplateMeta(componentTemplate)
: componentTemplate.meta;
if (mustMount) {
batches.push(() =>
componentTemplate.mount(el, context, parentScope, meta),
);
} else {
batches.push(() => componentTemplate.update(context, parentScope));
}
// create the collection of nodes to update or to add
// in case of template tags we need to add all its children nodes
if (isTemplateTag) {
nodes.push(...meta.children);
} else {
nodes.push(el);
}
// delete the old item from the children map
childrenMap.delete(key);
futureNodes.push(...nodes);
// update the children map
newChildrenMap.set(key, {
nodes,
template: componentTemplate,
context,
index,
});
});
return {
newChildrenMap,
batches,
futureNodes,
}
}
function create$6(
node,
{ evaluate, condition, itemName, indexName, getKey, template },
) {
const placeholder = document.createTextNode('');
const root = node.cloneNode();
insertBefore(placeholder, node);
removeChild(node);
return {
...EachBinding,
childrenMap: new Map(),
node,
root,
condition,
evaluate,
isTemplateTag: isTemplate(root),
template: template.createDOM(node),
getKey,
indexName,
itemName,
placeholder,
}
}
/**
* Binding responsible for the `if` directive
*/
const IfBinding = {
// dynamic binding properties
// node: null,
// evaluate: null,
// isTemplateTag: false,
// placeholder: null,
// template: null,
// API methods
mount(scope, parentScope) {
return this.update(scope, parentScope)
},
update(scope, parentScope) {
const value = !!this.evaluate(scope);
const mustMount = !this.value && value;
const mustUnmount = this.value && !value;
const mount = () => {
const pristine = this.node.cloneNode();
insertBefore(pristine, this.placeholder);
this.template = this.template.clone();
this.template.mount(pristine, scope, parentScope);
};
switch (true) {
case mustMount:
mount();
break
case mustUnmount:
this.unmount(scope);
break
default:
if (value) this.template.update(scope, parentScope);
}
this.value = value;
return this
},
unmount(scope, parentScope) {
this.template.unmount(scope, parentScope, true);
return this
},
};
function create$5(node, { evaluate, template }) {
const placeholder = document.createTextNode('');
insertBefore(placeholder, node);
removeChild(node);
return {
...IfBinding,
node,
evaluate,
placeholder,
template: template.createDOM(node),
}
}
const ElementProto = typeof Element === 'undefined' ? {} : Element.prototype;
const isNativeHtmlProperty = memoize(
(name) => ElementProto.hasOwnProperty(name), // eslint-disable-line
);
/**
* Add all the attributes provided
* @param {HTMLElement} node - target node
* @param {Object} attributes - object containing the attributes names and values
* @returns {undefined} sorry it's a void function :(
*/
function setAllAttributes(node, attributes) {
Object.entries(attributes).forEach(([name, value]) =>
attributeExpression(node, { name }, value),
);
}
/**
* Remove all the attributes provided
* @param {HTMLElement} node - target node
* @param {Object} newAttributes - object containing all the new attribute names
* @param {Object} oldAttributes - object containing all the old attribute names
* @returns {undefined} sorry it's a void function :(
*/
function removeAllAttributes(node, newAttributes, oldAttributes) {
const newKeys = newAttributes ? Object.keys(newAttributes) : [];
Object.keys(oldAttributes)
.filter((name) => !newKeys.includes(name))
.forEach((attribute) => node.removeAttribute(attribute));
}
/**
* Check whether the attribute value can be rendered
* @param {*} value - expression value
* @returns {boolean} true if we can render this attribute value
*/
function canRenderAttribute(value) {
return ['string', 'number', 'boolean'].includes(typeof value)
}
/**
* Check whether the attribute should be removed
* @param {*} value - expression value
* @param {boolean} isBoolean - flag to handle boolean attributes
* @returns {boolean} boolean - true if the attribute can be removed}
*/
function shouldRemoveAttribute(value, isBoolean) {
// boolean attributes should be removed if the value is falsy
if (isBoolean) return !value && value !== 0
// otherwise we can try to render it
return typeof value === 'undefined' || value === null
}
/**
* This methods handles the DOM attributes updates
* @param {HTMLElement} node - target node
* @param {Object} expression - expression object
* @param {string} expression.name - attribute name
* @param {boolean} expression.isBoolean - flag to handle boolean attributes
* @param {*} value - new expression value
* @param {*} oldValue - the old expression cached value
* @returns {undefined}
*/
function attributeExpression(
node,
{ name, isBoolean: isBoolean$1 },
value,
oldValue,
) {
// is it a spread operator? {...attributes}
if (!name) {
if (oldValue) {
// remove all the old attributes
removeAllAttributes(node, value, oldValue);
}
// is the value still truthy?
if (value) {
setAllAttributes(node, value);
}
return
}
// store the attribute on the node to make it compatible with native custom elements
if (
!isNativeHtmlProperty(name) &&
(isBoolean(value) || isObject(value) || isFunction(value))
) {
node[name] = value;
}
if (shouldRemoveAttribute(value, isBoolean$1)) {
node.removeAttribute(name);
} else if (canRenderAttribute(value)) {
node.setAttribute(name, normalizeValue(name, value, isBoolean$1));
}
}
/**
* Get the value as string
* @param {string} name - attribute name
* @param {*} value - user input value
* @param {boolean} isBoolean - boolean attributes flag
* @returns {string} input value as string
*/
function normalizeValue(name, value, isBoolean) {
// be sure that expressions like selected={ true } will always be rendered as selected='selected'
// fix https://github.com/riot/riot/issues/2975
return value === true && isBoolean ? name : value
}
const RE_EVENTS_PREFIX = /^on/;
const getCallbackAndOptions = (value) =>
Array.isArray(value) ? value : [value, false];
// see also https://medium.com/@WebReflection/dom-handleevent-a-cross-platform-standard-since-year-2000-5bf17287fd38
const EventListener = {
handleEvent(event) {
this[event.type](event);
},
};
const ListenersWeakMap = new WeakMap();
const createListener = (node) => {
const listener = Object.create(EventListener);
ListenersWeakMap.set(node, listener);
return listener
};
/**
* Set a new event listener
* @param {HTMLElement} node - target node
* @param {Object} expression - expression object
* @param {string} expression.name - event name
* @param {*} value - new expression value
* @returns {value} the callback just received
*/
function eventExpression(node, { name }, value) {
const normalizedEventName = name.replace(RE_EVENTS_PREFIX, '');
const eventListener = ListenersWeakMap.get(node) || createListener(node);
const [callback, options] = getCallbackAndOptions(value);
const handler = eventListener[normalizedEventName];
const mustRemoveEvent = handler && !callback;
const mustAddEvent = callback && !handler;
if (mustRemoveEvent) {
node.removeEventListener(normalizedEventName, eventListener);
}
if (mustAddEvent) {
node.addEventListener(normalizedEventName, eventListener, options);