hotwire-spark 0.1.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (30) hide show
  1. checksums.yaml +7 -0
  2. data/MIT-LICENSE +20 -0
  3. data/README.md +49 -0
  4. data/Rakefile +8 -0
  5. data/app/assets/javascripts/hotwire_spark.js +3705 -0
  6. data/app/assets/javascripts/hotwire_spark.js.map +1 -0
  7. data/app/assets/javascripts/hotwire_spark.min.js +2 -0
  8. data/app/assets/javascripts/hotwire_spark.min.js.map +1 -0
  9. data/app/assets/stylesheets/hotwire_spark/application.css +15 -0
  10. data/app/channels/hotwire/spark/channel.rb +5 -0
  11. data/app/javascript/hotwire/spark/channels/consumer.js +3 -0
  12. data/app/javascript/hotwire/spark/channels/monitoring_channel.js +47 -0
  13. data/app/javascript/hotwire/spark/helpers.js +37 -0
  14. data/app/javascript/hotwire/spark/index.js +14 -0
  15. data/app/javascript/hotwire/spark/logger.js +8 -0
  16. data/app/javascript/hotwire/spark/reloaders/css_reloader.js +65 -0
  17. data/app/javascript/hotwire/spark/reloaders/html_reloader.js +31 -0
  18. data/app/javascript/hotwire/spark/reloaders/stimulus_reloader.js +76 -0
  19. data/config/routes.rb +2 -0
  20. data/lib/hotwire/spark/action_cable/persistent_cable_middleware.rb +43 -0
  21. data/lib/hotwire/spark/action_cable/persistent_cable_server.rb +25 -0
  22. data/lib/hotwire/spark/action_cable/solid_cable_listener_with_safe_reloads.rb +8 -0
  23. data/lib/hotwire/spark/engine.rb +25 -0
  24. data/lib/hotwire/spark/file_watcher.rb +40 -0
  25. data/lib/hotwire/spark/installer.rb +52 -0
  26. data/lib/hotwire/spark/middleware.rb +55 -0
  27. data/lib/hotwire/spark/version.rb +5 -0
  28. data/lib/hotwire-spark.rb +26 -0
  29. data/lib/tasks/hotwire_spark_tasks.rake +4 -0
  30. metadata +173 -0
@@ -0,0 +1,3705 @@
1
+ var HotwireSpark = (function () {
2
+ 'use strict';
3
+
4
+ var adapters = {
5
+ logger: typeof console !== "undefined" ? console : undefined,
6
+ WebSocket: typeof WebSocket !== "undefined" ? WebSocket : undefined
7
+ };
8
+
9
+ var logger = {
10
+ log(...messages) {
11
+ if (this.enabled) {
12
+ messages.push(Date.now());
13
+ adapters.logger.log("[ActionCable]", ...messages);
14
+ }
15
+ }
16
+ };
17
+
18
+ const now = () => (new Date).getTime();
19
+
20
+ const secondsSince = time => (now() - time) / 1e3;
21
+
22
+ class ConnectionMonitor {
23
+ constructor(connection) {
24
+ this.visibilityDidChange = this.visibilityDidChange.bind(this);
25
+ this.connection = connection;
26
+ this.reconnectAttempts = 0;
27
+ }
28
+ start() {
29
+ if (!this.isRunning()) {
30
+ this.startedAt = now();
31
+ delete this.stoppedAt;
32
+ this.startPolling();
33
+ addEventListener("visibilitychange", this.visibilityDidChange);
34
+ logger.log(`ConnectionMonitor started. stale threshold = ${this.constructor.staleThreshold} s`);
35
+ }
36
+ }
37
+ stop() {
38
+ if (this.isRunning()) {
39
+ this.stoppedAt = now();
40
+ this.stopPolling();
41
+ removeEventListener("visibilitychange", this.visibilityDidChange);
42
+ logger.log("ConnectionMonitor stopped");
43
+ }
44
+ }
45
+ isRunning() {
46
+ return this.startedAt && !this.stoppedAt;
47
+ }
48
+ recordMessage() {
49
+ this.pingedAt = now();
50
+ }
51
+ recordConnect() {
52
+ this.reconnectAttempts = 0;
53
+ delete this.disconnectedAt;
54
+ logger.log("ConnectionMonitor recorded connect");
55
+ }
56
+ recordDisconnect() {
57
+ this.disconnectedAt = now();
58
+ logger.log("ConnectionMonitor recorded disconnect");
59
+ }
60
+ startPolling() {
61
+ this.stopPolling();
62
+ this.poll();
63
+ }
64
+ stopPolling() {
65
+ clearTimeout(this.pollTimeout);
66
+ }
67
+ poll() {
68
+ this.pollTimeout = setTimeout((() => {
69
+ this.reconnectIfStale();
70
+ this.poll();
71
+ }), this.getPollInterval());
72
+ }
73
+ getPollInterval() {
74
+ const {staleThreshold: staleThreshold, reconnectionBackoffRate: reconnectionBackoffRate} = this.constructor;
75
+ const backoff = Math.pow(1 + reconnectionBackoffRate, Math.min(this.reconnectAttempts, 10));
76
+ const jitterMax = this.reconnectAttempts === 0 ? 1 : reconnectionBackoffRate;
77
+ const jitter = jitterMax * Math.random();
78
+ return staleThreshold * 1e3 * backoff * (1 + jitter);
79
+ }
80
+ reconnectIfStale() {
81
+ if (this.connectionIsStale()) {
82
+ logger.log(`ConnectionMonitor detected stale connection. reconnectAttempts = ${this.reconnectAttempts}, time stale = ${secondsSince(this.refreshedAt)} s, stale threshold = ${this.constructor.staleThreshold} s`);
83
+ this.reconnectAttempts++;
84
+ if (this.disconnectedRecently()) {
85
+ logger.log(`ConnectionMonitor skipping reopening recent disconnect. time disconnected = ${secondsSince(this.disconnectedAt)} s`);
86
+ } else {
87
+ logger.log("ConnectionMonitor reopening");
88
+ this.connection.reopen();
89
+ }
90
+ }
91
+ }
92
+ get refreshedAt() {
93
+ return this.pingedAt ? this.pingedAt : this.startedAt;
94
+ }
95
+ connectionIsStale() {
96
+ return secondsSince(this.refreshedAt) > this.constructor.staleThreshold;
97
+ }
98
+ disconnectedRecently() {
99
+ return this.disconnectedAt && secondsSince(this.disconnectedAt) < this.constructor.staleThreshold;
100
+ }
101
+ visibilityDidChange() {
102
+ if (document.visibilityState === "visible") {
103
+ setTimeout((() => {
104
+ if (this.connectionIsStale() || !this.connection.isOpen()) {
105
+ logger.log(`ConnectionMonitor reopening stale connection on visibilitychange. visibilityState = ${document.visibilityState}`);
106
+ this.connection.reopen();
107
+ }
108
+ }), 200);
109
+ }
110
+ }
111
+ }
112
+
113
+ ConnectionMonitor.staleThreshold = 6;
114
+
115
+ ConnectionMonitor.reconnectionBackoffRate = .15;
116
+
117
+ var INTERNAL = {
118
+ message_types: {
119
+ welcome: "welcome",
120
+ disconnect: "disconnect",
121
+ ping: "ping",
122
+ confirmation: "confirm_subscription",
123
+ rejection: "reject_subscription"
124
+ },
125
+ disconnect_reasons: {
126
+ unauthorized: "unauthorized",
127
+ invalid_request: "invalid_request",
128
+ server_restart: "server_restart",
129
+ remote: "remote"
130
+ },
131
+ default_mount_path: "/cable",
132
+ protocols: [ "actioncable-v1-json", "actioncable-unsupported" ]
133
+ };
134
+
135
+ const {message_types: message_types, protocols: protocols} = INTERNAL;
136
+
137
+ const supportedProtocols = protocols.slice(0, protocols.length - 1);
138
+
139
+ const indexOf = [].indexOf;
140
+
141
+ class Connection {
142
+ constructor(consumer) {
143
+ this.open = this.open.bind(this);
144
+ this.consumer = consumer;
145
+ this.subscriptions = this.consumer.subscriptions;
146
+ this.monitor = new ConnectionMonitor(this);
147
+ this.disconnected = true;
148
+ }
149
+ send(data) {
150
+ if (this.isOpen()) {
151
+ this.webSocket.send(JSON.stringify(data));
152
+ return true;
153
+ } else {
154
+ return false;
155
+ }
156
+ }
157
+ open() {
158
+ if (this.isActive()) {
159
+ logger.log(`Attempted to open WebSocket, but existing socket is ${this.getState()}`);
160
+ return false;
161
+ } else {
162
+ const socketProtocols = [ ...protocols, ...this.consumer.subprotocols || [] ];
163
+ logger.log(`Opening WebSocket, current state is ${this.getState()}, subprotocols: ${socketProtocols}`);
164
+ if (this.webSocket) {
165
+ this.uninstallEventHandlers();
166
+ }
167
+ this.webSocket = new adapters.WebSocket(this.consumer.url, socketProtocols);
168
+ this.installEventHandlers();
169
+ this.monitor.start();
170
+ return true;
171
+ }
172
+ }
173
+ close({allowReconnect: allowReconnect} = {
174
+ allowReconnect: true
175
+ }) {
176
+ if (!allowReconnect) {
177
+ this.monitor.stop();
178
+ }
179
+ if (this.isOpen()) {
180
+ return this.webSocket.close();
181
+ }
182
+ }
183
+ reopen() {
184
+ logger.log(`Reopening WebSocket, current state is ${this.getState()}`);
185
+ if (this.isActive()) {
186
+ try {
187
+ return this.close();
188
+ } catch (error) {
189
+ logger.log("Failed to reopen WebSocket", error);
190
+ } finally {
191
+ logger.log(`Reopening WebSocket in ${this.constructor.reopenDelay}ms`);
192
+ setTimeout(this.open, this.constructor.reopenDelay);
193
+ }
194
+ } else {
195
+ return this.open();
196
+ }
197
+ }
198
+ getProtocol() {
199
+ if (this.webSocket) {
200
+ return this.webSocket.protocol;
201
+ }
202
+ }
203
+ isOpen() {
204
+ return this.isState("open");
205
+ }
206
+ isActive() {
207
+ return this.isState("open", "connecting");
208
+ }
209
+ triedToReconnect() {
210
+ return this.monitor.reconnectAttempts > 0;
211
+ }
212
+ isProtocolSupported() {
213
+ return indexOf.call(supportedProtocols, this.getProtocol()) >= 0;
214
+ }
215
+ isState(...states) {
216
+ return indexOf.call(states, this.getState()) >= 0;
217
+ }
218
+ getState() {
219
+ if (this.webSocket) {
220
+ for (let state in adapters.WebSocket) {
221
+ if (adapters.WebSocket[state] === this.webSocket.readyState) {
222
+ return state.toLowerCase();
223
+ }
224
+ }
225
+ }
226
+ return null;
227
+ }
228
+ installEventHandlers() {
229
+ for (let eventName in this.events) {
230
+ const handler = this.events[eventName].bind(this);
231
+ this.webSocket[`on${eventName}`] = handler;
232
+ }
233
+ }
234
+ uninstallEventHandlers() {
235
+ for (let eventName in this.events) {
236
+ this.webSocket[`on${eventName}`] = function() {};
237
+ }
238
+ }
239
+ }
240
+
241
+ Connection.reopenDelay = 500;
242
+
243
+ Connection.prototype.events = {
244
+ message(event) {
245
+ if (!this.isProtocolSupported()) {
246
+ return;
247
+ }
248
+ const {identifier: identifier, message: message, reason: reason, reconnect: reconnect, type: type} = JSON.parse(event.data);
249
+ this.monitor.recordMessage();
250
+ switch (type) {
251
+ case message_types.welcome:
252
+ if (this.triedToReconnect()) {
253
+ this.reconnectAttempted = true;
254
+ }
255
+ this.monitor.recordConnect();
256
+ return this.subscriptions.reload();
257
+
258
+ case message_types.disconnect:
259
+ logger.log(`Disconnecting. Reason: ${reason}`);
260
+ return this.close({
261
+ allowReconnect: reconnect
262
+ });
263
+
264
+ case message_types.ping:
265
+ return null;
266
+
267
+ case message_types.confirmation:
268
+ this.subscriptions.confirmSubscription(identifier);
269
+ if (this.reconnectAttempted) {
270
+ this.reconnectAttempted = false;
271
+ return this.subscriptions.notify(identifier, "connected", {
272
+ reconnected: true
273
+ });
274
+ } else {
275
+ return this.subscriptions.notify(identifier, "connected", {
276
+ reconnected: false
277
+ });
278
+ }
279
+
280
+ case message_types.rejection:
281
+ return this.subscriptions.reject(identifier);
282
+
283
+ default:
284
+ return this.subscriptions.notify(identifier, "received", message);
285
+ }
286
+ },
287
+ open() {
288
+ logger.log(`WebSocket onopen event, using '${this.getProtocol()}' subprotocol`);
289
+ this.disconnected = false;
290
+ if (!this.isProtocolSupported()) {
291
+ logger.log("Protocol is unsupported. Stopping monitor and disconnecting.");
292
+ return this.close({
293
+ allowReconnect: false
294
+ });
295
+ }
296
+ },
297
+ close(event) {
298
+ logger.log("WebSocket onclose event");
299
+ if (this.disconnected) {
300
+ return;
301
+ }
302
+ this.disconnected = true;
303
+ this.monitor.recordDisconnect();
304
+ return this.subscriptions.notifyAll("disconnected", {
305
+ willAttemptReconnect: this.monitor.isRunning()
306
+ });
307
+ },
308
+ error() {
309
+ logger.log("WebSocket onerror event");
310
+ }
311
+ };
312
+
313
+ const extend$1 = function(object, properties) {
314
+ if (properties != null) {
315
+ for (let key in properties) {
316
+ const value = properties[key];
317
+ object[key] = value;
318
+ }
319
+ }
320
+ return object;
321
+ };
322
+
323
+ class Subscription {
324
+ constructor(consumer, params = {}, mixin) {
325
+ this.consumer = consumer;
326
+ this.identifier = JSON.stringify(params);
327
+ extend$1(this, mixin);
328
+ }
329
+ perform(action, data = {}) {
330
+ data.action = action;
331
+ return this.send(data);
332
+ }
333
+ send(data) {
334
+ return this.consumer.send({
335
+ command: "message",
336
+ identifier: this.identifier,
337
+ data: JSON.stringify(data)
338
+ });
339
+ }
340
+ unsubscribe() {
341
+ return this.consumer.subscriptions.remove(this);
342
+ }
343
+ }
344
+
345
+ class SubscriptionGuarantor {
346
+ constructor(subscriptions) {
347
+ this.subscriptions = subscriptions;
348
+ this.pendingSubscriptions = [];
349
+ }
350
+ guarantee(subscription) {
351
+ if (this.pendingSubscriptions.indexOf(subscription) == -1) {
352
+ logger.log(`SubscriptionGuarantor guaranteeing ${subscription.identifier}`);
353
+ this.pendingSubscriptions.push(subscription);
354
+ } else {
355
+ logger.log(`SubscriptionGuarantor already guaranteeing ${subscription.identifier}`);
356
+ }
357
+ this.startGuaranteeing();
358
+ }
359
+ forget(subscription) {
360
+ logger.log(`SubscriptionGuarantor forgetting ${subscription.identifier}`);
361
+ this.pendingSubscriptions = this.pendingSubscriptions.filter((s => s !== subscription));
362
+ }
363
+ startGuaranteeing() {
364
+ this.stopGuaranteeing();
365
+ this.retrySubscribing();
366
+ }
367
+ stopGuaranteeing() {
368
+ clearTimeout(this.retryTimeout);
369
+ }
370
+ retrySubscribing() {
371
+ this.retryTimeout = setTimeout((() => {
372
+ if (this.subscriptions && typeof this.subscriptions.subscribe === "function") {
373
+ this.pendingSubscriptions.map((subscription => {
374
+ logger.log(`SubscriptionGuarantor resubscribing ${subscription.identifier}`);
375
+ this.subscriptions.subscribe(subscription);
376
+ }));
377
+ }
378
+ }), 500);
379
+ }
380
+ }
381
+
382
+ class Subscriptions {
383
+ constructor(consumer) {
384
+ this.consumer = consumer;
385
+ this.guarantor = new SubscriptionGuarantor(this);
386
+ this.subscriptions = [];
387
+ }
388
+ create(channelName, mixin) {
389
+ const channel = channelName;
390
+ const params = typeof channel === "object" ? channel : {
391
+ channel: channel
392
+ };
393
+ const subscription = new Subscription(this.consumer, params, mixin);
394
+ return this.add(subscription);
395
+ }
396
+ add(subscription) {
397
+ this.subscriptions.push(subscription);
398
+ this.consumer.ensureActiveConnection();
399
+ this.notify(subscription, "initialized");
400
+ this.subscribe(subscription);
401
+ return subscription;
402
+ }
403
+ remove(subscription) {
404
+ this.forget(subscription);
405
+ if (!this.findAll(subscription.identifier).length) {
406
+ this.sendCommand(subscription, "unsubscribe");
407
+ }
408
+ return subscription;
409
+ }
410
+ reject(identifier) {
411
+ return this.findAll(identifier).map((subscription => {
412
+ this.forget(subscription);
413
+ this.notify(subscription, "rejected");
414
+ return subscription;
415
+ }));
416
+ }
417
+ forget(subscription) {
418
+ this.guarantor.forget(subscription);
419
+ this.subscriptions = this.subscriptions.filter((s => s !== subscription));
420
+ return subscription;
421
+ }
422
+ findAll(identifier) {
423
+ return this.subscriptions.filter((s => s.identifier === identifier));
424
+ }
425
+ reload() {
426
+ return this.subscriptions.map((subscription => this.subscribe(subscription)));
427
+ }
428
+ notifyAll(callbackName, ...args) {
429
+ return this.subscriptions.map((subscription => this.notify(subscription, callbackName, ...args)));
430
+ }
431
+ notify(subscription, callbackName, ...args) {
432
+ let subscriptions;
433
+ if (typeof subscription === "string") {
434
+ subscriptions = this.findAll(subscription);
435
+ } else {
436
+ subscriptions = [ subscription ];
437
+ }
438
+ return subscriptions.map((subscription => typeof subscription[callbackName] === "function" ? subscription[callbackName](...args) : undefined));
439
+ }
440
+ subscribe(subscription) {
441
+ if (this.sendCommand(subscription, "subscribe")) {
442
+ this.guarantor.guarantee(subscription);
443
+ }
444
+ }
445
+ confirmSubscription(identifier) {
446
+ logger.log(`Subscription confirmed ${identifier}`);
447
+ this.findAll(identifier).map((subscription => this.guarantor.forget(subscription)));
448
+ }
449
+ sendCommand(subscription, command) {
450
+ const {identifier: identifier} = subscription;
451
+ return this.consumer.send({
452
+ command: command,
453
+ identifier: identifier
454
+ });
455
+ }
456
+ }
457
+
458
+ class Consumer {
459
+ constructor(url) {
460
+ this._url = url;
461
+ this.subscriptions = new Subscriptions(this);
462
+ this.connection = new Connection(this);
463
+ this.subprotocols = [];
464
+ }
465
+ get url() {
466
+ return createWebSocketURL(this._url);
467
+ }
468
+ send(data) {
469
+ return this.connection.send(data);
470
+ }
471
+ connect() {
472
+ return this.connection.open();
473
+ }
474
+ disconnect() {
475
+ return this.connection.close({
476
+ allowReconnect: false
477
+ });
478
+ }
479
+ ensureActiveConnection() {
480
+ if (!this.connection.isActive()) {
481
+ return this.connection.open();
482
+ }
483
+ }
484
+ addSubProtocol(subprotocol) {
485
+ this.subprotocols = [ ...this.subprotocols, subprotocol ];
486
+ }
487
+ }
488
+
489
+ function createWebSocketURL(url) {
490
+ if (typeof url === "function") {
491
+ url = url();
492
+ }
493
+ if (url && !/^wss?:/i.test(url)) {
494
+ const a = document.createElement("a");
495
+ a.href = url;
496
+ a.href = a.href;
497
+ a.protocol = a.protocol.replace("http", "ws");
498
+ return a.href;
499
+ } else {
500
+ return url;
501
+ }
502
+ }
503
+
504
+ function createConsumer(url = getConfig("url") || INTERNAL.default_mount_path) {
505
+ return new Consumer(url);
506
+ }
507
+
508
+ function getConfig(name) {
509
+ const element = document.head.querySelector(`meta[name='action-cable-${name}']`);
510
+ if (element) {
511
+ return element.getAttribute("content");
512
+ }
513
+ }
514
+
515
+ var consumer = createConsumer();
516
+
517
+ function assetNameFromPath(path) {
518
+ return path.split("/").pop().split(".")[0];
519
+ }
520
+ function pathWithoutAssetDigest(path) {
521
+ return path.replace(/-[a-z0-9]+\.(\w+)(\?.*)?$/, ".$1");
522
+ }
523
+ function urlWithParams(urlString, params) {
524
+ const url = new URL(urlString, window.location.origin);
525
+ Object.entries(params).forEach(_ref => {
526
+ let [key, value] = _ref;
527
+ url.searchParams.set(key, value);
528
+ });
529
+ return url.toString();
530
+ }
531
+ function cacheBustedUrl(urlString) {
532
+ return urlWithParams(urlString, {
533
+ reload: Date.now()
534
+ });
535
+ }
536
+ async function reloadHtmlDocument() {
537
+ let currentUrl = cacheBustedUrl(urlWithParams(window.location.href, {
538
+ hotwire_spark: "true"
539
+ }));
540
+ const response = await fetch(currentUrl);
541
+ if (!response.ok) {
542
+ throw new Error(`${response.status} when fetching ${currentUrl}`);
543
+ }
544
+ const fetchedHTML = await response.text();
545
+ const parser = new DOMParser();
546
+ return parser.parseFromString(fetchedHTML, "text/html");
547
+ }
548
+ function getConfigurationProperty(name) {
549
+ return document.querySelector(`meta[name="hotwire-spark:${name}"]`)?.content;
550
+ }
551
+
552
+ // base IIFE to define idiomorph
553
+ var Idiomorph = (function () {
554
+
555
+ //=============================================================================
556
+ // AND NOW IT BEGINS...
557
+ //=============================================================================
558
+ let EMPTY_SET = new Set();
559
+
560
+ // default configuration values, updatable by users now
561
+ let defaults = {
562
+ morphStyle: "outerHTML",
563
+ callbacks : {
564
+ beforeNodeAdded: noOp,
565
+ afterNodeAdded: noOp,
566
+ beforeNodeMorphed: noOp,
567
+ afterNodeMorphed: noOp,
568
+ beforeNodeRemoved: noOp,
569
+ afterNodeRemoved: noOp,
570
+ beforeAttributeUpdated: noOp,
571
+
572
+ },
573
+ head: {
574
+ style: 'merge',
575
+ shouldPreserve: function (elt) {
576
+ return elt.getAttribute("im-preserve") === "true";
577
+ },
578
+ shouldReAppend: function (elt) {
579
+ return elt.getAttribute("im-re-append") === "true";
580
+ },
581
+ shouldRemove: noOp,
582
+ afterHeadMorphed: noOp,
583
+ }
584
+ };
585
+
586
+ //=============================================================================
587
+ // Core Morphing Algorithm - morph, morphNormalizedContent, morphOldNodeTo, morphChildren
588
+ //=============================================================================
589
+ function morph(oldNode, newContent, config = {}) {
590
+
591
+ if (oldNode instanceof Document) {
592
+ oldNode = oldNode.documentElement;
593
+ }
594
+
595
+ if (typeof newContent === 'string') {
596
+ newContent = parseContent(newContent);
597
+ }
598
+
599
+ let normalizedContent = normalizeContent(newContent);
600
+
601
+ let ctx = createMorphContext(oldNode, normalizedContent, config);
602
+
603
+ return morphNormalizedContent(oldNode, normalizedContent, ctx);
604
+ }
605
+
606
+ function morphNormalizedContent(oldNode, normalizedNewContent, ctx) {
607
+ if (ctx.head.block) {
608
+ let oldHead = oldNode.querySelector('head');
609
+ let newHead = normalizedNewContent.querySelector('head');
610
+ if (oldHead && newHead) {
611
+ let promises = handleHeadElement(newHead, oldHead, ctx);
612
+ // when head promises resolve, call morph again, ignoring the head tag
613
+ Promise.all(promises).then(function () {
614
+ morphNormalizedContent(oldNode, normalizedNewContent, Object.assign(ctx, {
615
+ head: {
616
+ block: false,
617
+ ignore: true
618
+ }
619
+ }));
620
+ });
621
+ return;
622
+ }
623
+ }
624
+
625
+ if (ctx.morphStyle === "innerHTML") {
626
+
627
+ // innerHTML, so we are only updating the children
628
+ morphChildren(normalizedNewContent, oldNode, ctx);
629
+ return oldNode.children;
630
+
631
+ } else if (ctx.morphStyle === "outerHTML" || ctx.morphStyle == null) {
632
+ // otherwise find the best element match in the new content, morph that, and merge its siblings
633
+ // into either side of the best match
634
+ let bestMatch = findBestNodeMatch(normalizedNewContent, oldNode, ctx);
635
+
636
+ // stash the siblings that will need to be inserted on either side of the best match
637
+ let previousSibling = bestMatch?.previousSibling;
638
+ let nextSibling = bestMatch?.nextSibling;
639
+
640
+ // morph it
641
+ let morphedNode = morphOldNodeTo(oldNode, bestMatch, ctx);
642
+
643
+ if (bestMatch) {
644
+ // if there was a best match, merge the siblings in too and return the
645
+ // whole bunch
646
+ return insertSiblings(previousSibling, morphedNode, nextSibling);
647
+ } else {
648
+ // otherwise nothing was added to the DOM
649
+ return []
650
+ }
651
+ } else {
652
+ throw "Do not understand how to morph style " + ctx.morphStyle;
653
+ }
654
+ }
655
+
656
+
657
+ /**
658
+ * @param possibleActiveElement
659
+ * @param ctx
660
+ * @returns {boolean}
661
+ */
662
+ function ignoreValueOfActiveElement(possibleActiveElement, ctx) {
663
+ return ctx.ignoreActiveValue && possibleActiveElement === document.activeElement;
664
+ }
665
+
666
+ /**
667
+ * @param oldNode root node to merge content into
668
+ * @param newContent new content to merge
669
+ * @param ctx the merge context
670
+ * @returns {Element} the element that ended up in the DOM
671
+ */
672
+ function morphOldNodeTo(oldNode, newContent, ctx) {
673
+ if (ctx.ignoreActive && oldNode === document.activeElement) ; else if (newContent == null) {
674
+ if (ctx.callbacks.beforeNodeRemoved(oldNode) === false) return oldNode;
675
+
676
+ oldNode.remove();
677
+ ctx.callbacks.afterNodeRemoved(oldNode);
678
+ return null;
679
+ } else if (!isSoftMatch(oldNode, newContent)) {
680
+ if (ctx.callbacks.beforeNodeRemoved(oldNode) === false) return oldNode;
681
+ if (ctx.callbacks.beforeNodeAdded(newContent) === false) return oldNode;
682
+
683
+ oldNode.parentElement.replaceChild(newContent, oldNode);
684
+ ctx.callbacks.afterNodeAdded(newContent);
685
+ ctx.callbacks.afterNodeRemoved(oldNode);
686
+ return newContent;
687
+ } else {
688
+ if (ctx.callbacks.beforeNodeMorphed(oldNode, newContent) === false) return oldNode;
689
+
690
+ if (oldNode instanceof HTMLHeadElement && ctx.head.ignore) ; else if (oldNode instanceof HTMLHeadElement && ctx.head.style !== "morph") {
691
+ handleHeadElement(newContent, oldNode, ctx);
692
+ } else {
693
+ syncNodeFrom(newContent, oldNode, ctx);
694
+ if (!ignoreValueOfActiveElement(oldNode, ctx)) {
695
+ morphChildren(newContent, oldNode, ctx);
696
+ }
697
+ }
698
+ ctx.callbacks.afterNodeMorphed(oldNode, newContent);
699
+ return oldNode;
700
+ }
701
+ }
702
+
703
+ /**
704
+ * This is the core algorithm for matching up children. The idea is to use id sets to try to match up
705
+ * nodes as faithfully as possible. We greedily match, which allows us to keep the algorithm fast, but
706
+ * by using id sets, we are able to better match up with content deeper in the DOM.
707
+ *
708
+ * Basic algorithm is, for each node in the new content:
709
+ *
710
+ * - if we have reached the end of the old parent, append the new content
711
+ * - if the new content has an id set match with the current insertion point, morph
712
+ * - search for an id set match
713
+ * - if id set match found, morph
714
+ * - otherwise search for a "soft" match
715
+ * - if a soft match is found, morph
716
+ * - otherwise, prepend the new node before the current insertion point
717
+ *
718
+ * The two search algorithms terminate if competing node matches appear to outweigh what can be achieved
719
+ * with the current node. See findIdSetMatch() and findSoftMatch() for details.
720
+ *
721
+ * @param {Element} newParent the parent element of the new content
722
+ * @param {Element } oldParent the old content that we are merging the new content into
723
+ * @param ctx the merge context
724
+ */
725
+ function morphChildren(newParent, oldParent, ctx) {
726
+
727
+ let nextNewChild = newParent.firstChild;
728
+ let insertionPoint = oldParent.firstChild;
729
+ let newChild;
730
+
731
+ // run through all the new content
732
+ while (nextNewChild) {
733
+
734
+ newChild = nextNewChild;
735
+ nextNewChild = newChild.nextSibling;
736
+
737
+ // if we are at the end of the exiting parent's children, just append
738
+ if (insertionPoint == null) {
739
+ if (ctx.callbacks.beforeNodeAdded(newChild) === false) return;
740
+
741
+ oldParent.appendChild(newChild);
742
+ ctx.callbacks.afterNodeAdded(newChild);
743
+ removeIdsFromConsideration(ctx, newChild);
744
+ continue;
745
+ }
746
+
747
+ // if the current node has an id set match then morph
748
+ if (isIdSetMatch(newChild, insertionPoint, ctx)) {
749
+ morphOldNodeTo(insertionPoint, newChild, ctx);
750
+ insertionPoint = insertionPoint.nextSibling;
751
+ removeIdsFromConsideration(ctx, newChild);
752
+ continue;
753
+ }
754
+
755
+ // otherwise search forward in the existing old children for an id set match
756
+ let idSetMatch = findIdSetMatch(newParent, oldParent, newChild, insertionPoint, ctx);
757
+
758
+ // if we found a potential match, remove the nodes until that point and morph
759
+ if (idSetMatch) {
760
+ insertionPoint = removeNodesBetween(insertionPoint, idSetMatch, ctx);
761
+ morphOldNodeTo(idSetMatch, newChild, ctx);
762
+ removeIdsFromConsideration(ctx, newChild);
763
+ continue;
764
+ }
765
+
766
+ // no id set match found, so scan forward for a soft match for the current node
767
+ let softMatch = findSoftMatch(newParent, oldParent, newChild, insertionPoint, ctx);
768
+
769
+ // if we found a soft match for the current node, morph
770
+ if (softMatch) {
771
+ insertionPoint = removeNodesBetween(insertionPoint, softMatch, ctx);
772
+ morphOldNodeTo(softMatch, newChild, ctx);
773
+ removeIdsFromConsideration(ctx, newChild);
774
+ continue;
775
+ }
776
+
777
+ // abandon all hope of morphing, just insert the new child before the insertion point
778
+ // and move on
779
+ if (ctx.callbacks.beforeNodeAdded(newChild) === false) return;
780
+
781
+ oldParent.insertBefore(newChild, insertionPoint);
782
+ ctx.callbacks.afterNodeAdded(newChild);
783
+ removeIdsFromConsideration(ctx, newChild);
784
+ }
785
+
786
+ // remove any remaining old nodes that didn't match up with new content
787
+ while (insertionPoint !== null) {
788
+
789
+ let tempNode = insertionPoint;
790
+ insertionPoint = insertionPoint.nextSibling;
791
+ removeNode(tempNode, ctx);
792
+ }
793
+ }
794
+
795
+ //=============================================================================
796
+ // Attribute Syncing Code
797
+ //=============================================================================
798
+
799
+ /**
800
+ * @param attr {String} the attribute to be mutated
801
+ * @param to {Element} the element that is going to be updated
802
+ * @param updateType {("update"|"remove")}
803
+ * @param ctx the merge context
804
+ * @returns {boolean} true if the attribute should be ignored, false otherwise
805
+ */
806
+ function ignoreAttribute(attr, to, updateType, ctx) {
807
+ if(attr === 'value' && ctx.ignoreActiveValue && to === document.activeElement){
808
+ return true;
809
+ }
810
+ return ctx.callbacks.beforeAttributeUpdated(attr, to, updateType) === false;
811
+ }
812
+
813
+ /**
814
+ * syncs a given node with another node, copying over all attributes and
815
+ * inner element state from the 'from' node to the 'to' node
816
+ *
817
+ * @param {Element} from the element to copy attributes & state from
818
+ * @param {Element} to the element to copy attributes & state to
819
+ * @param ctx the merge context
820
+ */
821
+ function syncNodeFrom(from, to, ctx) {
822
+ let type = from.nodeType;
823
+
824
+ // if is an element type, sync the attributes from the
825
+ // new node into the new node
826
+ if (type === 1 /* element type */) {
827
+ const fromAttributes = from.attributes;
828
+ const toAttributes = to.attributes;
829
+ for (const fromAttribute of fromAttributes) {
830
+ if (ignoreAttribute(fromAttribute.name, to, 'update', ctx)) {
831
+ continue;
832
+ }
833
+ if (to.getAttribute(fromAttribute.name) !== fromAttribute.value) {
834
+ to.setAttribute(fromAttribute.name, fromAttribute.value);
835
+ }
836
+ }
837
+ // iterate backwards to avoid skipping over items when a delete occurs
838
+ for (let i = toAttributes.length - 1; 0 <= i; i--) {
839
+ const toAttribute = toAttributes[i];
840
+ if (ignoreAttribute(toAttribute.name, to, 'remove', ctx)) {
841
+ continue;
842
+ }
843
+ if (!from.hasAttribute(toAttribute.name)) {
844
+ to.removeAttribute(toAttribute.name);
845
+ }
846
+ }
847
+ }
848
+
849
+ // sync text nodes
850
+ if (type === 8 /* comment */ || type === 3 /* text */) {
851
+ if (to.nodeValue !== from.nodeValue) {
852
+ to.nodeValue = from.nodeValue;
853
+ }
854
+ }
855
+
856
+ if (!ignoreValueOfActiveElement(to, ctx)) {
857
+ // sync input values
858
+ syncInputValue(from, to, ctx);
859
+ }
860
+ }
861
+
862
+ /**
863
+ * @param from {Element} element to sync the value from
864
+ * @param to {Element} element to sync the value to
865
+ * @param attributeName {String} the attribute name
866
+ * @param ctx the merge context
867
+ */
868
+ function syncBooleanAttribute(from, to, attributeName, ctx) {
869
+ if (from[attributeName] !== to[attributeName]) {
870
+ let ignoreUpdate = ignoreAttribute(attributeName, to, 'update', ctx);
871
+ if (!ignoreUpdate) {
872
+ to[attributeName] = from[attributeName];
873
+ }
874
+ if (from[attributeName]) {
875
+ if (!ignoreUpdate) {
876
+ to.setAttribute(attributeName, from[attributeName]);
877
+ }
878
+ } else {
879
+ if (!ignoreAttribute(attributeName, to, 'remove', ctx)) {
880
+ to.removeAttribute(attributeName);
881
+ }
882
+ }
883
+ }
884
+ }
885
+
886
+ /**
887
+ * NB: many bothans died to bring us information:
888
+ *
889
+ * https://github.com/patrick-steele-idem/morphdom/blob/master/src/specialElHandlers.js
890
+ * https://github.com/choojs/nanomorph/blob/master/lib/morph.jsL113
891
+ *
892
+ * @param from {Element} the element to sync the input value from
893
+ * @param to {Element} the element to sync the input value to
894
+ * @param ctx the merge context
895
+ */
896
+ function syncInputValue(from, to, ctx) {
897
+ if (from instanceof HTMLInputElement &&
898
+ to instanceof HTMLInputElement &&
899
+ from.type !== 'file') {
900
+
901
+ let fromValue = from.value;
902
+ let toValue = to.value;
903
+
904
+ // sync boolean attributes
905
+ syncBooleanAttribute(from, to, 'checked', ctx);
906
+ syncBooleanAttribute(from, to, 'disabled', ctx);
907
+
908
+ if (!from.hasAttribute('value')) {
909
+ if (!ignoreAttribute('value', to, 'remove', ctx)) {
910
+ to.value = '';
911
+ to.removeAttribute('value');
912
+ }
913
+ } else if (fromValue !== toValue) {
914
+ if (!ignoreAttribute('value', to, 'update', ctx)) {
915
+ to.setAttribute('value', fromValue);
916
+ to.value = fromValue;
917
+ }
918
+ }
919
+ } else if (from instanceof HTMLOptionElement) {
920
+ syncBooleanAttribute(from, to, 'selected', ctx);
921
+ } else if (from instanceof HTMLTextAreaElement && to instanceof HTMLTextAreaElement) {
922
+ let fromValue = from.value;
923
+ let toValue = to.value;
924
+ if (ignoreAttribute('value', to, 'update', ctx)) {
925
+ return;
926
+ }
927
+ if (fromValue !== toValue) {
928
+ to.value = fromValue;
929
+ }
930
+ if (to.firstChild && to.firstChild.nodeValue !== fromValue) {
931
+ to.firstChild.nodeValue = fromValue;
932
+ }
933
+ }
934
+ }
935
+
936
+ //=============================================================================
937
+ // the HEAD tag can be handled specially, either w/ a 'merge' or 'append' style
938
+ //=============================================================================
939
+ function handleHeadElement(newHeadTag, currentHead, ctx) {
940
+
941
+ let added = [];
942
+ let removed = [];
943
+ let preserved = [];
944
+ let nodesToAppend = [];
945
+
946
+ let headMergeStyle = ctx.head.style;
947
+
948
+ // put all new head elements into a Map, by their outerHTML
949
+ let srcToNewHeadNodes = new Map();
950
+ for (const newHeadChild of newHeadTag.children) {
951
+ srcToNewHeadNodes.set(newHeadChild.outerHTML, newHeadChild);
952
+ }
953
+
954
+ // for each elt in the current head
955
+ for (const currentHeadElt of currentHead.children) {
956
+
957
+ // If the current head element is in the map
958
+ let inNewContent = srcToNewHeadNodes.has(currentHeadElt.outerHTML);
959
+ let isReAppended = ctx.head.shouldReAppend(currentHeadElt);
960
+ let isPreserved = ctx.head.shouldPreserve(currentHeadElt);
961
+ if (inNewContent || isPreserved) {
962
+ if (isReAppended) {
963
+ // remove the current version and let the new version replace it and re-execute
964
+ removed.push(currentHeadElt);
965
+ } else {
966
+ // this element already exists and should not be re-appended, so remove it from
967
+ // the new content map, preserving it in the DOM
968
+ srcToNewHeadNodes.delete(currentHeadElt.outerHTML);
969
+ preserved.push(currentHeadElt);
970
+ }
971
+ } else {
972
+ if (headMergeStyle === "append") {
973
+ // we are appending and this existing element is not new content
974
+ // so if and only if it is marked for re-append do we do anything
975
+ if (isReAppended) {
976
+ removed.push(currentHeadElt);
977
+ nodesToAppend.push(currentHeadElt);
978
+ }
979
+ } else {
980
+ // if this is a merge, we remove this content since it is not in the new head
981
+ if (ctx.head.shouldRemove(currentHeadElt) !== false) {
982
+ removed.push(currentHeadElt);
983
+ }
984
+ }
985
+ }
986
+ }
987
+
988
+ // Push the remaining new head elements in the Map into the
989
+ // nodes to append to the head tag
990
+ nodesToAppend.push(...srcToNewHeadNodes.values());
991
+
992
+ let promises = [];
993
+ for (const newNode of nodesToAppend) {
994
+ let newElt = document.createRange().createContextualFragment(newNode.outerHTML).firstChild;
995
+ if (ctx.callbacks.beforeNodeAdded(newElt) !== false) {
996
+ if (newElt.href || newElt.src) {
997
+ let resolve = null;
998
+ let promise = new Promise(function (_resolve) {
999
+ resolve = _resolve;
1000
+ });
1001
+ newElt.addEventListener('load', function () {
1002
+ resolve();
1003
+ });
1004
+ promises.push(promise);
1005
+ }
1006
+ currentHead.appendChild(newElt);
1007
+ ctx.callbacks.afterNodeAdded(newElt);
1008
+ added.push(newElt);
1009
+ }
1010
+ }
1011
+
1012
+ // remove all removed elements, after we have appended the new elements to avoid
1013
+ // additional network requests for things like style sheets
1014
+ for (const removedElement of removed) {
1015
+ if (ctx.callbacks.beforeNodeRemoved(removedElement) !== false) {
1016
+ currentHead.removeChild(removedElement);
1017
+ ctx.callbacks.afterNodeRemoved(removedElement);
1018
+ }
1019
+ }
1020
+
1021
+ ctx.head.afterHeadMorphed(currentHead, {added: added, kept: preserved, removed: removed});
1022
+ return promises;
1023
+ }
1024
+
1025
+ function noOp() {
1026
+ }
1027
+
1028
+ /*
1029
+ Deep merges the config object and the Idiomoroph.defaults object to
1030
+ produce a final configuration object
1031
+ */
1032
+ function mergeDefaults(config) {
1033
+ let finalConfig = {};
1034
+ // copy top level stuff into final config
1035
+ Object.assign(finalConfig, defaults);
1036
+ Object.assign(finalConfig, config);
1037
+
1038
+ // copy callbacks into final config (do this to deep merge the callbacks)
1039
+ finalConfig.callbacks = {};
1040
+ Object.assign(finalConfig.callbacks, defaults.callbacks);
1041
+ Object.assign(finalConfig.callbacks, config.callbacks);
1042
+
1043
+ // copy head config into final config (do this to deep merge the head)
1044
+ finalConfig.head = {};
1045
+ Object.assign(finalConfig.head, defaults.head);
1046
+ Object.assign(finalConfig.head, config.head);
1047
+ return finalConfig;
1048
+ }
1049
+
1050
+ function createMorphContext(oldNode, newContent, config) {
1051
+ config = mergeDefaults(config);
1052
+ return {
1053
+ target: oldNode,
1054
+ newContent: newContent,
1055
+ config: config,
1056
+ morphStyle: config.morphStyle,
1057
+ ignoreActive: config.ignoreActive,
1058
+ ignoreActiveValue: config.ignoreActiveValue,
1059
+ idMap: createIdMap(oldNode, newContent),
1060
+ deadIds: new Set(),
1061
+ callbacks: config.callbacks,
1062
+ head: config.head
1063
+ }
1064
+ }
1065
+
1066
+ function isIdSetMatch(node1, node2, ctx) {
1067
+ if (node1 == null || node2 == null) {
1068
+ return false;
1069
+ }
1070
+ if (node1.nodeType === node2.nodeType && node1.tagName === node2.tagName) {
1071
+ if (node1.id !== "" && node1.id === node2.id) {
1072
+ return true;
1073
+ } else {
1074
+ return getIdIntersectionCount(ctx, node1, node2) > 0;
1075
+ }
1076
+ }
1077
+ return false;
1078
+ }
1079
+
1080
+ function isSoftMatch(node1, node2) {
1081
+ if (node1 == null || node2 == null) {
1082
+ return false;
1083
+ }
1084
+ return node1.nodeType === node2.nodeType && node1.tagName === node2.tagName
1085
+ }
1086
+
1087
+ function removeNodesBetween(startInclusive, endExclusive, ctx) {
1088
+ while (startInclusive !== endExclusive) {
1089
+ let tempNode = startInclusive;
1090
+ startInclusive = startInclusive.nextSibling;
1091
+ removeNode(tempNode, ctx);
1092
+ }
1093
+ removeIdsFromConsideration(ctx, endExclusive);
1094
+ return endExclusive.nextSibling;
1095
+ }
1096
+
1097
+ //=============================================================================
1098
+ // Scans forward from the insertionPoint in the old parent looking for a potential id match
1099
+ // for the newChild. We stop if we find a potential id match for the new child OR
1100
+ // if the number of potential id matches we are discarding is greater than the
1101
+ // potential id matches for the new child
1102
+ //=============================================================================
1103
+ function findIdSetMatch(newContent, oldParent, newChild, insertionPoint, ctx) {
1104
+
1105
+ // max id matches we are willing to discard in our search
1106
+ let newChildPotentialIdCount = getIdIntersectionCount(ctx, newChild, oldParent);
1107
+
1108
+ let potentialMatch = null;
1109
+
1110
+ // only search forward if there is a possibility of an id match
1111
+ if (newChildPotentialIdCount > 0) {
1112
+ let potentialMatch = insertionPoint;
1113
+ // if there is a possibility of an id match, scan forward
1114
+ // keep track of the potential id match count we are discarding (the
1115
+ // newChildPotentialIdCount must be greater than this to make it likely
1116
+ // worth it)
1117
+ let otherMatchCount = 0;
1118
+ while (potentialMatch != null) {
1119
+
1120
+ // If we have an id match, return the current potential match
1121
+ if (isIdSetMatch(newChild, potentialMatch, ctx)) {
1122
+ return potentialMatch;
1123
+ }
1124
+
1125
+ // computer the other potential matches of this new content
1126
+ otherMatchCount += getIdIntersectionCount(ctx, potentialMatch, newContent);
1127
+ if (otherMatchCount > newChildPotentialIdCount) {
1128
+ // if we have more potential id matches in _other_ content, we
1129
+ // do not have a good candidate for an id match, so return null
1130
+ return null;
1131
+ }
1132
+
1133
+ // advanced to the next old content child
1134
+ potentialMatch = potentialMatch.nextSibling;
1135
+ }
1136
+ }
1137
+ return potentialMatch;
1138
+ }
1139
+
1140
+ //=============================================================================
1141
+ // Scans forward from the insertionPoint in the old parent looking for a potential soft match
1142
+ // for the newChild. We stop if we find a potential soft match for the new child OR
1143
+ // if we find a potential id match in the old parents children OR if we find two
1144
+ // potential soft matches for the next two pieces of new content
1145
+ //=============================================================================
1146
+ function findSoftMatch(newContent, oldParent, newChild, insertionPoint, ctx) {
1147
+
1148
+ let potentialSoftMatch = insertionPoint;
1149
+ let nextSibling = newChild.nextSibling;
1150
+ let siblingSoftMatchCount = 0;
1151
+
1152
+ while (potentialSoftMatch != null) {
1153
+
1154
+ if (getIdIntersectionCount(ctx, potentialSoftMatch, newContent) > 0) {
1155
+ // the current potential soft match has a potential id set match with the remaining new
1156
+ // content so bail out of looking
1157
+ return null;
1158
+ }
1159
+
1160
+ // if we have a soft match with the current node, return it
1161
+ if (isSoftMatch(newChild, potentialSoftMatch)) {
1162
+ return potentialSoftMatch;
1163
+ }
1164
+
1165
+ if (isSoftMatch(nextSibling, potentialSoftMatch)) {
1166
+ // the next new node has a soft match with this node, so
1167
+ // increment the count of future soft matches
1168
+ siblingSoftMatchCount++;
1169
+ nextSibling = nextSibling.nextSibling;
1170
+
1171
+ // If there are two future soft matches, bail to allow the siblings to soft match
1172
+ // so that we don't consume future soft matches for the sake of the current node
1173
+ if (siblingSoftMatchCount >= 2) {
1174
+ return null;
1175
+ }
1176
+ }
1177
+
1178
+ // advanced to the next old content child
1179
+ potentialSoftMatch = potentialSoftMatch.nextSibling;
1180
+ }
1181
+
1182
+ return potentialSoftMatch;
1183
+ }
1184
+
1185
+ function parseContent(newContent) {
1186
+ let parser = new DOMParser();
1187
+
1188
+ // remove svgs to avoid false-positive matches on head, etc.
1189
+ let contentWithSvgsRemoved = newContent.replace(/<svg(\s[^>]*>|>)([\s\S]*?)<\/svg>/gim, '');
1190
+
1191
+ // if the newContent contains a html, head or body tag, we can simply parse it w/o wrapping
1192
+ if (contentWithSvgsRemoved.match(/<\/html>/) || contentWithSvgsRemoved.match(/<\/head>/) || contentWithSvgsRemoved.match(/<\/body>/)) {
1193
+ let content = parser.parseFromString(newContent, "text/html");
1194
+ // if it is a full HTML document, return the document itself as the parent container
1195
+ if (contentWithSvgsRemoved.match(/<\/html>/)) {
1196
+ content.generatedByIdiomorph = true;
1197
+ return content;
1198
+ } else {
1199
+ // otherwise return the html element as the parent container
1200
+ let htmlElement = content.firstChild;
1201
+ if (htmlElement) {
1202
+ htmlElement.generatedByIdiomorph = true;
1203
+ return htmlElement;
1204
+ } else {
1205
+ return null;
1206
+ }
1207
+ }
1208
+ } else {
1209
+ // if it is partial HTML, wrap it in a template tag to provide a parent element and also to help
1210
+ // deal with touchy tags like tr, tbody, etc.
1211
+ let responseDoc = parser.parseFromString("<body><template>" + newContent + "</template></body>", "text/html");
1212
+ let content = responseDoc.body.querySelector('template').content;
1213
+ content.generatedByIdiomorph = true;
1214
+ return content
1215
+ }
1216
+ }
1217
+
1218
+ function normalizeContent(newContent) {
1219
+ if (newContent == null) {
1220
+ // noinspection UnnecessaryLocalVariableJS
1221
+ const dummyParent = document.createElement('div');
1222
+ return dummyParent;
1223
+ } else if (newContent.generatedByIdiomorph) {
1224
+ // the template tag created by idiomorph parsing can serve as a dummy parent
1225
+ return newContent;
1226
+ } else if (newContent instanceof Node) {
1227
+ // a single node is added as a child to a dummy parent
1228
+ const dummyParent = document.createElement('div');
1229
+ dummyParent.append(newContent);
1230
+ return dummyParent;
1231
+ } else {
1232
+ // all nodes in the array or HTMLElement collection are consolidated under
1233
+ // a single dummy parent element
1234
+ const dummyParent = document.createElement('div');
1235
+ for (const elt of [...newContent]) {
1236
+ dummyParent.append(elt);
1237
+ }
1238
+ return dummyParent;
1239
+ }
1240
+ }
1241
+
1242
+ function insertSiblings(previousSibling, morphedNode, nextSibling) {
1243
+ let stack = [];
1244
+ let added = [];
1245
+ while (previousSibling != null) {
1246
+ stack.push(previousSibling);
1247
+ previousSibling = previousSibling.previousSibling;
1248
+ }
1249
+ while (stack.length > 0) {
1250
+ let node = stack.pop();
1251
+ added.push(node); // push added preceding siblings on in order and insert
1252
+ morphedNode.parentElement.insertBefore(node, morphedNode);
1253
+ }
1254
+ added.push(morphedNode);
1255
+ while (nextSibling != null) {
1256
+ stack.push(nextSibling);
1257
+ added.push(nextSibling); // here we are going in order, so push on as we scan, rather than add
1258
+ nextSibling = nextSibling.nextSibling;
1259
+ }
1260
+ while (stack.length > 0) {
1261
+ morphedNode.parentElement.insertBefore(stack.pop(), morphedNode.nextSibling);
1262
+ }
1263
+ return added;
1264
+ }
1265
+
1266
+ function findBestNodeMatch(newContent, oldNode, ctx) {
1267
+ let currentElement;
1268
+ currentElement = newContent.firstChild;
1269
+ let bestElement = currentElement;
1270
+ let score = 0;
1271
+ while (currentElement) {
1272
+ let newScore = scoreElement(currentElement, oldNode, ctx);
1273
+ if (newScore > score) {
1274
+ bestElement = currentElement;
1275
+ score = newScore;
1276
+ }
1277
+ currentElement = currentElement.nextSibling;
1278
+ }
1279
+ return bestElement;
1280
+ }
1281
+
1282
+ function scoreElement(node1, node2, ctx) {
1283
+ if (isSoftMatch(node1, node2)) {
1284
+ return .5 + getIdIntersectionCount(ctx, node1, node2);
1285
+ }
1286
+ return 0;
1287
+ }
1288
+
1289
+ function removeNode(tempNode, ctx) {
1290
+ removeIdsFromConsideration(ctx, tempNode);
1291
+ if (ctx.callbacks.beforeNodeRemoved(tempNode) === false) return;
1292
+
1293
+ tempNode.remove();
1294
+ ctx.callbacks.afterNodeRemoved(tempNode);
1295
+ }
1296
+
1297
+ //=============================================================================
1298
+ // ID Set Functions
1299
+ //=============================================================================
1300
+
1301
+ function isIdInConsideration(ctx, id) {
1302
+ return !ctx.deadIds.has(id);
1303
+ }
1304
+
1305
+ function idIsWithinNode(ctx, id, targetNode) {
1306
+ let idSet = ctx.idMap.get(targetNode) || EMPTY_SET;
1307
+ return idSet.has(id);
1308
+ }
1309
+
1310
+ function removeIdsFromConsideration(ctx, node) {
1311
+ let idSet = ctx.idMap.get(node) || EMPTY_SET;
1312
+ for (const id of idSet) {
1313
+ ctx.deadIds.add(id);
1314
+ }
1315
+ }
1316
+
1317
+ function getIdIntersectionCount(ctx, node1, node2) {
1318
+ let sourceSet = ctx.idMap.get(node1) || EMPTY_SET;
1319
+ let matchCount = 0;
1320
+ for (const id of sourceSet) {
1321
+ // a potential match is an id in the source and potentialIdsSet, but
1322
+ // that has not already been merged into the DOM
1323
+ if (isIdInConsideration(ctx, id) && idIsWithinNode(ctx, id, node2)) {
1324
+ ++matchCount;
1325
+ }
1326
+ }
1327
+ return matchCount;
1328
+ }
1329
+
1330
+ /**
1331
+ * A bottom up algorithm that finds all elements with ids inside of the node
1332
+ * argument and populates id sets for those nodes and all their parents, generating
1333
+ * a set of ids contained within all nodes for the entire hierarchy in the DOM
1334
+ *
1335
+ * @param node {Element}
1336
+ * @param {Map<Node, Set<String>>} idMap
1337
+ */
1338
+ function populateIdMapForNode(node, idMap) {
1339
+ let nodeParent = node.parentElement;
1340
+ // find all elements with an id property
1341
+ let idElements = node.querySelectorAll('[id]');
1342
+ for (const elt of idElements) {
1343
+ let current = elt;
1344
+ // walk up the parent hierarchy of that element, adding the id
1345
+ // of element to the parent's id set
1346
+ while (current !== nodeParent && current != null) {
1347
+ let idSet = idMap.get(current);
1348
+ // if the id set doesn't exist, create it and insert it in the map
1349
+ if (idSet == null) {
1350
+ idSet = new Set();
1351
+ idMap.set(current, idSet);
1352
+ }
1353
+ idSet.add(elt.id);
1354
+ current = current.parentElement;
1355
+ }
1356
+ }
1357
+ }
1358
+
1359
+ /**
1360
+ * This function computes a map of nodes to all ids contained within that node (inclusive of the
1361
+ * node). This map can be used to ask if two nodes have intersecting sets of ids, which allows
1362
+ * for a looser definition of "matching" than tradition id matching, and allows child nodes
1363
+ * to contribute to a parent nodes matching.
1364
+ *
1365
+ * @param {Element} oldContent the old content that will be morphed
1366
+ * @param {Element} newContent the new content to morph to
1367
+ * @returns {Map<Node, Set<String>>} a map of nodes to id sets for the
1368
+ */
1369
+ function createIdMap(oldContent, newContent) {
1370
+ let idMap = new Map();
1371
+ populateIdMapForNode(oldContent, idMap);
1372
+ populateIdMapForNode(newContent, idMap);
1373
+ return idMap;
1374
+ }
1375
+
1376
+ //=============================================================================
1377
+ // This is what ends up becoming the Idiomorph global object
1378
+ //=============================================================================
1379
+ return {
1380
+ morph,
1381
+ defaults
1382
+ }
1383
+ })();
1384
+
1385
+ function log() {
1386
+ if (HotwireSpark.config.loggingEnabled) {
1387
+ for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
1388
+ args[_key] = arguments[_key];
1389
+ }
1390
+ console.log(`[hotwire_spark]`, ...args);
1391
+ }
1392
+ }
1393
+
1394
+ /*
1395
+ Stimulus 3.2.1
1396
+ Copyright © 2023 Basecamp, LLC
1397
+ */
1398
+ class EventListener {
1399
+ constructor(eventTarget, eventName, eventOptions) {
1400
+ this.eventTarget = eventTarget;
1401
+ this.eventName = eventName;
1402
+ this.eventOptions = eventOptions;
1403
+ this.unorderedBindings = new Set();
1404
+ }
1405
+ connect() {
1406
+ this.eventTarget.addEventListener(this.eventName, this, this.eventOptions);
1407
+ }
1408
+ disconnect() {
1409
+ this.eventTarget.removeEventListener(this.eventName, this, this.eventOptions);
1410
+ }
1411
+ bindingConnected(binding) {
1412
+ this.unorderedBindings.add(binding);
1413
+ }
1414
+ bindingDisconnected(binding) {
1415
+ this.unorderedBindings.delete(binding);
1416
+ }
1417
+ handleEvent(event) {
1418
+ const extendedEvent = extendEvent(event);
1419
+ for (const binding of this.bindings) {
1420
+ if (extendedEvent.immediatePropagationStopped) {
1421
+ break;
1422
+ }
1423
+ else {
1424
+ binding.handleEvent(extendedEvent);
1425
+ }
1426
+ }
1427
+ }
1428
+ hasBindings() {
1429
+ return this.unorderedBindings.size > 0;
1430
+ }
1431
+ get bindings() {
1432
+ return Array.from(this.unorderedBindings).sort((left, right) => {
1433
+ const leftIndex = left.index, rightIndex = right.index;
1434
+ return leftIndex < rightIndex ? -1 : leftIndex > rightIndex ? 1 : 0;
1435
+ });
1436
+ }
1437
+ }
1438
+ function extendEvent(event) {
1439
+ if ("immediatePropagationStopped" in event) {
1440
+ return event;
1441
+ }
1442
+ else {
1443
+ const { stopImmediatePropagation } = event;
1444
+ return Object.assign(event, {
1445
+ immediatePropagationStopped: false,
1446
+ stopImmediatePropagation() {
1447
+ this.immediatePropagationStopped = true;
1448
+ stopImmediatePropagation.call(this);
1449
+ },
1450
+ });
1451
+ }
1452
+ }
1453
+
1454
+ class Dispatcher {
1455
+ constructor(application) {
1456
+ this.application = application;
1457
+ this.eventListenerMaps = new Map();
1458
+ this.started = false;
1459
+ }
1460
+ start() {
1461
+ if (!this.started) {
1462
+ this.started = true;
1463
+ this.eventListeners.forEach((eventListener) => eventListener.connect());
1464
+ }
1465
+ }
1466
+ stop() {
1467
+ if (this.started) {
1468
+ this.started = false;
1469
+ this.eventListeners.forEach((eventListener) => eventListener.disconnect());
1470
+ }
1471
+ }
1472
+ get eventListeners() {
1473
+ return Array.from(this.eventListenerMaps.values()).reduce((listeners, map) => listeners.concat(Array.from(map.values())), []);
1474
+ }
1475
+ bindingConnected(binding) {
1476
+ this.fetchEventListenerForBinding(binding).bindingConnected(binding);
1477
+ }
1478
+ bindingDisconnected(binding, clearEventListeners = false) {
1479
+ this.fetchEventListenerForBinding(binding).bindingDisconnected(binding);
1480
+ if (clearEventListeners)
1481
+ this.clearEventListenersForBinding(binding);
1482
+ }
1483
+ handleError(error, message, detail = {}) {
1484
+ this.application.handleError(error, `Error ${message}`, detail);
1485
+ }
1486
+ clearEventListenersForBinding(binding) {
1487
+ const eventListener = this.fetchEventListenerForBinding(binding);
1488
+ if (!eventListener.hasBindings()) {
1489
+ eventListener.disconnect();
1490
+ this.removeMappedEventListenerFor(binding);
1491
+ }
1492
+ }
1493
+ removeMappedEventListenerFor(binding) {
1494
+ const { eventTarget, eventName, eventOptions } = binding;
1495
+ const eventListenerMap = this.fetchEventListenerMapForEventTarget(eventTarget);
1496
+ const cacheKey = this.cacheKey(eventName, eventOptions);
1497
+ eventListenerMap.delete(cacheKey);
1498
+ if (eventListenerMap.size == 0)
1499
+ this.eventListenerMaps.delete(eventTarget);
1500
+ }
1501
+ fetchEventListenerForBinding(binding) {
1502
+ const { eventTarget, eventName, eventOptions } = binding;
1503
+ return this.fetchEventListener(eventTarget, eventName, eventOptions);
1504
+ }
1505
+ fetchEventListener(eventTarget, eventName, eventOptions) {
1506
+ const eventListenerMap = this.fetchEventListenerMapForEventTarget(eventTarget);
1507
+ const cacheKey = this.cacheKey(eventName, eventOptions);
1508
+ let eventListener = eventListenerMap.get(cacheKey);
1509
+ if (!eventListener) {
1510
+ eventListener = this.createEventListener(eventTarget, eventName, eventOptions);
1511
+ eventListenerMap.set(cacheKey, eventListener);
1512
+ }
1513
+ return eventListener;
1514
+ }
1515
+ createEventListener(eventTarget, eventName, eventOptions) {
1516
+ const eventListener = new EventListener(eventTarget, eventName, eventOptions);
1517
+ if (this.started) {
1518
+ eventListener.connect();
1519
+ }
1520
+ return eventListener;
1521
+ }
1522
+ fetchEventListenerMapForEventTarget(eventTarget) {
1523
+ let eventListenerMap = this.eventListenerMaps.get(eventTarget);
1524
+ if (!eventListenerMap) {
1525
+ eventListenerMap = new Map();
1526
+ this.eventListenerMaps.set(eventTarget, eventListenerMap);
1527
+ }
1528
+ return eventListenerMap;
1529
+ }
1530
+ cacheKey(eventName, eventOptions) {
1531
+ const parts = [eventName];
1532
+ Object.keys(eventOptions)
1533
+ .sort()
1534
+ .forEach((key) => {
1535
+ parts.push(`${eventOptions[key] ? "" : "!"}${key}`);
1536
+ });
1537
+ return parts.join(":");
1538
+ }
1539
+ }
1540
+
1541
+ const defaultActionDescriptorFilters = {
1542
+ stop({ event, value }) {
1543
+ if (value)
1544
+ event.stopPropagation();
1545
+ return true;
1546
+ },
1547
+ prevent({ event, value }) {
1548
+ if (value)
1549
+ event.preventDefault();
1550
+ return true;
1551
+ },
1552
+ self({ event, value, element }) {
1553
+ if (value) {
1554
+ return element === event.target;
1555
+ }
1556
+ else {
1557
+ return true;
1558
+ }
1559
+ },
1560
+ };
1561
+ const descriptorPattern = /^(?:(?:([^.]+?)\+)?(.+?)(?:\.(.+?))?(?:@(window|document))?->)?(.+?)(?:#([^:]+?))(?::(.+))?$/;
1562
+ function parseActionDescriptorString(descriptorString) {
1563
+ const source = descriptorString.trim();
1564
+ const matches = source.match(descriptorPattern) || [];
1565
+ let eventName = matches[2];
1566
+ let keyFilter = matches[3];
1567
+ if (keyFilter && !["keydown", "keyup", "keypress"].includes(eventName)) {
1568
+ eventName += `.${keyFilter}`;
1569
+ keyFilter = "";
1570
+ }
1571
+ return {
1572
+ eventTarget: parseEventTarget(matches[4]),
1573
+ eventName,
1574
+ eventOptions: matches[7] ? parseEventOptions(matches[7]) : {},
1575
+ identifier: matches[5],
1576
+ methodName: matches[6],
1577
+ keyFilter: matches[1] || keyFilter,
1578
+ };
1579
+ }
1580
+ function parseEventTarget(eventTargetName) {
1581
+ if (eventTargetName == "window") {
1582
+ return window;
1583
+ }
1584
+ else if (eventTargetName == "document") {
1585
+ return document;
1586
+ }
1587
+ }
1588
+ function parseEventOptions(eventOptions) {
1589
+ return eventOptions
1590
+ .split(":")
1591
+ .reduce((options, token) => Object.assign(options, { [token.replace(/^!/, "")]: !/^!/.test(token) }), {});
1592
+ }
1593
+ function stringifyEventTarget(eventTarget) {
1594
+ if (eventTarget == window) {
1595
+ return "window";
1596
+ }
1597
+ else if (eventTarget == document) {
1598
+ return "document";
1599
+ }
1600
+ }
1601
+
1602
+ function camelize(value) {
1603
+ return value.replace(/(?:[_-])([a-z0-9])/g, (_, char) => char.toUpperCase());
1604
+ }
1605
+ function namespaceCamelize(value) {
1606
+ return camelize(value.replace(/--/g, "-").replace(/__/g, "_"));
1607
+ }
1608
+ function capitalize(value) {
1609
+ return value.charAt(0).toUpperCase() + value.slice(1);
1610
+ }
1611
+ function dasherize(value) {
1612
+ return value.replace(/([A-Z])/g, (_, char) => `-${char.toLowerCase()}`);
1613
+ }
1614
+ function tokenize(value) {
1615
+ return value.match(/[^\s]+/g) || [];
1616
+ }
1617
+ function hasProperty(object, property) {
1618
+ return Object.prototype.hasOwnProperty.call(object, property);
1619
+ }
1620
+
1621
+ const allModifiers = ["meta", "ctrl", "alt", "shift"];
1622
+ class Action {
1623
+ constructor(element, index, descriptor, schema) {
1624
+ this.element = element;
1625
+ this.index = index;
1626
+ this.eventTarget = descriptor.eventTarget || element;
1627
+ this.eventName = descriptor.eventName || getDefaultEventNameForElement(element) || error("missing event name");
1628
+ this.eventOptions = descriptor.eventOptions || {};
1629
+ this.identifier = descriptor.identifier || error("missing identifier");
1630
+ this.methodName = descriptor.methodName || error("missing method name");
1631
+ this.keyFilter = descriptor.keyFilter || "";
1632
+ this.schema = schema;
1633
+ }
1634
+ static forToken(token, schema) {
1635
+ return new this(token.element, token.index, parseActionDescriptorString(token.content), schema);
1636
+ }
1637
+ toString() {
1638
+ const eventFilter = this.keyFilter ? `.${this.keyFilter}` : "";
1639
+ const eventTarget = this.eventTargetName ? `@${this.eventTargetName}` : "";
1640
+ return `${this.eventName}${eventFilter}${eventTarget}->${this.identifier}#${this.methodName}`;
1641
+ }
1642
+ shouldIgnoreKeyboardEvent(event) {
1643
+ if (!this.keyFilter) {
1644
+ return false;
1645
+ }
1646
+ const filters = this.keyFilter.split("+");
1647
+ if (this.keyFilterDissatisfied(event, filters)) {
1648
+ return true;
1649
+ }
1650
+ const standardFilter = filters.filter((key) => !allModifiers.includes(key))[0];
1651
+ if (!standardFilter) {
1652
+ return false;
1653
+ }
1654
+ if (!hasProperty(this.keyMappings, standardFilter)) {
1655
+ error(`contains unknown key filter: ${this.keyFilter}`);
1656
+ }
1657
+ return this.keyMappings[standardFilter].toLowerCase() !== event.key.toLowerCase();
1658
+ }
1659
+ shouldIgnoreMouseEvent(event) {
1660
+ if (!this.keyFilter) {
1661
+ return false;
1662
+ }
1663
+ const filters = [this.keyFilter];
1664
+ if (this.keyFilterDissatisfied(event, filters)) {
1665
+ return true;
1666
+ }
1667
+ return false;
1668
+ }
1669
+ get params() {
1670
+ const params = {};
1671
+ const pattern = new RegExp(`^data-${this.identifier}-(.+)-param$`, "i");
1672
+ for (const { name, value } of Array.from(this.element.attributes)) {
1673
+ const match = name.match(pattern);
1674
+ const key = match && match[1];
1675
+ if (key) {
1676
+ params[camelize(key)] = typecast(value);
1677
+ }
1678
+ }
1679
+ return params;
1680
+ }
1681
+ get eventTargetName() {
1682
+ return stringifyEventTarget(this.eventTarget);
1683
+ }
1684
+ get keyMappings() {
1685
+ return this.schema.keyMappings;
1686
+ }
1687
+ keyFilterDissatisfied(event, filters) {
1688
+ const [meta, ctrl, alt, shift] = allModifiers.map((modifier) => filters.includes(modifier));
1689
+ return event.metaKey !== meta || event.ctrlKey !== ctrl || event.altKey !== alt || event.shiftKey !== shift;
1690
+ }
1691
+ }
1692
+ const defaultEventNames = {
1693
+ a: () => "click",
1694
+ button: () => "click",
1695
+ form: () => "submit",
1696
+ details: () => "toggle",
1697
+ input: (e) => (e.getAttribute("type") == "submit" ? "click" : "input"),
1698
+ select: () => "change",
1699
+ textarea: () => "input",
1700
+ };
1701
+ function getDefaultEventNameForElement(element) {
1702
+ const tagName = element.tagName.toLowerCase();
1703
+ if (tagName in defaultEventNames) {
1704
+ return defaultEventNames[tagName](element);
1705
+ }
1706
+ }
1707
+ function error(message) {
1708
+ throw new Error(message);
1709
+ }
1710
+ function typecast(value) {
1711
+ try {
1712
+ return JSON.parse(value);
1713
+ }
1714
+ catch (o_O) {
1715
+ return value;
1716
+ }
1717
+ }
1718
+
1719
+ class Binding {
1720
+ constructor(context, action) {
1721
+ this.context = context;
1722
+ this.action = action;
1723
+ }
1724
+ get index() {
1725
+ return this.action.index;
1726
+ }
1727
+ get eventTarget() {
1728
+ return this.action.eventTarget;
1729
+ }
1730
+ get eventOptions() {
1731
+ return this.action.eventOptions;
1732
+ }
1733
+ get identifier() {
1734
+ return this.context.identifier;
1735
+ }
1736
+ handleEvent(event) {
1737
+ const actionEvent = this.prepareActionEvent(event);
1738
+ if (this.willBeInvokedByEvent(event) && this.applyEventModifiers(actionEvent)) {
1739
+ this.invokeWithEvent(actionEvent);
1740
+ }
1741
+ }
1742
+ get eventName() {
1743
+ return this.action.eventName;
1744
+ }
1745
+ get method() {
1746
+ const method = this.controller[this.methodName];
1747
+ if (typeof method == "function") {
1748
+ return method;
1749
+ }
1750
+ throw new Error(`Action "${this.action}" references undefined method "${this.methodName}"`);
1751
+ }
1752
+ applyEventModifiers(event) {
1753
+ const { element } = this.action;
1754
+ const { actionDescriptorFilters } = this.context.application;
1755
+ const { controller } = this.context;
1756
+ let passes = true;
1757
+ for (const [name, value] of Object.entries(this.eventOptions)) {
1758
+ if (name in actionDescriptorFilters) {
1759
+ const filter = actionDescriptorFilters[name];
1760
+ passes = passes && filter({ name, value, event, element, controller });
1761
+ }
1762
+ else {
1763
+ continue;
1764
+ }
1765
+ }
1766
+ return passes;
1767
+ }
1768
+ prepareActionEvent(event) {
1769
+ return Object.assign(event, { params: this.action.params });
1770
+ }
1771
+ invokeWithEvent(event) {
1772
+ const { target, currentTarget } = event;
1773
+ try {
1774
+ this.method.call(this.controller, event);
1775
+ this.context.logDebugActivity(this.methodName, { event, target, currentTarget, action: this.methodName });
1776
+ }
1777
+ catch (error) {
1778
+ const { identifier, controller, element, index } = this;
1779
+ const detail = { identifier, controller, element, index, event };
1780
+ this.context.handleError(error, `invoking action "${this.action}"`, detail);
1781
+ }
1782
+ }
1783
+ willBeInvokedByEvent(event) {
1784
+ const eventTarget = event.target;
1785
+ if (event instanceof KeyboardEvent && this.action.shouldIgnoreKeyboardEvent(event)) {
1786
+ return false;
1787
+ }
1788
+ if (event instanceof MouseEvent && this.action.shouldIgnoreMouseEvent(event)) {
1789
+ return false;
1790
+ }
1791
+ if (this.element === eventTarget) {
1792
+ return true;
1793
+ }
1794
+ else if (eventTarget instanceof Element && this.element.contains(eventTarget)) {
1795
+ return this.scope.containsElement(eventTarget);
1796
+ }
1797
+ else {
1798
+ return this.scope.containsElement(this.action.element);
1799
+ }
1800
+ }
1801
+ get controller() {
1802
+ return this.context.controller;
1803
+ }
1804
+ get methodName() {
1805
+ return this.action.methodName;
1806
+ }
1807
+ get element() {
1808
+ return this.scope.element;
1809
+ }
1810
+ get scope() {
1811
+ return this.context.scope;
1812
+ }
1813
+ }
1814
+
1815
+ class ElementObserver {
1816
+ constructor(element, delegate) {
1817
+ this.mutationObserverInit = { attributes: true, childList: true, subtree: true };
1818
+ this.element = element;
1819
+ this.started = false;
1820
+ this.delegate = delegate;
1821
+ this.elements = new Set();
1822
+ this.mutationObserver = new MutationObserver((mutations) => this.processMutations(mutations));
1823
+ }
1824
+ start() {
1825
+ if (!this.started) {
1826
+ this.started = true;
1827
+ this.mutationObserver.observe(this.element, this.mutationObserverInit);
1828
+ this.refresh();
1829
+ }
1830
+ }
1831
+ pause(callback) {
1832
+ if (this.started) {
1833
+ this.mutationObserver.disconnect();
1834
+ this.started = false;
1835
+ }
1836
+ callback();
1837
+ if (!this.started) {
1838
+ this.mutationObserver.observe(this.element, this.mutationObserverInit);
1839
+ this.started = true;
1840
+ }
1841
+ }
1842
+ stop() {
1843
+ if (this.started) {
1844
+ this.mutationObserver.takeRecords();
1845
+ this.mutationObserver.disconnect();
1846
+ this.started = false;
1847
+ }
1848
+ }
1849
+ refresh() {
1850
+ if (this.started) {
1851
+ const matches = new Set(this.matchElementsInTree());
1852
+ for (const element of Array.from(this.elements)) {
1853
+ if (!matches.has(element)) {
1854
+ this.removeElement(element);
1855
+ }
1856
+ }
1857
+ for (const element of Array.from(matches)) {
1858
+ this.addElement(element);
1859
+ }
1860
+ }
1861
+ }
1862
+ processMutations(mutations) {
1863
+ if (this.started) {
1864
+ for (const mutation of mutations) {
1865
+ this.processMutation(mutation);
1866
+ }
1867
+ }
1868
+ }
1869
+ processMutation(mutation) {
1870
+ if (mutation.type == "attributes") {
1871
+ this.processAttributeChange(mutation.target, mutation.attributeName);
1872
+ }
1873
+ else if (mutation.type == "childList") {
1874
+ this.processRemovedNodes(mutation.removedNodes);
1875
+ this.processAddedNodes(mutation.addedNodes);
1876
+ }
1877
+ }
1878
+ processAttributeChange(element, attributeName) {
1879
+ if (this.elements.has(element)) {
1880
+ if (this.delegate.elementAttributeChanged && this.matchElement(element)) {
1881
+ this.delegate.elementAttributeChanged(element, attributeName);
1882
+ }
1883
+ else {
1884
+ this.removeElement(element);
1885
+ }
1886
+ }
1887
+ else if (this.matchElement(element)) {
1888
+ this.addElement(element);
1889
+ }
1890
+ }
1891
+ processRemovedNodes(nodes) {
1892
+ for (const node of Array.from(nodes)) {
1893
+ const element = this.elementFromNode(node);
1894
+ if (element) {
1895
+ this.processTree(element, this.removeElement);
1896
+ }
1897
+ }
1898
+ }
1899
+ processAddedNodes(nodes) {
1900
+ for (const node of Array.from(nodes)) {
1901
+ const element = this.elementFromNode(node);
1902
+ if (element && this.elementIsActive(element)) {
1903
+ this.processTree(element, this.addElement);
1904
+ }
1905
+ }
1906
+ }
1907
+ matchElement(element) {
1908
+ return this.delegate.matchElement(element);
1909
+ }
1910
+ matchElementsInTree(tree = this.element) {
1911
+ return this.delegate.matchElementsInTree(tree);
1912
+ }
1913
+ processTree(tree, processor) {
1914
+ for (const element of this.matchElementsInTree(tree)) {
1915
+ processor.call(this, element);
1916
+ }
1917
+ }
1918
+ elementFromNode(node) {
1919
+ if (node.nodeType == Node.ELEMENT_NODE) {
1920
+ return node;
1921
+ }
1922
+ }
1923
+ elementIsActive(element) {
1924
+ if (element.isConnected != this.element.isConnected) {
1925
+ return false;
1926
+ }
1927
+ else {
1928
+ return this.element.contains(element);
1929
+ }
1930
+ }
1931
+ addElement(element) {
1932
+ if (!this.elements.has(element)) {
1933
+ if (this.elementIsActive(element)) {
1934
+ this.elements.add(element);
1935
+ if (this.delegate.elementMatched) {
1936
+ this.delegate.elementMatched(element);
1937
+ }
1938
+ }
1939
+ }
1940
+ }
1941
+ removeElement(element) {
1942
+ if (this.elements.has(element)) {
1943
+ this.elements.delete(element);
1944
+ if (this.delegate.elementUnmatched) {
1945
+ this.delegate.elementUnmatched(element);
1946
+ }
1947
+ }
1948
+ }
1949
+ }
1950
+
1951
+ class AttributeObserver {
1952
+ constructor(element, attributeName, delegate) {
1953
+ this.attributeName = attributeName;
1954
+ this.delegate = delegate;
1955
+ this.elementObserver = new ElementObserver(element, this);
1956
+ }
1957
+ get element() {
1958
+ return this.elementObserver.element;
1959
+ }
1960
+ get selector() {
1961
+ return `[${this.attributeName}]`;
1962
+ }
1963
+ start() {
1964
+ this.elementObserver.start();
1965
+ }
1966
+ pause(callback) {
1967
+ this.elementObserver.pause(callback);
1968
+ }
1969
+ stop() {
1970
+ this.elementObserver.stop();
1971
+ }
1972
+ refresh() {
1973
+ this.elementObserver.refresh();
1974
+ }
1975
+ get started() {
1976
+ return this.elementObserver.started;
1977
+ }
1978
+ matchElement(element) {
1979
+ return element.hasAttribute(this.attributeName);
1980
+ }
1981
+ matchElementsInTree(tree) {
1982
+ const match = this.matchElement(tree) ? [tree] : [];
1983
+ const matches = Array.from(tree.querySelectorAll(this.selector));
1984
+ return match.concat(matches);
1985
+ }
1986
+ elementMatched(element) {
1987
+ if (this.delegate.elementMatchedAttribute) {
1988
+ this.delegate.elementMatchedAttribute(element, this.attributeName);
1989
+ }
1990
+ }
1991
+ elementUnmatched(element) {
1992
+ if (this.delegate.elementUnmatchedAttribute) {
1993
+ this.delegate.elementUnmatchedAttribute(element, this.attributeName);
1994
+ }
1995
+ }
1996
+ elementAttributeChanged(element, attributeName) {
1997
+ if (this.delegate.elementAttributeValueChanged && this.attributeName == attributeName) {
1998
+ this.delegate.elementAttributeValueChanged(element, attributeName);
1999
+ }
2000
+ }
2001
+ }
2002
+
2003
+ function add(map, key, value) {
2004
+ fetch$1(map, key).add(value);
2005
+ }
2006
+ function del(map, key, value) {
2007
+ fetch$1(map, key).delete(value);
2008
+ prune(map, key);
2009
+ }
2010
+ function fetch$1(map, key) {
2011
+ let values = map.get(key);
2012
+ if (!values) {
2013
+ values = new Set();
2014
+ map.set(key, values);
2015
+ }
2016
+ return values;
2017
+ }
2018
+ function prune(map, key) {
2019
+ const values = map.get(key);
2020
+ if (values != null && values.size == 0) {
2021
+ map.delete(key);
2022
+ }
2023
+ }
2024
+
2025
+ class Multimap {
2026
+ constructor() {
2027
+ this.valuesByKey = new Map();
2028
+ }
2029
+ get keys() {
2030
+ return Array.from(this.valuesByKey.keys());
2031
+ }
2032
+ get values() {
2033
+ const sets = Array.from(this.valuesByKey.values());
2034
+ return sets.reduce((values, set) => values.concat(Array.from(set)), []);
2035
+ }
2036
+ get size() {
2037
+ const sets = Array.from(this.valuesByKey.values());
2038
+ return sets.reduce((size, set) => size + set.size, 0);
2039
+ }
2040
+ add(key, value) {
2041
+ add(this.valuesByKey, key, value);
2042
+ }
2043
+ delete(key, value) {
2044
+ del(this.valuesByKey, key, value);
2045
+ }
2046
+ has(key, value) {
2047
+ const values = this.valuesByKey.get(key);
2048
+ return values != null && values.has(value);
2049
+ }
2050
+ hasKey(key) {
2051
+ return this.valuesByKey.has(key);
2052
+ }
2053
+ hasValue(value) {
2054
+ const sets = Array.from(this.valuesByKey.values());
2055
+ return sets.some((set) => set.has(value));
2056
+ }
2057
+ getValuesForKey(key) {
2058
+ const values = this.valuesByKey.get(key);
2059
+ return values ? Array.from(values) : [];
2060
+ }
2061
+ getKeysForValue(value) {
2062
+ return Array.from(this.valuesByKey)
2063
+ .filter(([_key, values]) => values.has(value))
2064
+ .map(([key, _values]) => key);
2065
+ }
2066
+ }
2067
+
2068
+ class SelectorObserver {
2069
+ constructor(element, selector, delegate, details) {
2070
+ this._selector = selector;
2071
+ this.details = details;
2072
+ this.elementObserver = new ElementObserver(element, this);
2073
+ this.delegate = delegate;
2074
+ this.matchesByElement = new Multimap();
2075
+ }
2076
+ get started() {
2077
+ return this.elementObserver.started;
2078
+ }
2079
+ get selector() {
2080
+ return this._selector;
2081
+ }
2082
+ set selector(selector) {
2083
+ this._selector = selector;
2084
+ this.refresh();
2085
+ }
2086
+ start() {
2087
+ this.elementObserver.start();
2088
+ }
2089
+ pause(callback) {
2090
+ this.elementObserver.pause(callback);
2091
+ }
2092
+ stop() {
2093
+ this.elementObserver.stop();
2094
+ }
2095
+ refresh() {
2096
+ this.elementObserver.refresh();
2097
+ }
2098
+ get element() {
2099
+ return this.elementObserver.element;
2100
+ }
2101
+ matchElement(element) {
2102
+ const { selector } = this;
2103
+ if (selector) {
2104
+ const matches = element.matches(selector);
2105
+ if (this.delegate.selectorMatchElement) {
2106
+ return matches && this.delegate.selectorMatchElement(element, this.details);
2107
+ }
2108
+ return matches;
2109
+ }
2110
+ else {
2111
+ return false;
2112
+ }
2113
+ }
2114
+ matchElementsInTree(tree) {
2115
+ const { selector } = this;
2116
+ if (selector) {
2117
+ const match = this.matchElement(tree) ? [tree] : [];
2118
+ const matches = Array.from(tree.querySelectorAll(selector)).filter((match) => this.matchElement(match));
2119
+ return match.concat(matches);
2120
+ }
2121
+ else {
2122
+ return [];
2123
+ }
2124
+ }
2125
+ elementMatched(element) {
2126
+ const { selector } = this;
2127
+ if (selector) {
2128
+ this.selectorMatched(element, selector);
2129
+ }
2130
+ }
2131
+ elementUnmatched(element) {
2132
+ const selectors = this.matchesByElement.getKeysForValue(element);
2133
+ for (const selector of selectors) {
2134
+ this.selectorUnmatched(element, selector);
2135
+ }
2136
+ }
2137
+ elementAttributeChanged(element, _attributeName) {
2138
+ const { selector } = this;
2139
+ if (selector) {
2140
+ const matches = this.matchElement(element);
2141
+ const matchedBefore = this.matchesByElement.has(selector, element);
2142
+ if (matches && !matchedBefore) {
2143
+ this.selectorMatched(element, selector);
2144
+ }
2145
+ else if (!matches && matchedBefore) {
2146
+ this.selectorUnmatched(element, selector);
2147
+ }
2148
+ }
2149
+ }
2150
+ selectorMatched(element, selector) {
2151
+ this.delegate.selectorMatched(element, selector, this.details);
2152
+ this.matchesByElement.add(selector, element);
2153
+ }
2154
+ selectorUnmatched(element, selector) {
2155
+ this.delegate.selectorUnmatched(element, selector, this.details);
2156
+ this.matchesByElement.delete(selector, element);
2157
+ }
2158
+ }
2159
+
2160
+ class StringMapObserver {
2161
+ constructor(element, delegate) {
2162
+ this.element = element;
2163
+ this.delegate = delegate;
2164
+ this.started = false;
2165
+ this.stringMap = new Map();
2166
+ this.mutationObserver = new MutationObserver((mutations) => this.processMutations(mutations));
2167
+ }
2168
+ start() {
2169
+ if (!this.started) {
2170
+ this.started = true;
2171
+ this.mutationObserver.observe(this.element, { attributes: true, attributeOldValue: true });
2172
+ this.refresh();
2173
+ }
2174
+ }
2175
+ stop() {
2176
+ if (this.started) {
2177
+ this.mutationObserver.takeRecords();
2178
+ this.mutationObserver.disconnect();
2179
+ this.started = false;
2180
+ }
2181
+ }
2182
+ refresh() {
2183
+ if (this.started) {
2184
+ for (const attributeName of this.knownAttributeNames) {
2185
+ this.refreshAttribute(attributeName, null);
2186
+ }
2187
+ }
2188
+ }
2189
+ processMutations(mutations) {
2190
+ if (this.started) {
2191
+ for (const mutation of mutations) {
2192
+ this.processMutation(mutation);
2193
+ }
2194
+ }
2195
+ }
2196
+ processMutation(mutation) {
2197
+ const attributeName = mutation.attributeName;
2198
+ if (attributeName) {
2199
+ this.refreshAttribute(attributeName, mutation.oldValue);
2200
+ }
2201
+ }
2202
+ refreshAttribute(attributeName, oldValue) {
2203
+ const key = this.delegate.getStringMapKeyForAttribute(attributeName);
2204
+ if (key != null) {
2205
+ if (!this.stringMap.has(attributeName)) {
2206
+ this.stringMapKeyAdded(key, attributeName);
2207
+ }
2208
+ const value = this.element.getAttribute(attributeName);
2209
+ if (this.stringMap.get(attributeName) != value) {
2210
+ this.stringMapValueChanged(value, key, oldValue);
2211
+ }
2212
+ if (value == null) {
2213
+ const oldValue = this.stringMap.get(attributeName);
2214
+ this.stringMap.delete(attributeName);
2215
+ if (oldValue)
2216
+ this.stringMapKeyRemoved(key, attributeName, oldValue);
2217
+ }
2218
+ else {
2219
+ this.stringMap.set(attributeName, value);
2220
+ }
2221
+ }
2222
+ }
2223
+ stringMapKeyAdded(key, attributeName) {
2224
+ if (this.delegate.stringMapKeyAdded) {
2225
+ this.delegate.stringMapKeyAdded(key, attributeName);
2226
+ }
2227
+ }
2228
+ stringMapValueChanged(value, key, oldValue) {
2229
+ if (this.delegate.stringMapValueChanged) {
2230
+ this.delegate.stringMapValueChanged(value, key, oldValue);
2231
+ }
2232
+ }
2233
+ stringMapKeyRemoved(key, attributeName, oldValue) {
2234
+ if (this.delegate.stringMapKeyRemoved) {
2235
+ this.delegate.stringMapKeyRemoved(key, attributeName, oldValue);
2236
+ }
2237
+ }
2238
+ get knownAttributeNames() {
2239
+ return Array.from(new Set(this.currentAttributeNames.concat(this.recordedAttributeNames)));
2240
+ }
2241
+ get currentAttributeNames() {
2242
+ return Array.from(this.element.attributes).map((attribute) => attribute.name);
2243
+ }
2244
+ get recordedAttributeNames() {
2245
+ return Array.from(this.stringMap.keys());
2246
+ }
2247
+ }
2248
+
2249
+ class TokenListObserver {
2250
+ constructor(element, attributeName, delegate) {
2251
+ this.attributeObserver = new AttributeObserver(element, attributeName, this);
2252
+ this.delegate = delegate;
2253
+ this.tokensByElement = new Multimap();
2254
+ }
2255
+ get started() {
2256
+ return this.attributeObserver.started;
2257
+ }
2258
+ start() {
2259
+ this.attributeObserver.start();
2260
+ }
2261
+ pause(callback) {
2262
+ this.attributeObserver.pause(callback);
2263
+ }
2264
+ stop() {
2265
+ this.attributeObserver.stop();
2266
+ }
2267
+ refresh() {
2268
+ this.attributeObserver.refresh();
2269
+ }
2270
+ get element() {
2271
+ return this.attributeObserver.element;
2272
+ }
2273
+ get attributeName() {
2274
+ return this.attributeObserver.attributeName;
2275
+ }
2276
+ elementMatchedAttribute(element) {
2277
+ this.tokensMatched(this.readTokensForElement(element));
2278
+ }
2279
+ elementAttributeValueChanged(element) {
2280
+ const [unmatchedTokens, matchedTokens] = this.refreshTokensForElement(element);
2281
+ this.tokensUnmatched(unmatchedTokens);
2282
+ this.tokensMatched(matchedTokens);
2283
+ }
2284
+ elementUnmatchedAttribute(element) {
2285
+ this.tokensUnmatched(this.tokensByElement.getValuesForKey(element));
2286
+ }
2287
+ tokensMatched(tokens) {
2288
+ tokens.forEach((token) => this.tokenMatched(token));
2289
+ }
2290
+ tokensUnmatched(tokens) {
2291
+ tokens.forEach((token) => this.tokenUnmatched(token));
2292
+ }
2293
+ tokenMatched(token) {
2294
+ this.delegate.tokenMatched(token);
2295
+ this.tokensByElement.add(token.element, token);
2296
+ }
2297
+ tokenUnmatched(token) {
2298
+ this.delegate.tokenUnmatched(token);
2299
+ this.tokensByElement.delete(token.element, token);
2300
+ }
2301
+ refreshTokensForElement(element) {
2302
+ const previousTokens = this.tokensByElement.getValuesForKey(element);
2303
+ const currentTokens = this.readTokensForElement(element);
2304
+ const firstDifferingIndex = zip(previousTokens, currentTokens).findIndex(([previousToken, currentToken]) => !tokensAreEqual(previousToken, currentToken));
2305
+ if (firstDifferingIndex == -1) {
2306
+ return [[], []];
2307
+ }
2308
+ else {
2309
+ return [previousTokens.slice(firstDifferingIndex), currentTokens.slice(firstDifferingIndex)];
2310
+ }
2311
+ }
2312
+ readTokensForElement(element) {
2313
+ const attributeName = this.attributeName;
2314
+ const tokenString = element.getAttribute(attributeName) || "";
2315
+ return parseTokenString(tokenString, element, attributeName);
2316
+ }
2317
+ }
2318
+ function parseTokenString(tokenString, element, attributeName) {
2319
+ return tokenString
2320
+ .trim()
2321
+ .split(/\s+/)
2322
+ .filter((content) => content.length)
2323
+ .map((content, index) => ({ element, attributeName, content, index }));
2324
+ }
2325
+ function zip(left, right) {
2326
+ const length = Math.max(left.length, right.length);
2327
+ return Array.from({ length }, (_, index) => [left[index], right[index]]);
2328
+ }
2329
+ function tokensAreEqual(left, right) {
2330
+ return left && right && left.index == right.index && left.content == right.content;
2331
+ }
2332
+
2333
+ class ValueListObserver {
2334
+ constructor(element, attributeName, delegate) {
2335
+ this.tokenListObserver = new TokenListObserver(element, attributeName, this);
2336
+ this.delegate = delegate;
2337
+ this.parseResultsByToken = new WeakMap();
2338
+ this.valuesByTokenByElement = new WeakMap();
2339
+ }
2340
+ get started() {
2341
+ return this.tokenListObserver.started;
2342
+ }
2343
+ start() {
2344
+ this.tokenListObserver.start();
2345
+ }
2346
+ stop() {
2347
+ this.tokenListObserver.stop();
2348
+ }
2349
+ refresh() {
2350
+ this.tokenListObserver.refresh();
2351
+ }
2352
+ get element() {
2353
+ return this.tokenListObserver.element;
2354
+ }
2355
+ get attributeName() {
2356
+ return this.tokenListObserver.attributeName;
2357
+ }
2358
+ tokenMatched(token) {
2359
+ const { element } = token;
2360
+ const { value } = this.fetchParseResultForToken(token);
2361
+ if (value) {
2362
+ this.fetchValuesByTokenForElement(element).set(token, value);
2363
+ this.delegate.elementMatchedValue(element, value);
2364
+ }
2365
+ }
2366
+ tokenUnmatched(token) {
2367
+ const { element } = token;
2368
+ const { value } = this.fetchParseResultForToken(token);
2369
+ if (value) {
2370
+ this.fetchValuesByTokenForElement(element).delete(token);
2371
+ this.delegate.elementUnmatchedValue(element, value);
2372
+ }
2373
+ }
2374
+ fetchParseResultForToken(token) {
2375
+ let parseResult = this.parseResultsByToken.get(token);
2376
+ if (!parseResult) {
2377
+ parseResult = this.parseToken(token);
2378
+ this.parseResultsByToken.set(token, parseResult);
2379
+ }
2380
+ return parseResult;
2381
+ }
2382
+ fetchValuesByTokenForElement(element) {
2383
+ let valuesByToken = this.valuesByTokenByElement.get(element);
2384
+ if (!valuesByToken) {
2385
+ valuesByToken = new Map();
2386
+ this.valuesByTokenByElement.set(element, valuesByToken);
2387
+ }
2388
+ return valuesByToken;
2389
+ }
2390
+ parseToken(token) {
2391
+ try {
2392
+ const value = this.delegate.parseValueForToken(token);
2393
+ return { value };
2394
+ }
2395
+ catch (error) {
2396
+ return { error };
2397
+ }
2398
+ }
2399
+ }
2400
+
2401
+ class BindingObserver {
2402
+ constructor(context, delegate) {
2403
+ this.context = context;
2404
+ this.delegate = delegate;
2405
+ this.bindingsByAction = new Map();
2406
+ }
2407
+ start() {
2408
+ if (!this.valueListObserver) {
2409
+ this.valueListObserver = new ValueListObserver(this.element, this.actionAttribute, this);
2410
+ this.valueListObserver.start();
2411
+ }
2412
+ }
2413
+ stop() {
2414
+ if (this.valueListObserver) {
2415
+ this.valueListObserver.stop();
2416
+ delete this.valueListObserver;
2417
+ this.disconnectAllActions();
2418
+ }
2419
+ }
2420
+ get element() {
2421
+ return this.context.element;
2422
+ }
2423
+ get identifier() {
2424
+ return this.context.identifier;
2425
+ }
2426
+ get actionAttribute() {
2427
+ return this.schema.actionAttribute;
2428
+ }
2429
+ get schema() {
2430
+ return this.context.schema;
2431
+ }
2432
+ get bindings() {
2433
+ return Array.from(this.bindingsByAction.values());
2434
+ }
2435
+ connectAction(action) {
2436
+ const binding = new Binding(this.context, action);
2437
+ this.bindingsByAction.set(action, binding);
2438
+ this.delegate.bindingConnected(binding);
2439
+ }
2440
+ disconnectAction(action) {
2441
+ const binding = this.bindingsByAction.get(action);
2442
+ if (binding) {
2443
+ this.bindingsByAction.delete(action);
2444
+ this.delegate.bindingDisconnected(binding);
2445
+ }
2446
+ }
2447
+ disconnectAllActions() {
2448
+ this.bindings.forEach((binding) => this.delegate.bindingDisconnected(binding, true));
2449
+ this.bindingsByAction.clear();
2450
+ }
2451
+ parseValueForToken(token) {
2452
+ const action = Action.forToken(token, this.schema);
2453
+ if (action.identifier == this.identifier) {
2454
+ return action;
2455
+ }
2456
+ }
2457
+ elementMatchedValue(element, action) {
2458
+ this.connectAction(action);
2459
+ }
2460
+ elementUnmatchedValue(element, action) {
2461
+ this.disconnectAction(action);
2462
+ }
2463
+ }
2464
+
2465
+ class ValueObserver {
2466
+ constructor(context, receiver) {
2467
+ this.context = context;
2468
+ this.receiver = receiver;
2469
+ this.stringMapObserver = new StringMapObserver(this.element, this);
2470
+ this.valueDescriptorMap = this.controller.valueDescriptorMap;
2471
+ }
2472
+ start() {
2473
+ this.stringMapObserver.start();
2474
+ this.invokeChangedCallbacksForDefaultValues();
2475
+ }
2476
+ stop() {
2477
+ this.stringMapObserver.stop();
2478
+ }
2479
+ get element() {
2480
+ return this.context.element;
2481
+ }
2482
+ get controller() {
2483
+ return this.context.controller;
2484
+ }
2485
+ getStringMapKeyForAttribute(attributeName) {
2486
+ if (attributeName in this.valueDescriptorMap) {
2487
+ return this.valueDescriptorMap[attributeName].name;
2488
+ }
2489
+ }
2490
+ stringMapKeyAdded(key, attributeName) {
2491
+ const descriptor = this.valueDescriptorMap[attributeName];
2492
+ if (!this.hasValue(key)) {
2493
+ this.invokeChangedCallback(key, descriptor.writer(this.receiver[key]), descriptor.writer(descriptor.defaultValue));
2494
+ }
2495
+ }
2496
+ stringMapValueChanged(value, name, oldValue) {
2497
+ const descriptor = this.valueDescriptorNameMap[name];
2498
+ if (value === null)
2499
+ return;
2500
+ if (oldValue === null) {
2501
+ oldValue = descriptor.writer(descriptor.defaultValue);
2502
+ }
2503
+ this.invokeChangedCallback(name, value, oldValue);
2504
+ }
2505
+ stringMapKeyRemoved(key, attributeName, oldValue) {
2506
+ const descriptor = this.valueDescriptorNameMap[key];
2507
+ if (this.hasValue(key)) {
2508
+ this.invokeChangedCallback(key, descriptor.writer(this.receiver[key]), oldValue);
2509
+ }
2510
+ else {
2511
+ this.invokeChangedCallback(key, descriptor.writer(descriptor.defaultValue), oldValue);
2512
+ }
2513
+ }
2514
+ invokeChangedCallbacksForDefaultValues() {
2515
+ for (const { key, name, defaultValue, writer } of this.valueDescriptors) {
2516
+ if (defaultValue != undefined && !this.controller.data.has(key)) {
2517
+ this.invokeChangedCallback(name, writer(defaultValue), undefined);
2518
+ }
2519
+ }
2520
+ }
2521
+ invokeChangedCallback(name, rawValue, rawOldValue) {
2522
+ const changedMethodName = `${name}Changed`;
2523
+ const changedMethod = this.receiver[changedMethodName];
2524
+ if (typeof changedMethod == "function") {
2525
+ const descriptor = this.valueDescriptorNameMap[name];
2526
+ try {
2527
+ const value = descriptor.reader(rawValue);
2528
+ let oldValue = rawOldValue;
2529
+ if (rawOldValue) {
2530
+ oldValue = descriptor.reader(rawOldValue);
2531
+ }
2532
+ changedMethod.call(this.receiver, value, oldValue);
2533
+ }
2534
+ catch (error) {
2535
+ if (error instanceof TypeError) {
2536
+ error.message = `Stimulus Value "${this.context.identifier}.${descriptor.name}" - ${error.message}`;
2537
+ }
2538
+ throw error;
2539
+ }
2540
+ }
2541
+ }
2542
+ get valueDescriptors() {
2543
+ const { valueDescriptorMap } = this;
2544
+ return Object.keys(valueDescriptorMap).map((key) => valueDescriptorMap[key]);
2545
+ }
2546
+ get valueDescriptorNameMap() {
2547
+ const descriptors = {};
2548
+ Object.keys(this.valueDescriptorMap).forEach((key) => {
2549
+ const descriptor = this.valueDescriptorMap[key];
2550
+ descriptors[descriptor.name] = descriptor;
2551
+ });
2552
+ return descriptors;
2553
+ }
2554
+ hasValue(attributeName) {
2555
+ const descriptor = this.valueDescriptorNameMap[attributeName];
2556
+ const hasMethodName = `has${capitalize(descriptor.name)}`;
2557
+ return this.receiver[hasMethodName];
2558
+ }
2559
+ }
2560
+
2561
+ class TargetObserver {
2562
+ constructor(context, delegate) {
2563
+ this.context = context;
2564
+ this.delegate = delegate;
2565
+ this.targetsByName = new Multimap();
2566
+ }
2567
+ start() {
2568
+ if (!this.tokenListObserver) {
2569
+ this.tokenListObserver = new TokenListObserver(this.element, this.attributeName, this);
2570
+ this.tokenListObserver.start();
2571
+ }
2572
+ }
2573
+ stop() {
2574
+ if (this.tokenListObserver) {
2575
+ this.disconnectAllTargets();
2576
+ this.tokenListObserver.stop();
2577
+ delete this.tokenListObserver;
2578
+ }
2579
+ }
2580
+ tokenMatched({ element, content: name }) {
2581
+ if (this.scope.containsElement(element)) {
2582
+ this.connectTarget(element, name);
2583
+ }
2584
+ }
2585
+ tokenUnmatched({ element, content: name }) {
2586
+ this.disconnectTarget(element, name);
2587
+ }
2588
+ connectTarget(element, name) {
2589
+ var _a;
2590
+ if (!this.targetsByName.has(name, element)) {
2591
+ this.targetsByName.add(name, element);
2592
+ (_a = this.tokenListObserver) === null || _a === void 0 ? void 0 : _a.pause(() => this.delegate.targetConnected(element, name));
2593
+ }
2594
+ }
2595
+ disconnectTarget(element, name) {
2596
+ var _a;
2597
+ if (this.targetsByName.has(name, element)) {
2598
+ this.targetsByName.delete(name, element);
2599
+ (_a = this.tokenListObserver) === null || _a === void 0 ? void 0 : _a.pause(() => this.delegate.targetDisconnected(element, name));
2600
+ }
2601
+ }
2602
+ disconnectAllTargets() {
2603
+ for (const name of this.targetsByName.keys) {
2604
+ for (const element of this.targetsByName.getValuesForKey(name)) {
2605
+ this.disconnectTarget(element, name);
2606
+ }
2607
+ }
2608
+ }
2609
+ get attributeName() {
2610
+ return `data-${this.context.identifier}-target`;
2611
+ }
2612
+ get element() {
2613
+ return this.context.element;
2614
+ }
2615
+ get scope() {
2616
+ return this.context.scope;
2617
+ }
2618
+ }
2619
+
2620
+ function readInheritableStaticArrayValues(constructor, propertyName) {
2621
+ const ancestors = getAncestorsForConstructor(constructor);
2622
+ return Array.from(ancestors.reduce((values, constructor) => {
2623
+ getOwnStaticArrayValues(constructor, propertyName).forEach((name) => values.add(name));
2624
+ return values;
2625
+ }, new Set()));
2626
+ }
2627
+ function getAncestorsForConstructor(constructor) {
2628
+ const ancestors = [];
2629
+ while (constructor) {
2630
+ ancestors.push(constructor);
2631
+ constructor = Object.getPrototypeOf(constructor);
2632
+ }
2633
+ return ancestors.reverse();
2634
+ }
2635
+ function getOwnStaticArrayValues(constructor, propertyName) {
2636
+ const definition = constructor[propertyName];
2637
+ return Array.isArray(definition) ? definition : [];
2638
+ }
2639
+
2640
+ class OutletObserver {
2641
+ constructor(context, delegate) {
2642
+ this.started = false;
2643
+ this.context = context;
2644
+ this.delegate = delegate;
2645
+ this.outletsByName = new Multimap();
2646
+ this.outletElementsByName = new Multimap();
2647
+ this.selectorObserverMap = new Map();
2648
+ this.attributeObserverMap = new Map();
2649
+ }
2650
+ start() {
2651
+ if (!this.started) {
2652
+ this.outletDefinitions.forEach((outletName) => {
2653
+ this.setupSelectorObserverForOutlet(outletName);
2654
+ this.setupAttributeObserverForOutlet(outletName);
2655
+ });
2656
+ this.started = true;
2657
+ this.dependentContexts.forEach((context) => context.refresh());
2658
+ }
2659
+ }
2660
+ refresh() {
2661
+ this.selectorObserverMap.forEach((observer) => observer.refresh());
2662
+ this.attributeObserverMap.forEach((observer) => observer.refresh());
2663
+ }
2664
+ stop() {
2665
+ if (this.started) {
2666
+ this.started = false;
2667
+ this.disconnectAllOutlets();
2668
+ this.stopSelectorObservers();
2669
+ this.stopAttributeObservers();
2670
+ }
2671
+ }
2672
+ stopSelectorObservers() {
2673
+ if (this.selectorObserverMap.size > 0) {
2674
+ this.selectorObserverMap.forEach((observer) => observer.stop());
2675
+ this.selectorObserverMap.clear();
2676
+ }
2677
+ }
2678
+ stopAttributeObservers() {
2679
+ if (this.attributeObserverMap.size > 0) {
2680
+ this.attributeObserverMap.forEach((observer) => observer.stop());
2681
+ this.attributeObserverMap.clear();
2682
+ }
2683
+ }
2684
+ selectorMatched(element, _selector, { outletName }) {
2685
+ const outlet = this.getOutlet(element, outletName);
2686
+ if (outlet) {
2687
+ this.connectOutlet(outlet, element, outletName);
2688
+ }
2689
+ }
2690
+ selectorUnmatched(element, _selector, { outletName }) {
2691
+ const outlet = this.getOutletFromMap(element, outletName);
2692
+ if (outlet) {
2693
+ this.disconnectOutlet(outlet, element, outletName);
2694
+ }
2695
+ }
2696
+ selectorMatchElement(element, { outletName }) {
2697
+ const selector = this.selector(outletName);
2698
+ const hasOutlet = this.hasOutlet(element, outletName);
2699
+ const hasOutletController = element.matches(`[${this.schema.controllerAttribute}~=${outletName}]`);
2700
+ if (selector) {
2701
+ return hasOutlet && hasOutletController && element.matches(selector);
2702
+ }
2703
+ else {
2704
+ return false;
2705
+ }
2706
+ }
2707
+ elementMatchedAttribute(_element, attributeName) {
2708
+ const outletName = this.getOutletNameFromOutletAttributeName(attributeName);
2709
+ if (outletName) {
2710
+ this.updateSelectorObserverForOutlet(outletName);
2711
+ }
2712
+ }
2713
+ elementAttributeValueChanged(_element, attributeName) {
2714
+ const outletName = this.getOutletNameFromOutletAttributeName(attributeName);
2715
+ if (outletName) {
2716
+ this.updateSelectorObserverForOutlet(outletName);
2717
+ }
2718
+ }
2719
+ elementUnmatchedAttribute(_element, attributeName) {
2720
+ const outletName = this.getOutletNameFromOutletAttributeName(attributeName);
2721
+ if (outletName) {
2722
+ this.updateSelectorObserverForOutlet(outletName);
2723
+ }
2724
+ }
2725
+ connectOutlet(outlet, element, outletName) {
2726
+ var _a;
2727
+ if (!this.outletElementsByName.has(outletName, element)) {
2728
+ this.outletsByName.add(outletName, outlet);
2729
+ this.outletElementsByName.add(outletName, element);
2730
+ (_a = this.selectorObserverMap.get(outletName)) === null || _a === void 0 ? void 0 : _a.pause(() => this.delegate.outletConnected(outlet, element, outletName));
2731
+ }
2732
+ }
2733
+ disconnectOutlet(outlet, element, outletName) {
2734
+ var _a;
2735
+ if (this.outletElementsByName.has(outletName, element)) {
2736
+ this.outletsByName.delete(outletName, outlet);
2737
+ this.outletElementsByName.delete(outletName, element);
2738
+ (_a = this.selectorObserverMap
2739
+ .get(outletName)) === null || _a === void 0 ? void 0 : _a.pause(() => this.delegate.outletDisconnected(outlet, element, outletName));
2740
+ }
2741
+ }
2742
+ disconnectAllOutlets() {
2743
+ for (const outletName of this.outletElementsByName.keys) {
2744
+ for (const element of this.outletElementsByName.getValuesForKey(outletName)) {
2745
+ for (const outlet of this.outletsByName.getValuesForKey(outletName)) {
2746
+ this.disconnectOutlet(outlet, element, outletName);
2747
+ }
2748
+ }
2749
+ }
2750
+ }
2751
+ updateSelectorObserverForOutlet(outletName) {
2752
+ const observer = this.selectorObserverMap.get(outletName);
2753
+ if (observer) {
2754
+ observer.selector = this.selector(outletName);
2755
+ }
2756
+ }
2757
+ setupSelectorObserverForOutlet(outletName) {
2758
+ const selector = this.selector(outletName);
2759
+ const selectorObserver = new SelectorObserver(document.body, selector, this, { outletName });
2760
+ this.selectorObserverMap.set(outletName, selectorObserver);
2761
+ selectorObserver.start();
2762
+ }
2763
+ setupAttributeObserverForOutlet(outletName) {
2764
+ const attributeName = this.attributeNameForOutletName(outletName);
2765
+ const attributeObserver = new AttributeObserver(this.scope.element, attributeName, this);
2766
+ this.attributeObserverMap.set(outletName, attributeObserver);
2767
+ attributeObserver.start();
2768
+ }
2769
+ selector(outletName) {
2770
+ return this.scope.outlets.getSelectorForOutletName(outletName);
2771
+ }
2772
+ attributeNameForOutletName(outletName) {
2773
+ return this.scope.schema.outletAttributeForScope(this.identifier, outletName);
2774
+ }
2775
+ getOutletNameFromOutletAttributeName(attributeName) {
2776
+ return this.outletDefinitions.find((outletName) => this.attributeNameForOutletName(outletName) === attributeName);
2777
+ }
2778
+ get outletDependencies() {
2779
+ const dependencies = new Multimap();
2780
+ this.router.modules.forEach((module) => {
2781
+ const constructor = module.definition.controllerConstructor;
2782
+ const outlets = readInheritableStaticArrayValues(constructor, "outlets");
2783
+ outlets.forEach((outlet) => dependencies.add(outlet, module.identifier));
2784
+ });
2785
+ return dependencies;
2786
+ }
2787
+ get outletDefinitions() {
2788
+ return this.outletDependencies.getKeysForValue(this.identifier);
2789
+ }
2790
+ get dependentControllerIdentifiers() {
2791
+ return this.outletDependencies.getValuesForKey(this.identifier);
2792
+ }
2793
+ get dependentContexts() {
2794
+ const identifiers = this.dependentControllerIdentifiers;
2795
+ return this.router.contexts.filter((context) => identifiers.includes(context.identifier));
2796
+ }
2797
+ hasOutlet(element, outletName) {
2798
+ return !!this.getOutlet(element, outletName) || !!this.getOutletFromMap(element, outletName);
2799
+ }
2800
+ getOutlet(element, outletName) {
2801
+ return this.application.getControllerForElementAndIdentifier(element, outletName);
2802
+ }
2803
+ getOutletFromMap(element, outletName) {
2804
+ return this.outletsByName.getValuesForKey(outletName).find((outlet) => outlet.element === element);
2805
+ }
2806
+ get scope() {
2807
+ return this.context.scope;
2808
+ }
2809
+ get schema() {
2810
+ return this.context.schema;
2811
+ }
2812
+ get identifier() {
2813
+ return this.context.identifier;
2814
+ }
2815
+ get application() {
2816
+ return this.context.application;
2817
+ }
2818
+ get router() {
2819
+ return this.application.router;
2820
+ }
2821
+ }
2822
+
2823
+ class Context {
2824
+ constructor(module, scope) {
2825
+ this.logDebugActivity = (functionName, detail = {}) => {
2826
+ const { identifier, controller, element } = this;
2827
+ detail = Object.assign({ identifier, controller, element }, detail);
2828
+ this.application.logDebugActivity(this.identifier, functionName, detail);
2829
+ };
2830
+ this.module = module;
2831
+ this.scope = scope;
2832
+ this.controller = new module.controllerConstructor(this);
2833
+ this.bindingObserver = new BindingObserver(this, this.dispatcher);
2834
+ this.valueObserver = new ValueObserver(this, this.controller);
2835
+ this.targetObserver = new TargetObserver(this, this);
2836
+ this.outletObserver = new OutletObserver(this, this);
2837
+ try {
2838
+ this.controller.initialize();
2839
+ this.logDebugActivity("initialize");
2840
+ }
2841
+ catch (error) {
2842
+ this.handleError(error, "initializing controller");
2843
+ }
2844
+ }
2845
+ connect() {
2846
+ this.bindingObserver.start();
2847
+ this.valueObserver.start();
2848
+ this.targetObserver.start();
2849
+ this.outletObserver.start();
2850
+ try {
2851
+ this.controller.connect();
2852
+ this.logDebugActivity("connect");
2853
+ }
2854
+ catch (error) {
2855
+ this.handleError(error, "connecting controller");
2856
+ }
2857
+ }
2858
+ refresh() {
2859
+ this.outletObserver.refresh();
2860
+ }
2861
+ disconnect() {
2862
+ try {
2863
+ this.controller.disconnect();
2864
+ this.logDebugActivity("disconnect");
2865
+ }
2866
+ catch (error) {
2867
+ this.handleError(error, "disconnecting controller");
2868
+ }
2869
+ this.outletObserver.stop();
2870
+ this.targetObserver.stop();
2871
+ this.valueObserver.stop();
2872
+ this.bindingObserver.stop();
2873
+ }
2874
+ get application() {
2875
+ return this.module.application;
2876
+ }
2877
+ get identifier() {
2878
+ return this.module.identifier;
2879
+ }
2880
+ get schema() {
2881
+ return this.application.schema;
2882
+ }
2883
+ get dispatcher() {
2884
+ return this.application.dispatcher;
2885
+ }
2886
+ get element() {
2887
+ return this.scope.element;
2888
+ }
2889
+ get parentElement() {
2890
+ return this.element.parentElement;
2891
+ }
2892
+ handleError(error, message, detail = {}) {
2893
+ const { identifier, controller, element } = this;
2894
+ detail = Object.assign({ identifier, controller, element }, detail);
2895
+ this.application.handleError(error, `Error ${message}`, detail);
2896
+ }
2897
+ targetConnected(element, name) {
2898
+ this.invokeControllerMethod(`${name}TargetConnected`, element);
2899
+ }
2900
+ targetDisconnected(element, name) {
2901
+ this.invokeControllerMethod(`${name}TargetDisconnected`, element);
2902
+ }
2903
+ outletConnected(outlet, element, name) {
2904
+ this.invokeControllerMethod(`${namespaceCamelize(name)}OutletConnected`, outlet, element);
2905
+ }
2906
+ outletDisconnected(outlet, element, name) {
2907
+ this.invokeControllerMethod(`${namespaceCamelize(name)}OutletDisconnected`, outlet, element);
2908
+ }
2909
+ invokeControllerMethod(methodName, ...args) {
2910
+ const controller = this.controller;
2911
+ if (typeof controller[methodName] == "function") {
2912
+ controller[methodName](...args);
2913
+ }
2914
+ }
2915
+ }
2916
+
2917
+ function bless(constructor) {
2918
+ return shadow(constructor, getBlessedProperties(constructor));
2919
+ }
2920
+ function shadow(constructor, properties) {
2921
+ const shadowConstructor = extend(constructor);
2922
+ const shadowProperties = getShadowProperties(constructor.prototype, properties);
2923
+ Object.defineProperties(shadowConstructor.prototype, shadowProperties);
2924
+ return shadowConstructor;
2925
+ }
2926
+ function getBlessedProperties(constructor) {
2927
+ const blessings = readInheritableStaticArrayValues(constructor, "blessings");
2928
+ return blessings.reduce((blessedProperties, blessing) => {
2929
+ const properties = blessing(constructor);
2930
+ for (const key in properties) {
2931
+ const descriptor = blessedProperties[key] || {};
2932
+ blessedProperties[key] = Object.assign(descriptor, properties[key]);
2933
+ }
2934
+ return blessedProperties;
2935
+ }, {});
2936
+ }
2937
+ function getShadowProperties(prototype, properties) {
2938
+ return getOwnKeys(properties).reduce((shadowProperties, key) => {
2939
+ const descriptor = getShadowedDescriptor(prototype, properties, key);
2940
+ if (descriptor) {
2941
+ Object.assign(shadowProperties, { [key]: descriptor });
2942
+ }
2943
+ return shadowProperties;
2944
+ }, {});
2945
+ }
2946
+ function getShadowedDescriptor(prototype, properties, key) {
2947
+ const shadowingDescriptor = Object.getOwnPropertyDescriptor(prototype, key);
2948
+ const shadowedByValue = shadowingDescriptor && "value" in shadowingDescriptor;
2949
+ if (!shadowedByValue) {
2950
+ const descriptor = Object.getOwnPropertyDescriptor(properties, key).value;
2951
+ if (shadowingDescriptor) {
2952
+ descriptor.get = shadowingDescriptor.get || descriptor.get;
2953
+ descriptor.set = shadowingDescriptor.set || descriptor.set;
2954
+ }
2955
+ return descriptor;
2956
+ }
2957
+ }
2958
+ const getOwnKeys = (() => {
2959
+ if (typeof Object.getOwnPropertySymbols == "function") {
2960
+ return (object) => [...Object.getOwnPropertyNames(object), ...Object.getOwnPropertySymbols(object)];
2961
+ }
2962
+ else {
2963
+ return Object.getOwnPropertyNames;
2964
+ }
2965
+ })();
2966
+ const extend = (() => {
2967
+ function extendWithReflect(constructor) {
2968
+ function extended() {
2969
+ return Reflect.construct(constructor, arguments, new.target);
2970
+ }
2971
+ extended.prototype = Object.create(constructor.prototype, {
2972
+ constructor: { value: extended },
2973
+ });
2974
+ Reflect.setPrototypeOf(extended, constructor);
2975
+ return extended;
2976
+ }
2977
+ function testReflectExtension() {
2978
+ const a = function () {
2979
+ this.a.call(this);
2980
+ };
2981
+ const b = extendWithReflect(a);
2982
+ b.prototype.a = function () { };
2983
+ return new b();
2984
+ }
2985
+ try {
2986
+ testReflectExtension();
2987
+ return extendWithReflect;
2988
+ }
2989
+ catch (error) {
2990
+ return (constructor) => class extended extends constructor {
2991
+ };
2992
+ }
2993
+ })();
2994
+
2995
+ function blessDefinition(definition) {
2996
+ return {
2997
+ identifier: definition.identifier,
2998
+ controllerConstructor: bless(definition.controllerConstructor),
2999
+ };
3000
+ }
3001
+
3002
+ class Module {
3003
+ constructor(application, definition) {
3004
+ this.application = application;
3005
+ this.definition = blessDefinition(definition);
3006
+ this.contextsByScope = new WeakMap();
3007
+ this.connectedContexts = new Set();
3008
+ }
3009
+ get identifier() {
3010
+ return this.definition.identifier;
3011
+ }
3012
+ get controllerConstructor() {
3013
+ return this.definition.controllerConstructor;
3014
+ }
3015
+ get contexts() {
3016
+ return Array.from(this.connectedContexts);
3017
+ }
3018
+ connectContextForScope(scope) {
3019
+ const context = this.fetchContextForScope(scope);
3020
+ this.connectedContexts.add(context);
3021
+ context.connect();
3022
+ }
3023
+ disconnectContextForScope(scope) {
3024
+ const context = this.contextsByScope.get(scope);
3025
+ if (context) {
3026
+ this.connectedContexts.delete(context);
3027
+ context.disconnect();
3028
+ }
3029
+ }
3030
+ fetchContextForScope(scope) {
3031
+ let context = this.contextsByScope.get(scope);
3032
+ if (!context) {
3033
+ context = new Context(this, scope);
3034
+ this.contextsByScope.set(scope, context);
3035
+ }
3036
+ return context;
3037
+ }
3038
+ }
3039
+
3040
+ class ClassMap {
3041
+ constructor(scope) {
3042
+ this.scope = scope;
3043
+ }
3044
+ has(name) {
3045
+ return this.data.has(this.getDataKey(name));
3046
+ }
3047
+ get(name) {
3048
+ return this.getAll(name)[0];
3049
+ }
3050
+ getAll(name) {
3051
+ const tokenString = this.data.get(this.getDataKey(name)) || "";
3052
+ return tokenize(tokenString);
3053
+ }
3054
+ getAttributeName(name) {
3055
+ return this.data.getAttributeNameForKey(this.getDataKey(name));
3056
+ }
3057
+ getDataKey(name) {
3058
+ return `${name}-class`;
3059
+ }
3060
+ get data() {
3061
+ return this.scope.data;
3062
+ }
3063
+ }
3064
+
3065
+ class DataMap {
3066
+ constructor(scope) {
3067
+ this.scope = scope;
3068
+ }
3069
+ get element() {
3070
+ return this.scope.element;
3071
+ }
3072
+ get identifier() {
3073
+ return this.scope.identifier;
3074
+ }
3075
+ get(key) {
3076
+ const name = this.getAttributeNameForKey(key);
3077
+ return this.element.getAttribute(name);
3078
+ }
3079
+ set(key, value) {
3080
+ const name = this.getAttributeNameForKey(key);
3081
+ this.element.setAttribute(name, value);
3082
+ return this.get(key);
3083
+ }
3084
+ has(key) {
3085
+ const name = this.getAttributeNameForKey(key);
3086
+ return this.element.hasAttribute(name);
3087
+ }
3088
+ delete(key) {
3089
+ if (this.has(key)) {
3090
+ const name = this.getAttributeNameForKey(key);
3091
+ this.element.removeAttribute(name);
3092
+ return true;
3093
+ }
3094
+ else {
3095
+ return false;
3096
+ }
3097
+ }
3098
+ getAttributeNameForKey(key) {
3099
+ return `data-${this.identifier}-${dasherize(key)}`;
3100
+ }
3101
+ }
3102
+
3103
+ class Guide {
3104
+ constructor(logger) {
3105
+ this.warnedKeysByObject = new WeakMap();
3106
+ this.logger = logger;
3107
+ }
3108
+ warn(object, key, message) {
3109
+ let warnedKeys = this.warnedKeysByObject.get(object);
3110
+ if (!warnedKeys) {
3111
+ warnedKeys = new Set();
3112
+ this.warnedKeysByObject.set(object, warnedKeys);
3113
+ }
3114
+ if (!warnedKeys.has(key)) {
3115
+ warnedKeys.add(key);
3116
+ this.logger.warn(message, object);
3117
+ }
3118
+ }
3119
+ }
3120
+
3121
+ function attributeValueContainsToken(attributeName, token) {
3122
+ return `[${attributeName}~="${token}"]`;
3123
+ }
3124
+
3125
+ class TargetSet {
3126
+ constructor(scope) {
3127
+ this.scope = scope;
3128
+ }
3129
+ get element() {
3130
+ return this.scope.element;
3131
+ }
3132
+ get identifier() {
3133
+ return this.scope.identifier;
3134
+ }
3135
+ get schema() {
3136
+ return this.scope.schema;
3137
+ }
3138
+ has(targetName) {
3139
+ return this.find(targetName) != null;
3140
+ }
3141
+ find(...targetNames) {
3142
+ return targetNames.reduce((target, targetName) => target || this.findTarget(targetName) || this.findLegacyTarget(targetName), undefined);
3143
+ }
3144
+ findAll(...targetNames) {
3145
+ return targetNames.reduce((targets, targetName) => [
3146
+ ...targets,
3147
+ ...this.findAllTargets(targetName),
3148
+ ...this.findAllLegacyTargets(targetName),
3149
+ ], []);
3150
+ }
3151
+ findTarget(targetName) {
3152
+ const selector = this.getSelectorForTargetName(targetName);
3153
+ return this.scope.findElement(selector);
3154
+ }
3155
+ findAllTargets(targetName) {
3156
+ const selector = this.getSelectorForTargetName(targetName);
3157
+ return this.scope.findAllElements(selector);
3158
+ }
3159
+ getSelectorForTargetName(targetName) {
3160
+ const attributeName = this.schema.targetAttributeForScope(this.identifier);
3161
+ return attributeValueContainsToken(attributeName, targetName);
3162
+ }
3163
+ findLegacyTarget(targetName) {
3164
+ const selector = this.getLegacySelectorForTargetName(targetName);
3165
+ return this.deprecate(this.scope.findElement(selector), targetName);
3166
+ }
3167
+ findAllLegacyTargets(targetName) {
3168
+ const selector = this.getLegacySelectorForTargetName(targetName);
3169
+ return this.scope.findAllElements(selector).map((element) => this.deprecate(element, targetName));
3170
+ }
3171
+ getLegacySelectorForTargetName(targetName) {
3172
+ const targetDescriptor = `${this.identifier}.${targetName}`;
3173
+ return attributeValueContainsToken(this.schema.targetAttribute, targetDescriptor);
3174
+ }
3175
+ deprecate(element, targetName) {
3176
+ if (element) {
3177
+ const { identifier } = this;
3178
+ const attributeName = this.schema.targetAttribute;
3179
+ const revisedAttributeName = this.schema.targetAttributeForScope(identifier);
3180
+ this.guide.warn(element, `target:${targetName}`, `Please replace ${attributeName}="${identifier}.${targetName}" with ${revisedAttributeName}="${targetName}". ` +
3181
+ `The ${attributeName} attribute is deprecated and will be removed in a future version of Stimulus.`);
3182
+ }
3183
+ return element;
3184
+ }
3185
+ get guide() {
3186
+ return this.scope.guide;
3187
+ }
3188
+ }
3189
+
3190
+ class OutletSet {
3191
+ constructor(scope, controllerElement) {
3192
+ this.scope = scope;
3193
+ this.controllerElement = controllerElement;
3194
+ }
3195
+ get element() {
3196
+ return this.scope.element;
3197
+ }
3198
+ get identifier() {
3199
+ return this.scope.identifier;
3200
+ }
3201
+ get schema() {
3202
+ return this.scope.schema;
3203
+ }
3204
+ has(outletName) {
3205
+ return this.find(outletName) != null;
3206
+ }
3207
+ find(...outletNames) {
3208
+ return outletNames.reduce((outlet, outletName) => outlet || this.findOutlet(outletName), undefined);
3209
+ }
3210
+ findAll(...outletNames) {
3211
+ return outletNames.reduce((outlets, outletName) => [...outlets, ...this.findAllOutlets(outletName)], []);
3212
+ }
3213
+ getSelectorForOutletName(outletName) {
3214
+ const attributeName = this.schema.outletAttributeForScope(this.identifier, outletName);
3215
+ return this.controllerElement.getAttribute(attributeName);
3216
+ }
3217
+ findOutlet(outletName) {
3218
+ const selector = this.getSelectorForOutletName(outletName);
3219
+ if (selector)
3220
+ return this.findElement(selector, outletName);
3221
+ }
3222
+ findAllOutlets(outletName) {
3223
+ const selector = this.getSelectorForOutletName(outletName);
3224
+ return selector ? this.findAllElements(selector, outletName) : [];
3225
+ }
3226
+ findElement(selector, outletName) {
3227
+ const elements = this.scope.queryElements(selector);
3228
+ return elements.filter((element) => this.matchesElement(element, selector, outletName))[0];
3229
+ }
3230
+ findAllElements(selector, outletName) {
3231
+ const elements = this.scope.queryElements(selector);
3232
+ return elements.filter((element) => this.matchesElement(element, selector, outletName));
3233
+ }
3234
+ matchesElement(element, selector, outletName) {
3235
+ const controllerAttribute = element.getAttribute(this.scope.schema.controllerAttribute) || "";
3236
+ return element.matches(selector) && controllerAttribute.split(" ").includes(outletName);
3237
+ }
3238
+ }
3239
+
3240
+ class Scope {
3241
+ constructor(schema, element, identifier, logger) {
3242
+ this.targets = new TargetSet(this);
3243
+ this.classes = new ClassMap(this);
3244
+ this.data = new DataMap(this);
3245
+ this.containsElement = (element) => {
3246
+ return element.closest(this.controllerSelector) === this.element;
3247
+ };
3248
+ this.schema = schema;
3249
+ this.element = element;
3250
+ this.identifier = identifier;
3251
+ this.guide = new Guide(logger);
3252
+ this.outlets = new OutletSet(this.documentScope, element);
3253
+ }
3254
+ findElement(selector) {
3255
+ return this.element.matches(selector) ? this.element : this.queryElements(selector).find(this.containsElement);
3256
+ }
3257
+ findAllElements(selector) {
3258
+ return [
3259
+ ...(this.element.matches(selector) ? [this.element] : []),
3260
+ ...this.queryElements(selector).filter(this.containsElement),
3261
+ ];
3262
+ }
3263
+ queryElements(selector) {
3264
+ return Array.from(this.element.querySelectorAll(selector));
3265
+ }
3266
+ get controllerSelector() {
3267
+ return attributeValueContainsToken(this.schema.controllerAttribute, this.identifier);
3268
+ }
3269
+ get isDocumentScope() {
3270
+ return this.element === document.documentElement;
3271
+ }
3272
+ get documentScope() {
3273
+ return this.isDocumentScope
3274
+ ? this
3275
+ : new Scope(this.schema, document.documentElement, this.identifier, this.guide.logger);
3276
+ }
3277
+ }
3278
+
3279
+ class ScopeObserver {
3280
+ constructor(element, schema, delegate) {
3281
+ this.element = element;
3282
+ this.schema = schema;
3283
+ this.delegate = delegate;
3284
+ this.valueListObserver = new ValueListObserver(this.element, this.controllerAttribute, this);
3285
+ this.scopesByIdentifierByElement = new WeakMap();
3286
+ this.scopeReferenceCounts = new WeakMap();
3287
+ }
3288
+ start() {
3289
+ this.valueListObserver.start();
3290
+ }
3291
+ stop() {
3292
+ this.valueListObserver.stop();
3293
+ }
3294
+ get controllerAttribute() {
3295
+ return this.schema.controllerAttribute;
3296
+ }
3297
+ parseValueForToken(token) {
3298
+ const { element, content: identifier } = token;
3299
+ return this.parseValueForElementAndIdentifier(element, identifier);
3300
+ }
3301
+ parseValueForElementAndIdentifier(element, identifier) {
3302
+ const scopesByIdentifier = this.fetchScopesByIdentifierForElement(element);
3303
+ let scope = scopesByIdentifier.get(identifier);
3304
+ if (!scope) {
3305
+ scope = this.delegate.createScopeForElementAndIdentifier(element, identifier);
3306
+ scopesByIdentifier.set(identifier, scope);
3307
+ }
3308
+ return scope;
3309
+ }
3310
+ elementMatchedValue(element, value) {
3311
+ const referenceCount = (this.scopeReferenceCounts.get(value) || 0) + 1;
3312
+ this.scopeReferenceCounts.set(value, referenceCount);
3313
+ if (referenceCount == 1) {
3314
+ this.delegate.scopeConnected(value);
3315
+ }
3316
+ }
3317
+ elementUnmatchedValue(element, value) {
3318
+ const referenceCount = this.scopeReferenceCounts.get(value);
3319
+ if (referenceCount) {
3320
+ this.scopeReferenceCounts.set(value, referenceCount - 1);
3321
+ if (referenceCount == 1) {
3322
+ this.delegate.scopeDisconnected(value);
3323
+ }
3324
+ }
3325
+ }
3326
+ fetchScopesByIdentifierForElement(element) {
3327
+ let scopesByIdentifier = this.scopesByIdentifierByElement.get(element);
3328
+ if (!scopesByIdentifier) {
3329
+ scopesByIdentifier = new Map();
3330
+ this.scopesByIdentifierByElement.set(element, scopesByIdentifier);
3331
+ }
3332
+ return scopesByIdentifier;
3333
+ }
3334
+ }
3335
+
3336
+ class Router {
3337
+ constructor(application) {
3338
+ this.application = application;
3339
+ this.scopeObserver = new ScopeObserver(this.element, this.schema, this);
3340
+ this.scopesByIdentifier = new Multimap();
3341
+ this.modulesByIdentifier = new Map();
3342
+ }
3343
+ get element() {
3344
+ return this.application.element;
3345
+ }
3346
+ get schema() {
3347
+ return this.application.schema;
3348
+ }
3349
+ get logger() {
3350
+ return this.application.logger;
3351
+ }
3352
+ get controllerAttribute() {
3353
+ return this.schema.controllerAttribute;
3354
+ }
3355
+ get modules() {
3356
+ return Array.from(this.modulesByIdentifier.values());
3357
+ }
3358
+ get contexts() {
3359
+ return this.modules.reduce((contexts, module) => contexts.concat(module.contexts), []);
3360
+ }
3361
+ start() {
3362
+ this.scopeObserver.start();
3363
+ }
3364
+ stop() {
3365
+ this.scopeObserver.stop();
3366
+ }
3367
+ loadDefinition(definition) {
3368
+ this.unloadIdentifier(definition.identifier);
3369
+ const module = new Module(this.application, definition);
3370
+ this.connectModule(module);
3371
+ const afterLoad = definition.controllerConstructor.afterLoad;
3372
+ if (afterLoad) {
3373
+ afterLoad.call(definition.controllerConstructor, definition.identifier, this.application);
3374
+ }
3375
+ }
3376
+ unloadIdentifier(identifier) {
3377
+ const module = this.modulesByIdentifier.get(identifier);
3378
+ if (module) {
3379
+ this.disconnectModule(module);
3380
+ }
3381
+ }
3382
+ getContextForElementAndIdentifier(element, identifier) {
3383
+ const module = this.modulesByIdentifier.get(identifier);
3384
+ if (module) {
3385
+ return module.contexts.find((context) => context.element == element);
3386
+ }
3387
+ }
3388
+ proposeToConnectScopeForElementAndIdentifier(element, identifier) {
3389
+ const scope = this.scopeObserver.parseValueForElementAndIdentifier(element, identifier);
3390
+ if (scope) {
3391
+ this.scopeObserver.elementMatchedValue(scope.element, scope);
3392
+ }
3393
+ else {
3394
+ console.error(`Couldn't find or create scope for identifier: "${identifier}" and element:`, element);
3395
+ }
3396
+ }
3397
+ handleError(error, message, detail) {
3398
+ this.application.handleError(error, message, detail);
3399
+ }
3400
+ createScopeForElementAndIdentifier(element, identifier) {
3401
+ return new Scope(this.schema, element, identifier, this.logger);
3402
+ }
3403
+ scopeConnected(scope) {
3404
+ this.scopesByIdentifier.add(scope.identifier, scope);
3405
+ const module = this.modulesByIdentifier.get(scope.identifier);
3406
+ if (module) {
3407
+ module.connectContextForScope(scope);
3408
+ }
3409
+ }
3410
+ scopeDisconnected(scope) {
3411
+ this.scopesByIdentifier.delete(scope.identifier, scope);
3412
+ const module = this.modulesByIdentifier.get(scope.identifier);
3413
+ if (module) {
3414
+ module.disconnectContextForScope(scope);
3415
+ }
3416
+ }
3417
+ connectModule(module) {
3418
+ this.modulesByIdentifier.set(module.identifier, module);
3419
+ const scopes = this.scopesByIdentifier.getValuesForKey(module.identifier);
3420
+ scopes.forEach((scope) => module.connectContextForScope(scope));
3421
+ }
3422
+ disconnectModule(module) {
3423
+ this.modulesByIdentifier.delete(module.identifier);
3424
+ const scopes = this.scopesByIdentifier.getValuesForKey(module.identifier);
3425
+ scopes.forEach((scope) => module.disconnectContextForScope(scope));
3426
+ }
3427
+ }
3428
+
3429
+ const defaultSchema = {
3430
+ controllerAttribute: "data-controller",
3431
+ actionAttribute: "data-action",
3432
+ targetAttribute: "data-target",
3433
+ targetAttributeForScope: (identifier) => `data-${identifier}-target`,
3434
+ outletAttributeForScope: (identifier, outlet) => `data-${identifier}-${outlet}-outlet`,
3435
+ keyMappings: Object.assign(Object.assign({ enter: "Enter", tab: "Tab", esc: "Escape", space: " ", up: "ArrowUp", down: "ArrowDown", left: "ArrowLeft", right: "ArrowRight", home: "Home", end: "End", page_up: "PageUp", page_down: "PageDown" }, objectFromEntries("abcdefghijklmnopqrstuvwxyz".split("").map((c) => [c, c]))), objectFromEntries("0123456789".split("").map((n) => [n, n]))),
3436
+ };
3437
+ function objectFromEntries(array) {
3438
+ return array.reduce((memo, [k, v]) => (Object.assign(Object.assign({}, memo), { [k]: v })), {});
3439
+ }
3440
+
3441
+ class Application {
3442
+ constructor(element = document.documentElement, schema = defaultSchema) {
3443
+ this.logger = console;
3444
+ this.debug = false;
3445
+ this.logDebugActivity = (identifier, functionName, detail = {}) => {
3446
+ if (this.debug) {
3447
+ this.logFormattedMessage(identifier, functionName, detail);
3448
+ }
3449
+ };
3450
+ this.element = element;
3451
+ this.schema = schema;
3452
+ this.dispatcher = new Dispatcher(this);
3453
+ this.router = new Router(this);
3454
+ this.actionDescriptorFilters = Object.assign({}, defaultActionDescriptorFilters);
3455
+ }
3456
+ static start(element, schema) {
3457
+ const application = new this(element, schema);
3458
+ application.start();
3459
+ return application;
3460
+ }
3461
+ async start() {
3462
+ await domReady();
3463
+ this.logDebugActivity("application", "starting");
3464
+ this.dispatcher.start();
3465
+ this.router.start();
3466
+ this.logDebugActivity("application", "start");
3467
+ }
3468
+ stop() {
3469
+ this.logDebugActivity("application", "stopping");
3470
+ this.dispatcher.stop();
3471
+ this.router.stop();
3472
+ this.logDebugActivity("application", "stop");
3473
+ }
3474
+ register(identifier, controllerConstructor) {
3475
+ this.load({ identifier, controllerConstructor });
3476
+ }
3477
+ registerActionOption(name, filter) {
3478
+ this.actionDescriptorFilters[name] = filter;
3479
+ }
3480
+ load(head, ...rest) {
3481
+ const definitions = Array.isArray(head) ? head : [head, ...rest];
3482
+ definitions.forEach((definition) => {
3483
+ if (definition.controllerConstructor.shouldLoad) {
3484
+ this.router.loadDefinition(definition);
3485
+ }
3486
+ });
3487
+ }
3488
+ unload(head, ...rest) {
3489
+ const identifiers = Array.isArray(head) ? head : [head, ...rest];
3490
+ identifiers.forEach((identifier) => this.router.unloadIdentifier(identifier));
3491
+ }
3492
+ get controllers() {
3493
+ return this.router.contexts.map((context) => context.controller);
3494
+ }
3495
+ getControllerForElementAndIdentifier(element, identifier) {
3496
+ const context = this.router.getContextForElementAndIdentifier(element, identifier);
3497
+ return context ? context.controller : null;
3498
+ }
3499
+ handleError(error, message, detail) {
3500
+ var _a;
3501
+ this.logger.error(`%s\n\n%o\n\n%o`, message, error, detail);
3502
+ (_a = window.onerror) === null || _a === void 0 ? void 0 : _a.call(window, message, "", 0, 0, error);
3503
+ }
3504
+ logFormattedMessage(identifier, functionName, detail = {}) {
3505
+ detail = Object.assign({ application: this }, detail);
3506
+ this.logger.groupCollapsed(`${identifier} #${functionName}`);
3507
+ this.logger.log("details:", Object.assign({}, detail));
3508
+ this.logger.groupEnd();
3509
+ }
3510
+ }
3511
+ function domReady() {
3512
+ return new Promise((resolve) => {
3513
+ if (document.readyState == "loading") {
3514
+ document.addEventListener("DOMContentLoaded", () => resolve());
3515
+ }
3516
+ else {
3517
+ resolve();
3518
+ }
3519
+ });
3520
+ }
3521
+
3522
+ class StimulusReloader {
3523
+ static async reload(filePattern) {
3524
+ const document = await reloadHtmlDocument();
3525
+ return new StimulusReloader(document, filePattern).reload();
3526
+ }
3527
+ constructor(document) {
3528
+ let filePattern = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : /./;
3529
+ this.document = document;
3530
+ this.filePattern = filePattern;
3531
+ this.application = window.Stimulus || Application.start();
3532
+ }
3533
+ async reload() {
3534
+ log("Reload Stimulus controllers...");
3535
+ this.application.stop();
3536
+ await this.#reloadStimulusControllers();
3537
+ this.application.start();
3538
+ }
3539
+ async #reloadStimulusControllers() {
3540
+ await Promise.all(this.#stimulusControllerPaths.map(async moduleName => this.#reloadStimulusController(moduleName)));
3541
+ }
3542
+ get #stimulusControllerPaths() {
3543
+ return Object.keys(this.#stimulusPathsByModule).filter(path => path.endsWith("_controller") && this.#shouldReloadController(path));
3544
+ }
3545
+ #shouldReloadController(path) {
3546
+ return this.filePattern.test(path);
3547
+ }
3548
+ get #stimulusPathsByModule() {
3549
+ this.pathsByModule = this.pathsByModule || this.#parseImportmapJson();
3550
+ return this.pathsByModule;
3551
+ }
3552
+ #parseImportmapJson() {
3553
+ const importmapScript = this.document.querySelector("script[type=importmap]");
3554
+ return JSON.parse(importmapScript.text).imports;
3555
+ }
3556
+ async #reloadStimulusController(moduleName) {
3557
+ log(`\t${moduleName}`);
3558
+ const controllerName = this.#extractControllerName(moduleName);
3559
+ const path = cacheBustedUrl(this.#pathForModuleName(moduleName));
3560
+ const module = await import(path);
3561
+ this.#registerController(controllerName, module);
3562
+ }
3563
+ #pathForModuleName(moduleName) {
3564
+ return this.#stimulusPathsByModule[moduleName];
3565
+ }
3566
+ #extractControllerName(path) {
3567
+ return path.replace(/^.*\//, "").replace("_controller", "").replace(/\//g, "--").replace(/_/g, "-");
3568
+ }
3569
+ #registerController(name, module) {
3570
+ this.application.unload(name);
3571
+ this.application.register(name, module.default);
3572
+ }
3573
+ }
3574
+
3575
+ class HtmlReloader {
3576
+ static async reload() {
3577
+ return new HtmlReloader().reload();
3578
+ }
3579
+ async reload() {
3580
+ const reloadedDocument = await this.#reloadHtml();
3581
+ await this.#reloadStimulus(reloadedDocument);
3582
+ }
3583
+ async #reloadHtml() {
3584
+ log("Reload html...");
3585
+ const reloadedDocument = await reloadHtmlDocument();
3586
+ this.#updateBody(reloadedDocument.body);
3587
+ return reloadedDocument;
3588
+ }
3589
+ #updateBody(newBody) {
3590
+ Idiomorph.morph(document.body, newBody);
3591
+ }
3592
+ async #reloadStimulus(reloadedDocument) {
3593
+ return new StimulusReloader(reloadedDocument).reload();
3594
+ }
3595
+ }
3596
+
3597
+ class CssReloader {
3598
+ static async reload() {
3599
+ for (var _len = arguments.length, params = new Array(_len), _key = 0; _key < _len; _key++) {
3600
+ params[_key] = arguments[_key];
3601
+ }
3602
+ return new CssReloader(...params).reload();
3603
+ }
3604
+ constructor() {
3605
+ let filePattern = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : /./;
3606
+ this.filePattern = filePattern;
3607
+ }
3608
+ async reload() {
3609
+ log("Reload css...");
3610
+ await Promise.all(await this.#reloadAllLinks());
3611
+ }
3612
+ async #reloadAllLinks() {
3613
+ const cssLinks = await this.#loadNewCssLinks();
3614
+ return cssLinks.map(link => this.#reloadLinkIfNeeded(link));
3615
+ }
3616
+ async #loadNewCssLinks() {
3617
+ const reloadedDocument = await reloadHtmlDocument();
3618
+ return Array.from(reloadedDocument.head.querySelectorAll("link[rel='stylesheet']"));
3619
+ }
3620
+ #reloadLinkIfNeeded(link) {
3621
+ if (this.#shouldReloadLink(link)) {
3622
+ return this.#reloadLink(link);
3623
+ } else {
3624
+ return Promise.resolve();
3625
+ }
3626
+ }
3627
+ #shouldReloadLink(link) {
3628
+ return this.filePattern.test(link.getAttribute("href"));
3629
+ }
3630
+ async #reloadLink(link) {
3631
+ return new Promise(resolve => {
3632
+ const href = link.getAttribute("href");
3633
+ const newLink = this.#findExistingLinkFor(link) || this.#appendNewLink(link);
3634
+ newLink.setAttribute("href", cacheBustedUrl(link.getAttribute("href")));
3635
+ newLink.onload = () => {
3636
+ log(`\t${href}`);
3637
+ resolve();
3638
+ };
3639
+ });
3640
+ }
3641
+ #findExistingLinkFor(link) {
3642
+ return this.#cssLinks.find(newLink => pathWithoutAssetDigest(link.href) === pathWithoutAssetDigest(newLink.href));
3643
+ }
3644
+ get #cssLinks() {
3645
+ return Array.from(document.querySelectorAll("link[rel='stylesheet']"));
3646
+ }
3647
+ #appendNewLink(link) {
3648
+ document.head.append(link);
3649
+ return link;
3650
+ }
3651
+ }
3652
+
3653
+ consumer.subscriptions.create({
3654
+ channel: "Hotwire::Spark::Channel"
3655
+ }, {
3656
+ connected() {
3657
+ document.body.setAttribute("data-hotwire-spark-ready", "");
3658
+ },
3659
+ async received(message) {
3660
+ try {
3661
+ await this.dispatch(message);
3662
+ } catch (error) {
3663
+ console.log(`Error on ${message.action}`, error);
3664
+ }
3665
+ },
3666
+ dispatch(_ref) {
3667
+ let {
3668
+ action,
3669
+ path
3670
+ } = _ref;
3671
+ const fileName = assetNameFromPath(path);
3672
+ switch (action) {
3673
+ case "reload_html":
3674
+ return this.reloadHtml();
3675
+ case "reload_css":
3676
+ return this.reloadCss(fileName);
3677
+ case "reload_stimulus":
3678
+ return this.reloadStimulus(fileName);
3679
+ default:
3680
+ throw new Error(`Unknown action: ${action}`);
3681
+ }
3682
+ },
3683
+ reloadHtml() {
3684
+ return HtmlReloader.reload();
3685
+ },
3686
+ reloadCss(fileName) {
3687
+ return CssReloader.reload(new RegExp(fileName));
3688
+ },
3689
+ reloadStimulus(fileName) {
3690
+ return StimulusReloader.reload(new RegExp(fileName));
3691
+ }
3692
+ });
3693
+
3694
+ const HotwireSpark = {
3695
+ config: {
3696
+ loggingEnabled: false
3697
+ }
3698
+ };
3699
+ document.addEventListener("DOMContentLoaded", function () {
3700
+ HotwireSpark.config.loggingEnabled = getConfigurationProperty("logging");
3701
+ });
3702
+
3703
+ return HotwireSpark;
3704
+
3705
+ })();