stimulus-rails 0.5.3 → 0.5.4

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