stimulus-rails 0.5.3 → 0.6.2

Sign up to get free protection for your applications and to get access to all the features.
@@ -1,4 +1,1947 @@
1
- //= require ./stimulus@2.js
2
- //= link ./stimulus@3.0.0-beta.2.js
3
1
  //= link ./stimulus-autoloader.js
4
2
  //= link ./stimulus-importmap-autoloader.js
3
+
4
+ /*
5
+ Stimulus 3.0.1
6
+ Copyright © 2021 Basecamp, LLC
7
+ */
8
+ class EventListener {
9
+ constructor(eventTarget, eventName, eventOptions) {
10
+ this.eventTarget = eventTarget;
11
+ this.eventName = eventName;
12
+ this.eventOptions = eventOptions;
13
+ this.unorderedBindings = new Set();
14
+ }
15
+ connect() {
16
+ this.eventTarget.addEventListener(this.eventName, this, this.eventOptions);
17
+ }
18
+ disconnect() {
19
+ this.eventTarget.removeEventListener(this.eventName, this, this.eventOptions);
20
+ }
21
+ bindingConnected(binding) {
22
+ this.unorderedBindings.add(binding);
23
+ }
24
+ bindingDisconnected(binding) {
25
+ this.unorderedBindings.delete(binding);
26
+ }
27
+ handleEvent(event) {
28
+ const extendedEvent = extendEvent(event);
29
+ for (const binding of this.bindings) {
30
+ if (extendedEvent.immediatePropagationStopped) {
31
+ break;
32
+ }
33
+ else {
34
+ binding.handleEvent(extendedEvent);
35
+ }
36
+ }
37
+ }
38
+ get bindings() {
39
+ return Array.from(this.unorderedBindings).sort((left, right) => {
40
+ const leftIndex = left.index, rightIndex = right.index;
41
+ return leftIndex < rightIndex ? -1 : leftIndex > rightIndex ? 1 : 0;
42
+ });
43
+ }
44
+ }
45
+ function extendEvent(event) {
46
+ if ("immediatePropagationStopped" in event) {
47
+ return event;
48
+ }
49
+ else {
50
+ const { stopImmediatePropagation } = event;
51
+ return Object.assign(event, {
52
+ immediatePropagationStopped: false,
53
+ stopImmediatePropagation() {
54
+ this.immediatePropagationStopped = true;
55
+ stopImmediatePropagation.call(this);
56
+ }
57
+ });
58
+ }
59
+ }
60
+
61
+ class Dispatcher {
62
+ constructor(application) {
63
+ this.application = application;
64
+ this.eventListenerMaps = new Map;
65
+ this.started = false;
66
+ }
67
+ start() {
68
+ if (!this.started) {
69
+ this.started = true;
70
+ this.eventListeners.forEach(eventListener => eventListener.connect());
71
+ }
72
+ }
73
+ stop() {
74
+ if (this.started) {
75
+ this.started = false;
76
+ this.eventListeners.forEach(eventListener => eventListener.disconnect());
77
+ }
78
+ }
79
+ get eventListeners() {
80
+ return Array.from(this.eventListenerMaps.values())
81
+ .reduce((listeners, map) => listeners.concat(Array.from(map.values())), []);
82
+ }
83
+ bindingConnected(binding) {
84
+ this.fetchEventListenerForBinding(binding).bindingConnected(binding);
85
+ }
86
+ bindingDisconnected(binding) {
87
+ this.fetchEventListenerForBinding(binding).bindingDisconnected(binding);
88
+ }
89
+ handleError(error, message, detail = {}) {
90
+ this.application.handleError(error, `Error ${message}`, detail);
91
+ }
92
+ fetchEventListenerForBinding(binding) {
93
+ const { eventTarget, eventName, eventOptions } = binding;
94
+ return this.fetchEventListener(eventTarget, eventName, eventOptions);
95
+ }
96
+ fetchEventListener(eventTarget, eventName, eventOptions) {
97
+ const eventListenerMap = this.fetchEventListenerMapForEventTarget(eventTarget);
98
+ const cacheKey = this.cacheKey(eventName, eventOptions);
99
+ let eventListener = eventListenerMap.get(cacheKey);
100
+ if (!eventListener) {
101
+ eventListener = this.createEventListener(eventTarget, eventName, eventOptions);
102
+ eventListenerMap.set(cacheKey, eventListener);
103
+ }
104
+ return eventListener;
105
+ }
106
+ createEventListener(eventTarget, eventName, eventOptions) {
107
+ const eventListener = new EventListener(eventTarget, eventName, eventOptions);
108
+ if (this.started) {
109
+ eventListener.connect();
110
+ }
111
+ return eventListener;
112
+ }
113
+ fetchEventListenerMapForEventTarget(eventTarget) {
114
+ let eventListenerMap = this.eventListenerMaps.get(eventTarget);
115
+ if (!eventListenerMap) {
116
+ eventListenerMap = new Map;
117
+ this.eventListenerMaps.set(eventTarget, eventListenerMap);
118
+ }
119
+ return eventListenerMap;
120
+ }
121
+ cacheKey(eventName, eventOptions) {
122
+ const parts = [eventName];
123
+ Object.keys(eventOptions).sort().forEach(key => {
124
+ parts.push(`${eventOptions[key] ? "" : "!"}${key}`);
125
+ });
126
+ return parts.join(":");
127
+ }
128
+ }
129
+
130
+ const descriptorPattern = /^((.+?)(@(window|document))?->)?(.+?)(#([^:]+?))(:(.+))?$/;
131
+ function parseActionDescriptorString(descriptorString) {
132
+ const source = descriptorString.trim();
133
+ const matches = source.match(descriptorPattern) || [];
134
+ return {
135
+ eventTarget: parseEventTarget(matches[4]),
136
+ eventName: matches[2],
137
+ eventOptions: matches[9] ? parseEventOptions(matches[9]) : {},
138
+ identifier: matches[5],
139
+ methodName: matches[7]
140
+ };
141
+ }
142
+ function parseEventTarget(eventTargetName) {
143
+ if (eventTargetName == "window") {
144
+ return window;
145
+ }
146
+ else if (eventTargetName == "document") {
147
+ return document;
148
+ }
149
+ }
150
+ function parseEventOptions(eventOptions) {
151
+ return eventOptions.split(":").reduce((options, token) => Object.assign(options, { [token.replace(/^!/, "")]: !/^!/.test(token) }), {});
152
+ }
153
+ function stringifyEventTarget(eventTarget) {
154
+ if (eventTarget == window) {
155
+ return "window";
156
+ }
157
+ else if (eventTarget == document) {
158
+ return "document";
159
+ }
160
+ }
161
+
162
+ function camelize(value) {
163
+ return value.replace(/(?:[_-])([a-z0-9])/g, (_, char) => char.toUpperCase());
164
+ }
165
+ function capitalize(value) {
166
+ return value.charAt(0).toUpperCase() + value.slice(1);
167
+ }
168
+ function dasherize(value) {
169
+ return value.replace(/([A-Z])/g, (_, char) => `-${char.toLowerCase()}`);
170
+ }
171
+ function tokenize(value) {
172
+ return value.match(/[^\s]+/g) || [];
173
+ }
174
+
175
+ class Action {
176
+ constructor(element, index, descriptor) {
177
+ this.element = element;
178
+ this.index = index;
179
+ this.eventTarget = descriptor.eventTarget || element;
180
+ this.eventName = descriptor.eventName || getDefaultEventNameForElement(element) || error("missing event name");
181
+ this.eventOptions = descriptor.eventOptions || {};
182
+ this.identifier = descriptor.identifier || error("missing identifier");
183
+ this.methodName = descriptor.methodName || error("missing method name");
184
+ }
185
+ static forToken(token) {
186
+ return new this(token.element, token.index, parseActionDescriptorString(token.content));
187
+ }
188
+ toString() {
189
+ const eventNameSuffix = this.eventTargetName ? `@${this.eventTargetName}` : "";
190
+ return `${this.eventName}${eventNameSuffix}->${this.identifier}#${this.methodName}`;
191
+ }
192
+ get params() {
193
+ if (this.eventTarget instanceof Element) {
194
+ return this.getParamsFromEventTargetAttributes(this.eventTarget);
195
+ }
196
+ else {
197
+ return {};
198
+ }
199
+ }
200
+ getParamsFromEventTargetAttributes(eventTarget) {
201
+ const params = {};
202
+ const pattern = new RegExp(`^data-${this.identifier}-(.+)-param$`);
203
+ const attributes = Array.from(eventTarget.attributes);
204
+ attributes.forEach(({ name, value }) => {
205
+ const match = name.match(pattern);
206
+ const key = match && match[1];
207
+ if (key) {
208
+ Object.assign(params, { [camelize(key)]: typecast(value) });
209
+ }
210
+ });
211
+ return params;
212
+ }
213
+ get eventTargetName() {
214
+ return stringifyEventTarget(this.eventTarget);
215
+ }
216
+ }
217
+ const defaultEventNames = {
218
+ "a": e => "click",
219
+ "button": e => "click",
220
+ "form": e => "submit",
221
+ "details": e => "toggle",
222
+ "input": e => e.getAttribute("type") == "submit" ? "click" : "input",
223
+ "select": e => "change",
224
+ "textarea": e => "input"
225
+ };
226
+ function getDefaultEventNameForElement(element) {
227
+ const tagName = element.tagName.toLowerCase();
228
+ if (tagName in defaultEventNames) {
229
+ return defaultEventNames[tagName](element);
230
+ }
231
+ }
232
+ function error(message) {
233
+ throw new Error(message);
234
+ }
235
+ function typecast(value) {
236
+ try {
237
+ return JSON.parse(value);
238
+ }
239
+ catch (o_O) {
240
+ return value;
241
+ }
242
+ }
243
+
244
+ class Binding {
245
+ constructor(context, action) {
246
+ this.context = context;
247
+ this.action = action;
248
+ }
249
+ get index() {
250
+ return this.action.index;
251
+ }
252
+ get eventTarget() {
253
+ return this.action.eventTarget;
254
+ }
255
+ get eventOptions() {
256
+ return this.action.eventOptions;
257
+ }
258
+ get identifier() {
259
+ return this.context.identifier;
260
+ }
261
+ handleEvent(event) {
262
+ if (this.willBeInvokedByEvent(event)) {
263
+ this.invokeWithEvent(event);
264
+ }
265
+ }
266
+ get eventName() {
267
+ return this.action.eventName;
268
+ }
269
+ get method() {
270
+ const method = this.controller[this.methodName];
271
+ if (typeof method == "function") {
272
+ return method;
273
+ }
274
+ throw new Error(`Action "${this.action}" references undefined method "${this.methodName}"`);
275
+ }
276
+ invokeWithEvent(event) {
277
+ const { target, currentTarget } = event;
278
+ try {
279
+ const { params } = this.action;
280
+ const actionEvent = Object.assign(event, { params });
281
+ this.method.call(this.controller, actionEvent);
282
+ this.context.logDebugActivity(this.methodName, { event, target, currentTarget, action: this.methodName });
283
+ }
284
+ catch (error) {
285
+ const { identifier, controller, element, index } = this;
286
+ const detail = { identifier, controller, element, index, event };
287
+ this.context.handleError(error, `invoking action "${this.action}"`, detail);
288
+ }
289
+ }
290
+ willBeInvokedByEvent(event) {
291
+ const eventTarget = event.target;
292
+ if (this.element === eventTarget) {
293
+ return true;
294
+ }
295
+ else if (eventTarget instanceof Element && this.element.contains(eventTarget)) {
296
+ return this.scope.containsElement(eventTarget);
297
+ }
298
+ else {
299
+ return this.scope.containsElement(this.action.element);
300
+ }
301
+ }
302
+ get controller() {
303
+ return this.context.controller;
304
+ }
305
+ get methodName() {
306
+ return this.action.methodName;
307
+ }
308
+ get element() {
309
+ return this.scope.element;
310
+ }
311
+ get scope() {
312
+ return this.context.scope;
313
+ }
314
+ }
315
+
316
+ class ElementObserver {
317
+ constructor(element, delegate) {
318
+ this.mutationObserverInit = { attributes: true, childList: true, subtree: true };
319
+ this.element = element;
320
+ this.started = false;
321
+ this.delegate = delegate;
322
+ this.elements = new Set;
323
+ this.mutationObserver = new MutationObserver((mutations) => this.processMutations(mutations));
324
+ }
325
+ start() {
326
+ if (!this.started) {
327
+ this.started = true;
328
+ this.mutationObserver.observe(this.element, this.mutationObserverInit);
329
+ this.refresh();
330
+ }
331
+ }
332
+ pause(callback) {
333
+ if (this.started) {
334
+ this.mutationObserver.disconnect();
335
+ this.started = false;
336
+ }
337
+ callback();
338
+ if (!this.started) {
339
+ this.mutationObserver.observe(this.element, this.mutationObserverInit);
340
+ this.started = true;
341
+ }
342
+ }
343
+ stop() {
344
+ if (this.started) {
345
+ this.mutationObserver.takeRecords();
346
+ this.mutationObserver.disconnect();
347
+ this.started = false;
348
+ }
349
+ }
350
+ refresh() {
351
+ if (this.started) {
352
+ const matches = new Set(this.matchElementsInTree());
353
+ for (const element of Array.from(this.elements)) {
354
+ if (!matches.has(element)) {
355
+ this.removeElement(element);
356
+ }
357
+ }
358
+ for (const element of Array.from(matches)) {
359
+ this.addElement(element);
360
+ }
361
+ }
362
+ }
363
+ processMutations(mutations) {
364
+ if (this.started) {
365
+ for (const mutation of mutations) {
366
+ this.processMutation(mutation);
367
+ }
368
+ }
369
+ }
370
+ processMutation(mutation) {
371
+ if (mutation.type == "attributes") {
372
+ this.processAttributeChange(mutation.target, mutation.attributeName);
373
+ }
374
+ else if (mutation.type == "childList") {
375
+ this.processRemovedNodes(mutation.removedNodes);
376
+ this.processAddedNodes(mutation.addedNodes);
377
+ }
378
+ }
379
+ processAttributeChange(node, attributeName) {
380
+ const element = node;
381
+ if (this.elements.has(element)) {
382
+ if (this.delegate.elementAttributeChanged && this.matchElement(element)) {
383
+ this.delegate.elementAttributeChanged(element, attributeName);
384
+ }
385
+ else {
386
+ this.removeElement(element);
387
+ }
388
+ }
389
+ else if (this.matchElement(element)) {
390
+ this.addElement(element);
391
+ }
392
+ }
393
+ processRemovedNodes(nodes) {
394
+ for (const node of Array.from(nodes)) {
395
+ const element = this.elementFromNode(node);
396
+ if (element) {
397
+ this.processTree(element, this.removeElement);
398
+ }
399
+ }
400
+ }
401
+ processAddedNodes(nodes) {
402
+ for (const node of Array.from(nodes)) {
403
+ const element = this.elementFromNode(node);
404
+ if (element && this.elementIsActive(element)) {
405
+ this.processTree(element, this.addElement);
406
+ }
407
+ }
408
+ }
409
+ matchElement(element) {
410
+ return this.delegate.matchElement(element);
411
+ }
412
+ matchElementsInTree(tree = this.element) {
413
+ return this.delegate.matchElementsInTree(tree);
414
+ }
415
+ processTree(tree, processor) {
416
+ for (const element of this.matchElementsInTree(tree)) {
417
+ processor.call(this, element);
418
+ }
419
+ }
420
+ elementFromNode(node) {
421
+ if (node.nodeType == Node.ELEMENT_NODE) {
422
+ return node;
423
+ }
424
+ }
425
+ elementIsActive(element) {
426
+ if (element.isConnected != this.element.isConnected) {
427
+ return false;
428
+ }
429
+ else {
430
+ return this.element.contains(element);
431
+ }
432
+ }
433
+ addElement(element) {
434
+ if (!this.elements.has(element)) {
435
+ if (this.elementIsActive(element)) {
436
+ this.elements.add(element);
437
+ if (this.delegate.elementMatched) {
438
+ this.delegate.elementMatched(element);
439
+ }
440
+ }
441
+ }
442
+ }
443
+ removeElement(element) {
444
+ if (this.elements.has(element)) {
445
+ this.elements.delete(element);
446
+ if (this.delegate.elementUnmatched) {
447
+ this.delegate.elementUnmatched(element);
448
+ }
449
+ }
450
+ }
451
+ }
452
+
453
+ class AttributeObserver {
454
+ constructor(element, attributeName, delegate) {
455
+ this.attributeName = attributeName;
456
+ this.delegate = delegate;
457
+ this.elementObserver = new ElementObserver(element, this);
458
+ }
459
+ get element() {
460
+ return this.elementObserver.element;
461
+ }
462
+ get selector() {
463
+ return `[${this.attributeName}]`;
464
+ }
465
+ start() {
466
+ this.elementObserver.start();
467
+ }
468
+ pause(callback) {
469
+ this.elementObserver.pause(callback);
470
+ }
471
+ stop() {
472
+ this.elementObserver.stop();
473
+ }
474
+ refresh() {
475
+ this.elementObserver.refresh();
476
+ }
477
+ get started() {
478
+ return this.elementObserver.started;
479
+ }
480
+ matchElement(element) {
481
+ return element.hasAttribute(this.attributeName);
482
+ }
483
+ matchElementsInTree(tree) {
484
+ const match = this.matchElement(tree) ? [tree] : [];
485
+ const matches = Array.from(tree.querySelectorAll(this.selector));
486
+ return match.concat(matches);
487
+ }
488
+ elementMatched(element) {
489
+ if (this.delegate.elementMatchedAttribute) {
490
+ this.delegate.elementMatchedAttribute(element, this.attributeName);
491
+ }
492
+ }
493
+ elementUnmatched(element) {
494
+ if (this.delegate.elementUnmatchedAttribute) {
495
+ this.delegate.elementUnmatchedAttribute(element, this.attributeName);
496
+ }
497
+ }
498
+ elementAttributeChanged(element, attributeName) {
499
+ if (this.delegate.elementAttributeValueChanged && this.attributeName == attributeName) {
500
+ this.delegate.elementAttributeValueChanged(element, attributeName);
501
+ }
502
+ }
503
+ }
504
+
505
+ class StringMapObserver {
506
+ constructor(element, delegate) {
507
+ this.element = element;
508
+ this.delegate = delegate;
509
+ this.started = false;
510
+ this.stringMap = new Map;
511
+ this.mutationObserver = new MutationObserver(mutations => this.processMutations(mutations));
512
+ }
513
+ start() {
514
+ if (!this.started) {
515
+ this.started = true;
516
+ this.mutationObserver.observe(this.element, { attributes: true, attributeOldValue: true });
517
+ this.refresh();
518
+ }
519
+ }
520
+ stop() {
521
+ if (this.started) {
522
+ this.mutationObserver.takeRecords();
523
+ this.mutationObserver.disconnect();
524
+ this.started = false;
525
+ }
526
+ }
527
+ refresh() {
528
+ if (this.started) {
529
+ for (const attributeName of this.knownAttributeNames) {
530
+ this.refreshAttribute(attributeName, null);
531
+ }
532
+ }
533
+ }
534
+ processMutations(mutations) {
535
+ if (this.started) {
536
+ for (const mutation of mutations) {
537
+ this.processMutation(mutation);
538
+ }
539
+ }
540
+ }
541
+ processMutation(mutation) {
542
+ const attributeName = mutation.attributeName;
543
+ if (attributeName) {
544
+ this.refreshAttribute(attributeName, mutation.oldValue);
545
+ }
546
+ }
547
+ refreshAttribute(attributeName, oldValue) {
548
+ const key = this.delegate.getStringMapKeyForAttribute(attributeName);
549
+ if (key != null) {
550
+ if (!this.stringMap.has(attributeName)) {
551
+ this.stringMapKeyAdded(key, attributeName);
552
+ }
553
+ const value = this.element.getAttribute(attributeName);
554
+ if (this.stringMap.get(attributeName) != value) {
555
+ this.stringMapValueChanged(value, key, oldValue);
556
+ }
557
+ if (value == null) {
558
+ const oldValue = this.stringMap.get(attributeName);
559
+ this.stringMap.delete(attributeName);
560
+ if (oldValue)
561
+ this.stringMapKeyRemoved(key, attributeName, oldValue);
562
+ }
563
+ else {
564
+ this.stringMap.set(attributeName, value);
565
+ }
566
+ }
567
+ }
568
+ stringMapKeyAdded(key, attributeName) {
569
+ if (this.delegate.stringMapKeyAdded) {
570
+ this.delegate.stringMapKeyAdded(key, attributeName);
571
+ }
572
+ }
573
+ stringMapValueChanged(value, key, oldValue) {
574
+ if (this.delegate.stringMapValueChanged) {
575
+ this.delegate.stringMapValueChanged(value, key, oldValue);
576
+ }
577
+ }
578
+ stringMapKeyRemoved(key, attributeName, oldValue) {
579
+ if (this.delegate.stringMapKeyRemoved) {
580
+ this.delegate.stringMapKeyRemoved(key, attributeName, oldValue);
581
+ }
582
+ }
583
+ get knownAttributeNames() {
584
+ return Array.from(new Set(this.currentAttributeNames.concat(this.recordedAttributeNames)));
585
+ }
586
+ get currentAttributeNames() {
587
+ return Array.from(this.element.attributes).map(attribute => attribute.name);
588
+ }
589
+ get recordedAttributeNames() {
590
+ return Array.from(this.stringMap.keys());
591
+ }
592
+ }
593
+
594
+ function add(map, key, value) {
595
+ fetch(map, key).add(value);
596
+ }
597
+ function del(map, key, value) {
598
+ fetch(map, key).delete(value);
599
+ prune(map, key);
600
+ }
601
+ function fetch(map, key) {
602
+ let values = map.get(key);
603
+ if (!values) {
604
+ values = new Set();
605
+ map.set(key, values);
606
+ }
607
+ return values;
608
+ }
609
+ function prune(map, key) {
610
+ const values = map.get(key);
611
+ if (values != null && values.size == 0) {
612
+ map.delete(key);
613
+ }
614
+ }
615
+
616
+ class Multimap {
617
+ constructor() {
618
+ this.valuesByKey = new Map();
619
+ }
620
+ get keys() {
621
+ return Array.from(this.valuesByKey.keys());
622
+ }
623
+ get values() {
624
+ const sets = Array.from(this.valuesByKey.values());
625
+ return sets.reduce((values, set) => values.concat(Array.from(set)), []);
626
+ }
627
+ get size() {
628
+ const sets = Array.from(this.valuesByKey.values());
629
+ return sets.reduce((size, set) => size + set.size, 0);
630
+ }
631
+ add(key, value) {
632
+ add(this.valuesByKey, key, value);
633
+ }
634
+ delete(key, value) {
635
+ del(this.valuesByKey, key, value);
636
+ }
637
+ has(key, value) {
638
+ const values = this.valuesByKey.get(key);
639
+ return values != null && values.has(value);
640
+ }
641
+ hasKey(key) {
642
+ return this.valuesByKey.has(key);
643
+ }
644
+ hasValue(value) {
645
+ const sets = Array.from(this.valuesByKey.values());
646
+ return sets.some(set => set.has(value));
647
+ }
648
+ getValuesForKey(key) {
649
+ const values = this.valuesByKey.get(key);
650
+ return values ? Array.from(values) : [];
651
+ }
652
+ getKeysForValue(value) {
653
+ return Array.from(this.valuesByKey)
654
+ .filter(([key, values]) => values.has(value))
655
+ .map(([key, values]) => key);
656
+ }
657
+ }
658
+
659
+ class IndexedMultimap extends Multimap {
660
+ constructor() {
661
+ super();
662
+ this.keysByValue = new Map;
663
+ }
664
+ get values() {
665
+ return Array.from(this.keysByValue.keys());
666
+ }
667
+ add(key, value) {
668
+ super.add(key, value);
669
+ add(this.keysByValue, value, key);
670
+ }
671
+ delete(key, value) {
672
+ super.delete(key, value);
673
+ del(this.keysByValue, value, key);
674
+ }
675
+ hasValue(value) {
676
+ return this.keysByValue.has(value);
677
+ }
678
+ getKeysForValue(value) {
679
+ const set = this.keysByValue.get(value);
680
+ return set ? Array.from(set) : [];
681
+ }
682
+ }
683
+
684
+ class TokenListObserver {
685
+ constructor(element, attributeName, delegate) {
686
+ this.attributeObserver = new AttributeObserver(element, attributeName, this);
687
+ this.delegate = delegate;
688
+ this.tokensByElement = new Multimap;
689
+ }
690
+ get started() {
691
+ return this.attributeObserver.started;
692
+ }
693
+ start() {
694
+ this.attributeObserver.start();
695
+ }
696
+ pause(callback) {
697
+ this.attributeObserver.pause(callback);
698
+ }
699
+ stop() {
700
+ this.attributeObserver.stop();
701
+ }
702
+ refresh() {
703
+ this.attributeObserver.refresh();
704
+ }
705
+ get element() {
706
+ return this.attributeObserver.element;
707
+ }
708
+ get attributeName() {
709
+ return this.attributeObserver.attributeName;
710
+ }
711
+ elementMatchedAttribute(element) {
712
+ this.tokensMatched(this.readTokensForElement(element));
713
+ }
714
+ elementAttributeValueChanged(element) {
715
+ const [unmatchedTokens, matchedTokens] = this.refreshTokensForElement(element);
716
+ this.tokensUnmatched(unmatchedTokens);
717
+ this.tokensMatched(matchedTokens);
718
+ }
719
+ elementUnmatchedAttribute(element) {
720
+ this.tokensUnmatched(this.tokensByElement.getValuesForKey(element));
721
+ }
722
+ tokensMatched(tokens) {
723
+ tokens.forEach(token => this.tokenMatched(token));
724
+ }
725
+ tokensUnmatched(tokens) {
726
+ tokens.forEach(token => this.tokenUnmatched(token));
727
+ }
728
+ tokenMatched(token) {
729
+ this.delegate.tokenMatched(token);
730
+ this.tokensByElement.add(token.element, token);
731
+ }
732
+ tokenUnmatched(token) {
733
+ this.delegate.tokenUnmatched(token);
734
+ this.tokensByElement.delete(token.element, token);
735
+ }
736
+ refreshTokensForElement(element) {
737
+ const previousTokens = this.tokensByElement.getValuesForKey(element);
738
+ const currentTokens = this.readTokensForElement(element);
739
+ const firstDifferingIndex = zip(previousTokens, currentTokens)
740
+ .findIndex(([previousToken, currentToken]) => !tokensAreEqual(previousToken, currentToken));
741
+ if (firstDifferingIndex == -1) {
742
+ return [[], []];
743
+ }
744
+ else {
745
+ return [previousTokens.slice(firstDifferingIndex), currentTokens.slice(firstDifferingIndex)];
746
+ }
747
+ }
748
+ readTokensForElement(element) {
749
+ const attributeName = this.attributeName;
750
+ const tokenString = element.getAttribute(attributeName) || "";
751
+ return parseTokenString(tokenString, element, attributeName);
752
+ }
753
+ }
754
+ function parseTokenString(tokenString, element, attributeName) {
755
+ return tokenString.trim().split(/\s+/).filter(content => content.length)
756
+ .map((content, index) => ({ element, attributeName, content, index }));
757
+ }
758
+ function zip(left, right) {
759
+ const length = Math.max(left.length, right.length);
760
+ return Array.from({ length }, (_, index) => [left[index], right[index]]);
761
+ }
762
+ function tokensAreEqual(left, right) {
763
+ return left && right && left.index == right.index && left.content == right.content;
764
+ }
765
+
766
+ class ValueListObserver {
767
+ constructor(element, attributeName, delegate) {
768
+ this.tokenListObserver = new TokenListObserver(element, attributeName, this);
769
+ this.delegate = delegate;
770
+ this.parseResultsByToken = new WeakMap;
771
+ this.valuesByTokenByElement = new WeakMap;
772
+ }
773
+ get started() {
774
+ return this.tokenListObserver.started;
775
+ }
776
+ start() {
777
+ this.tokenListObserver.start();
778
+ }
779
+ stop() {
780
+ this.tokenListObserver.stop();
781
+ }
782
+ refresh() {
783
+ this.tokenListObserver.refresh();
784
+ }
785
+ get element() {
786
+ return this.tokenListObserver.element;
787
+ }
788
+ get attributeName() {
789
+ return this.tokenListObserver.attributeName;
790
+ }
791
+ tokenMatched(token) {
792
+ const { element } = token;
793
+ const { value } = this.fetchParseResultForToken(token);
794
+ if (value) {
795
+ this.fetchValuesByTokenForElement(element).set(token, value);
796
+ this.delegate.elementMatchedValue(element, value);
797
+ }
798
+ }
799
+ tokenUnmatched(token) {
800
+ const { element } = token;
801
+ const { value } = this.fetchParseResultForToken(token);
802
+ if (value) {
803
+ this.fetchValuesByTokenForElement(element).delete(token);
804
+ this.delegate.elementUnmatchedValue(element, value);
805
+ }
806
+ }
807
+ fetchParseResultForToken(token) {
808
+ let parseResult = this.parseResultsByToken.get(token);
809
+ if (!parseResult) {
810
+ parseResult = this.parseToken(token);
811
+ this.parseResultsByToken.set(token, parseResult);
812
+ }
813
+ return parseResult;
814
+ }
815
+ fetchValuesByTokenForElement(element) {
816
+ let valuesByToken = this.valuesByTokenByElement.get(element);
817
+ if (!valuesByToken) {
818
+ valuesByToken = new Map;
819
+ this.valuesByTokenByElement.set(element, valuesByToken);
820
+ }
821
+ return valuesByToken;
822
+ }
823
+ parseToken(token) {
824
+ try {
825
+ const value = this.delegate.parseValueForToken(token);
826
+ return { value };
827
+ }
828
+ catch (error) {
829
+ return { error };
830
+ }
831
+ }
832
+ }
833
+
834
+ class BindingObserver {
835
+ constructor(context, delegate) {
836
+ this.context = context;
837
+ this.delegate = delegate;
838
+ this.bindingsByAction = new Map;
839
+ }
840
+ start() {
841
+ if (!this.valueListObserver) {
842
+ this.valueListObserver = new ValueListObserver(this.element, this.actionAttribute, this);
843
+ this.valueListObserver.start();
844
+ }
845
+ }
846
+ stop() {
847
+ if (this.valueListObserver) {
848
+ this.valueListObserver.stop();
849
+ delete this.valueListObserver;
850
+ this.disconnectAllActions();
851
+ }
852
+ }
853
+ get element() {
854
+ return this.context.element;
855
+ }
856
+ get identifier() {
857
+ return this.context.identifier;
858
+ }
859
+ get actionAttribute() {
860
+ return this.schema.actionAttribute;
861
+ }
862
+ get schema() {
863
+ return this.context.schema;
864
+ }
865
+ get bindings() {
866
+ return Array.from(this.bindingsByAction.values());
867
+ }
868
+ connectAction(action) {
869
+ const binding = new Binding(this.context, action);
870
+ this.bindingsByAction.set(action, binding);
871
+ this.delegate.bindingConnected(binding);
872
+ }
873
+ disconnectAction(action) {
874
+ const binding = this.bindingsByAction.get(action);
875
+ if (binding) {
876
+ this.bindingsByAction.delete(action);
877
+ this.delegate.bindingDisconnected(binding);
878
+ }
879
+ }
880
+ disconnectAllActions() {
881
+ this.bindings.forEach(binding => this.delegate.bindingDisconnected(binding));
882
+ this.bindingsByAction.clear();
883
+ }
884
+ parseValueForToken(token) {
885
+ const action = Action.forToken(token);
886
+ if (action.identifier == this.identifier) {
887
+ return action;
888
+ }
889
+ }
890
+ elementMatchedValue(element, action) {
891
+ this.connectAction(action);
892
+ }
893
+ elementUnmatchedValue(element, action) {
894
+ this.disconnectAction(action);
895
+ }
896
+ }
897
+
898
+ class ValueObserver {
899
+ constructor(context, receiver) {
900
+ this.context = context;
901
+ this.receiver = receiver;
902
+ this.stringMapObserver = new StringMapObserver(this.element, this);
903
+ this.valueDescriptorMap = this.controller.valueDescriptorMap;
904
+ this.invokeChangedCallbacksForDefaultValues();
905
+ }
906
+ start() {
907
+ this.stringMapObserver.start();
908
+ }
909
+ stop() {
910
+ this.stringMapObserver.stop();
911
+ }
912
+ get element() {
913
+ return this.context.element;
914
+ }
915
+ get controller() {
916
+ return this.context.controller;
917
+ }
918
+ getStringMapKeyForAttribute(attributeName) {
919
+ if (attributeName in this.valueDescriptorMap) {
920
+ return this.valueDescriptorMap[attributeName].name;
921
+ }
922
+ }
923
+ stringMapKeyAdded(key, attributeName) {
924
+ const descriptor = this.valueDescriptorMap[attributeName];
925
+ if (!this.hasValue(key)) {
926
+ this.invokeChangedCallback(key, descriptor.writer(this.receiver[key]), descriptor.writer(descriptor.defaultValue));
927
+ }
928
+ }
929
+ stringMapValueChanged(value, name, oldValue) {
930
+ const descriptor = this.valueDescriptorNameMap[name];
931
+ if (value === null)
932
+ return;
933
+ if (oldValue === null) {
934
+ oldValue = descriptor.writer(descriptor.defaultValue);
935
+ }
936
+ this.invokeChangedCallback(name, value, oldValue);
937
+ }
938
+ stringMapKeyRemoved(key, attributeName, oldValue) {
939
+ const descriptor = this.valueDescriptorNameMap[key];
940
+ if (this.hasValue(key)) {
941
+ this.invokeChangedCallback(key, descriptor.writer(this.receiver[key]), oldValue);
942
+ }
943
+ else {
944
+ this.invokeChangedCallback(key, descriptor.writer(descriptor.defaultValue), oldValue);
945
+ }
946
+ }
947
+ invokeChangedCallbacksForDefaultValues() {
948
+ for (const { key, name, defaultValue, writer } of this.valueDescriptors) {
949
+ if (defaultValue != undefined && !this.controller.data.has(key)) {
950
+ this.invokeChangedCallback(name, writer(defaultValue), undefined);
951
+ }
952
+ }
953
+ }
954
+ invokeChangedCallback(name, rawValue, rawOldValue) {
955
+ const changedMethodName = `${name}Changed`;
956
+ const changedMethod = this.receiver[changedMethodName];
957
+ if (typeof changedMethod == "function") {
958
+ const descriptor = this.valueDescriptorNameMap[name];
959
+ const value = descriptor.reader(rawValue);
960
+ let oldValue = rawOldValue;
961
+ if (rawOldValue) {
962
+ oldValue = descriptor.reader(rawOldValue);
963
+ }
964
+ changedMethod.call(this.receiver, value, oldValue);
965
+ }
966
+ }
967
+ get valueDescriptors() {
968
+ const { valueDescriptorMap } = this;
969
+ return Object.keys(valueDescriptorMap).map(key => valueDescriptorMap[key]);
970
+ }
971
+ get valueDescriptorNameMap() {
972
+ const descriptors = {};
973
+ Object.keys(this.valueDescriptorMap).forEach(key => {
974
+ const descriptor = this.valueDescriptorMap[key];
975
+ descriptors[descriptor.name] = descriptor;
976
+ });
977
+ return descriptors;
978
+ }
979
+ hasValue(attributeName) {
980
+ const descriptor = this.valueDescriptorNameMap[attributeName];
981
+ const hasMethodName = `has${capitalize(descriptor.name)}`;
982
+ return this.receiver[hasMethodName];
983
+ }
984
+ }
985
+
986
+ class TargetObserver {
987
+ constructor(context, delegate) {
988
+ this.context = context;
989
+ this.delegate = delegate;
990
+ this.targetsByName = new Multimap;
991
+ }
992
+ start() {
993
+ if (!this.tokenListObserver) {
994
+ this.tokenListObserver = new TokenListObserver(this.element, this.attributeName, this);
995
+ this.tokenListObserver.start();
996
+ }
997
+ }
998
+ stop() {
999
+ if (this.tokenListObserver) {
1000
+ this.disconnectAllTargets();
1001
+ this.tokenListObserver.stop();
1002
+ delete this.tokenListObserver;
1003
+ }
1004
+ }
1005
+ tokenMatched({ element, content: name }) {
1006
+ if (this.scope.containsElement(element)) {
1007
+ this.connectTarget(element, name);
1008
+ }
1009
+ }
1010
+ tokenUnmatched({ element, content: name }) {
1011
+ this.disconnectTarget(element, name);
1012
+ }
1013
+ connectTarget(element, name) {
1014
+ var _a;
1015
+ if (!this.targetsByName.has(name, element)) {
1016
+ this.targetsByName.add(name, element);
1017
+ (_a = this.tokenListObserver) === null || _a === void 0 ? void 0 : _a.pause(() => this.delegate.targetConnected(element, name));
1018
+ }
1019
+ }
1020
+ disconnectTarget(element, name) {
1021
+ var _a;
1022
+ if (this.targetsByName.has(name, element)) {
1023
+ this.targetsByName.delete(name, element);
1024
+ (_a = this.tokenListObserver) === null || _a === void 0 ? void 0 : _a.pause(() => this.delegate.targetDisconnected(element, name));
1025
+ }
1026
+ }
1027
+ disconnectAllTargets() {
1028
+ for (const name of this.targetsByName.keys) {
1029
+ for (const element of this.targetsByName.getValuesForKey(name)) {
1030
+ this.disconnectTarget(element, name);
1031
+ }
1032
+ }
1033
+ }
1034
+ get attributeName() {
1035
+ return `data-${this.context.identifier}-target`;
1036
+ }
1037
+ get element() {
1038
+ return this.context.element;
1039
+ }
1040
+ get scope() {
1041
+ return this.context.scope;
1042
+ }
1043
+ }
1044
+
1045
+ class Context {
1046
+ constructor(module, scope) {
1047
+ this.logDebugActivity = (functionName, detail = {}) => {
1048
+ const { identifier, controller, element } = this;
1049
+ detail = Object.assign({ identifier, controller, element }, detail);
1050
+ this.application.logDebugActivity(this.identifier, functionName, detail);
1051
+ };
1052
+ this.module = module;
1053
+ this.scope = scope;
1054
+ this.controller = new module.controllerConstructor(this);
1055
+ this.bindingObserver = new BindingObserver(this, this.dispatcher);
1056
+ this.valueObserver = new ValueObserver(this, this.controller);
1057
+ this.targetObserver = new TargetObserver(this, this);
1058
+ try {
1059
+ this.controller.initialize();
1060
+ this.logDebugActivity("initialize");
1061
+ }
1062
+ catch (error) {
1063
+ this.handleError(error, "initializing controller");
1064
+ }
1065
+ }
1066
+ connect() {
1067
+ this.bindingObserver.start();
1068
+ this.valueObserver.start();
1069
+ this.targetObserver.start();
1070
+ try {
1071
+ this.controller.connect();
1072
+ this.logDebugActivity("connect");
1073
+ }
1074
+ catch (error) {
1075
+ this.handleError(error, "connecting controller");
1076
+ }
1077
+ }
1078
+ disconnect() {
1079
+ try {
1080
+ this.controller.disconnect();
1081
+ this.logDebugActivity("disconnect");
1082
+ }
1083
+ catch (error) {
1084
+ this.handleError(error, "disconnecting controller");
1085
+ }
1086
+ this.targetObserver.stop();
1087
+ this.valueObserver.stop();
1088
+ this.bindingObserver.stop();
1089
+ }
1090
+ get application() {
1091
+ return this.module.application;
1092
+ }
1093
+ get identifier() {
1094
+ return this.module.identifier;
1095
+ }
1096
+ get schema() {
1097
+ return this.application.schema;
1098
+ }
1099
+ get dispatcher() {
1100
+ return this.application.dispatcher;
1101
+ }
1102
+ get element() {
1103
+ return this.scope.element;
1104
+ }
1105
+ get parentElement() {
1106
+ return this.element.parentElement;
1107
+ }
1108
+ handleError(error, message, detail = {}) {
1109
+ const { identifier, controller, element } = this;
1110
+ detail = Object.assign({ identifier, controller, element }, detail);
1111
+ this.application.handleError(error, `Error ${message}`, detail);
1112
+ }
1113
+ targetConnected(element, name) {
1114
+ this.invokeControllerMethod(`${name}TargetConnected`, element);
1115
+ }
1116
+ targetDisconnected(element, name) {
1117
+ this.invokeControllerMethod(`${name}TargetDisconnected`, element);
1118
+ }
1119
+ invokeControllerMethod(methodName, ...args) {
1120
+ const controller = this.controller;
1121
+ if (typeof controller[methodName] == "function") {
1122
+ controller[methodName](...args);
1123
+ }
1124
+ }
1125
+ }
1126
+
1127
+ function readInheritableStaticArrayValues(constructor, propertyName) {
1128
+ const ancestors = getAncestorsForConstructor(constructor);
1129
+ return Array.from(ancestors.reduce((values, constructor) => {
1130
+ getOwnStaticArrayValues(constructor, propertyName).forEach(name => values.add(name));
1131
+ return values;
1132
+ }, new Set));
1133
+ }
1134
+ function readInheritableStaticObjectPairs(constructor, propertyName) {
1135
+ const ancestors = getAncestorsForConstructor(constructor);
1136
+ return ancestors.reduce((pairs, constructor) => {
1137
+ pairs.push(...getOwnStaticObjectPairs(constructor, propertyName));
1138
+ return pairs;
1139
+ }, []);
1140
+ }
1141
+ function getAncestorsForConstructor(constructor) {
1142
+ const ancestors = [];
1143
+ while (constructor) {
1144
+ ancestors.push(constructor);
1145
+ constructor = Object.getPrototypeOf(constructor);
1146
+ }
1147
+ return ancestors.reverse();
1148
+ }
1149
+ function getOwnStaticArrayValues(constructor, propertyName) {
1150
+ const definition = constructor[propertyName];
1151
+ return Array.isArray(definition) ? definition : [];
1152
+ }
1153
+ function getOwnStaticObjectPairs(constructor, propertyName) {
1154
+ const definition = constructor[propertyName];
1155
+ return definition ? Object.keys(definition).map(key => [key, definition[key]]) : [];
1156
+ }
1157
+
1158
+ function bless(constructor) {
1159
+ return shadow(constructor, getBlessedProperties(constructor));
1160
+ }
1161
+ function shadow(constructor, properties) {
1162
+ const shadowConstructor = extend(constructor);
1163
+ const shadowProperties = getShadowProperties(constructor.prototype, properties);
1164
+ Object.defineProperties(shadowConstructor.prototype, shadowProperties);
1165
+ return shadowConstructor;
1166
+ }
1167
+ function getBlessedProperties(constructor) {
1168
+ const blessings = readInheritableStaticArrayValues(constructor, "blessings");
1169
+ return blessings.reduce((blessedProperties, blessing) => {
1170
+ const properties = blessing(constructor);
1171
+ for (const key in properties) {
1172
+ const descriptor = blessedProperties[key] || {};
1173
+ blessedProperties[key] = Object.assign(descriptor, properties[key]);
1174
+ }
1175
+ return blessedProperties;
1176
+ }, {});
1177
+ }
1178
+ function getShadowProperties(prototype, properties) {
1179
+ return getOwnKeys(properties).reduce((shadowProperties, key) => {
1180
+ const descriptor = getShadowedDescriptor(prototype, properties, key);
1181
+ if (descriptor) {
1182
+ Object.assign(shadowProperties, { [key]: descriptor });
1183
+ }
1184
+ return shadowProperties;
1185
+ }, {});
1186
+ }
1187
+ function getShadowedDescriptor(prototype, properties, key) {
1188
+ const shadowingDescriptor = Object.getOwnPropertyDescriptor(prototype, key);
1189
+ const shadowedByValue = shadowingDescriptor && "value" in shadowingDescriptor;
1190
+ if (!shadowedByValue) {
1191
+ const descriptor = Object.getOwnPropertyDescriptor(properties, key).value;
1192
+ if (shadowingDescriptor) {
1193
+ descriptor.get = shadowingDescriptor.get || descriptor.get;
1194
+ descriptor.set = shadowingDescriptor.set || descriptor.set;
1195
+ }
1196
+ return descriptor;
1197
+ }
1198
+ }
1199
+ const getOwnKeys = (() => {
1200
+ if (typeof Object.getOwnPropertySymbols == "function") {
1201
+ return (object) => [
1202
+ ...Object.getOwnPropertyNames(object),
1203
+ ...Object.getOwnPropertySymbols(object)
1204
+ ];
1205
+ }
1206
+ else {
1207
+ return Object.getOwnPropertyNames;
1208
+ }
1209
+ })();
1210
+ const extend = (() => {
1211
+ function extendWithReflect(constructor) {
1212
+ function extended() {
1213
+ return Reflect.construct(constructor, arguments, new.target);
1214
+ }
1215
+ extended.prototype = Object.create(constructor.prototype, {
1216
+ constructor: { value: extended }
1217
+ });
1218
+ Reflect.setPrototypeOf(extended, constructor);
1219
+ return extended;
1220
+ }
1221
+ function testReflectExtension() {
1222
+ const a = function () { this.a.call(this); };
1223
+ const b = extendWithReflect(a);
1224
+ b.prototype.a = function () { };
1225
+ return new b;
1226
+ }
1227
+ try {
1228
+ testReflectExtension();
1229
+ return extendWithReflect;
1230
+ }
1231
+ catch (error) {
1232
+ return (constructor) => class extended extends constructor {
1233
+ };
1234
+ }
1235
+ })();
1236
+
1237
+ function blessDefinition(definition) {
1238
+ return {
1239
+ identifier: definition.identifier,
1240
+ controllerConstructor: bless(definition.controllerConstructor)
1241
+ };
1242
+ }
1243
+
1244
+ class Module {
1245
+ constructor(application, definition) {
1246
+ this.application = application;
1247
+ this.definition = blessDefinition(definition);
1248
+ this.contextsByScope = new WeakMap;
1249
+ this.connectedContexts = new Set;
1250
+ }
1251
+ get identifier() {
1252
+ return this.definition.identifier;
1253
+ }
1254
+ get controllerConstructor() {
1255
+ return this.definition.controllerConstructor;
1256
+ }
1257
+ get contexts() {
1258
+ return Array.from(this.connectedContexts);
1259
+ }
1260
+ connectContextForScope(scope) {
1261
+ const context = this.fetchContextForScope(scope);
1262
+ this.connectedContexts.add(context);
1263
+ context.connect();
1264
+ }
1265
+ disconnectContextForScope(scope) {
1266
+ const context = this.contextsByScope.get(scope);
1267
+ if (context) {
1268
+ this.connectedContexts.delete(context);
1269
+ context.disconnect();
1270
+ }
1271
+ }
1272
+ fetchContextForScope(scope) {
1273
+ let context = this.contextsByScope.get(scope);
1274
+ if (!context) {
1275
+ context = new Context(this, scope);
1276
+ this.contextsByScope.set(scope, context);
1277
+ }
1278
+ return context;
1279
+ }
1280
+ }
1281
+
1282
+ class ClassMap {
1283
+ constructor(scope) {
1284
+ this.scope = scope;
1285
+ }
1286
+ has(name) {
1287
+ return this.data.has(this.getDataKey(name));
1288
+ }
1289
+ get(name) {
1290
+ return this.getAll(name)[0];
1291
+ }
1292
+ getAll(name) {
1293
+ const tokenString = this.data.get(this.getDataKey(name)) || "";
1294
+ return tokenize(tokenString);
1295
+ }
1296
+ getAttributeName(name) {
1297
+ return this.data.getAttributeNameForKey(this.getDataKey(name));
1298
+ }
1299
+ getDataKey(name) {
1300
+ return `${name}-class`;
1301
+ }
1302
+ get data() {
1303
+ return this.scope.data;
1304
+ }
1305
+ }
1306
+
1307
+ class DataMap {
1308
+ constructor(scope) {
1309
+ this.scope = scope;
1310
+ }
1311
+ get element() {
1312
+ return this.scope.element;
1313
+ }
1314
+ get identifier() {
1315
+ return this.scope.identifier;
1316
+ }
1317
+ get(key) {
1318
+ const name = this.getAttributeNameForKey(key);
1319
+ return this.element.getAttribute(name);
1320
+ }
1321
+ set(key, value) {
1322
+ const name = this.getAttributeNameForKey(key);
1323
+ this.element.setAttribute(name, value);
1324
+ return this.get(key);
1325
+ }
1326
+ has(key) {
1327
+ const name = this.getAttributeNameForKey(key);
1328
+ return this.element.hasAttribute(name);
1329
+ }
1330
+ delete(key) {
1331
+ if (this.has(key)) {
1332
+ const name = this.getAttributeNameForKey(key);
1333
+ this.element.removeAttribute(name);
1334
+ return true;
1335
+ }
1336
+ else {
1337
+ return false;
1338
+ }
1339
+ }
1340
+ getAttributeNameForKey(key) {
1341
+ return `data-${this.identifier}-${dasherize(key)}`;
1342
+ }
1343
+ }
1344
+
1345
+ class Guide {
1346
+ constructor(logger) {
1347
+ this.warnedKeysByObject = new WeakMap;
1348
+ this.logger = logger;
1349
+ }
1350
+ warn(object, key, message) {
1351
+ let warnedKeys = this.warnedKeysByObject.get(object);
1352
+ if (!warnedKeys) {
1353
+ warnedKeys = new Set;
1354
+ this.warnedKeysByObject.set(object, warnedKeys);
1355
+ }
1356
+ if (!warnedKeys.has(key)) {
1357
+ warnedKeys.add(key);
1358
+ this.logger.warn(message, object);
1359
+ }
1360
+ }
1361
+ }
1362
+
1363
+ function attributeValueContainsToken(attributeName, token) {
1364
+ return `[${attributeName}~="${token}"]`;
1365
+ }
1366
+
1367
+ class TargetSet {
1368
+ constructor(scope) {
1369
+ this.scope = scope;
1370
+ }
1371
+ get element() {
1372
+ return this.scope.element;
1373
+ }
1374
+ get identifier() {
1375
+ return this.scope.identifier;
1376
+ }
1377
+ get schema() {
1378
+ return this.scope.schema;
1379
+ }
1380
+ has(targetName) {
1381
+ return this.find(targetName) != null;
1382
+ }
1383
+ find(...targetNames) {
1384
+ return targetNames.reduce((target, targetName) => target
1385
+ || this.findTarget(targetName)
1386
+ || this.findLegacyTarget(targetName), undefined);
1387
+ }
1388
+ findAll(...targetNames) {
1389
+ return targetNames.reduce((targets, targetName) => [
1390
+ ...targets,
1391
+ ...this.findAllTargets(targetName),
1392
+ ...this.findAllLegacyTargets(targetName)
1393
+ ], []);
1394
+ }
1395
+ findTarget(targetName) {
1396
+ const selector = this.getSelectorForTargetName(targetName);
1397
+ return this.scope.findElement(selector);
1398
+ }
1399
+ findAllTargets(targetName) {
1400
+ const selector = this.getSelectorForTargetName(targetName);
1401
+ return this.scope.findAllElements(selector);
1402
+ }
1403
+ getSelectorForTargetName(targetName) {
1404
+ const attributeName = this.schema.targetAttributeForScope(this.identifier);
1405
+ return attributeValueContainsToken(attributeName, targetName);
1406
+ }
1407
+ findLegacyTarget(targetName) {
1408
+ const selector = this.getLegacySelectorForTargetName(targetName);
1409
+ return this.deprecate(this.scope.findElement(selector), targetName);
1410
+ }
1411
+ findAllLegacyTargets(targetName) {
1412
+ const selector = this.getLegacySelectorForTargetName(targetName);
1413
+ return this.scope.findAllElements(selector).map(element => this.deprecate(element, targetName));
1414
+ }
1415
+ getLegacySelectorForTargetName(targetName) {
1416
+ const targetDescriptor = `${this.identifier}.${targetName}`;
1417
+ return attributeValueContainsToken(this.schema.targetAttribute, targetDescriptor);
1418
+ }
1419
+ deprecate(element, targetName) {
1420
+ if (element) {
1421
+ const { identifier } = this;
1422
+ const attributeName = this.schema.targetAttribute;
1423
+ const revisedAttributeName = this.schema.targetAttributeForScope(identifier);
1424
+ this.guide.warn(element, `target:${targetName}`, `Please replace ${attributeName}="${identifier}.${targetName}" with ${revisedAttributeName}="${targetName}". ` +
1425
+ `The ${attributeName} attribute is deprecated and will be removed in a future version of Stimulus.`);
1426
+ }
1427
+ return element;
1428
+ }
1429
+ get guide() {
1430
+ return this.scope.guide;
1431
+ }
1432
+ }
1433
+
1434
+ class Scope {
1435
+ constructor(schema, element, identifier, logger) {
1436
+ this.targets = new TargetSet(this);
1437
+ this.classes = new ClassMap(this);
1438
+ this.data = new DataMap(this);
1439
+ this.containsElement = (element) => {
1440
+ return element.closest(this.controllerSelector) === this.element;
1441
+ };
1442
+ this.schema = schema;
1443
+ this.element = element;
1444
+ this.identifier = identifier;
1445
+ this.guide = new Guide(logger);
1446
+ }
1447
+ findElement(selector) {
1448
+ return this.element.matches(selector)
1449
+ ? this.element
1450
+ : this.queryElements(selector).find(this.containsElement);
1451
+ }
1452
+ findAllElements(selector) {
1453
+ return [
1454
+ ...this.element.matches(selector) ? [this.element] : [],
1455
+ ...this.queryElements(selector).filter(this.containsElement)
1456
+ ];
1457
+ }
1458
+ queryElements(selector) {
1459
+ return Array.from(this.element.querySelectorAll(selector));
1460
+ }
1461
+ get controllerSelector() {
1462
+ return attributeValueContainsToken(this.schema.controllerAttribute, this.identifier);
1463
+ }
1464
+ }
1465
+
1466
+ class ScopeObserver {
1467
+ constructor(element, schema, delegate) {
1468
+ this.element = element;
1469
+ this.schema = schema;
1470
+ this.delegate = delegate;
1471
+ this.valueListObserver = new ValueListObserver(this.element, this.controllerAttribute, this);
1472
+ this.scopesByIdentifierByElement = new WeakMap;
1473
+ this.scopeReferenceCounts = new WeakMap;
1474
+ }
1475
+ start() {
1476
+ this.valueListObserver.start();
1477
+ }
1478
+ stop() {
1479
+ this.valueListObserver.stop();
1480
+ }
1481
+ get controllerAttribute() {
1482
+ return this.schema.controllerAttribute;
1483
+ }
1484
+ parseValueForToken(token) {
1485
+ const { element, content: identifier } = token;
1486
+ const scopesByIdentifier = this.fetchScopesByIdentifierForElement(element);
1487
+ let scope = scopesByIdentifier.get(identifier);
1488
+ if (!scope) {
1489
+ scope = this.delegate.createScopeForElementAndIdentifier(element, identifier);
1490
+ scopesByIdentifier.set(identifier, scope);
1491
+ }
1492
+ return scope;
1493
+ }
1494
+ elementMatchedValue(element, value) {
1495
+ const referenceCount = (this.scopeReferenceCounts.get(value) || 0) + 1;
1496
+ this.scopeReferenceCounts.set(value, referenceCount);
1497
+ if (referenceCount == 1) {
1498
+ this.delegate.scopeConnected(value);
1499
+ }
1500
+ }
1501
+ elementUnmatchedValue(element, value) {
1502
+ const referenceCount = this.scopeReferenceCounts.get(value);
1503
+ if (referenceCount) {
1504
+ this.scopeReferenceCounts.set(value, referenceCount - 1);
1505
+ if (referenceCount == 1) {
1506
+ this.delegate.scopeDisconnected(value);
1507
+ }
1508
+ }
1509
+ }
1510
+ fetchScopesByIdentifierForElement(element) {
1511
+ let scopesByIdentifier = this.scopesByIdentifierByElement.get(element);
1512
+ if (!scopesByIdentifier) {
1513
+ scopesByIdentifier = new Map;
1514
+ this.scopesByIdentifierByElement.set(element, scopesByIdentifier);
1515
+ }
1516
+ return scopesByIdentifier;
1517
+ }
1518
+ }
1519
+
1520
+ class Router {
1521
+ constructor(application) {
1522
+ this.application = application;
1523
+ this.scopeObserver = new ScopeObserver(this.element, this.schema, this);
1524
+ this.scopesByIdentifier = new Multimap;
1525
+ this.modulesByIdentifier = new Map;
1526
+ }
1527
+ get element() {
1528
+ return this.application.element;
1529
+ }
1530
+ get schema() {
1531
+ return this.application.schema;
1532
+ }
1533
+ get logger() {
1534
+ return this.application.logger;
1535
+ }
1536
+ get controllerAttribute() {
1537
+ return this.schema.controllerAttribute;
1538
+ }
1539
+ get modules() {
1540
+ return Array.from(this.modulesByIdentifier.values());
1541
+ }
1542
+ get contexts() {
1543
+ return this.modules.reduce((contexts, module) => contexts.concat(module.contexts), []);
1544
+ }
1545
+ start() {
1546
+ this.scopeObserver.start();
1547
+ }
1548
+ stop() {
1549
+ this.scopeObserver.stop();
1550
+ }
1551
+ loadDefinition(definition) {
1552
+ this.unloadIdentifier(definition.identifier);
1553
+ const module = new Module(this.application, definition);
1554
+ this.connectModule(module);
1555
+ }
1556
+ unloadIdentifier(identifier) {
1557
+ const module = this.modulesByIdentifier.get(identifier);
1558
+ if (module) {
1559
+ this.disconnectModule(module);
1560
+ }
1561
+ }
1562
+ getContextForElementAndIdentifier(element, identifier) {
1563
+ const module = this.modulesByIdentifier.get(identifier);
1564
+ if (module) {
1565
+ return module.contexts.find(context => context.element == element);
1566
+ }
1567
+ }
1568
+ handleError(error, message, detail) {
1569
+ this.application.handleError(error, message, detail);
1570
+ }
1571
+ createScopeForElementAndIdentifier(element, identifier) {
1572
+ return new Scope(this.schema, element, identifier, this.logger);
1573
+ }
1574
+ scopeConnected(scope) {
1575
+ this.scopesByIdentifier.add(scope.identifier, scope);
1576
+ const module = this.modulesByIdentifier.get(scope.identifier);
1577
+ if (module) {
1578
+ module.connectContextForScope(scope);
1579
+ }
1580
+ }
1581
+ scopeDisconnected(scope) {
1582
+ this.scopesByIdentifier.delete(scope.identifier, scope);
1583
+ const module = this.modulesByIdentifier.get(scope.identifier);
1584
+ if (module) {
1585
+ module.disconnectContextForScope(scope);
1586
+ }
1587
+ }
1588
+ connectModule(module) {
1589
+ this.modulesByIdentifier.set(module.identifier, module);
1590
+ const scopes = this.scopesByIdentifier.getValuesForKey(module.identifier);
1591
+ scopes.forEach(scope => module.connectContextForScope(scope));
1592
+ }
1593
+ disconnectModule(module) {
1594
+ this.modulesByIdentifier.delete(module.identifier);
1595
+ const scopes = this.scopesByIdentifier.getValuesForKey(module.identifier);
1596
+ scopes.forEach(scope => module.disconnectContextForScope(scope));
1597
+ }
1598
+ }
1599
+
1600
+ const defaultSchema = {
1601
+ controllerAttribute: "data-controller",
1602
+ actionAttribute: "data-action",
1603
+ targetAttribute: "data-target",
1604
+ targetAttributeForScope: identifier => `data-${identifier}-target`
1605
+ };
1606
+
1607
+ class Application {
1608
+ constructor(element = document.documentElement, schema = defaultSchema) {
1609
+ this.logger = console;
1610
+ this.debug = false;
1611
+ this.logDebugActivity = (identifier, functionName, detail = {}) => {
1612
+ if (this.debug) {
1613
+ this.logFormattedMessage(identifier, functionName, detail);
1614
+ }
1615
+ };
1616
+ this.element = element;
1617
+ this.schema = schema;
1618
+ this.dispatcher = new Dispatcher(this);
1619
+ this.router = new Router(this);
1620
+ }
1621
+ static start(element, schema) {
1622
+ const application = new Application(element, schema);
1623
+ application.start();
1624
+ return application;
1625
+ }
1626
+ async start() {
1627
+ await domReady();
1628
+ this.logDebugActivity("application", "starting");
1629
+ this.dispatcher.start();
1630
+ this.router.start();
1631
+ this.logDebugActivity("application", "start");
1632
+ }
1633
+ stop() {
1634
+ this.logDebugActivity("application", "stopping");
1635
+ this.dispatcher.stop();
1636
+ this.router.stop();
1637
+ this.logDebugActivity("application", "stop");
1638
+ }
1639
+ register(identifier, controllerConstructor) {
1640
+ if (controllerConstructor.shouldLoad) {
1641
+ this.load({ identifier, controllerConstructor });
1642
+ }
1643
+ }
1644
+ load(head, ...rest) {
1645
+ const definitions = Array.isArray(head) ? head : [head, ...rest];
1646
+ definitions.forEach(definition => this.router.loadDefinition(definition));
1647
+ }
1648
+ unload(head, ...rest) {
1649
+ const identifiers = Array.isArray(head) ? head : [head, ...rest];
1650
+ identifiers.forEach(identifier => this.router.unloadIdentifier(identifier));
1651
+ }
1652
+ get controllers() {
1653
+ return this.router.contexts.map(context => context.controller);
1654
+ }
1655
+ getControllerForElementAndIdentifier(element, identifier) {
1656
+ const context = this.router.getContextForElementAndIdentifier(element, identifier);
1657
+ return context ? context.controller : null;
1658
+ }
1659
+ handleError(error, message, detail) {
1660
+ var _a;
1661
+ this.logger.error(`%s\n\n%o\n\n%o`, message, error, detail);
1662
+ (_a = window.onerror) === null || _a === void 0 ? void 0 : _a.call(window, message, "", 0, 0, error);
1663
+ }
1664
+ logFormattedMessage(identifier, functionName, detail = {}) {
1665
+ detail = Object.assign({ application: this }, detail);
1666
+ this.logger.groupCollapsed(`${identifier} #${functionName}`);
1667
+ this.logger.log("details:", Object.assign({}, detail));
1668
+ this.logger.groupEnd();
1669
+ }
1670
+ }
1671
+ function domReady() {
1672
+ return new Promise(resolve => {
1673
+ if (document.readyState == "loading") {
1674
+ document.addEventListener("DOMContentLoaded", () => resolve());
1675
+ }
1676
+ else {
1677
+ resolve();
1678
+ }
1679
+ });
1680
+ }
1681
+
1682
+ function ClassPropertiesBlessing(constructor) {
1683
+ const classes = readInheritableStaticArrayValues(constructor, "classes");
1684
+ return classes.reduce((properties, classDefinition) => {
1685
+ return Object.assign(properties, propertiesForClassDefinition(classDefinition));
1686
+ }, {});
1687
+ }
1688
+ function propertiesForClassDefinition(key) {
1689
+ return {
1690
+ [`${key}Class`]: {
1691
+ get() {
1692
+ const { classes } = this;
1693
+ if (classes.has(key)) {
1694
+ return classes.get(key);
1695
+ }
1696
+ else {
1697
+ const attribute = classes.getAttributeName(key);
1698
+ throw new Error(`Missing attribute "${attribute}"`);
1699
+ }
1700
+ }
1701
+ },
1702
+ [`${key}Classes`]: {
1703
+ get() {
1704
+ return this.classes.getAll(key);
1705
+ }
1706
+ },
1707
+ [`has${capitalize(key)}Class`]: {
1708
+ get() {
1709
+ return this.classes.has(key);
1710
+ }
1711
+ }
1712
+ };
1713
+ }
1714
+
1715
+ function TargetPropertiesBlessing(constructor) {
1716
+ const targets = readInheritableStaticArrayValues(constructor, "targets");
1717
+ return targets.reduce((properties, targetDefinition) => {
1718
+ return Object.assign(properties, propertiesForTargetDefinition(targetDefinition));
1719
+ }, {});
1720
+ }
1721
+ function propertiesForTargetDefinition(name) {
1722
+ return {
1723
+ [`${name}Target`]: {
1724
+ get() {
1725
+ const target = this.targets.find(name);
1726
+ if (target) {
1727
+ return target;
1728
+ }
1729
+ else {
1730
+ throw new Error(`Missing target element "${name}" for "${this.identifier}" controller`);
1731
+ }
1732
+ }
1733
+ },
1734
+ [`${name}Targets`]: {
1735
+ get() {
1736
+ return this.targets.findAll(name);
1737
+ }
1738
+ },
1739
+ [`has${capitalize(name)}Target`]: {
1740
+ get() {
1741
+ return this.targets.has(name);
1742
+ }
1743
+ }
1744
+ };
1745
+ }
1746
+
1747
+ function ValuePropertiesBlessing(constructor) {
1748
+ const valueDefinitionPairs = readInheritableStaticObjectPairs(constructor, "values");
1749
+ const propertyDescriptorMap = {
1750
+ valueDescriptorMap: {
1751
+ get() {
1752
+ return valueDefinitionPairs.reduce((result, valueDefinitionPair) => {
1753
+ const valueDescriptor = parseValueDefinitionPair(valueDefinitionPair);
1754
+ const attributeName = this.data.getAttributeNameForKey(valueDescriptor.key);
1755
+ return Object.assign(result, { [attributeName]: valueDescriptor });
1756
+ }, {});
1757
+ }
1758
+ }
1759
+ };
1760
+ return valueDefinitionPairs.reduce((properties, valueDefinitionPair) => {
1761
+ return Object.assign(properties, propertiesForValueDefinitionPair(valueDefinitionPair));
1762
+ }, propertyDescriptorMap);
1763
+ }
1764
+ function propertiesForValueDefinitionPair(valueDefinitionPair) {
1765
+ const definition = parseValueDefinitionPair(valueDefinitionPair);
1766
+ const { key, name, reader: read, writer: write } = definition;
1767
+ return {
1768
+ [name]: {
1769
+ get() {
1770
+ const value = this.data.get(key);
1771
+ if (value !== null) {
1772
+ return read(value);
1773
+ }
1774
+ else {
1775
+ return definition.defaultValue;
1776
+ }
1777
+ },
1778
+ set(value) {
1779
+ if (value === undefined) {
1780
+ this.data.delete(key);
1781
+ }
1782
+ else {
1783
+ this.data.set(key, write(value));
1784
+ }
1785
+ }
1786
+ },
1787
+ [`has${capitalize(name)}`]: {
1788
+ get() {
1789
+ return this.data.has(key) || definition.hasCustomDefaultValue;
1790
+ }
1791
+ }
1792
+ };
1793
+ }
1794
+ function parseValueDefinitionPair([token, typeDefinition]) {
1795
+ return valueDescriptorForTokenAndTypeDefinition(token, typeDefinition);
1796
+ }
1797
+ function parseValueTypeConstant(constant) {
1798
+ switch (constant) {
1799
+ case Array: return "array";
1800
+ case Boolean: return "boolean";
1801
+ case Number: return "number";
1802
+ case Object: return "object";
1803
+ case String: return "string";
1804
+ }
1805
+ }
1806
+ function parseValueTypeDefault(defaultValue) {
1807
+ switch (typeof defaultValue) {
1808
+ case "boolean": return "boolean";
1809
+ case "number": return "number";
1810
+ case "string": return "string";
1811
+ }
1812
+ if (Array.isArray(defaultValue))
1813
+ return "array";
1814
+ if (Object.prototype.toString.call(defaultValue) === "[object Object]")
1815
+ return "object";
1816
+ }
1817
+ function parseValueTypeObject(typeObject) {
1818
+ const typeFromObject = parseValueTypeConstant(typeObject.type);
1819
+ if (typeFromObject) {
1820
+ const defaultValueType = parseValueTypeDefault(typeObject.default);
1821
+ if (typeFromObject !== defaultValueType) {
1822
+ throw new Error(`Type "${typeFromObject}" must match the type of the default value. Given default value: "${typeObject.default}" as "${defaultValueType}"`);
1823
+ }
1824
+ return typeFromObject;
1825
+ }
1826
+ }
1827
+ function parseValueTypeDefinition(typeDefinition) {
1828
+ const typeFromObject = parseValueTypeObject(typeDefinition);
1829
+ const typeFromDefaultValue = parseValueTypeDefault(typeDefinition);
1830
+ const typeFromConstant = parseValueTypeConstant(typeDefinition);
1831
+ const type = typeFromObject || typeFromDefaultValue || typeFromConstant;
1832
+ if (type)
1833
+ return type;
1834
+ throw new Error(`Unknown value type "${typeDefinition}"`);
1835
+ }
1836
+ function defaultValueForDefinition(typeDefinition) {
1837
+ const constant = parseValueTypeConstant(typeDefinition);
1838
+ if (constant)
1839
+ return defaultValuesByType[constant];
1840
+ const defaultValue = typeDefinition.default;
1841
+ if (defaultValue !== undefined)
1842
+ return defaultValue;
1843
+ return typeDefinition;
1844
+ }
1845
+ function valueDescriptorForTokenAndTypeDefinition(token, typeDefinition) {
1846
+ const key = `${dasherize(token)}-value`;
1847
+ const type = parseValueTypeDefinition(typeDefinition);
1848
+ return {
1849
+ type,
1850
+ key,
1851
+ name: camelize(key),
1852
+ get defaultValue() { return defaultValueForDefinition(typeDefinition); },
1853
+ get hasCustomDefaultValue() { return parseValueTypeDefault(typeDefinition) !== undefined; },
1854
+ reader: readers[type],
1855
+ writer: writers[type] || writers.default
1856
+ };
1857
+ }
1858
+ const defaultValuesByType = {
1859
+ get array() { return []; },
1860
+ boolean: false,
1861
+ number: 0,
1862
+ get object() { return {}; },
1863
+ string: ""
1864
+ };
1865
+ const readers = {
1866
+ array(value) {
1867
+ const array = JSON.parse(value);
1868
+ if (!Array.isArray(array)) {
1869
+ throw new TypeError("Expected array");
1870
+ }
1871
+ return array;
1872
+ },
1873
+ boolean(value) {
1874
+ return !(value == "0" || value == "false");
1875
+ },
1876
+ number(value) {
1877
+ return Number(value);
1878
+ },
1879
+ object(value) {
1880
+ const object = JSON.parse(value);
1881
+ if (object === null || typeof object != "object" || Array.isArray(object)) {
1882
+ throw new TypeError("Expected object");
1883
+ }
1884
+ return object;
1885
+ },
1886
+ string(value) {
1887
+ return value;
1888
+ }
1889
+ };
1890
+ const writers = {
1891
+ default: writeString,
1892
+ array: writeJSON,
1893
+ object: writeJSON
1894
+ };
1895
+ function writeJSON(value) {
1896
+ return JSON.stringify(value);
1897
+ }
1898
+ function writeString(value) {
1899
+ return `${value}`;
1900
+ }
1901
+
1902
+ class Controller {
1903
+ constructor(context) {
1904
+ this.context = context;
1905
+ }
1906
+ static get shouldLoad() {
1907
+ return true;
1908
+ }
1909
+ get application() {
1910
+ return this.context.application;
1911
+ }
1912
+ get scope() {
1913
+ return this.context.scope;
1914
+ }
1915
+ get element() {
1916
+ return this.scope.element;
1917
+ }
1918
+ get identifier() {
1919
+ return this.scope.identifier;
1920
+ }
1921
+ get targets() {
1922
+ return this.scope.targets;
1923
+ }
1924
+ get classes() {
1925
+ return this.scope.classes;
1926
+ }
1927
+ get data() {
1928
+ return this.scope.data;
1929
+ }
1930
+ initialize() {
1931
+ }
1932
+ connect() {
1933
+ }
1934
+ disconnect() {
1935
+ }
1936
+ dispatch(eventName, { target = this.element, detail = {}, prefix = this.identifier, bubbles = true, cancelable = true } = {}) {
1937
+ const type = prefix ? `${prefix}:${eventName}` : eventName;
1938
+ const event = new CustomEvent(type, { detail, bubbles, cancelable });
1939
+ target.dispatchEvent(event);
1940
+ return event;
1941
+ }
1942
+ }
1943
+ Controller.blessings = [ClassPropertiesBlessing, TargetPropertiesBlessing, ValuePropertiesBlessing];
1944
+ Controller.targets = [];
1945
+ Controller.values = {};
1946
+
1947
+ export { Application, AttributeObserver, Context, Controller, ElementObserver, IndexedMultimap, Multimap, StringMapObserver, TokenListObserver, ValueListObserver, add, defaultSchema, del, fetch, prune };