-
-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
alpine.js
1705 lines (1514 loc) · 65.2 KB
/
alpine.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
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
typeof define === 'function' && define.amd ? define(factory) :
(global = global || self, global.Alpine = factory());
}(this, (function () { 'use strict';
function _defineProperty(obj, key, value) {
if (key in obj) {
Object.defineProperty(obj, key, {
value: value,
enumerable: true,
configurable: true,
writable: true
});
} else {
obj[key] = value;
}
return obj;
}
function ownKeys(object, enumerableOnly) {
var keys = Object.keys(object);
if (Object.getOwnPropertySymbols) {
var symbols = Object.getOwnPropertySymbols(object);
if (enumerableOnly) symbols = symbols.filter(function (sym) {
return Object.getOwnPropertyDescriptor(object, sym).enumerable;
});
keys.push.apply(keys, symbols);
}
return keys;
}
function _objectSpread2(target) {
for (var i = 1; i < arguments.length; i++) {
var source = arguments[i] != null ? arguments[i] : {};
if (i % 2) {
ownKeys(Object(source), true).forEach(function (key) {
_defineProperty(target, key, source[key]);
});
} else if (Object.getOwnPropertyDescriptors) {
Object.defineProperties(target, Object.getOwnPropertyDescriptors(source));
} else {
ownKeys(Object(source)).forEach(function (key) {
Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key));
});
}
}
return target;
}
// Thanks @stimulus:
// https://github.com/stimulusjs/stimulus/blob/master/packages/%40stimulus/core/src/application.ts
function domReady() {
return new Promise(resolve => {
if (document.readyState == "loading") {
document.addEventListener("DOMContentLoaded", resolve);
} else {
resolve();
}
});
}
function arrayUnique(array) {
return Array.from(new Set(array));
}
function isTesting() {
return navigator.userAgent.includes("Node.js") || navigator.userAgent.includes("jsdom");
}
function kebabCase(subject) {
return subject.replace(/([a-z])([A-Z])/g, '$1-$2').replace(/[_\s]/, '-').toLowerCase();
}
function walk(el, callback) {
if (callback(el) === false) return;
let node = el.firstElementChild;
while (node) {
walk(node, callback);
node = node.nextElementSibling;
}
}
function debounce(func, wait) {
var timeout;
return function () {
var context = this,
args = arguments;
var later = function later() {
timeout = null;
func.apply(context, args);
};
clearTimeout(timeout);
timeout = setTimeout(later, wait);
};
}
function saferEval(expression, dataContext, additionalHelperVariables = {}) {
return new Function(['$data', ...Object.keys(additionalHelperVariables)], `var result; with($data) { result = ${expression} }; return result`)(dataContext, ...Object.values(additionalHelperVariables));
}
function saferEvalNoReturn(expression, dataContext, additionalHelperVariables = {}) {
// For the cases when users pass only a function reference to the caller: `x-on:click="foo"`
// Where "foo" is a function. Also, we'll pass the function the event instance when we call it.
if (Object.keys(dataContext).includes(expression)) {
let methodReference = new Function(['dataContext', ...Object.keys(additionalHelperVariables)], `with(dataContext) { return ${expression} }`)(dataContext, ...Object.values(additionalHelperVariables));
if (typeof methodReference === 'function') {
return methodReference.call(dataContext, additionalHelperVariables['$event']);
}
}
return new Function(['dataContext', ...Object.keys(additionalHelperVariables)], `with(dataContext) { ${expression} }`)(dataContext, ...Object.values(additionalHelperVariables));
}
const xAttrRE = /^x-(on|bind|data|text|html|model|if|for|show|cloak|transition|ref)\b/;
function isXAttr(attr) {
const name = replaceAtAndColonWithStandardSyntax(attr.name);
return xAttrRE.test(name);
}
function getXAttrs(el, type) {
return Array.from(el.attributes).filter(isXAttr).map(attr => {
const name = replaceAtAndColonWithStandardSyntax(attr.name);
const typeMatch = name.match(xAttrRE);
const valueMatch = name.match(/:([a-zA-Z\-:]+)/);
const modifiers = name.match(/\.[^.\]]+(?=[^\]]*$)/g) || [];
return {
type: typeMatch ? typeMatch[1] : null,
value: valueMatch ? valueMatch[1] : null,
modifiers: modifiers.map(i => i.replace('.', '')),
expression: attr.value
};
}).filter(i => {
// If no type is passed in for filtering, bypass filter
if (!type) return true;
return i.type === type;
});
}
function isBooleanAttr(attrName) {
// As per HTML spec table https://html.spec.whatwg.org/multipage/indices.html#attributes-3:boolean-attribute
// Array roughly ordered by estimated usage
const booleanAttributes = ['disabled', 'checked', 'required', 'readonly', 'hidden', 'open', 'selected', 'autofocus', 'itemscope', 'multiple', 'novalidate', 'allowfullscreen', 'allowpaymentrequest', 'formnovalidate', 'autoplay', 'controls', 'loop', 'muted', 'playsinline', 'default', 'ismap', 'reversed', 'async', 'defer', 'nomodule'];
return booleanAttributes.includes(attrName);
}
function replaceAtAndColonWithStandardSyntax(name) {
if (name.startsWith('@')) {
return name.replace('@', 'x-on:');
} else if (name.startsWith(':')) {
return name.replace(':', 'x-bind:');
}
return name;
}
function transitionIn(el, show, forceSkip = false) {
// We don't want to transition on the initial page load.
if (forceSkip) return show();
const attrs = getXAttrs(el, 'transition');
const showAttr = getXAttrs(el, 'show')[0]; // If this is triggered by a x-show.transition.
if (showAttr && showAttr.modifiers.includes('transition')) {
let modifiers = showAttr.modifiers; // If x-show.transition.out, we'll skip the "in" transition.
if (modifiers.includes('out') && !modifiers.includes('in')) return show();
const settingBothSidesOfTransition = modifiers.includes('in') && modifiers.includes('out'); // If x-show.transition.in...out... only use "in" related modifiers for this transition.
modifiers = settingBothSidesOfTransition ? modifiers.filter((i, index) => index < modifiers.indexOf('out')) : modifiers;
transitionHelperIn(el, modifiers, show); // Otherwise, we can assume x-transition:enter.
} else if (attrs.length > 0) {
transitionClassesIn(el, attrs, show);
} else {
// If neither, just show that damn thing.
show();
}
}
function transitionOut(el, hide, forceSkip = false) {
if (forceSkip) return hide();
const attrs = getXAttrs(el, 'transition');
const showAttr = getXAttrs(el, 'show')[0];
if (showAttr && showAttr.modifiers.includes('transition')) {
let modifiers = showAttr.modifiers;
if (modifiers.includes('in') && !modifiers.includes('out')) return hide();
const settingBothSidesOfTransition = modifiers.includes('in') && modifiers.includes('out');
modifiers = settingBothSidesOfTransition ? modifiers.filter((i, index) => index > modifiers.indexOf('out')) : modifiers;
transitionHelperOut(el, modifiers, settingBothSidesOfTransition, hide);
} else if (attrs.length > 0) {
transitionClassesOut(el, attrs, hide);
} else {
hide();
}
}
function transitionHelperIn(el, modifiers, showCallback) {
// Default values inspired by: https://material.io/design/motion/speed.html#duration
const styleValues = {
duration: modifierValue(modifiers, 'duration', 150),
origin: modifierValue(modifiers, 'origin', 'center'),
first: {
opacity: 0,
scale: modifierValue(modifiers, 'scale', 95)
},
second: {
opacity: 1,
scale: 100
}
};
transitionHelper(el, modifiers, showCallback, () => {}, styleValues);
}
function transitionHelperOut(el, modifiers, settingBothSidesOfTransition, hideCallback) {
// Make the "out" transition .5x slower than the "in". (Visually better)
// HOWEVER, if they explicitly set a duration for the "out" transition,
// use that.
const duration = settingBothSidesOfTransition ? modifierValue(modifiers, 'duration', 150) : modifierValue(modifiers, 'duration', 150) / 2;
const styleValues = {
duration: duration,
origin: modifierValue(modifiers, 'origin', 'center'),
first: {
opacity: 1,
scale: 100
},
second: {
opacity: 0,
scale: modifierValue(modifiers, 'scale', 95)
}
};
transitionHelper(el, modifiers, () => {}, hideCallback, styleValues);
}
function modifierValue(modifiers, key, fallback) {
// If the modifier isn't present, use the default.
if (modifiers.indexOf(key) === -1) return fallback; // If it IS present, grab the value after it: x-show.transition.duration.500ms
const rawValue = modifiers[modifiers.indexOf(key) + 1];
if (!rawValue) return fallback;
if (key === 'scale') {
// Check if the very next value is NOT a number and return the fallback.
// If x-show.transition.scale, we'll use the default scale value.
// That is how a user opts out of the opacity transition.
if (!isNumeric(rawValue)) return fallback;
}
if (key === 'duration') {
// Support x-show.transition.duration.500ms && duration.500
let match = rawValue.match(/([0-9]+)ms/);
if (match) return match[1];
}
if (key === 'origin') {
// Support chaining origin directions: x-show.transition.top.right
if (['top', 'right', 'left', 'center', 'bottom'].includes(modifiers[modifiers.indexOf(key) + 2])) {
return [rawValue, modifiers[modifiers.indexOf(key) + 2]].join(' ');
}
}
return rawValue;
}
function transitionHelper(el, modifiers, hook1, hook2, styleValues) {
// If the user set these style values, we'll put them back when we're done with them.
const opacityCache = el.style.opacity;
const transformCache = el.style.transform;
const transformOriginCache = el.style.transformOrigin; // If no modifiers are present: x-show.transition, we'll default to both opacity and scale.
const noModifiers = !modifiers.includes('opacity') && !modifiers.includes('scale');
const transitionOpacity = noModifiers || modifiers.includes('opacity');
const transitionScale = noModifiers || modifiers.includes('scale'); // These are the explicit stages of a transition (same stages for in and for out).
// This way you can get a birds eye view of the hooks, and the differences
// between them.
const stages = {
start() {
if (transitionOpacity) el.style.opacity = styleValues.first.opacity;
if (transitionScale) el.style.transform = `scale(${styleValues.first.scale / 100})`;
},
during() {
if (transitionScale) el.style.transformOrigin = styleValues.origin;
el.style.transitionProperty = [transitionOpacity ? `opacity` : ``, transitionScale ? `transform` : ``].join(' ').trim();
el.style.transitionDuration = `${styleValues.duration / 1000}s`;
el.style.transitionTimingFunction = `cubic-bezier(0.4, 0.0, 0.2, 1)`;
},
show() {
hook1();
},
end() {
if (transitionOpacity) el.style.opacity = styleValues.second.opacity;
if (transitionScale) el.style.transform = `scale(${styleValues.second.scale / 100})`;
},
hide() {
hook2();
},
cleanup() {
if (transitionOpacity) el.style.opacity = opacityCache;
if (transitionScale) el.style.transform = transformCache;
if (transitionScale) el.style.transformOrigin = transformOriginCache;
el.style.transitionProperty = null;
el.style.transitionDuration = null;
el.style.transitionTimingFunction = null;
}
};
transition(el, stages);
}
function transitionClassesIn(el, directives, showCallback) {
const enter = (directives.find(i => i.value === 'enter') || {
expression: ''
}).expression.split(' ').filter(i => i !== '');
const enterStart = (directives.find(i => i.value === 'enter-start') || {
expression: ''
}).expression.split(' ').filter(i => i !== '');
const enterEnd = (directives.find(i => i.value === 'enter-end') || {
expression: ''
}).expression.split(' ').filter(i => i !== '');
transitionClasses(el, enter, enterStart, enterEnd, showCallback, () => {});
}
function transitionClassesOut(el, directives, hideCallback) {
const leave = (directives.find(i => i.value === 'leave') || {
expression: ''
}).expression.split(' ').filter(i => i !== '');
const leaveStart = (directives.find(i => i.value === 'leave-start') || {
expression: ''
}).expression.split(' ').filter(i => i !== '');
const leaveEnd = (directives.find(i => i.value === 'leave-end') || {
expression: ''
}).expression.split(' ').filter(i => i !== '');
transitionClasses(el, leave, leaveStart, leaveEnd, () => {}, hideCallback);
}
function transitionClasses(el, classesDuring, classesStart, classesEnd, hook1, hook2) {
const originalClasses = el.__x_original_classes || [];
const stages = {
start() {
el.classList.add(...classesStart);
},
during() {
el.classList.add(...classesDuring);
},
show() {
hook1();
},
end() {
// Don't remove classes that were in the original class attribute.
el.classList.remove(...classesStart.filter(i => !originalClasses.includes(i)));
el.classList.add(...classesEnd);
},
hide() {
hook2();
},
cleanup() {
el.classList.remove(...classesDuring.filter(i => !originalClasses.includes(i)));
el.classList.remove(...classesEnd.filter(i => !originalClasses.includes(i)));
}
};
transition(el, stages);
}
function transition(el, stages) {
stages.start();
stages.during();
requestAnimationFrame(() => {
// Note: Safari's transitionDuration property will list out comma separated transition durations
// for every single transition property. Let's grab the first one and call it a day.
let duration = Number(getComputedStyle(el).transitionDuration.replace(/,.*/, '').replace('s', '')) * 1000;
stages.show();
requestAnimationFrame(() => {
stages.end();
setTimeout(() => {
stages.hide(); // Adding an "isConnected" check, in case the callback
// removed the element from the DOM.
if (el.isConnected) {
stages.cleanup();
}
}, duration);
});
});
}
function isNumeric(subject) {
return !isNaN(subject);
}
function handleForDirective(component, templateEl, expression, initialUpdate, extraVars) {
warnIfNotTemplateTag(templateEl);
let iteratorNames = parseForExpression(expression);
let items = evaluateItemsAndReturnEmptyIfXIfIsPresentAndFalseOnElement(component, templateEl, iteratorNames, extraVars); // As we walk the array, we'll also walk the DOM (updating/creating as we go).
let currentEl = templateEl;
items.forEach((item, index) => {
let iterationScopeVariables = getIterationScopeVariables(iteratorNames, item, index, items, extraVars());
let currentKey = generateKeyForIteration(component, templateEl, index, iterationScopeVariables);
let nextEl = lookAheadForMatchingKeyedElementAndMoveItIfFound(currentEl.nextElementSibling, currentKey); // If we haven't found a matching key, insert the element at the current position.
if (!nextEl) {
nextEl = addElementInLoopAfterCurrentEl(templateEl, currentEl); // And transition it in if it's not the first page load.
transitionIn(nextEl, () => {}, initialUpdate);
nextEl.__x_for = iterationScopeVariables;
component.initializeElements(nextEl, () => nextEl.__x_for); // Otherwise update the element we found.
} else {
// Temporarily remove the key indicator to allow the normal "updateElements" to work.
delete nextEl.__x_for_key;
nextEl.__x_for = iterationScopeVariables;
component.updateElements(nextEl, () => nextEl.__x_for);
}
currentEl = nextEl;
currentEl.__x_for_key = currentKey;
});
removeAnyLeftOverElementsFromPreviousUpdate(currentEl);
} // This was taken from VueJS 2.* core. Thanks Vue!
function parseForExpression(expression) {
let forIteratorRE = /,([^,\}\]]*)(?:,([^,\}\]]*))?$/;
let stripParensRE = /^\(|\)$/g;
let forAliasRE = /([\s\S]*?)\s+(?:in|of)\s+([\s\S]*)/;
let inMatch = expression.match(forAliasRE);
if (!inMatch) return;
let res = {};
res.items = inMatch[2].trim();
let item = inMatch[1].trim().replace(stripParensRE, '');
let iteratorMatch = item.match(forIteratorRE);
if (iteratorMatch) {
res.item = item.replace(forIteratorRE, '').trim();
res.index = iteratorMatch[1].trim();
if (iteratorMatch[2]) {
res.collection = iteratorMatch[2].trim();
}
} else {
res.item = item;
}
return res;
}
function getIterationScopeVariables(iteratorNames, item, index, items, extraVars) {
// We must create a new object, so each iteration has a new scope
let scopeVariables = extraVars ? _objectSpread2({}, extraVars) : {};
scopeVariables[iteratorNames.item] = item;
if (iteratorNames.index) scopeVariables[iteratorNames.index] = index;
if (iteratorNames.collection) scopeVariables[iteratorNames.collection] = items;
return scopeVariables;
}
function generateKeyForIteration(component, el, index, iterationScopeVariables) {
let bindKeyAttribute = getXAttrs(el, 'bind').filter(attr => attr.value === 'key')[0]; // If the dev hasn't specified a key, just return the index of the iteration.
if (!bindKeyAttribute) return index;
return component.evaluateReturnExpression(el, bindKeyAttribute.expression, () => iterationScopeVariables);
}
function warnIfNotTemplateTag(el) {
if (el.tagName.toLowerCase() !== 'template') console.warn('Alpine: [x-for] directive should only be added to <template> tags.');
}
function evaluateItemsAndReturnEmptyIfXIfIsPresentAndFalseOnElement(component, el, iteratorNames, extraVars) {
let ifAttribute = getXAttrs(el, 'if')[0];
if (ifAttribute && !component.evaluateReturnExpression(el, ifAttribute.expression)) {
return [];
}
return component.evaluateReturnExpression(el, iteratorNames.items, extraVars);
}
function addElementInLoopAfterCurrentEl(templateEl, currentEl) {
let clone = document.importNode(templateEl.content, true);
if (clone.childElementCount !== 1) console.warn('Alpine: <template> tag with [x-for] encountered with multiple element roots. Make sure <template> only has a single child node.');
currentEl.parentElement.insertBefore(clone, currentEl.nextElementSibling);
return currentEl.nextElementSibling;
}
function lookAheadForMatchingKeyedElementAndMoveItIfFound(nextEl, currentKey) {
if (!nextEl) return; // If the the key's DO match, no need to look ahead.
if (nextEl.__x_for_key === currentKey) return nextEl; // If they don't, we'll look ahead for a match.
// If we find it, we'll move it to the current position in the loop.
let tmpNextEl = nextEl;
while (tmpNextEl) {
if (tmpNextEl.__x_for_key === currentKey) {
return tmpNextEl.parentElement.insertBefore(tmpNextEl, nextEl);
}
tmpNextEl = tmpNextEl.nextElementSibling && tmpNextEl.nextElementSibling.__x_for_key !== undefined ? tmpNextEl.nextElementSibling : false;
}
}
function removeAnyLeftOverElementsFromPreviousUpdate(currentEl) {
var nextElementFromOldLoop = currentEl.nextElementSibling && currentEl.nextElementSibling.__x_for_key !== undefined ? currentEl.nextElementSibling : false;
while (nextElementFromOldLoop) {
let nextElementFromOldLoopImmutable = nextElementFromOldLoop;
let nextSibling = nextElementFromOldLoop.nextElementSibling;
transitionOut(nextElementFromOldLoop, () => {
nextElementFromOldLoopImmutable.remove();
});
nextElementFromOldLoop = nextSibling && nextSibling.__x_for_key !== undefined ? nextSibling : false;
}
}
function handleAttributeBindingDirective(component, el, attrName, expression, extraVars, attrType) {
var value = component.evaluateReturnExpression(el, expression, extraVars);
if (attrName === 'value') {
// If nested model key is undefined, set the default value to empty string.
if (value === undefined && expression.match(/\./).length) {
value = '';
}
if (el.type === 'radio') {
// Set radio value from x-bind:value, if no "value" attribute exists.
// If there are any initial state values, radio will have a correct
// "checked" value since x-bind:value is processed before x-model.
if (el.attributes.value === undefined && attrType === 'bind') {
el.value = value;
} else if (attrType !== 'bind') {
el.checked = el.value == value;
}
} else if (el.type === 'checkbox') {
if (Array.isArray(value)) {
// I'm purposely not using Array.includes here because it's
// strict, and because of Numeric/String mis-casting, I
// want the "includes" to be "fuzzy".
let valueFound = false;
value.forEach(val => {
if (val == el.value) {
valueFound = true;
}
});
el.checked = valueFound;
} else {
el.checked = !!value;
} // If we are explicitly binding a string to the :value, set the string,
// If the value is a boolean, leave it alone, it will be set to "on"
// automatically.
if (typeof value === 'string') {
el.value = value;
}
} else if (el.tagName === 'SELECT') {
updateSelect(el, value);
} else {
if (el.value === value) return;
el.value = value;
}
} else if (attrName === 'class') {
if (Array.isArray(value)) {
const originalClasses = el.__x_original_classes || [];
el.setAttribute('class', arrayUnique(originalClasses.concat(value)).join(' '));
} else if (typeof value === 'object') {
// Sorting the keys / class names by their boolean value will ensure that
// anything that evaluates to `false` and needs to remove classes is run first.
const keysSortedByBooleanValue = Object.keys(value).sort((a, b) => value[a] - value[b]);
keysSortedByBooleanValue.forEach(classNames => {
if (value[classNames]) {
classNames.split(' ').filter(Boolean).forEach(className => el.classList.add(className));
} else {
classNames.split(' ').filter(Boolean).forEach(className => el.classList.remove(className));
}
});
} else {
const originalClasses = el.__x_original_classes || [];
const newClasses = value.split(' ').filter(Boolean);
el.setAttribute('class', arrayUnique(originalClasses.concat(newClasses)).join(' '));
}
} else {
// If an attribute's bound value is null, undefined or false, remove the attribute
if ([null, undefined, false].includes(value)) {
el.removeAttribute(attrName);
} else {
isBooleanAttr(attrName) ? el.setAttribute(attrName, attrName) : el.setAttribute(attrName, value);
}
}
}
function updateSelect(el, value) {
const arrayWrappedValue = [].concat(value).map(value => {
return value + '';
});
Array.from(el.options).forEach(option => {
option.selected = arrayWrappedValue.includes(option.value || option.text);
});
}
function handleTextDirective(el, output, expression) {
// If nested model key is undefined, set the default value to empty string.
if (output === undefined && expression.match(/\./).length) {
output = '';
}
el.innerText = output;
}
function handleHtmlDirective(component, el, expression, extraVars) {
el.innerHTML = component.evaluateReturnExpression(el, expression, extraVars);
}
function handleShowDirective(component, el, value, modifiers, initialUpdate = false) {
const hide = () => {
el.style.display = 'none';
};
const show = () => {
if (el.style.length === 1 && el.style.display === 'none') {
el.removeAttribute('style');
} else {
el.style.removeProperty('display');
}
};
if (initialUpdate === true) {
if (value) {
show();
} else {
hide();
}
return;
}
const handle = resolve => {
if (!value) {
if (el.style.display !== 'none') {
transitionOut(el, () => {
resolve(() => {
hide();
});
});
} else {
resolve(() => {});
}
} else {
if (el.style.display !== '') {
transitionIn(el, () => {
show();
});
} // Resolve immediately, only hold up parent `x-show`s for hidin.
resolve(() => {});
}
}; // The working of x-show is a bit complex because we need to
// wait for any child transitions to finish before hiding
// some element. Also, this has to be done recursively.
// If x-show.immediate, foregoe the waiting.
if (modifiers.includes('immediate')) {
handle(finish => finish());
return;
} // x-show is encountered during a DOM tree walk. If an element
// we encounter is NOT a child of another x-show element we
// can execute the previous x-show stack (if one exists).
if (component.showDirectiveLastElement && !component.showDirectiveLastElement.contains(el)) {
component.executeAndClearRemainingShowDirectiveStack();
} // We'll push the handler onto a stack to be handled later.
component.showDirectiveStack.push(handle);
component.showDirectiveLastElement = el;
}
function handleIfDirective(component, el, expressionResult, initialUpdate, extraVars) {
if (el.nodeName.toLowerCase() !== 'template') console.warn(`Alpine: [x-if] directive should only be added to <template> tags. See https://github.com/alpinejs/alpine#x-if`);
const elementHasAlreadyBeenAdded = el.nextElementSibling && el.nextElementSibling.__x_inserted_me === true;
if (expressionResult && !elementHasAlreadyBeenAdded) {
const clone = document.importNode(el.content, true);
el.parentElement.insertBefore(clone, el.nextElementSibling);
transitionIn(el.nextElementSibling, () => {}, initialUpdate);
component.initializeElements(el.nextElementSibling, extraVars);
el.nextElementSibling.__x_inserted_me = true;
} else if (!expressionResult && elementHasAlreadyBeenAdded) {
transitionOut(el.nextElementSibling, () => {
el.nextElementSibling.remove();
}, initialUpdate);
}
}
function registerListener(component, el, event, modifiers, expression, extraVars = {}) {
if (modifiers.includes('away')) {
let handler = e => {
// Don't do anything if the click came form the element or within it.
if (el.contains(e.target)) return; // Don't do anything if this element isn't currently visible.
if (el.offsetWidth < 1 && el.offsetHeight < 1) return; // Now that we are sure the element is visible, AND the click
// is from outside it, let's run the expression.
runListenerHandler(component, expression, e, extraVars);
if (modifiers.includes('once')) {
document.removeEventListener(event, handler);
}
}; // Listen for this event at the root level.
document.addEventListener(event, handler);
} else {
let listenerTarget = modifiers.includes('window') ? window : modifiers.includes('document') ? document : el;
let handler = e => {
// Remove this global event handler if the element that declared it
// has been removed. It's now stale.
if (listenerTarget === window || listenerTarget === document) {
if (!document.body.contains(el)) {
listenerTarget.removeEventListener(event, handler);
return;
}
}
if (isKeyEvent(event)) {
if (isListeningForASpecificKeyThatHasntBeenPressed(e, modifiers)) {
return;
}
}
if (modifiers.includes('prevent')) e.preventDefault();
if (modifiers.includes('stop')) e.stopPropagation(); // If the .self modifier isn't present, or if it is present and
// the target element matches the element we are registering the
// event on, run the handler
if (!modifiers.includes('self') || e.target === el) {
const returnValue = runListenerHandler(component, expression, e, extraVars);
if (returnValue === false) {
e.preventDefault();
} else {
if (modifiers.includes('once')) {
listenerTarget.removeEventListener(event, handler);
}
}
}
};
if (modifiers.includes('debounce')) {
let nextModifier = modifiers[modifiers.indexOf('debounce') + 1] || 'invalid-wait';
let wait = isNumeric(nextModifier.split('ms')[0]) ? Number(nextModifier.split('ms')[0]) : 250;
handler = debounce(handler, wait);
}
listenerTarget.addEventListener(event, handler);
}
}
function runListenerHandler(component, expression, e, extraVars) {
return component.evaluateCommandExpression(e.target, expression, () => {
return _objectSpread2({}, extraVars(), {
'$event': e
});
});
}
function isKeyEvent(event) {
return ['keydown', 'keyup'].includes(event);
}
function isListeningForASpecificKeyThatHasntBeenPressed(e, modifiers) {
let keyModifiers = modifiers.filter(i => {
return !['window', 'document', 'prevent', 'stop'].includes(i);
});
if (keyModifiers.includes('debounce')) {
let debounceIndex = keyModifiers.indexOf('debounce');
keyModifiers.splice(debounceIndex, isNumeric((keyModifiers[debounceIndex + 1] || 'invalid-wait').split('ms')[0]) ? 2 : 1);
} // If no modifier is specified, we'll call it a press.
if (keyModifiers.length === 0) return false; // If one is passed, AND it matches the key pressed, we'll call it a press.
if (keyModifiers.length === 1 && keyModifiers[0] === keyToModifier(e.key)) return false; // The user is listening for key combinations.
const systemKeyModifiers = ['ctrl', 'shift', 'alt', 'meta', 'cmd', 'super'];
const selectedSystemKeyModifiers = systemKeyModifiers.filter(modifier => keyModifiers.includes(modifier));
keyModifiers = keyModifiers.filter(i => !selectedSystemKeyModifiers.includes(i));
if (selectedSystemKeyModifiers.length > 0) {
const activelyPressedKeyModifiers = selectedSystemKeyModifiers.filter(modifier => {
// Alias "cmd" and "super" to "meta"
if (modifier === 'cmd' || modifier === 'super') modifier = 'meta';
return e[`${modifier}Key`];
}); // If all the modifiers selected are pressed, ...
if (activelyPressedKeyModifiers.length === selectedSystemKeyModifiers.length) {
// AND the remaining key is pressed as well. It's a press.
if (keyModifiers[0] === keyToModifier(e.key)) return false;
}
} // We'll call it NOT a valid keypress.
return true;
}
function keyToModifier(key) {
switch (key) {
case '/':
return 'slash';
case ' ':
case 'Spacebar':
return 'space';
default:
return key && kebabCase(key);
}
}
function registerModelListener(component, el, modifiers, expression, extraVars) {
// If the element we are binding to is a select, a radio, or checkbox
// we'll listen for the change event instead of the "input" event.
var event = el.tagName.toLowerCase() === 'select' || ['checkbox', 'radio'].includes(el.type) || modifiers.includes('lazy') ? 'change' : 'input';
const listenerExpression = `${expression} = rightSideOfExpression($event, ${expression})`;
registerListener(component, el, event, modifiers, listenerExpression, () => {
return _objectSpread2({}, extraVars(), {
rightSideOfExpression: generateModelAssignmentFunction(el, modifiers, expression)
});
});
}
function generateModelAssignmentFunction(el, modifiers, expression) {
if (el.type === 'radio') {
// Radio buttons only work properly when they share a name attribute.
// People might assume we take care of that for them, because
// they already set a shared "x-model" attribute.
if (!el.hasAttribute('name')) el.setAttribute('name', expression);
}
return (event, currentValue) => {
// Check for event.detail due to an issue where IE11 handles other events as a CustomEvent.
if (event instanceof CustomEvent && event.detail) {
return event.detail;
} else if (el.type === 'checkbox') {
// If the data we are binding to is an array, toggle it's value inside the array.
if (Array.isArray(currentValue)) {
return event.target.checked ? currentValue.concat([event.target.value]) : currentValue.filter(i => i !== event.target.value);
} else {
return event.target.checked;
}
} else if (el.tagName.toLowerCase() === 'select' && el.multiple) {
return modifiers.includes('number') ? Array.from(event.target.selectedOptions).map(option => {
const rawValue = option.value || option.text;
const number = rawValue ? parseFloat(rawValue) : null;
return isNaN(number) ? rawValue : number;
}) : Array.from(event.target.selectedOptions).map(option => {
return option.value || option.text;
});
} else {
const rawValue = event.target.value;
const number = rawValue ? parseFloat(rawValue) : null;
return modifiers.includes('number') ? isNaN(number) ? rawValue : number : modifiers.includes('trim') ? rawValue.trim() : rawValue;
}
};
}
/**
* Copyright (C) 2017 salesforce.com, inc.
*/
const { isArray } = Array;
const { getPrototypeOf, create: ObjectCreate, defineProperty: ObjectDefineProperty, defineProperties: ObjectDefineProperties, isExtensible, getOwnPropertyDescriptor, getOwnPropertyNames, getOwnPropertySymbols, preventExtensions, hasOwnProperty, } = Object;
const { push: ArrayPush, concat: ArrayConcat, map: ArrayMap, } = Array.prototype;
function isUndefined(obj) {
return obj === undefined;
}
function isFunction(obj) {
return typeof obj === 'function';
}
function isObject(obj) {
return typeof obj === 'object';
}
const proxyToValueMap = new WeakMap();
function registerProxy(proxy, value) {
proxyToValueMap.set(proxy, value);
}
const unwrap = (replicaOrAny) => proxyToValueMap.get(replicaOrAny) || replicaOrAny;
function wrapValue(membrane, value) {
return membrane.valueIsObservable(value) ? membrane.getProxy(value) : value;
}
/**
* Unwrap property descriptors will set value on original descriptor
* We only need to unwrap if value is specified
* @param descriptor external descrpitor provided to define new property on original value
*/
function unwrapDescriptor(descriptor) {
if (hasOwnProperty.call(descriptor, 'value')) {
descriptor.value = unwrap(descriptor.value);
}
return descriptor;
}
function lockShadowTarget(membrane, shadowTarget, originalTarget) {
const targetKeys = ArrayConcat.call(getOwnPropertyNames(originalTarget), getOwnPropertySymbols(originalTarget));
targetKeys.forEach((key) => {
let descriptor = getOwnPropertyDescriptor(originalTarget, key);
// We do not need to wrap the descriptor if configurable
// Because we can deal with wrapping it when user goes through
// Get own property descriptor. There is also a chance that this descriptor
// could change sometime in the future, so we can defer wrapping
// until we need to
if (!descriptor.configurable) {
descriptor = wrapDescriptor(membrane, descriptor, wrapValue);
}
ObjectDefineProperty(shadowTarget, key, descriptor);
});
preventExtensions(shadowTarget);
}
class ReactiveProxyHandler {
constructor(membrane, value) {
this.originalTarget = value;
this.membrane = membrane;
}
get(shadowTarget, key) {
const { originalTarget, membrane } = this;
const value = originalTarget[key];
const { valueObserved } = membrane;
valueObserved(originalTarget, key);
return membrane.getProxy(value);
}
set(shadowTarget, key, value) {
const { originalTarget, membrane: { valueMutated } } = this;
const oldValue = originalTarget[key];
if (oldValue !== value) {
originalTarget[key] = value;
valueMutated(originalTarget, key);
}
else if (key === 'length' && isArray(originalTarget)) {
// fix for issue #236: push will add the new index, and by the time length
// is updated, the internal length is already equal to the new length value
// therefore, the oldValue is equal to the value. This is the forking logic
// to support this use case.
valueMutated(originalTarget, key);
}
return true;
}
deleteProperty(shadowTarget, key) {
const { originalTarget, membrane: { valueMutated } } = this;
delete originalTarget[key];
valueMutated(originalTarget, key);
return true;
}
apply(shadowTarget, thisArg, argArray) {
/* No op */
}
construct(target, argArray, newTarget) {
/* No op */
}
has(shadowTarget, key) {
const { originalTarget, membrane: { valueObserved } } = this;
valueObserved(originalTarget, key);
return key in originalTarget;
}
ownKeys(shadowTarget) {
const { originalTarget } = this;
return ArrayConcat.call(getOwnPropertyNames(originalTarget), getOwnPropertySymbols(originalTarget));
}
isExtensible(shadowTarget) {
const shadowIsExtensible = isExtensible(shadowTarget);
if (!shadowIsExtensible) {
return shadowIsExtensible;
}
const { originalTarget, membrane } = this;
const targetIsExtensible = isExtensible(originalTarget);
if (!targetIsExtensible) {
lockShadowTarget(membrane, shadowTarget, originalTarget);
}
return targetIsExtensible;
}
setPrototypeOf(shadowTarget, prototype) {
}
getPrototypeOf(shadowTarget) {
const { originalTarget } = this;
return getPrototypeOf(originalTarget);
}
getOwnPropertyDescriptor(shadowTarget, key) {
const { originalTarget, membrane } = this;
const { valueObserved } = this.membrane;
// keys looked up via hasOwnProperty need to be reactive
valueObserved(originalTarget, key);
let desc = getOwnPropertyDescriptor(originalTarget, key);
if (isUndefined(desc)) {
return desc;
}
const shadowDescriptor = getOwnPropertyDescriptor(shadowTarget, key);
if (!isUndefined(shadowDescriptor)) {
return shadowDescriptor;
}
// Note: by accessing the descriptor, the key is marked as observed
// but access to the value, setter or getter (if available) cannot observe