stimulus-rails 0.3.9 → 0.3.10

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