good_job 3.12.5 → 3.12.6

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