From fb7ce15fa2e05b317b020bf3ceb10878bb6a4b8a Mon Sep 17 00:00:00 2001 From: Adrien Poly Date: Sat, 21 Dec 2024 18:05:36 +0100 Subject: [PATCH] remove Stimulus from bundle --- app/assets/javascripts/hotwire_spark.js | 2134 +---------------- app/assets/javascripts/hotwire_spark.min.js | 2 +- .../javascripts/hotwire_spark.min.js.map | 2 +- .../spark/reloaders/stimulus_reloader.js | 3 +- 4 files changed, 6 insertions(+), 2135 deletions(-) diff --git a/app/assets/javascripts/hotwire_spark.js b/app/assets/javascripts/hotwire_spark.js index 87fa5fe..1286f76 100644 --- a/app/assets/javascripts/hotwire_spark.js +++ b/app/assets/javascripts/hotwire_spark.js @@ -310,7 +310,7 @@ var HotwireSpark = (function () { } }; - const extend$1 = function(object, properties) { + const extend = function(object, properties) { if (properties != null) { for (let key in properties) { const value = properties[key]; @@ -324,7 +324,7 @@ var HotwireSpark = (function () { constructor(consumer, params = {}, mixin) { this.consumer = consumer; this.identifier = JSON.stringify(params); - extend$1(this, mixin); + extend(this, mixin); } perform(action, data = {}) { data.action = action; @@ -1395,2134 +1395,6 @@ var HotwireSpark = (function () { } } - /* - Stimulus 3.2.1 - Copyright © 2023 Basecamp, LLC - */ - class EventListener { - constructor(eventTarget, eventName, eventOptions) { - this.eventTarget = eventTarget; - this.eventName = eventName; - this.eventOptions = eventOptions; - this.unorderedBindings = new Set(); - } - connect() { - this.eventTarget.addEventListener(this.eventName, this, this.eventOptions); - } - disconnect() { - this.eventTarget.removeEventListener(this.eventName, this, this.eventOptions); - } - bindingConnected(binding) { - this.unorderedBindings.add(binding); - } - bindingDisconnected(binding) { - this.unorderedBindings.delete(binding); - } - handleEvent(event) { - const extendedEvent = extendEvent(event); - for (const binding of this.bindings) { - if (extendedEvent.immediatePropagationStopped) { - break; - } - else { - binding.handleEvent(extendedEvent); - } - } - } - hasBindings() { - return this.unorderedBindings.size > 0; - } - get bindings() { - return Array.from(this.unorderedBindings).sort((left, right) => { - const leftIndex = left.index, rightIndex = right.index; - return leftIndex < rightIndex ? -1 : leftIndex > rightIndex ? 1 : 0; - }); - } - } - function extendEvent(event) { - if ("immediatePropagationStopped" in event) { - return event; - } - else { - const { stopImmediatePropagation } = event; - return Object.assign(event, { - immediatePropagationStopped: false, - stopImmediatePropagation() { - this.immediatePropagationStopped = true; - stopImmediatePropagation.call(this); - }, - }); - } - } - - class Dispatcher { - constructor(application) { - this.application = application; - this.eventListenerMaps = new Map(); - this.started = false; - } - start() { - if (!this.started) { - this.started = true; - this.eventListeners.forEach((eventListener) => eventListener.connect()); - } - } - stop() { - if (this.started) { - this.started = false; - this.eventListeners.forEach((eventListener) => eventListener.disconnect()); - } - } - get eventListeners() { - return Array.from(this.eventListenerMaps.values()).reduce((listeners, map) => listeners.concat(Array.from(map.values())), []); - } - bindingConnected(binding) { - this.fetchEventListenerForBinding(binding).bindingConnected(binding); - } - bindingDisconnected(binding, clearEventListeners = false) { - this.fetchEventListenerForBinding(binding).bindingDisconnected(binding); - if (clearEventListeners) - this.clearEventListenersForBinding(binding); - } - handleError(error, message, detail = {}) { - this.application.handleError(error, `Error ${message}`, detail); - } - clearEventListenersForBinding(binding) { - const eventListener = this.fetchEventListenerForBinding(binding); - if (!eventListener.hasBindings()) { - eventListener.disconnect(); - this.removeMappedEventListenerFor(binding); - } - } - removeMappedEventListenerFor(binding) { - const { eventTarget, eventName, eventOptions } = binding; - const eventListenerMap = this.fetchEventListenerMapForEventTarget(eventTarget); - const cacheKey = this.cacheKey(eventName, eventOptions); - eventListenerMap.delete(cacheKey); - if (eventListenerMap.size == 0) - this.eventListenerMaps.delete(eventTarget); - } - fetchEventListenerForBinding(binding) { - const { eventTarget, eventName, eventOptions } = binding; - return this.fetchEventListener(eventTarget, eventName, eventOptions); - } - fetchEventListener(eventTarget, eventName, eventOptions) { - const eventListenerMap = this.fetchEventListenerMapForEventTarget(eventTarget); - const cacheKey = this.cacheKey(eventName, eventOptions); - let eventListener = eventListenerMap.get(cacheKey); - if (!eventListener) { - eventListener = this.createEventListener(eventTarget, eventName, eventOptions); - eventListenerMap.set(cacheKey, eventListener); - } - return eventListener; - } - createEventListener(eventTarget, eventName, eventOptions) { - const eventListener = new EventListener(eventTarget, eventName, eventOptions); - if (this.started) { - eventListener.connect(); - } - return eventListener; - } - fetchEventListenerMapForEventTarget(eventTarget) { - let eventListenerMap = this.eventListenerMaps.get(eventTarget); - if (!eventListenerMap) { - eventListenerMap = new Map(); - this.eventListenerMaps.set(eventTarget, eventListenerMap); - } - return eventListenerMap; - } - cacheKey(eventName, eventOptions) { - const parts = [eventName]; - Object.keys(eventOptions) - .sort() - .forEach((key) => { - parts.push(`${eventOptions[key] ? "" : "!"}${key}`); - }); - return parts.join(":"); - } - } - - const defaultActionDescriptorFilters = { - stop({ event, value }) { - if (value) - event.stopPropagation(); - return true; - }, - prevent({ event, value }) { - if (value) - event.preventDefault(); - return true; - }, - self({ event, value, element }) { - if (value) { - return element === event.target; - } - else { - return true; - } - }, - }; - const descriptorPattern = /^(?:(?:([^.]+?)\+)?(.+?)(?:\.(.+?))?(?:@(window|document))?->)?(.+?)(?:#([^:]+?))(?::(.+))?$/; - function parseActionDescriptorString(descriptorString) { - const source = descriptorString.trim(); - const matches = source.match(descriptorPattern) || []; - let eventName = matches[2]; - let keyFilter = matches[3]; - if (keyFilter && !["keydown", "keyup", "keypress"].includes(eventName)) { - eventName += `.${keyFilter}`; - keyFilter = ""; - } - return { - eventTarget: parseEventTarget(matches[4]), - eventName, - eventOptions: matches[7] ? parseEventOptions(matches[7]) : {}, - identifier: matches[5], - methodName: matches[6], - keyFilter: matches[1] || keyFilter, - }; - } - function parseEventTarget(eventTargetName) { - if (eventTargetName == "window") { - return window; - } - else if (eventTargetName == "document") { - return document; - } - } - function parseEventOptions(eventOptions) { - return eventOptions - .split(":") - .reduce((options, token) => Object.assign(options, { [token.replace(/^!/, "")]: !/^!/.test(token) }), {}); - } - function stringifyEventTarget(eventTarget) { - if (eventTarget == window) { - return "window"; - } - else if (eventTarget == document) { - return "document"; - } - } - - function camelize(value) { - return value.replace(/(?:[_-])([a-z0-9])/g, (_, char) => char.toUpperCase()); - } - function namespaceCamelize(value) { - return camelize(value.replace(/--/g, "-").replace(/__/g, "_")); - } - function capitalize(value) { - return value.charAt(0).toUpperCase() + value.slice(1); - } - function dasherize(value) { - return value.replace(/([A-Z])/g, (_, char) => `-${char.toLowerCase()}`); - } - function tokenize(value) { - return value.match(/[^\s]+/g) || []; - } - function hasProperty(object, property) { - return Object.prototype.hasOwnProperty.call(object, property); - } - - const allModifiers = ["meta", "ctrl", "alt", "shift"]; - class Action { - constructor(element, index, descriptor, schema) { - this.element = element; - this.index = index; - this.eventTarget = descriptor.eventTarget || element; - this.eventName = descriptor.eventName || getDefaultEventNameForElement(element) || error("missing event name"); - this.eventOptions = descriptor.eventOptions || {}; - this.identifier = descriptor.identifier || error("missing identifier"); - this.methodName = descriptor.methodName || error("missing method name"); - this.keyFilter = descriptor.keyFilter || ""; - this.schema = schema; - } - static forToken(token, schema) { - return new this(token.element, token.index, parseActionDescriptorString(token.content), schema); - } - toString() { - const eventFilter = this.keyFilter ? `.${this.keyFilter}` : ""; - const eventTarget = this.eventTargetName ? `@${this.eventTargetName}` : ""; - return `${this.eventName}${eventFilter}${eventTarget}->${this.identifier}#${this.methodName}`; - } - shouldIgnoreKeyboardEvent(event) { - if (!this.keyFilter) { - return false; - } - const filters = this.keyFilter.split("+"); - if (this.keyFilterDissatisfied(event, filters)) { - return true; - } - const standardFilter = filters.filter((key) => !allModifiers.includes(key))[0]; - if (!standardFilter) { - return false; - } - if (!hasProperty(this.keyMappings, standardFilter)) { - error(`contains unknown key filter: ${this.keyFilter}`); - } - return this.keyMappings[standardFilter].toLowerCase() !== event.key.toLowerCase(); - } - shouldIgnoreMouseEvent(event) { - if (!this.keyFilter) { - return false; - } - const filters = [this.keyFilter]; - if (this.keyFilterDissatisfied(event, filters)) { - return true; - } - return false; - } - get params() { - const params = {}; - const pattern = new RegExp(`^data-${this.identifier}-(.+)-param$`, "i"); - for (const { name, value } of Array.from(this.element.attributes)) { - const match = name.match(pattern); - const key = match && match[1]; - if (key) { - params[camelize(key)] = typecast(value); - } - } - return params; - } - get eventTargetName() { - return stringifyEventTarget(this.eventTarget); - } - get keyMappings() { - return this.schema.keyMappings; - } - keyFilterDissatisfied(event, filters) { - const [meta, ctrl, alt, shift] = allModifiers.map((modifier) => filters.includes(modifier)); - return event.metaKey !== meta || event.ctrlKey !== ctrl || event.altKey !== alt || event.shiftKey !== shift; - } - } - const defaultEventNames = { - a: () => "click", - button: () => "click", - form: () => "submit", - details: () => "toggle", - input: (e) => (e.getAttribute("type") == "submit" ? "click" : "input"), - select: () => "change", - textarea: () => "input", - }; - function getDefaultEventNameForElement(element) { - const tagName = element.tagName.toLowerCase(); - if (tagName in defaultEventNames) { - return defaultEventNames[tagName](element); - } - } - function error(message) { - throw new Error(message); - } - function typecast(value) { - try { - return JSON.parse(value); - } - catch (o_O) { - return value; - } - } - - class Binding { - constructor(context, action) { - this.context = context; - this.action = action; - } - get index() { - return this.action.index; - } - get eventTarget() { - return this.action.eventTarget; - } - get eventOptions() { - return this.action.eventOptions; - } - get identifier() { - return this.context.identifier; - } - handleEvent(event) { - const actionEvent = this.prepareActionEvent(event); - if (this.willBeInvokedByEvent(event) && this.applyEventModifiers(actionEvent)) { - this.invokeWithEvent(actionEvent); - } - } - get eventName() { - return this.action.eventName; - } - get method() { - const method = this.controller[this.methodName]; - if (typeof method == "function") { - return method; - } - throw new Error(`Action "${this.action}" references undefined method "${this.methodName}"`); - } - applyEventModifiers(event) { - const { element } = this.action; - const { actionDescriptorFilters } = this.context.application; - const { controller } = this.context; - let passes = true; - for (const [name, value] of Object.entries(this.eventOptions)) { - if (name in actionDescriptorFilters) { - const filter = actionDescriptorFilters[name]; - passes = passes && filter({ name, value, event, element, controller }); - } - else { - continue; - } - } - return passes; - } - prepareActionEvent(event) { - return Object.assign(event, { params: this.action.params }); - } - invokeWithEvent(event) { - const { target, currentTarget } = event; - try { - this.method.call(this.controller, event); - this.context.logDebugActivity(this.methodName, { event, target, currentTarget, action: this.methodName }); - } - catch (error) { - const { identifier, controller, element, index } = this; - const detail = { identifier, controller, element, index, event }; - this.context.handleError(error, `invoking action "${this.action}"`, detail); - } - } - willBeInvokedByEvent(event) { - const eventTarget = event.target; - if (event instanceof KeyboardEvent && this.action.shouldIgnoreKeyboardEvent(event)) { - return false; - } - if (event instanceof MouseEvent && this.action.shouldIgnoreMouseEvent(event)) { - return false; - } - if (this.element === eventTarget) { - return true; - } - else if (eventTarget instanceof Element && this.element.contains(eventTarget)) { - return this.scope.containsElement(eventTarget); - } - else { - return this.scope.containsElement(this.action.element); - } - } - get controller() { - return this.context.controller; - } - get methodName() { - return this.action.methodName; - } - get element() { - return this.scope.element; - } - get scope() { - return this.context.scope; - } - } - - class ElementObserver { - constructor(element, delegate) { - this.mutationObserverInit = { attributes: true, childList: true, subtree: true }; - this.element = element; - this.started = false; - this.delegate = delegate; - this.elements = new Set(); - this.mutationObserver = new MutationObserver((mutations) => this.processMutations(mutations)); - } - start() { - if (!this.started) { - this.started = true; - this.mutationObserver.observe(this.element, this.mutationObserverInit); - this.refresh(); - } - } - pause(callback) { - if (this.started) { - this.mutationObserver.disconnect(); - this.started = false; - } - callback(); - if (!this.started) { - this.mutationObserver.observe(this.element, this.mutationObserverInit); - this.started = true; - } - } - stop() { - if (this.started) { - this.mutationObserver.takeRecords(); - this.mutationObserver.disconnect(); - this.started = false; - } - } - refresh() { - if (this.started) { - const matches = new Set(this.matchElementsInTree()); - for (const element of Array.from(this.elements)) { - if (!matches.has(element)) { - this.removeElement(element); - } - } - for (const element of Array.from(matches)) { - this.addElement(element); - } - } - } - processMutations(mutations) { - if (this.started) { - for (const mutation of mutations) { - this.processMutation(mutation); - } - } - } - processMutation(mutation) { - if (mutation.type == "attributes") { - this.processAttributeChange(mutation.target, mutation.attributeName); - } - else if (mutation.type == "childList") { - this.processRemovedNodes(mutation.removedNodes); - this.processAddedNodes(mutation.addedNodes); - } - } - processAttributeChange(element, attributeName) { - if (this.elements.has(element)) { - if (this.delegate.elementAttributeChanged && this.matchElement(element)) { - this.delegate.elementAttributeChanged(element, attributeName); - } - else { - this.removeElement(element); - } - } - else if (this.matchElement(element)) { - this.addElement(element); - } - } - processRemovedNodes(nodes) { - for (const node of Array.from(nodes)) { - const element = this.elementFromNode(node); - if (element) { - this.processTree(element, this.removeElement); - } - } - } - processAddedNodes(nodes) { - for (const node of Array.from(nodes)) { - const element = this.elementFromNode(node); - if (element && this.elementIsActive(element)) { - this.processTree(element, this.addElement); - } - } - } - matchElement(element) { - return this.delegate.matchElement(element); - } - matchElementsInTree(tree = this.element) { - return this.delegate.matchElementsInTree(tree); - } - processTree(tree, processor) { - for (const element of this.matchElementsInTree(tree)) { - processor.call(this, element); - } - } - elementFromNode(node) { - if (node.nodeType == Node.ELEMENT_NODE) { - return node; - } - } - elementIsActive(element) { - if (element.isConnected != this.element.isConnected) { - return false; - } - else { - return this.element.contains(element); - } - } - addElement(element) { - if (!this.elements.has(element)) { - if (this.elementIsActive(element)) { - this.elements.add(element); - if (this.delegate.elementMatched) { - this.delegate.elementMatched(element); - } - } - } - } - removeElement(element) { - if (this.elements.has(element)) { - this.elements.delete(element); - if (this.delegate.elementUnmatched) { - this.delegate.elementUnmatched(element); - } - } - } - } - - class AttributeObserver { - constructor(element, attributeName, delegate) { - this.attributeName = attributeName; - this.delegate = delegate; - this.elementObserver = new ElementObserver(element, this); - } - get element() { - return this.elementObserver.element; - } - get selector() { - return `[${this.attributeName}]`; - } - start() { - this.elementObserver.start(); - } - pause(callback) { - this.elementObserver.pause(callback); - } - stop() { - this.elementObserver.stop(); - } - refresh() { - this.elementObserver.refresh(); - } - get started() { - return this.elementObserver.started; - } - matchElement(element) { - return element.hasAttribute(this.attributeName); - } - matchElementsInTree(tree) { - const match = this.matchElement(tree) ? [tree] : []; - const matches = Array.from(tree.querySelectorAll(this.selector)); - return match.concat(matches); - } - elementMatched(element) { - if (this.delegate.elementMatchedAttribute) { - this.delegate.elementMatchedAttribute(element, this.attributeName); - } - } - elementUnmatched(element) { - if (this.delegate.elementUnmatchedAttribute) { - this.delegate.elementUnmatchedAttribute(element, this.attributeName); - } - } - elementAttributeChanged(element, attributeName) { - if (this.delegate.elementAttributeValueChanged && this.attributeName == attributeName) { - this.delegate.elementAttributeValueChanged(element, attributeName); - } - } - } - - function add(map, key, value) { - fetch$1(map, key).add(value); - } - function del(map, key, value) { - fetch$1(map, key).delete(value); - prune(map, key); - } - function fetch$1(map, key) { - let values = map.get(key); - if (!values) { - values = new Set(); - map.set(key, values); - } - return values; - } - function prune(map, key) { - const values = map.get(key); - if (values != null && values.size == 0) { - map.delete(key); - } - } - - class Multimap { - constructor() { - this.valuesByKey = new Map(); - } - get keys() { - return Array.from(this.valuesByKey.keys()); - } - get values() { - const sets = Array.from(this.valuesByKey.values()); - return sets.reduce((values, set) => values.concat(Array.from(set)), []); - } - get size() { - const sets = Array.from(this.valuesByKey.values()); - return sets.reduce((size, set) => size + set.size, 0); - } - add(key, value) { - add(this.valuesByKey, key, value); - } - delete(key, value) { - del(this.valuesByKey, key, value); - } - has(key, value) { - const values = this.valuesByKey.get(key); - return values != null && values.has(value); - } - hasKey(key) { - return this.valuesByKey.has(key); - } - hasValue(value) { - const sets = Array.from(this.valuesByKey.values()); - return sets.some((set) => set.has(value)); - } - getValuesForKey(key) { - const values = this.valuesByKey.get(key); - return values ? Array.from(values) : []; - } - getKeysForValue(value) { - return Array.from(this.valuesByKey) - .filter(([_key, values]) => values.has(value)) - .map(([key, _values]) => key); - } - } - - class SelectorObserver { - constructor(element, selector, delegate, details) { - this._selector = selector; - this.details = details; - this.elementObserver = new ElementObserver(element, this); - this.delegate = delegate; - this.matchesByElement = new Multimap(); - } - get started() { - return this.elementObserver.started; - } - get selector() { - return this._selector; - } - set selector(selector) { - this._selector = selector; - this.refresh(); - } - start() { - this.elementObserver.start(); - } - pause(callback) { - this.elementObserver.pause(callback); - } - stop() { - this.elementObserver.stop(); - } - refresh() { - this.elementObserver.refresh(); - } - get element() { - return this.elementObserver.element; - } - matchElement(element) { - const { selector } = this; - if (selector) { - const matches = element.matches(selector); - if (this.delegate.selectorMatchElement) { - return matches && this.delegate.selectorMatchElement(element, this.details); - } - return matches; - } - else { - return false; - } - } - matchElementsInTree(tree) { - const { selector } = this; - if (selector) { - const match = this.matchElement(tree) ? [tree] : []; - const matches = Array.from(tree.querySelectorAll(selector)).filter((match) => this.matchElement(match)); - return match.concat(matches); - } - else { - return []; - } - } - elementMatched(element) { - const { selector } = this; - if (selector) { - this.selectorMatched(element, selector); - } - } - elementUnmatched(element) { - const selectors = this.matchesByElement.getKeysForValue(element); - for (const selector of selectors) { - this.selectorUnmatched(element, selector); - } - } - elementAttributeChanged(element, _attributeName) { - const { selector } = this; - if (selector) { - const matches = this.matchElement(element); - const matchedBefore = this.matchesByElement.has(selector, element); - if (matches && !matchedBefore) { - this.selectorMatched(element, selector); - } - else if (!matches && matchedBefore) { - this.selectorUnmatched(element, selector); - } - } - } - selectorMatched(element, selector) { - this.delegate.selectorMatched(element, selector, this.details); - this.matchesByElement.add(selector, element); - } - selectorUnmatched(element, selector) { - this.delegate.selectorUnmatched(element, selector, this.details); - this.matchesByElement.delete(selector, element); - } - } - - class StringMapObserver { - constructor(element, delegate) { - this.element = element; - this.delegate = delegate; - this.started = false; - this.stringMap = new Map(); - this.mutationObserver = new MutationObserver((mutations) => this.processMutations(mutations)); - } - start() { - if (!this.started) { - this.started = true; - this.mutationObserver.observe(this.element, { attributes: true, attributeOldValue: true }); - this.refresh(); - } - } - stop() { - if (this.started) { - this.mutationObserver.takeRecords(); - this.mutationObserver.disconnect(); - this.started = false; - } - } - refresh() { - if (this.started) { - for (const attributeName of this.knownAttributeNames) { - this.refreshAttribute(attributeName, null); - } - } - } - processMutations(mutations) { - if (this.started) { - for (const mutation of mutations) { - this.processMutation(mutation); - } - } - } - processMutation(mutation) { - const attributeName = mutation.attributeName; - if (attributeName) { - this.refreshAttribute(attributeName, mutation.oldValue); - } - } - refreshAttribute(attributeName, oldValue) { - const key = this.delegate.getStringMapKeyForAttribute(attributeName); - if (key != null) { - if (!this.stringMap.has(attributeName)) { - this.stringMapKeyAdded(key, attributeName); - } - const value = this.element.getAttribute(attributeName); - if (this.stringMap.get(attributeName) != value) { - this.stringMapValueChanged(value, key, oldValue); - } - if (value == null) { - const oldValue = this.stringMap.get(attributeName); - this.stringMap.delete(attributeName); - if (oldValue) - this.stringMapKeyRemoved(key, attributeName, oldValue); - } - else { - this.stringMap.set(attributeName, value); - } - } - } - stringMapKeyAdded(key, attributeName) { - if (this.delegate.stringMapKeyAdded) { - this.delegate.stringMapKeyAdded(key, attributeName); - } - } - stringMapValueChanged(value, key, oldValue) { - if (this.delegate.stringMapValueChanged) { - this.delegate.stringMapValueChanged(value, key, oldValue); - } - } - stringMapKeyRemoved(key, attributeName, oldValue) { - if (this.delegate.stringMapKeyRemoved) { - this.delegate.stringMapKeyRemoved(key, attributeName, oldValue); - } - } - get knownAttributeNames() { - return Array.from(new Set(this.currentAttributeNames.concat(this.recordedAttributeNames))); - } - get currentAttributeNames() { - return Array.from(this.element.attributes).map((attribute) => attribute.name); - } - get recordedAttributeNames() { - return Array.from(this.stringMap.keys()); - } - } - - class TokenListObserver { - constructor(element, attributeName, delegate) { - this.attributeObserver = new AttributeObserver(element, attributeName, this); - this.delegate = delegate; - this.tokensByElement = new Multimap(); - } - get started() { - return this.attributeObserver.started; - } - start() { - this.attributeObserver.start(); - } - pause(callback) { - this.attributeObserver.pause(callback); - } - stop() { - this.attributeObserver.stop(); - } - refresh() { - this.attributeObserver.refresh(); - } - get element() { - return this.attributeObserver.element; - } - get attributeName() { - return this.attributeObserver.attributeName; - } - elementMatchedAttribute(element) { - this.tokensMatched(this.readTokensForElement(element)); - } - elementAttributeValueChanged(element) { - const [unmatchedTokens, matchedTokens] = this.refreshTokensForElement(element); - this.tokensUnmatched(unmatchedTokens); - this.tokensMatched(matchedTokens); - } - elementUnmatchedAttribute(element) { - this.tokensUnmatched(this.tokensByElement.getValuesForKey(element)); - } - tokensMatched(tokens) { - tokens.forEach((token) => this.tokenMatched(token)); - } - tokensUnmatched(tokens) { - tokens.forEach((token) => this.tokenUnmatched(token)); - } - tokenMatched(token) { - this.delegate.tokenMatched(token); - this.tokensByElement.add(token.element, token); - } - tokenUnmatched(token) { - this.delegate.tokenUnmatched(token); - this.tokensByElement.delete(token.element, token); - } - refreshTokensForElement(element) { - const previousTokens = this.tokensByElement.getValuesForKey(element); - const currentTokens = this.readTokensForElement(element); - const firstDifferingIndex = zip(previousTokens, currentTokens).findIndex(([previousToken, currentToken]) => !tokensAreEqual(previousToken, currentToken)); - if (firstDifferingIndex == -1) { - return [[], []]; - } - else { - return [previousTokens.slice(firstDifferingIndex), currentTokens.slice(firstDifferingIndex)]; - } - } - readTokensForElement(element) { - const attributeName = this.attributeName; - const tokenString = element.getAttribute(attributeName) || ""; - return parseTokenString(tokenString, element, attributeName); - } - } - function parseTokenString(tokenString, element, attributeName) { - return tokenString - .trim() - .split(/\s+/) - .filter((content) => content.length) - .map((content, index) => ({ element, attributeName, content, index })); - } - function zip(left, right) { - const length = Math.max(left.length, right.length); - return Array.from({ length }, (_, index) => [left[index], right[index]]); - } - function tokensAreEqual(left, right) { - return left && right && left.index == right.index && left.content == right.content; - } - - class ValueListObserver { - constructor(element, attributeName, delegate) { - this.tokenListObserver = new TokenListObserver(element, attributeName, this); - this.delegate = delegate; - this.parseResultsByToken = new WeakMap(); - this.valuesByTokenByElement = new WeakMap(); - } - get started() { - return this.tokenListObserver.started; - } - start() { - this.tokenListObserver.start(); - } - stop() { - this.tokenListObserver.stop(); - } - refresh() { - this.tokenListObserver.refresh(); - } - get element() { - return this.tokenListObserver.element; - } - get attributeName() { - return this.tokenListObserver.attributeName; - } - tokenMatched(token) { - const { element } = token; - const { value } = this.fetchParseResultForToken(token); - if (value) { - this.fetchValuesByTokenForElement(element).set(token, value); - this.delegate.elementMatchedValue(element, value); - } - } - tokenUnmatched(token) { - const { element } = token; - const { value } = this.fetchParseResultForToken(token); - if (value) { - this.fetchValuesByTokenForElement(element).delete(token); - this.delegate.elementUnmatchedValue(element, value); - } - } - fetchParseResultForToken(token) { - let parseResult = this.parseResultsByToken.get(token); - if (!parseResult) { - parseResult = this.parseToken(token); - this.parseResultsByToken.set(token, parseResult); - } - return parseResult; - } - fetchValuesByTokenForElement(element) { - let valuesByToken = this.valuesByTokenByElement.get(element); - if (!valuesByToken) { - valuesByToken = new Map(); - this.valuesByTokenByElement.set(element, valuesByToken); - } - return valuesByToken; - } - parseToken(token) { - try { - const value = this.delegate.parseValueForToken(token); - return { value }; - } - catch (error) { - return { error }; - } - } - } - - class BindingObserver { - constructor(context, delegate) { - this.context = context; - this.delegate = delegate; - this.bindingsByAction = new Map(); - } - start() { - if (!this.valueListObserver) { - this.valueListObserver = new ValueListObserver(this.element, this.actionAttribute, this); - this.valueListObserver.start(); - } - } - stop() { - if (this.valueListObserver) { - this.valueListObserver.stop(); - delete this.valueListObserver; - this.disconnectAllActions(); - } - } - get element() { - return this.context.element; - } - get identifier() { - return this.context.identifier; - } - get actionAttribute() { - return this.schema.actionAttribute; - } - get schema() { - return this.context.schema; - } - get bindings() { - return Array.from(this.bindingsByAction.values()); - } - connectAction(action) { - const binding = new Binding(this.context, action); - this.bindingsByAction.set(action, binding); - this.delegate.bindingConnected(binding); - } - disconnectAction(action) { - const binding = this.bindingsByAction.get(action); - if (binding) { - this.bindingsByAction.delete(action); - this.delegate.bindingDisconnected(binding); - } - } - disconnectAllActions() { - this.bindings.forEach((binding) => this.delegate.bindingDisconnected(binding, true)); - this.bindingsByAction.clear(); - } - parseValueForToken(token) { - const action = Action.forToken(token, this.schema); - if (action.identifier == this.identifier) { - return action; - } - } - elementMatchedValue(element, action) { - this.connectAction(action); - } - elementUnmatchedValue(element, action) { - this.disconnectAction(action); - } - } - - class ValueObserver { - constructor(context, receiver) { - this.context = context; - this.receiver = receiver; - this.stringMapObserver = new StringMapObserver(this.element, this); - this.valueDescriptorMap = this.controller.valueDescriptorMap; - } - start() { - this.stringMapObserver.start(); - this.invokeChangedCallbacksForDefaultValues(); - } - stop() { - this.stringMapObserver.stop(); - } - get element() { - return this.context.element; - } - get controller() { - return this.context.controller; - } - getStringMapKeyForAttribute(attributeName) { - if (attributeName in this.valueDescriptorMap) { - return this.valueDescriptorMap[attributeName].name; - } - } - stringMapKeyAdded(key, attributeName) { - const descriptor = this.valueDescriptorMap[attributeName]; - if (!this.hasValue(key)) { - this.invokeChangedCallback(key, descriptor.writer(this.receiver[key]), descriptor.writer(descriptor.defaultValue)); - } - } - stringMapValueChanged(value, name, oldValue) { - const descriptor = this.valueDescriptorNameMap[name]; - if (value === null) - return; - if (oldValue === null) { - oldValue = descriptor.writer(descriptor.defaultValue); - } - this.invokeChangedCallback(name, value, oldValue); - } - stringMapKeyRemoved(key, attributeName, oldValue) { - const descriptor = this.valueDescriptorNameMap[key]; - if (this.hasValue(key)) { - this.invokeChangedCallback(key, descriptor.writer(this.receiver[key]), oldValue); - } - else { - this.invokeChangedCallback(key, descriptor.writer(descriptor.defaultValue), oldValue); - } - } - invokeChangedCallbacksForDefaultValues() { - for (const { key, name, defaultValue, writer } of this.valueDescriptors) { - if (defaultValue != undefined && !this.controller.data.has(key)) { - this.invokeChangedCallback(name, writer(defaultValue), undefined); - } - } - } - invokeChangedCallback(name, rawValue, rawOldValue) { - const changedMethodName = `${name}Changed`; - const changedMethod = this.receiver[changedMethodName]; - if (typeof changedMethod == "function") { - const descriptor = this.valueDescriptorNameMap[name]; - try { - const value = descriptor.reader(rawValue); - let oldValue = rawOldValue; - if (rawOldValue) { - oldValue = descriptor.reader(rawOldValue); - } - changedMethod.call(this.receiver, value, oldValue); - } - catch (error) { - if (error instanceof TypeError) { - error.message = `Stimulus Value "${this.context.identifier}.${descriptor.name}" - ${error.message}`; - } - throw error; - } - } - } - get valueDescriptors() { - const { valueDescriptorMap } = this; - return Object.keys(valueDescriptorMap).map((key) => valueDescriptorMap[key]); - } - get valueDescriptorNameMap() { - const descriptors = {}; - Object.keys(this.valueDescriptorMap).forEach((key) => { - const descriptor = this.valueDescriptorMap[key]; - descriptors[descriptor.name] = descriptor; - }); - return descriptors; - } - hasValue(attributeName) { - const descriptor = this.valueDescriptorNameMap[attributeName]; - const hasMethodName = `has${capitalize(descriptor.name)}`; - return this.receiver[hasMethodName]; - } - } - - class TargetObserver { - constructor(context, delegate) { - this.context = context; - this.delegate = delegate; - this.targetsByName = new Multimap(); - } - start() { - if (!this.tokenListObserver) { - this.tokenListObserver = new TokenListObserver(this.element, this.attributeName, this); - this.tokenListObserver.start(); - } - } - stop() { - if (this.tokenListObserver) { - this.disconnectAllTargets(); - this.tokenListObserver.stop(); - delete this.tokenListObserver; - } - } - tokenMatched({ element, content: name }) { - if (this.scope.containsElement(element)) { - this.connectTarget(element, name); - } - } - tokenUnmatched({ element, content: name }) { - this.disconnectTarget(element, name); - } - connectTarget(element, name) { - var _a; - if (!this.targetsByName.has(name, element)) { - this.targetsByName.add(name, element); - (_a = this.tokenListObserver) === null || _a === void 0 ? void 0 : _a.pause(() => this.delegate.targetConnected(element, name)); - } - } - disconnectTarget(element, name) { - var _a; - if (this.targetsByName.has(name, element)) { - this.targetsByName.delete(name, element); - (_a = this.tokenListObserver) === null || _a === void 0 ? void 0 : _a.pause(() => this.delegate.targetDisconnected(element, name)); - } - } - disconnectAllTargets() { - for (const name of this.targetsByName.keys) { - for (const element of this.targetsByName.getValuesForKey(name)) { - this.disconnectTarget(element, name); - } - } - } - get attributeName() { - return `data-${this.context.identifier}-target`; - } - get element() { - return this.context.element; - } - get scope() { - return this.context.scope; - } - } - - function readInheritableStaticArrayValues(constructor, propertyName) { - const ancestors = getAncestorsForConstructor(constructor); - return Array.from(ancestors.reduce((values, constructor) => { - getOwnStaticArrayValues(constructor, propertyName).forEach((name) => values.add(name)); - return values; - }, new Set())); - } - function getAncestorsForConstructor(constructor) { - const ancestors = []; - while (constructor) { - ancestors.push(constructor); - constructor = Object.getPrototypeOf(constructor); - } - return ancestors.reverse(); - } - function getOwnStaticArrayValues(constructor, propertyName) { - const definition = constructor[propertyName]; - return Array.isArray(definition) ? definition : []; - } - - class OutletObserver { - constructor(context, delegate) { - this.started = false; - this.context = context; - this.delegate = delegate; - this.outletsByName = new Multimap(); - this.outletElementsByName = new Multimap(); - this.selectorObserverMap = new Map(); - this.attributeObserverMap = new Map(); - } - start() { - if (!this.started) { - this.outletDefinitions.forEach((outletName) => { - this.setupSelectorObserverForOutlet(outletName); - this.setupAttributeObserverForOutlet(outletName); - }); - this.started = true; - this.dependentContexts.forEach((context) => context.refresh()); - } - } - refresh() { - this.selectorObserverMap.forEach((observer) => observer.refresh()); - this.attributeObserverMap.forEach((observer) => observer.refresh()); - } - stop() { - if (this.started) { - this.started = false; - this.disconnectAllOutlets(); - this.stopSelectorObservers(); - this.stopAttributeObservers(); - } - } - stopSelectorObservers() { - if (this.selectorObserverMap.size > 0) { - this.selectorObserverMap.forEach((observer) => observer.stop()); - this.selectorObserverMap.clear(); - } - } - stopAttributeObservers() { - if (this.attributeObserverMap.size > 0) { - this.attributeObserverMap.forEach((observer) => observer.stop()); - this.attributeObserverMap.clear(); - } - } - selectorMatched(element, _selector, { outletName }) { - const outlet = this.getOutlet(element, outletName); - if (outlet) { - this.connectOutlet(outlet, element, outletName); - } - } - selectorUnmatched(element, _selector, { outletName }) { - const outlet = this.getOutletFromMap(element, outletName); - if (outlet) { - this.disconnectOutlet(outlet, element, outletName); - } - } - selectorMatchElement(element, { outletName }) { - const selector = this.selector(outletName); - const hasOutlet = this.hasOutlet(element, outletName); - const hasOutletController = element.matches(`[${this.schema.controllerAttribute}~=${outletName}]`); - if (selector) { - return hasOutlet && hasOutletController && element.matches(selector); - } - else { - return false; - } - } - elementMatchedAttribute(_element, attributeName) { - const outletName = this.getOutletNameFromOutletAttributeName(attributeName); - if (outletName) { - this.updateSelectorObserverForOutlet(outletName); - } - } - elementAttributeValueChanged(_element, attributeName) { - const outletName = this.getOutletNameFromOutletAttributeName(attributeName); - if (outletName) { - this.updateSelectorObserverForOutlet(outletName); - } - } - elementUnmatchedAttribute(_element, attributeName) { - const outletName = this.getOutletNameFromOutletAttributeName(attributeName); - if (outletName) { - this.updateSelectorObserverForOutlet(outletName); - } - } - connectOutlet(outlet, element, outletName) { - var _a; - if (!this.outletElementsByName.has(outletName, element)) { - this.outletsByName.add(outletName, outlet); - this.outletElementsByName.add(outletName, element); - (_a = this.selectorObserverMap.get(outletName)) === null || _a === void 0 ? void 0 : _a.pause(() => this.delegate.outletConnected(outlet, element, outletName)); - } - } - disconnectOutlet(outlet, element, outletName) { - var _a; - if (this.outletElementsByName.has(outletName, element)) { - this.outletsByName.delete(outletName, outlet); - this.outletElementsByName.delete(outletName, element); - (_a = this.selectorObserverMap - .get(outletName)) === null || _a === void 0 ? void 0 : _a.pause(() => this.delegate.outletDisconnected(outlet, element, outletName)); - } - } - disconnectAllOutlets() { - for (const outletName of this.outletElementsByName.keys) { - for (const element of this.outletElementsByName.getValuesForKey(outletName)) { - for (const outlet of this.outletsByName.getValuesForKey(outletName)) { - this.disconnectOutlet(outlet, element, outletName); - } - } - } - } - updateSelectorObserverForOutlet(outletName) { - const observer = this.selectorObserverMap.get(outletName); - if (observer) { - observer.selector = this.selector(outletName); - } - } - setupSelectorObserverForOutlet(outletName) { - const selector = this.selector(outletName); - const selectorObserver = new SelectorObserver(document.body, selector, this, { outletName }); - this.selectorObserverMap.set(outletName, selectorObserver); - selectorObserver.start(); - } - setupAttributeObserverForOutlet(outletName) { - const attributeName = this.attributeNameForOutletName(outletName); - const attributeObserver = new AttributeObserver(this.scope.element, attributeName, this); - this.attributeObserverMap.set(outletName, attributeObserver); - attributeObserver.start(); - } - selector(outletName) { - return this.scope.outlets.getSelectorForOutletName(outletName); - } - attributeNameForOutletName(outletName) { - return this.scope.schema.outletAttributeForScope(this.identifier, outletName); - } - getOutletNameFromOutletAttributeName(attributeName) { - return this.outletDefinitions.find((outletName) => this.attributeNameForOutletName(outletName) === attributeName); - } - get outletDependencies() { - const dependencies = new Multimap(); - this.router.modules.forEach((module) => { - const constructor = module.definition.controllerConstructor; - const outlets = readInheritableStaticArrayValues(constructor, "outlets"); - outlets.forEach((outlet) => dependencies.add(outlet, module.identifier)); - }); - return dependencies; - } - get outletDefinitions() { - return this.outletDependencies.getKeysForValue(this.identifier); - } - get dependentControllerIdentifiers() { - return this.outletDependencies.getValuesForKey(this.identifier); - } - get dependentContexts() { - const identifiers = this.dependentControllerIdentifiers; - return this.router.contexts.filter((context) => identifiers.includes(context.identifier)); - } - hasOutlet(element, outletName) { - return !!this.getOutlet(element, outletName) || !!this.getOutletFromMap(element, outletName); - } - getOutlet(element, outletName) { - return this.application.getControllerForElementAndIdentifier(element, outletName); - } - getOutletFromMap(element, outletName) { - return this.outletsByName.getValuesForKey(outletName).find((outlet) => outlet.element === element); - } - get scope() { - return this.context.scope; - } - get schema() { - return this.context.schema; - } - get identifier() { - return this.context.identifier; - } - get application() { - return this.context.application; - } - get router() { - return this.application.router; - } - } - - class Context { - constructor(module, scope) { - this.logDebugActivity = (functionName, detail = {}) => { - const { identifier, controller, element } = this; - detail = Object.assign({ identifier, controller, element }, detail); - this.application.logDebugActivity(this.identifier, functionName, detail); - }; - this.module = module; - this.scope = scope; - this.controller = new module.controllerConstructor(this); - this.bindingObserver = new BindingObserver(this, this.dispatcher); - this.valueObserver = new ValueObserver(this, this.controller); - this.targetObserver = new TargetObserver(this, this); - this.outletObserver = new OutletObserver(this, this); - try { - this.controller.initialize(); - this.logDebugActivity("initialize"); - } - catch (error) { - this.handleError(error, "initializing controller"); - } - } - connect() { - this.bindingObserver.start(); - this.valueObserver.start(); - this.targetObserver.start(); - this.outletObserver.start(); - try { - this.controller.connect(); - this.logDebugActivity("connect"); - } - catch (error) { - this.handleError(error, "connecting controller"); - } - } - refresh() { - this.outletObserver.refresh(); - } - disconnect() { - try { - this.controller.disconnect(); - this.logDebugActivity("disconnect"); - } - catch (error) { - this.handleError(error, "disconnecting controller"); - } - this.outletObserver.stop(); - this.targetObserver.stop(); - this.valueObserver.stop(); - this.bindingObserver.stop(); - } - get application() { - return this.module.application; - } - get identifier() { - return this.module.identifier; - } - get schema() { - return this.application.schema; - } - get dispatcher() { - return this.application.dispatcher; - } - get element() { - return this.scope.element; - } - get parentElement() { - return this.element.parentElement; - } - handleError(error, message, detail = {}) { - const { identifier, controller, element } = this; - detail = Object.assign({ identifier, controller, element }, detail); - this.application.handleError(error, `Error ${message}`, detail); - } - targetConnected(element, name) { - this.invokeControllerMethod(`${name}TargetConnected`, element); - } - targetDisconnected(element, name) { - this.invokeControllerMethod(`${name}TargetDisconnected`, element); - } - outletConnected(outlet, element, name) { - this.invokeControllerMethod(`${namespaceCamelize(name)}OutletConnected`, outlet, element); - } - outletDisconnected(outlet, element, name) { - this.invokeControllerMethod(`${namespaceCamelize(name)}OutletDisconnected`, outlet, element); - } - invokeControllerMethod(methodName, ...args) { - const controller = this.controller; - if (typeof controller[methodName] == "function") { - controller[methodName](...args); - } - } - } - - function bless(constructor) { - return shadow(constructor, getBlessedProperties(constructor)); - } - function shadow(constructor, properties) { - const shadowConstructor = extend(constructor); - const shadowProperties = getShadowProperties(constructor.prototype, properties); - Object.defineProperties(shadowConstructor.prototype, shadowProperties); - return shadowConstructor; - } - function getBlessedProperties(constructor) { - const blessings = readInheritableStaticArrayValues(constructor, "blessings"); - return blessings.reduce((blessedProperties, blessing) => { - const properties = blessing(constructor); - for (const key in properties) { - const descriptor = blessedProperties[key] || {}; - blessedProperties[key] = Object.assign(descriptor, properties[key]); - } - return blessedProperties; - }, {}); - } - function getShadowProperties(prototype, properties) { - return getOwnKeys(properties).reduce((shadowProperties, key) => { - const descriptor = getShadowedDescriptor(prototype, properties, key); - if (descriptor) { - Object.assign(shadowProperties, { [key]: descriptor }); - } - return shadowProperties; - }, {}); - } - function getShadowedDescriptor(prototype, properties, key) { - const shadowingDescriptor = Object.getOwnPropertyDescriptor(prototype, key); - const shadowedByValue = shadowingDescriptor && "value" in shadowingDescriptor; - if (!shadowedByValue) { - const descriptor = Object.getOwnPropertyDescriptor(properties, key).value; - if (shadowingDescriptor) { - descriptor.get = shadowingDescriptor.get || descriptor.get; - descriptor.set = shadowingDescriptor.set || descriptor.set; - } - return descriptor; - } - } - const getOwnKeys = (() => { - if (typeof Object.getOwnPropertySymbols == "function") { - return (object) => [...Object.getOwnPropertyNames(object), ...Object.getOwnPropertySymbols(object)]; - } - else { - return Object.getOwnPropertyNames; - } - })(); - const extend = (() => { - function extendWithReflect(constructor) { - function extended() { - return Reflect.construct(constructor, arguments, new.target); - } - extended.prototype = Object.create(constructor.prototype, { - constructor: { value: extended }, - }); - Reflect.setPrototypeOf(extended, constructor); - return extended; - } - function testReflectExtension() { - const a = function () { - this.a.call(this); - }; - const b = extendWithReflect(a); - b.prototype.a = function () { }; - return new b(); - } - try { - testReflectExtension(); - return extendWithReflect; - } - catch (error) { - return (constructor) => class extended extends constructor { - }; - } - })(); - - function blessDefinition(definition) { - return { - identifier: definition.identifier, - controllerConstructor: bless(definition.controllerConstructor), - }; - } - - class Module { - constructor(application, definition) { - this.application = application; - this.definition = blessDefinition(definition); - this.contextsByScope = new WeakMap(); - this.connectedContexts = new Set(); - } - get identifier() { - return this.definition.identifier; - } - get controllerConstructor() { - return this.definition.controllerConstructor; - } - get contexts() { - return Array.from(this.connectedContexts); - } - connectContextForScope(scope) { - const context = this.fetchContextForScope(scope); - this.connectedContexts.add(context); - context.connect(); - } - disconnectContextForScope(scope) { - const context = this.contextsByScope.get(scope); - if (context) { - this.connectedContexts.delete(context); - context.disconnect(); - } - } - fetchContextForScope(scope) { - let context = this.contextsByScope.get(scope); - if (!context) { - context = new Context(this, scope); - this.contextsByScope.set(scope, context); - } - return context; - } - } - - class ClassMap { - constructor(scope) { - this.scope = scope; - } - has(name) { - return this.data.has(this.getDataKey(name)); - } - get(name) { - return this.getAll(name)[0]; - } - getAll(name) { - const tokenString = this.data.get(this.getDataKey(name)) || ""; - return tokenize(tokenString); - } - getAttributeName(name) { - return this.data.getAttributeNameForKey(this.getDataKey(name)); - } - getDataKey(name) { - return `${name}-class`; - } - get data() { - return this.scope.data; - } - } - - class DataMap { - constructor(scope) { - this.scope = scope; - } - get element() { - return this.scope.element; - } - get identifier() { - return this.scope.identifier; - } - get(key) { - const name = this.getAttributeNameForKey(key); - return this.element.getAttribute(name); - } - set(key, value) { - const name = this.getAttributeNameForKey(key); - this.element.setAttribute(name, value); - return this.get(key); - } - has(key) { - const name = this.getAttributeNameForKey(key); - return this.element.hasAttribute(name); - } - delete(key) { - if (this.has(key)) { - const name = this.getAttributeNameForKey(key); - this.element.removeAttribute(name); - return true; - } - else { - return false; - } - } - getAttributeNameForKey(key) { - return `data-${this.identifier}-${dasherize(key)}`; - } - } - - class Guide { - constructor(logger) { - this.warnedKeysByObject = new WeakMap(); - this.logger = logger; - } - warn(object, key, message) { - let warnedKeys = this.warnedKeysByObject.get(object); - if (!warnedKeys) { - warnedKeys = new Set(); - this.warnedKeysByObject.set(object, warnedKeys); - } - if (!warnedKeys.has(key)) { - warnedKeys.add(key); - this.logger.warn(message, object); - } - } - } - - function attributeValueContainsToken(attributeName, token) { - return `[${attributeName}~="${token}"]`; - } - - class TargetSet { - constructor(scope) { - this.scope = scope; - } - get element() { - return this.scope.element; - } - get identifier() { - return this.scope.identifier; - } - get schema() { - return this.scope.schema; - } - has(targetName) { - return this.find(targetName) != null; - } - find(...targetNames) { - return targetNames.reduce((target, targetName) => target || this.findTarget(targetName) || this.findLegacyTarget(targetName), undefined); - } - findAll(...targetNames) { - return targetNames.reduce((targets, targetName) => [ - ...targets, - ...this.findAllTargets(targetName), - ...this.findAllLegacyTargets(targetName), - ], []); - } - findTarget(targetName) { - const selector = this.getSelectorForTargetName(targetName); - return this.scope.findElement(selector); - } - findAllTargets(targetName) { - const selector = this.getSelectorForTargetName(targetName); - return this.scope.findAllElements(selector); - } - getSelectorForTargetName(targetName) { - const attributeName = this.schema.targetAttributeForScope(this.identifier); - return attributeValueContainsToken(attributeName, targetName); - } - findLegacyTarget(targetName) { - const selector = this.getLegacySelectorForTargetName(targetName); - return this.deprecate(this.scope.findElement(selector), targetName); - } - findAllLegacyTargets(targetName) { - const selector = this.getLegacySelectorForTargetName(targetName); - return this.scope.findAllElements(selector).map((element) => this.deprecate(element, targetName)); - } - getLegacySelectorForTargetName(targetName) { - const targetDescriptor = `${this.identifier}.${targetName}`; - return attributeValueContainsToken(this.schema.targetAttribute, targetDescriptor); - } - deprecate(element, targetName) { - if (element) { - const { identifier } = this; - const attributeName = this.schema.targetAttribute; - const revisedAttributeName = this.schema.targetAttributeForScope(identifier); - this.guide.warn(element, `target:${targetName}`, `Please replace ${attributeName}="${identifier}.${targetName}" with ${revisedAttributeName}="${targetName}". ` + - `The ${attributeName} attribute is deprecated and will be removed in a future version of Stimulus.`); - } - return element; - } - get guide() { - return this.scope.guide; - } - } - - class OutletSet { - constructor(scope, controllerElement) { - this.scope = scope; - this.controllerElement = controllerElement; - } - get element() { - return this.scope.element; - } - get identifier() { - return this.scope.identifier; - } - get schema() { - return this.scope.schema; - } - has(outletName) { - return this.find(outletName) != null; - } - find(...outletNames) { - return outletNames.reduce((outlet, outletName) => outlet || this.findOutlet(outletName), undefined); - } - findAll(...outletNames) { - return outletNames.reduce((outlets, outletName) => [...outlets, ...this.findAllOutlets(outletName)], []); - } - getSelectorForOutletName(outletName) { - const attributeName = this.schema.outletAttributeForScope(this.identifier, outletName); - return this.controllerElement.getAttribute(attributeName); - } - findOutlet(outletName) { - const selector = this.getSelectorForOutletName(outletName); - if (selector) - return this.findElement(selector, outletName); - } - findAllOutlets(outletName) { - const selector = this.getSelectorForOutletName(outletName); - return selector ? this.findAllElements(selector, outletName) : []; - } - findElement(selector, outletName) { - const elements = this.scope.queryElements(selector); - return elements.filter((element) => this.matchesElement(element, selector, outletName))[0]; - } - findAllElements(selector, outletName) { - const elements = this.scope.queryElements(selector); - return elements.filter((element) => this.matchesElement(element, selector, outletName)); - } - matchesElement(element, selector, outletName) { - const controllerAttribute = element.getAttribute(this.scope.schema.controllerAttribute) || ""; - return element.matches(selector) && controllerAttribute.split(" ").includes(outletName); - } - } - - class Scope { - constructor(schema, element, identifier, logger) { - this.targets = new TargetSet(this); - this.classes = new ClassMap(this); - this.data = new DataMap(this); - this.containsElement = (element) => { - return element.closest(this.controllerSelector) === this.element; - }; - this.schema = schema; - this.element = element; - this.identifier = identifier; - this.guide = new Guide(logger); - this.outlets = new OutletSet(this.documentScope, element); - } - findElement(selector) { - return this.element.matches(selector) ? this.element : this.queryElements(selector).find(this.containsElement); - } - findAllElements(selector) { - return [ - ...(this.element.matches(selector) ? [this.element] : []), - ...this.queryElements(selector).filter(this.containsElement), - ]; - } - queryElements(selector) { - return Array.from(this.element.querySelectorAll(selector)); - } - get controllerSelector() { - return attributeValueContainsToken(this.schema.controllerAttribute, this.identifier); - } - get isDocumentScope() { - return this.element === document.documentElement; - } - get documentScope() { - return this.isDocumentScope - ? this - : new Scope(this.schema, document.documentElement, this.identifier, this.guide.logger); - } - } - - class ScopeObserver { - constructor(element, schema, delegate) { - this.element = element; - this.schema = schema; - this.delegate = delegate; - this.valueListObserver = new ValueListObserver(this.element, this.controllerAttribute, this); - this.scopesByIdentifierByElement = new WeakMap(); - this.scopeReferenceCounts = new WeakMap(); - } - start() { - this.valueListObserver.start(); - } - stop() { - this.valueListObserver.stop(); - } - get controllerAttribute() { - return this.schema.controllerAttribute; - } - parseValueForToken(token) { - const { element, content: identifier } = token; - return this.parseValueForElementAndIdentifier(element, identifier); - } - parseValueForElementAndIdentifier(element, identifier) { - const scopesByIdentifier = this.fetchScopesByIdentifierForElement(element); - let scope = scopesByIdentifier.get(identifier); - if (!scope) { - scope = this.delegate.createScopeForElementAndIdentifier(element, identifier); - scopesByIdentifier.set(identifier, scope); - } - return scope; - } - elementMatchedValue(element, value) { - const referenceCount = (this.scopeReferenceCounts.get(value) || 0) + 1; - this.scopeReferenceCounts.set(value, referenceCount); - if (referenceCount == 1) { - this.delegate.scopeConnected(value); - } - } - elementUnmatchedValue(element, value) { - const referenceCount = this.scopeReferenceCounts.get(value); - if (referenceCount) { - this.scopeReferenceCounts.set(value, referenceCount - 1); - if (referenceCount == 1) { - this.delegate.scopeDisconnected(value); - } - } - } - fetchScopesByIdentifierForElement(element) { - let scopesByIdentifier = this.scopesByIdentifierByElement.get(element); - if (!scopesByIdentifier) { - scopesByIdentifier = new Map(); - this.scopesByIdentifierByElement.set(element, scopesByIdentifier); - } - return scopesByIdentifier; - } - } - - class Router { - constructor(application) { - this.application = application; - this.scopeObserver = new ScopeObserver(this.element, this.schema, this); - this.scopesByIdentifier = new Multimap(); - this.modulesByIdentifier = new Map(); - } - get element() { - return this.application.element; - } - get schema() { - return this.application.schema; - } - get logger() { - return this.application.logger; - } - get controllerAttribute() { - return this.schema.controllerAttribute; - } - get modules() { - return Array.from(this.modulesByIdentifier.values()); - } - get contexts() { - return this.modules.reduce((contexts, module) => contexts.concat(module.contexts), []); - } - start() { - this.scopeObserver.start(); - } - stop() { - this.scopeObserver.stop(); - } - loadDefinition(definition) { - this.unloadIdentifier(definition.identifier); - const module = new Module(this.application, definition); - this.connectModule(module); - const afterLoad = definition.controllerConstructor.afterLoad; - if (afterLoad) { - afterLoad.call(definition.controllerConstructor, definition.identifier, this.application); - } - } - unloadIdentifier(identifier) { - const module = this.modulesByIdentifier.get(identifier); - if (module) { - this.disconnectModule(module); - } - } - getContextForElementAndIdentifier(element, identifier) { - const module = this.modulesByIdentifier.get(identifier); - if (module) { - return module.contexts.find((context) => context.element == element); - } - } - proposeToConnectScopeForElementAndIdentifier(element, identifier) { - const scope = this.scopeObserver.parseValueForElementAndIdentifier(element, identifier); - if (scope) { - this.scopeObserver.elementMatchedValue(scope.element, scope); - } - else { - console.error(`Couldn't find or create scope for identifier: "${identifier}" and element:`, element); - } - } - handleError(error, message, detail) { - this.application.handleError(error, message, detail); - } - createScopeForElementAndIdentifier(element, identifier) { - return new Scope(this.schema, element, identifier, this.logger); - } - scopeConnected(scope) { - this.scopesByIdentifier.add(scope.identifier, scope); - const module = this.modulesByIdentifier.get(scope.identifier); - if (module) { - module.connectContextForScope(scope); - } - } - scopeDisconnected(scope) { - this.scopesByIdentifier.delete(scope.identifier, scope); - const module = this.modulesByIdentifier.get(scope.identifier); - if (module) { - module.disconnectContextForScope(scope); - } - } - connectModule(module) { - this.modulesByIdentifier.set(module.identifier, module); - const scopes = this.scopesByIdentifier.getValuesForKey(module.identifier); - scopes.forEach((scope) => module.connectContextForScope(scope)); - } - disconnectModule(module) { - this.modulesByIdentifier.delete(module.identifier); - const scopes = this.scopesByIdentifier.getValuesForKey(module.identifier); - scopes.forEach((scope) => module.disconnectContextForScope(scope)); - } - } - - const defaultSchema = { - controllerAttribute: "data-controller", - actionAttribute: "data-action", - targetAttribute: "data-target", - targetAttributeForScope: (identifier) => `data-${identifier}-target`, - outletAttributeForScope: (identifier, outlet) => `data-${identifier}-${outlet}-outlet`, - 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]))), - }; - function objectFromEntries(array) { - return array.reduce((memo, [k, v]) => (Object.assign(Object.assign({}, memo), { [k]: v })), {}); - } - - class Application { - constructor(element = document.documentElement, schema = defaultSchema) { - this.logger = console; - this.debug = false; - this.logDebugActivity = (identifier, functionName, detail = {}) => { - if (this.debug) { - this.logFormattedMessage(identifier, functionName, detail); - } - }; - this.element = element; - this.schema = schema; - this.dispatcher = new Dispatcher(this); - this.router = new Router(this); - this.actionDescriptorFilters = Object.assign({}, defaultActionDescriptorFilters); - } - static start(element, schema) { - const application = new this(element, schema); - application.start(); - return application; - } - async start() { - await domReady(); - this.logDebugActivity("application", "starting"); - this.dispatcher.start(); - this.router.start(); - this.logDebugActivity("application", "start"); - } - stop() { - this.logDebugActivity("application", "stopping"); - this.dispatcher.stop(); - this.router.stop(); - this.logDebugActivity("application", "stop"); - } - register(identifier, controllerConstructor) { - this.load({ identifier, controllerConstructor }); - } - registerActionOption(name, filter) { - this.actionDescriptorFilters[name] = filter; - } - load(head, ...rest) { - const definitions = Array.isArray(head) ? head : [head, ...rest]; - definitions.forEach((definition) => { - if (definition.controllerConstructor.shouldLoad) { - this.router.loadDefinition(definition); - } - }); - } - unload(head, ...rest) { - const identifiers = Array.isArray(head) ? head : [head, ...rest]; - identifiers.forEach((identifier) => this.router.unloadIdentifier(identifier)); - } - get controllers() { - return this.router.contexts.map((context) => context.controller); - } - getControllerForElementAndIdentifier(element, identifier) { - const context = this.router.getContextForElementAndIdentifier(element, identifier); - return context ? context.controller : null; - } - handleError(error, message, detail) { - var _a; - this.logger.error(`%s\n\n%o\n\n%o`, message, error, detail); - (_a = window.onerror) === null || _a === void 0 ? void 0 : _a.call(window, message, "", 0, 0, error); - } - logFormattedMessage(identifier, functionName, detail = {}) { - detail = Object.assign({ application: this }, detail); - this.logger.groupCollapsed(`${identifier} #${functionName}`); - this.logger.log("details:", Object.assign({}, detail)); - this.logger.groupEnd(); - } - } - function domReady() { - return new Promise((resolve) => { - if (document.readyState == "loading") { - document.addEventListener("DOMContentLoaded", () => resolve()); - } - else { - resolve(); - } - }); - } - class StimulusReloader { static async reload(filePattern) { const document = await reloadHtmlDocument(); @@ -3532,7 +1404,7 @@ var HotwireSpark = (function () { let filePattern = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : /./; this.document = document; this.filePattern = filePattern; - this.application = window.Stimulus || Application.start(); + this.application = window.Stimulus; } async reload() { log("Reload Stimulus controllers..."); diff --git a/app/assets/javascripts/hotwire_spark.min.js b/app/assets/javascripts/hotwire_spark.min.js index 3f53c17..83da97f 100644 --- a/app/assets/javascripts/hotwire_spark.min.js +++ b/app/assets/javascripts/hotwire_spark.min.js @@ -1,2 +1,2 @@ -var HotwireSpark=function(){"use strict";var e={logger:"undefined"!=typeof console?console:void 0,WebSocket:"undefined"!=typeof WebSocket?WebSocket:void 0},t={log(...t){this.enabled&&(t.push(Date.now()),e.logger.log("[ActionCable]",...t))}};const n=()=>(new Date).getTime(),s=e=>(n()-e)/1e3;class r{constructor(e){this.visibilityDidChange=this.visibilityDidChange.bind(this),this.connection=e,this.reconnectAttempts=0}start(){this.isRunning()||(this.startedAt=n(),delete this.stoppedAt,this.startPolling(),addEventListener("visibilitychange",this.visibilityDidChange),t.log(`ConnectionMonitor started. stale threshold = ${this.constructor.staleThreshold} s`))}stop(){this.isRunning()&&(this.stoppedAt=n(),this.stopPolling(),removeEventListener("visibilitychange",this.visibilityDidChange),t.log("ConnectionMonitor stopped"))}isRunning(){return this.startedAt&&!this.stoppedAt}recordMessage(){this.pingedAt=n()}recordConnect(){this.reconnectAttempts=0,delete this.disconnectedAt,t.log("ConnectionMonitor recorded connect")}recordDisconnect(){this.disconnectedAt=n(),t.log("ConnectionMonitor recorded disconnect")}startPolling(){this.stopPolling(),this.poll()}stopPolling(){clearTimeout(this.pollTimeout)}poll(){this.pollTimeout=setTimeout((()=>{this.reconnectIfStale(),this.poll()}),this.getPollInterval())}getPollInterval(){const{staleThreshold:e,reconnectionBackoffRate:t}=this.constructor;return 1e3*e*Math.pow(1+t,Math.min(this.reconnectAttempts,10))*(1+(0===this.reconnectAttempts?1:t)*Math.random())}reconnectIfStale(){this.connectionIsStale()&&(t.log(`ConnectionMonitor detected stale connection. reconnectAttempts = ${this.reconnectAttempts}, time stale = ${s(this.refreshedAt)} s, stale threshold = ${this.constructor.staleThreshold} s`),this.reconnectAttempts++,this.disconnectedRecently()?t.log(`ConnectionMonitor skipping reopening recent disconnect. time disconnected = ${s(this.disconnectedAt)} s`):(t.log("ConnectionMonitor reopening"),this.connection.reopen()))}get refreshedAt(){return this.pingedAt?this.pingedAt:this.startedAt}connectionIsStale(){return s(this.refreshedAt)>this.constructor.staleThreshold}disconnectedRecently(){return this.disconnectedAt&&s(this.disconnectedAt){!this.connectionIsStale()&&this.connection.isOpen()||(t.log(`ConnectionMonitor reopening stale connection on visibilitychange. visibilityState = ${document.visibilityState}`),this.connection.reopen())}),200)}}r.staleThreshold=6,r.reconnectionBackoffRate=.15;var i={message_types:{welcome:"welcome",disconnect:"disconnect",ping:"ping",confirmation:"confirm_subscription",rejection:"reject_subscription"},disconnect_reasons:{unauthorized:"unauthorized",invalid_request:"invalid_request",server_restart:"server_restart",remote:"remote"},default_mount_path:"/cable",protocols:["actioncable-v1-json","actioncable-unsupported"]};const{message_types:o,protocols:a}=i,c=a.slice(0,a.length-1),l=[].indexOf;class h{constructor(e){this.open=this.open.bind(this),this.consumer=e,this.subscriptions=this.consumer.subscriptions,this.monitor=new r(this),this.disconnected=!0}send(e){return!!this.isOpen()&&(this.webSocket.send(JSON.stringify(e)),!0)}open(){if(this.isActive())return t.log(`Attempted to open WebSocket, but existing socket is ${this.getState()}`),!1;{const n=[...a,...this.consumer.subprotocols||[]];return t.log(`Opening WebSocket, current state is ${this.getState()}, subprotocols: ${n}`),this.webSocket&&this.uninstallEventHandlers(),this.webSocket=new e.WebSocket(this.consumer.url,n),this.installEventHandlers(),this.monitor.start(),!0}}close({allowReconnect:e}={allowReconnect:!0}){if(e||this.monitor.stop(),this.isOpen())return this.webSocket.close()}reopen(){if(t.log(`Reopening WebSocket, current state is ${this.getState()}`),!this.isActive())return this.open();try{return this.close()}catch(e){t.log("Failed to reopen WebSocket",e)}finally{t.log(`Reopening WebSocket in ${this.constructor.reopenDelay}ms`),setTimeout(this.open,this.constructor.reopenDelay)}}getProtocol(){if(this.webSocket)return this.webSocket.protocol}isOpen(){return this.isState("open")}isActive(){return this.isState("open","connecting")}triedToReconnect(){return this.monitor.reconnectAttempts>0}isProtocolSupported(){return l.call(c,this.getProtocol())>=0}isState(...e){return l.call(e,this.getState())>=0}getState(){if(this.webSocket)for(let t in e.WebSocket)if(e.WebSocket[t]===this.webSocket.readyState)return t.toLowerCase();return null}installEventHandlers(){for(let e in this.events){const t=this.events[e].bind(this);this.webSocket[`on${e}`]=t}}uninstallEventHandlers(){for(let e in this.events)this.webSocket[`on${e}`]=function(){}}}h.reopenDelay=500,h.prototype.events={message(e){if(!this.isProtocolSupported())return;const{identifier:n,message:s,reason:r,reconnect:i,type:a}=JSON.parse(e.data);switch(this.monitor.recordMessage(),a){case o.welcome:return this.triedToReconnect()&&(this.reconnectAttempted=!0),this.monitor.recordConnect(),this.subscriptions.reload();case o.disconnect:return t.log(`Disconnecting. Reason: ${r}`),this.close({allowReconnect:i});case o.ping:return null;case o.confirmation:return this.subscriptions.confirmSubscription(n),this.reconnectAttempted?(this.reconnectAttempted=!1,this.subscriptions.notify(n,"connected",{reconnected:!0})):this.subscriptions.notify(n,"connected",{reconnected:!1});case o.rejection:return this.subscriptions.reject(n);default:return this.subscriptions.notify(n,"received",s)}},open(){if(t.log(`WebSocket onopen event, using '${this.getProtocol()}' subprotocol`),this.disconnected=!1,!this.isProtocolSupported())return t.log("Protocol is unsupported. Stopping monitor and disconnecting."),this.close({allowReconnect:!1})},close(e){if(t.log("WebSocket onclose event"),!this.disconnected)return this.disconnected=!0,this.monitor.recordDisconnect(),this.subscriptions.notifyAll("disconnected",{willAttemptReconnect:this.monitor.isRunning()})},error(){t.log("WebSocket onerror event")}};class u{constructor(e,t={},n){this.consumer=e,this.identifier=JSON.stringify(t),function(e,t){if(null!=t)for(let n in t){const s=t[n];e[n]=s}}(this,n)}perform(e,t={}){return t.action=e,this.send(t)}send(e){return this.consumer.send({command:"message",identifier:this.identifier,data:JSON.stringify(e)})}unsubscribe(){return this.consumer.subscriptions.remove(this)}}class d{constructor(e){this.subscriptions=e,this.pendingSubscriptions=[]}guarantee(e){-1==this.pendingSubscriptions.indexOf(e)?(t.log(`SubscriptionGuarantor guaranteeing ${e.identifier}`),this.pendingSubscriptions.push(e)):t.log(`SubscriptionGuarantor already guaranteeing ${e.identifier}`),this.startGuaranteeing()}forget(e){t.log(`SubscriptionGuarantor forgetting ${e.identifier}`),this.pendingSubscriptions=this.pendingSubscriptions.filter((t=>t!==e))}startGuaranteeing(){this.stopGuaranteeing(),this.retrySubscribing()}stopGuaranteeing(){clearTimeout(this.retryTimeout)}retrySubscribing(){this.retryTimeout=setTimeout((()=>{this.subscriptions&&"function"==typeof this.subscriptions.subscribe&&this.pendingSubscriptions.map((e=>{t.log(`SubscriptionGuarantor resubscribing ${e.identifier}`),this.subscriptions.subscribe(e)}))}),500)}}class m{constructor(e){this.consumer=e,this.guarantor=new d(this),this.subscriptions=[]}create(e,t){const n="object"==typeof e?e:{channel:e},s=new u(this.consumer,n,t);return this.add(s)}add(e){return this.subscriptions.push(e),this.consumer.ensureActiveConnection(),this.notify(e,"initialized"),this.subscribe(e),e}remove(e){return this.forget(e),this.findAll(e.identifier).length||this.sendCommand(e,"unsubscribe"),e}reject(e){return this.findAll(e).map((e=>(this.forget(e),this.notify(e,"rejected"),e)))}forget(e){return this.guarantor.forget(e),this.subscriptions=this.subscriptions.filter((t=>t!==e)),e}findAll(e){return this.subscriptions.filter((t=>t.identifier===e))}reload(){return this.subscriptions.map((e=>this.subscribe(e)))}notifyAll(e,...t){return this.subscriptions.map((n=>this.notify(n,e,...t)))}notify(e,t,...n){let s;return s="string"==typeof e?this.findAll(e):[e],s.map((e=>"function"==typeof e[t]?e[t](...n):void 0))}subscribe(e){this.sendCommand(e,"subscribe")&&this.guarantor.guarantee(e)}confirmSubscription(e){t.log(`Subscription confirmed ${e}`),this.findAll(e).map((e=>this.guarantor.forget(e)))}sendCommand(e,t){const{identifier:n}=e;return this.consumer.send({command:t,identifier:n})}}class p{constructor(e){this._url=e,this.subscriptions=new m(this),this.connection=new h(this),this.subprotocols=[]}get url(){return function(e){"function"==typeof e&&(e=e());if(e&&!/^wss?:/i.test(e)){const t=document.createElement("a");return t.href=e,t.href=t.href,t.protocol=t.protocol.replace("http","ws"),t.href}return e}(this._url)}send(e){return this.connection.send(e)}connect(){return this.connection.open()}disconnect(){return this.connection.close({allowReconnect:!1})}ensureActiveConnection(){if(!this.connection.isActive())return this.connection.open()}addSubProtocol(e){this.subprotocols=[...this.subprotocols,e]}}var g=function(e=function(e){const t=document.head.querySelector(`meta[name='action-cable-${e}']`);if(t)return t.getAttribute("content")}("url")||i.default_mount_path){return new p(e)}("/hotwire-spark");function f(e){return e.replace(/-[a-z0-9]+\.(\w+)(\?.*)?$/,".$1")}function b(e,t){const n=new URL(e,window.location.origin);return Object.entries(t).forEach((e=>{let[t,s]=e;n.searchParams.set(t,s)})),n.toString()}function v(e){return b(e,{reload:Date.now()})}async function y(){let e=v(b(window.location.href,{hotwire_spark:"true"}));const t=await fetch(e,{headers:{Accept:"text/html"}});if(!t.ok)throw new Error(`${t.status} when fetching ${e}`);const n=await t.text();return(new DOMParser).parseFromString(n,"text/html")}var A=function(){let e=new Set,t={morphStyle:"outerHTML",callbacks:{beforeNodeAdded:l,afterNodeAdded:l,beforeNodeMorphed:l,afterNodeMorphed:l,beforeNodeRemoved:l,afterNodeRemoved:l,beforeAttributeUpdated:l},head:{style:"merge",shouldPreserve:function(e){return"true"===e.getAttribute("im-preserve")},shouldReAppend:function(e){return"true"===e.getAttribute("im-re-append")},shouldRemove:l,afterHeadMorphed:l}};function n(e,t,s){if(s.head.block){let r=e.querySelector("head"),i=t.querySelector("head");if(r&&i){let o=c(i,r,s);return void Promise.all(o).then((function(){n(e,t,Object.assign(s,{head:{block:!1,ignore:!0}}))}))}}if("innerHTML"===s.morphStyle)return i(t,e,s),e.children;if("outerHTML"===s.morphStyle||null==s.morphStyle){let n=function(e,t,n){let s;s=e.firstChild;let r=s,i=0;for(;s;){let e=g(s,t,n);e>i&&(r=s,i=e),s=s.nextSibling}return r}(t,e,s),i=n?.previousSibling,o=n?.nextSibling,a=r(e,n,s);return n?function(e,t,n){let s=[],r=[];for(;null!=e;)s.push(e),e=e.previousSibling;for(;s.length>0;){let e=s.pop();r.push(e),t.parentElement.insertBefore(e,t)}r.push(t);for(;null!=n;)s.push(n),r.push(n),n=n.nextSibling;for(;s.length>0;)t.parentElement.insertBefore(s.pop(),t.nextSibling);return r}(i,a,o):[]}throw"Do not understand how to morph style "+s.morphStyle}function s(e,t){return t.ignoreActiveValue&&e===document.activeElement}function r(e,t,n){if(!n.ignoreActive||e!==document.activeElement)return null==t?!1===n.callbacks.beforeNodeRemoved(e)?e:(e.remove(),n.callbacks.afterNodeRemoved(e),null):u(e,t)?(!1===n.callbacks.beforeNodeMorphed(e,t)||(e instanceof HTMLHeadElement&&n.head.ignore||(e instanceof HTMLHeadElement&&"morph"!==n.head.style?c(t,e,n):(!function(e,t,n){let r=e.nodeType;if(1===r){const s=e.attributes,r=t.attributes;for(const e of s)o(e.name,t,"update",n)||t.getAttribute(e.name)!==e.value&&t.setAttribute(e.name,e.value);for(let s=r.length-1;0<=s;s--){const i=r[s];o(i.name,t,"remove",n)||(e.hasAttribute(i.name)||t.removeAttribute(i.name))}}8!==r&&3!==r||t.nodeValue!==e.nodeValue&&(t.nodeValue=e.nodeValue);s(t,n)||function(e,t,n){if(e instanceof HTMLInputElement&&t instanceof HTMLInputElement&&"file"!==e.type){let s=e.value,r=t.value;a(e,t,"checked",n),a(e,t,"disabled",n),e.hasAttribute("value")?s!==r&&(o("value",t,"update",n)||(t.setAttribute("value",s),t.value=s)):o("value",t,"remove",n)||(t.value="",t.removeAttribute("value"))}else if(e instanceof HTMLOptionElement)a(e,t,"selected",n);else if(e instanceof HTMLTextAreaElement&&t instanceof HTMLTextAreaElement){let s=e.value,r=t.value;if(o("value",t,"update",n))return;s!==r&&(t.value=s),t.firstChild&&t.firstChild.nodeValue!==s&&(t.firstChild.nodeValue=s)}}(e,t,n)}(t,e,n),s(e,n)||i(t,e,n))),n.callbacks.afterNodeMorphed(e,t)),e):!1===n.callbacks.beforeNodeRemoved(e)||!1===n.callbacks.beforeNodeAdded(t)?e:(e.parentElement.replaceChild(t,e),n.callbacks.afterNodeAdded(t),n.callbacks.afterNodeRemoved(e),t)}function i(e,t,n){let s,i=e.firstChild,o=t.firstChild;for(;i;){if(s=i,i=s.nextSibling,null==o){if(!1===n.callbacks.beforeNodeAdded(s))return;t.appendChild(s),n.callbacks.afterNodeAdded(s),y(n,s);continue}if(h(s,o,n)){r(o,s,n),o=o.nextSibling,y(n,s);continue}let a=m(e,t,s,o,n);if(a){o=d(o,a,n),r(a,s,n),y(n,s);continue}let c=p(e,t,s,o,n);if(c)o=d(o,c,n),r(c,s,n),y(n,s);else{if(!1===n.callbacks.beforeNodeAdded(s))return;t.insertBefore(s,o),n.callbacks.afterNodeAdded(s),y(n,s)}}for(;null!==o;){let e=o;o=o.nextSibling,f(e,n)}}function o(e,t,n,s){return!("value"!==e||!s.ignoreActiveValue||t!==document.activeElement)||!1===s.callbacks.beforeAttributeUpdated(e,t,n)}function a(e,t,n,s){if(e[n]!==t[n]){let r=o(n,t,"update",s);r||(t[n]=e[n]),e[n]?r||t.setAttribute(n,e[n]):o(n,t,"remove",s)||t.removeAttribute(n)}}function c(e,t,n){let s=[],r=[],i=[],o=[],a=n.head.style,c=new Map;for(const t of e.children)c.set(t.outerHTML,t);for(const e of t.children){let t=c.has(e.outerHTML),s=n.head.shouldReAppend(e),l=n.head.shouldPreserve(e);t||l?s?r.push(e):(c.delete(e.outerHTML),i.push(e)):"append"===a?s&&(r.push(e),o.push(e)):!1!==n.head.shouldRemove(e)&&r.push(e)}o.push(...c.values());let l=[];for(const e of o){let r=document.createRange().createContextualFragment(e.outerHTML).firstChild;if(!1!==n.callbacks.beforeNodeAdded(r)){if(r.href||r.src){let e=null,t=new Promise((function(t){e=t}));r.addEventListener("load",(function(){e()})),l.push(t)}t.appendChild(r),n.callbacks.afterNodeAdded(r),s.push(r)}}for(const e of r)!1!==n.callbacks.beforeNodeRemoved(e)&&(t.removeChild(e),n.callbacks.afterNodeRemoved(e));return n.head.afterHeadMorphed(t,{added:s,kept:i,removed:r}),l}function l(){}function h(e,t,n){return null!=e&&null!=t&&(e.nodeType===t.nodeType&&e.tagName===t.tagName&&(""!==e.id&&e.id===t.id||A(n,e,t)>0))}function u(e,t){return null!=e&&null!=t&&(e.nodeType===t.nodeType&&e.tagName===t.tagName)}function d(e,t,n){for(;e!==t;){let t=e;e=e.nextSibling,f(t,n)}return y(n,t),t.nextSibling}function m(e,t,n,s,r){let i=A(r,n,t);if(i>0){let t=s,o=0;for(;null!=t;){if(h(n,t,r))return t;if(o+=A(r,t,e),o>i)return null;t=t.nextSibling}}return null}function p(e,t,n,s,r){let i=s,o=n.nextSibling,a=0;for(;null!=i;){if(A(r,i,e)>0)return null;if(u(n,i))return i;if(u(o,i)&&(a++,o=o.nextSibling,a>=2))return null;i=i.nextSibling}return i}function g(e,t,n){return u(e,t)?.5+A(n,e,t):0}function f(e,t){y(t,e),!1!==t.callbacks.beforeNodeRemoved(e)&&(e.remove(),t.callbacks.afterNodeRemoved(e))}function b(e,t){return!e.deadIds.has(t)}function v(t,n,s){return(t.idMap.get(s)||e).has(n)}function y(t,n){let s=t.idMap.get(n)||e;for(const e of s)t.deadIds.add(e)}function A(t,n,s){let r=t.idMap.get(n)||e,i=0;for(const e of r)b(t,e)&&v(t,e,s)&&++i;return i}function O(e,t){let n=e.parentElement,s=e.querySelectorAll("[id]");for(const e of s){let s=e;for(;s!==n&&null!=s;){let n=t.get(s);null==n&&(n=new Set,t.set(s,n)),n.add(e.id),s=s.parentElement}}}function E(e,t){let n=new Map;return O(e,n),O(t,n),n}return{morph:function(e,s,r={}){e instanceof Document&&(e=e.documentElement),"string"==typeof s&&(s=function(e){let t=new DOMParser,n=e.replace(/]*>|>)([\s\S]*?)<\/svg>/gim,"");if(n.match(/<\/html>/)||n.match(/<\/head>/)||n.match(/<\/body>/)){let s=t.parseFromString(e,"text/html");if(n.match(/<\/html>/))return s.generatedByIdiomorph=!0,s;{let e=s.firstChild;return e?(e.generatedByIdiomorph=!0,e):null}}{let n=t.parseFromString("","text/html").body.querySelector("template").content;return n.generatedByIdiomorph=!0,n}}(s));let i=function(e){if(null==e){return document.createElement("div")}if(e.generatedByIdiomorph)return e;if(e instanceof Node){const t=document.createElement("div");return t.append(e),t}{const t=document.createElement("div");for(const n of[...e])t.append(n);return t}}(s),o=function(e,n,s){return s=function(e){let n={};return Object.assign(n,t),Object.assign(n,e),n.callbacks={},Object.assign(n.callbacks,t.callbacks),Object.assign(n.callbacks,e.callbacks),n.head={},Object.assign(n.head,t.head),Object.assign(n.head,e.head),n}(s),{target:e,newContent:n,config:s,morphStyle:s.morphStyle,ignoreActive:s.ignoreActive,ignoreActiveValue:s.ignoreActiveValue,idMap:E(e,n),deadIds:new Set,callbacks:s.callbacks,head:s.head}}(e,i,r);return n(e,i,o)},defaults:t}}();function O(){if(pe.config.loggingEnabled){for(var e=arguments.length,t=new Array(e),n=0;n0}get bindings(){return Array.from(this.unorderedBindings).sort(((e,t)=>{const n=e.index,s=t.index;return ns?1:0}))}}class w{constructor(e){this.application=e,this.eventListenerMaps=new Map,this.started=!1}start(){this.started||(this.started=!0,this.eventListeners.forEach((e=>e.connect())))}stop(){this.started&&(this.started=!1,this.eventListeners.forEach((e=>e.disconnect())))}get eventListeners(){return Array.from(this.eventListenerMaps.values()).reduce(((e,t)=>e.concat(Array.from(t.values()))),[])}bindingConnected(e){this.fetchEventListenerForBinding(e).bindingConnected(e)}bindingDisconnected(e,t=!1){this.fetchEventListenerForBinding(e).bindingDisconnected(e),t&&this.clearEventListenersForBinding(e)}handleError(e,t,n={}){this.application.handleError(e,`Error ${t}`,n)}clearEventListenersForBinding(e){const t=this.fetchEventListenerForBinding(e);t.hasBindings()||(t.disconnect(),this.removeMappedEventListenerFor(e))}removeMappedEventListenerFor(e){const{eventTarget:t,eventName:n,eventOptions:s}=e,r=this.fetchEventListenerMapForEventTarget(t),i=this.cacheKey(n,s);r.delete(i),0==r.size&&this.eventListenerMaps.delete(t)}fetchEventListenerForBinding(e){const{eventTarget:t,eventName:n,eventOptions:s}=e;return this.fetchEventListener(t,n,s)}fetchEventListener(e,t,n){const s=this.fetchEventListenerMapForEventTarget(e),r=this.cacheKey(t,n);let i=s.get(r);return i||(i=this.createEventListener(e,t,n),s.set(r,i)),i}createEventListener(e,t,n){const s=new E(e,t,n);return this.started&&s.connect(),s}fetchEventListenerMapForEventTarget(e){let t=this.eventListenerMaps.get(e);return t||(t=new Map,this.eventListenerMaps.set(e,t)),t}cacheKey(e,t){const n=[e];return Object.keys(t).sort().forEach((e=>{n.push(`${t[e]?"":"!"}${e}`)})),n.join(":")}}const k={stop:({event:e,value:t})=>(t&&e.stopPropagation(),!0),prevent:({event:e,value:t})=>(t&&e.preventDefault(),!0),self:({event:e,value:t,element:n})=>!t||n===e.target},M=/^(?:(?:([^.]+?)\+)?(.+?)(?:\.(.+?))?(?:@(window|document))?->)?(.+?)(?:#([^:]+?))(?::(.+))?$/;function S(e){return"window"==e?window:"document"==e?document:void 0}function N(e){return e.replace(/(?:[_-])([a-z0-9])/g,((e,t)=>t.toUpperCase()))}function C(e){return N(e.replace(/--/g,"-").replace(/__/g,"_"))}const F=["meta","ctrl","alt","shift"];class T{constructor(e,t,n,s){this.element=e,this.index=t,this.eventTarget=n.eventTarget||e,this.eventName=n.eventName||function(e){const t=e.tagName.toLowerCase();if(t in B)return B[t](e)}(e)||L("missing event name"),this.eventOptions=n.eventOptions||{},this.identifier=n.identifier||L("missing identifier"),this.methodName=n.methodName||L("missing method name"),this.keyFilter=n.keyFilter||"",this.schema=s}static forToken(e,t){return new this(e.element,e.index,function(e){const t=e.trim().match(M)||[];let n=t[2],s=t[3];return s&&!["keydown","keyup","keypress"].includes(n)&&(n+=`.${s}`,s=""),{eventTarget:S(t[4]),eventName:n,eventOptions:t[7]?(r=t[7],r.split(":").reduce(((e,t)=>Object.assign(e,{[t.replace(/^!/,"")]:!/^!/.test(t)})),{})):{},identifier:t[5],methodName:t[6],keyFilter:t[1]||s};var r}(e.content),t)}toString(){const e=this.keyFilter?`.${this.keyFilter}`:"",t=this.eventTargetName?`@${this.eventTargetName}`:"";return`${this.eventName}${e}${t}->${this.identifier}#${this.methodName}`}shouldIgnoreKeyboardEvent(e){if(!this.keyFilter)return!1;const t=this.keyFilter.split("+");if(this.keyFilterDissatisfied(e,t))return!0;const n=t.filter((e=>!F.includes(e)))[0];return!!n&&(s=this.keyMappings,r=n,Object.prototype.hasOwnProperty.call(s,r)||L(`contains unknown key filter: ${this.keyFilter}`),this.keyMappings[n].toLowerCase()!==e.key.toLowerCase());var s,r}shouldIgnoreMouseEvent(e){if(!this.keyFilter)return!1;const t=[this.keyFilter];return!!this.keyFilterDissatisfied(e,t)}get params(){const e={},t=new RegExp(`^data-${this.identifier}-(.+)-param$`,"i");for(const{name:n,value:s}of Array.from(this.element.attributes)){const r=n.match(t),i=r&&r[1];i&&(e[N(i)]=x(s))}return e}get eventTargetName(){return(e=this.eventTarget)==window?"window":e==document?"document":void 0;var e}get keyMappings(){return this.schema.keyMappings}keyFilterDissatisfied(e,t){const[n,s,r,i]=F.map((e=>t.includes(e)));return e.metaKey!==n||e.ctrlKey!==s||e.altKey!==r||e.shiftKey!==i}}const B={a:()=>"click",button:()=>"click",form:()=>"submit",details:()=>"toggle",input:e=>"submit"==e.getAttribute("type")?"click":"input",select:()=>"change",textarea:()=>"input"};function L(e){throw new Error(e)}function x(e){try{return JSON.parse(e)}catch(t){return e}}class D{constructor(e,t){this.context=e,this.action=t}get index(){return this.action.index}get eventTarget(){return this.action.eventTarget}get eventOptions(){return this.action.eventOptions}get identifier(){return this.context.identifier}handleEvent(e){const t=this.prepareActionEvent(e);this.willBeInvokedByEvent(e)&&this.applyEventModifiers(t)&&this.invokeWithEvent(t)}get eventName(){return this.action.eventName}get method(){const e=this.controller[this.methodName];if("function"==typeof e)return e;throw new Error(`Action "${this.action}" references undefined method "${this.methodName}"`)}applyEventModifiers(e){const{element:t}=this.action,{actionDescriptorFilters:n}=this.context.application,{controller:s}=this.context;let r=!0;for(const[i,o]of Object.entries(this.eventOptions))if(i in n){const a=n[i];r=r&&a({name:i,value:o,event:e,element:t,controller:s})}return r}prepareActionEvent(e){return Object.assign(e,{params:this.action.params})}invokeWithEvent(e){const{target:t,currentTarget:n}=e;try{this.method.call(this.controller,e),this.context.logDebugActivity(this.methodName,{event:e,target:t,currentTarget:n,action:this.methodName})}catch(t){const{identifier:n,controller:s,element:r,index:i}=this,o={identifier:n,controller:s,element:r,index:i,event:e};this.context.handleError(t,`invoking action "${this.action}"`,o)}}willBeInvokedByEvent(e){const t=e.target;return!(e instanceof KeyboardEvent&&this.action.shouldIgnoreKeyboardEvent(e))&&(!(e instanceof MouseEvent&&this.action.shouldIgnoreMouseEvent(e))&&(this.element===t||(t instanceof Element&&this.element.contains(t)?this.scope.containsElement(t):this.scope.containsElement(this.action.element))))}get controller(){return this.context.controller}get methodName(){return this.action.methodName}get element(){return this.scope.element}get scope(){return this.context.scope}}class ${constructor(e,t){this.mutationObserverInit={attributes:!0,childList:!0,subtree:!0},this.element=e,this.started=!1,this.delegate=t,this.elements=new Set,this.mutationObserver=new MutationObserver((e=>this.processMutations(e)))}start(){this.started||(this.started=!0,this.mutationObserver.observe(this.element,this.mutationObserverInit),this.refresh())}pause(e){this.started&&(this.mutationObserver.disconnect(),this.started=!1),e(),this.started||(this.mutationObserver.observe(this.element,this.mutationObserverInit),this.started=!0)}stop(){this.started&&(this.mutationObserver.takeRecords(),this.mutationObserver.disconnect(),this.started=!1)}refresh(){if(this.started){const e=new Set(this.matchElementsInTree());for(const t of Array.from(this.elements))e.has(t)||this.removeElement(t);for(const t of Array.from(e))this.addElement(t)}}processMutations(e){if(this.started)for(const t of e)this.processMutation(t)}processMutation(e){"attributes"==e.type?this.processAttributeChange(e.target,e.attributeName):"childList"==e.type&&(this.processRemovedNodes(e.removedNodes),this.processAddedNodes(e.addedNodes))}processAttributeChange(e,t){this.elements.has(e)?this.delegate.elementAttributeChanged&&this.matchElement(e)?this.delegate.elementAttributeChanged(e,t):this.removeElement(e):this.matchElement(e)&&this.addElement(e)}processRemovedNodes(e){for(const t of Array.from(e)){const e=this.elementFromNode(t);e&&this.processTree(e,this.removeElement)}}processAddedNodes(e){for(const t of Array.from(e)){const e=this.elementFromNode(t);e&&this.elementIsActive(e)&&this.processTree(e,this.addElement)}}matchElement(e){return this.delegate.matchElement(e)}matchElementsInTree(e=this.element){return this.delegate.matchElementsInTree(e)}processTree(e,t){for(const n of this.matchElementsInTree(e))t.call(this,n)}elementFromNode(e){if(e.nodeType==Node.ELEMENT_NODE)return e}elementIsActive(e){return e.isConnected==this.element.isConnected&&this.element.contains(e)}addElement(e){this.elements.has(e)||this.elementIsActive(e)&&(this.elements.add(e),this.delegate.elementMatched&&this.delegate.elementMatched(e))}removeElement(e){this.elements.has(e)&&(this.elements.delete(e),this.delegate.elementUnmatched&&this.delegate.elementUnmatched(e))}}class R{constructor(e,t,n){this.attributeName=t,this.delegate=n,this.elementObserver=new $(e,this)}get element(){return this.elementObserver.element}get selector(){return`[${this.attributeName}]`}start(){this.elementObserver.start()}pause(e){this.elementObserver.pause(e)}stop(){this.elementObserver.stop()}refresh(){this.elementObserver.refresh()}get started(){return this.elementObserver.started}matchElement(e){return e.hasAttribute(this.attributeName)}matchElementsInTree(e){const t=this.matchElement(e)?[e]:[],n=Array.from(e.querySelectorAll(this.selector));return t.concat(n)}elementMatched(e){this.delegate.elementMatchedAttribute&&this.delegate.elementMatchedAttribute(e,this.attributeName)}elementUnmatched(e){this.delegate.elementUnmatchedAttribute&&this.delegate.elementUnmatchedAttribute(e,this.attributeName)}elementAttributeChanged(e,t){this.delegate.elementAttributeValueChanged&&this.attributeName==t&&this.delegate.elementAttributeValueChanged(e,t)}}function I(e,t){let n=e.get(t);return n||(n=new Set,e.set(t,n)),n}class P{constructor(){this.valuesByKey=new Map}get keys(){return Array.from(this.valuesByKey.keys())}get values(){return Array.from(this.valuesByKey.values()).reduce(((e,t)=>e.concat(Array.from(t))),[])}get size(){return Array.from(this.valuesByKey.values()).reduce(((e,t)=>e+t.size),0)}add(e,t){!function(e,t,n){I(e,t).add(n)}(this.valuesByKey,e,t)}delete(e,t){!function(e,t,n){I(e,t).delete(n),function(e,t){const n=e.get(t);null!=n&&0==n.size&&e.delete(t)}(e,t)}(this.valuesByKey,e,t)}has(e,t){const n=this.valuesByKey.get(e);return null!=n&&n.has(t)}hasKey(e){return this.valuesByKey.has(e)}hasValue(e){return Array.from(this.valuesByKey.values()).some((t=>t.has(e)))}getValuesForKey(e){const t=this.valuesByKey.get(e);return t?Array.from(t):[]}getKeysForValue(e){return Array.from(this.valuesByKey).filter((([t,n])=>n.has(e))).map((([e,t])=>e))}}class V{constructor(e,t,n,s){this._selector=t,this.details=s,this.elementObserver=new $(e,this),this.delegate=n,this.matchesByElement=new P}get started(){return this.elementObserver.started}get selector(){return this._selector}set selector(e){this._selector=e,this.refresh()}start(){this.elementObserver.start()}pause(e){this.elementObserver.pause(e)}stop(){this.elementObserver.stop()}refresh(){this.elementObserver.refresh()}get element(){return this.elementObserver.element}matchElement(e){const{selector:t}=this;if(t){const n=e.matches(t);return this.delegate.selectorMatchElement?n&&this.delegate.selectorMatchElement(e,this.details):n}return!1}matchElementsInTree(e){const{selector:t}=this;if(t){const n=this.matchElement(e)?[e]:[],s=Array.from(e.querySelectorAll(t)).filter((e=>this.matchElement(e)));return n.concat(s)}return[]}elementMatched(e){const{selector:t}=this;t&&this.selectorMatched(e,t)}elementUnmatched(e){const t=this.matchesByElement.getKeysForValue(e);for(const n of t)this.selectorUnmatched(e,n)}elementAttributeChanged(e,t){const{selector:n}=this;if(n){const t=this.matchElement(e),s=this.matchesByElement.has(n,e);t&&!s?this.selectorMatched(e,n):!t&&s&&this.selectorUnmatched(e,n)}}selectorMatched(e,t){this.delegate.selectorMatched(e,t,this.details),this.matchesByElement.add(t,e)}selectorUnmatched(e,t){this.delegate.selectorUnmatched(e,t,this.details),this.matchesByElement.delete(t,e)}}class K{constructor(e,t){this.element=e,this.delegate=t,this.started=!1,this.stringMap=new Map,this.mutationObserver=new MutationObserver((e=>this.processMutations(e)))}start(){this.started||(this.started=!0,this.mutationObserver.observe(this.element,{attributes:!0,attributeOldValue:!0}),this.refresh())}stop(){this.started&&(this.mutationObserver.takeRecords(),this.mutationObserver.disconnect(),this.started=!1)}refresh(){if(this.started)for(const e of this.knownAttributeNames)this.refreshAttribute(e,null)}processMutations(e){if(this.started)for(const t of e)this.processMutation(t)}processMutation(e){const t=e.attributeName;t&&this.refreshAttribute(t,e.oldValue)}refreshAttribute(e,t){const n=this.delegate.getStringMapKeyForAttribute(e);if(null!=n){this.stringMap.has(e)||this.stringMapKeyAdded(n,e);const s=this.element.getAttribute(e);if(this.stringMap.get(e)!=s&&this.stringMapValueChanged(s,n,t),null==s){const t=this.stringMap.get(e);this.stringMap.delete(e),t&&this.stringMapKeyRemoved(n,e,t)}else this.stringMap.set(e,s)}}stringMapKeyAdded(e,t){this.delegate.stringMapKeyAdded&&this.delegate.stringMapKeyAdded(e,t)}stringMapValueChanged(e,t,n){this.delegate.stringMapValueChanged&&this.delegate.stringMapValueChanged(e,t,n)}stringMapKeyRemoved(e,t,n){this.delegate.stringMapKeyRemoved&&this.delegate.stringMapKeyRemoved(e,t,n)}get knownAttributeNames(){return Array.from(new Set(this.currentAttributeNames.concat(this.recordedAttributeNames)))}get currentAttributeNames(){return Array.from(this.element.attributes).map((e=>e.name))}get recordedAttributeNames(){return Array.from(this.stringMap.keys())}}class j{constructor(e,t,n){this.attributeObserver=new R(e,t,this),this.delegate=n,this.tokensByElement=new P}get started(){return this.attributeObserver.started}start(){this.attributeObserver.start()}pause(e){this.attributeObserver.pause(e)}stop(){this.attributeObserver.stop()}refresh(){this.attributeObserver.refresh()}get element(){return this.attributeObserver.element}get attributeName(){return this.attributeObserver.attributeName}elementMatchedAttribute(e){this.tokensMatched(this.readTokensForElement(e))}elementAttributeValueChanged(e){const[t,n]=this.refreshTokensForElement(e);this.tokensUnmatched(t),this.tokensMatched(n)}elementUnmatchedAttribute(e){this.tokensUnmatched(this.tokensByElement.getValuesForKey(e))}tokensMatched(e){e.forEach((e=>this.tokenMatched(e)))}tokensUnmatched(e){e.forEach((e=>this.tokenUnmatched(e)))}tokenMatched(e){this.delegate.tokenMatched(e),this.tokensByElement.add(e.element,e)}tokenUnmatched(e){this.delegate.tokenUnmatched(e),this.tokensByElement.delete(e.element,e)}refreshTokensForElement(e){const t=this.tokensByElement.getValuesForKey(e),n=this.readTokensForElement(e),s=function(e,t){const n=Math.max(e.length,t.length);return Array.from({length:n},((n,s)=>[e[s],t[s]]))}(t,n).findIndex((([e,t])=>{return s=t,!((n=e)&&s&&n.index==s.index&&n.content==s.content);var n,s}));return-1==s?[[],[]]:[t.slice(s),n.slice(s)]}readTokensForElement(e){const t=this.attributeName;return function(e,t,n){return e.trim().split(/\s+/).filter((e=>e.length)).map(((e,s)=>({element:t,attributeName:n,content:e,index:s})))}(e.getAttribute(t)||"",e,t)}}class U{constructor(e,t,n){this.tokenListObserver=new j(e,t,this),this.delegate=n,this.parseResultsByToken=new WeakMap,this.valuesByTokenByElement=new WeakMap}get started(){return this.tokenListObserver.started}start(){this.tokenListObserver.start()}stop(){this.tokenListObserver.stop()}refresh(){this.tokenListObserver.refresh()}get element(){return this.tokenListObserver.element}get attributeName(){return this.tokenListObserver.attributeName}tokenMatched(e){const{element:t}=e,{value:n}=this.fetchParseResultForToken(e);n&&(this.fetchValuesByTokenForElement(t).set(e,n),this.delegate.elementMatchedValue(t,n))}tokenUnmatched(e){const{element:t}=e,{value:n}=this.fetchParseResultForToken(e);n&&(this.fetchValuesByTokenForElement(t).delete(e),this.delegate.elementUnmatchedValue(t,n))}fetchParseResultForToken(e){let t=this.parseResultsByToken.get(e);return t||(t=this.parseToken(e),this.parseResultsByToken.set(e,t)),t}fetchValuesByTokenForElement(e){let t=this.valuesByTokenByElement.get(e);return t||(t=new Map,this.valuesByTokenByElement.set(e,t)),t}parseToken(e){try{return{value:this.delegate.parseValueForToken(e)}}catch(e){return{error:e}}}}class _{constructor(e,t){this.context=e,this.delegate=t,this.bindingsByAction=new Map}start(){this.valueListObserver||(this.valueListObserver=new U(this.element,this.actionAttribute,this),this.valueListObserver.start())}stop(){this.valueListObserver&&(this.valueListObserver.stop(),delete this.valueListObserver,this.disconnectAllActions())}get element(){return this.context.element}get identifier(){return this.context.identifier}get actionAttribute(){return this.schema.actionAttribute}get schema(){return this.context.schema}get bindings(){return Array.from(this.bindingsByAction.values())}connectAction(e){const t=new D(this.context,e);this.bindingsByAction.set(e,t),this.delegate.bindingConnected(t)}disconnectAction(e){const t=this.bindingsByAction.get(e);t&&(this.bindingsByAction.delete(e),this.delegate.bindingDisconnected(t))}disconnectAllActions(){this.bindings.forEach((e=>this.delegate.bindingDisconnected(e,!0))),this.bindingsByAction.clear()}parseValueForToken(e){const t=T.forToken(e,this.schema);if(t.identifier==this.identifier)return t}elementMatchedValue(e,t){this.connectAction(t)}elementUnmatchedValue(e,t){this.disconnectAction(t)}}class H{constructor(e,t){this.context=e,this.receiver=t,this.stringMapObserver=new K(this.element,this),this.valueDescriptorMap=this.controller.valueDescriptorMap}start(){this.stringMapObserver.start(),this.invokeChangedCallbacksForDefaultValues()}stop(){this.stringMapObserver.stop()}get element(){return this.context.element}get controller(){return this.context.controller}getStringMapKeyForAttribute(e){if(e in this.valueDescriptorMap)return this.valueDescriptorMap[e].name}stringMapKeyAdded(e,t){const n=this.valueDescriptorMap[t];this.hasValue(e)||this.invokeChangedCallback(e,n.writer(this.receiver[e]),n.writer(n.defaultValue))}stringMapValueChanged(e,t,n){const s=this.valueDescriptorNameMap[t];null!==e&&(null===n&&(n=s.writer(s.defaultValue)),this.invokeChangedCallback(t,e,n))}stringMapKeyRemoved(e,t,n){const s=this.valueDescriptorNameMap[e];this.hasValue(e)?this.invokeChangedCallback(e,s.writer(this.receiver[e]),n):this.invokeChangedCallback(e,s.writer(s.defaultValue),n)}invokeChangedCallbacksForDefaultValues(){for(const{key:e,name:t,defaultValue:n,writer:s}of this.valueDescriptors)null==n||this.controller.data.has(e)||this.invokeChangedCallback(t,s(n),void 0)}invokeChangedCallback(e,t,n){const s=`${e}Changed`,r=this.receiver[s];if("function"==typeof r){const s=this.valueDescriptorNameMap[e];try{const e=s.reader(t);let i=n;n&&(i=s.reader(n)),r.call(this.receiver,e,i)}catch(e){throw e instanceof TypeError&&(e.message=`Stimulus Value "${this.context.identifier}.${s.name}" - ${e.message}`),e}}}get valueDescriptors(){const{valueDescriptorMap:e}=this;return Object.keys(e).map((t=>e[t]))}get valueDescriptorNameMap(){const e={};return Object.keys(this.valueDescriptorMap).forEach((t=>{const n=this.valueDescriptorMap[t];e[n.name]=n})),e}hasValue(e){const t=this.valueDescriptorNameMap[e],n=`has${s=t.name,s.charAt(0).toUpperCase()+s.slice(1)}`;var s;return this.receiver[n]}}class W{constructor(e,t){this.context=e,this.delegate=t,this.targetsByName=new P}start(){this.tokenListObserver||(this.tokenListObserver=new j(this.element,this.attributeName,this),this.tokenListObserver.start())}stop(){this.tokenListObserver&&(this.disconnectAllTargets(),this.tokenListObserver.stop(),delete this.tokenListObserver)}tokenMatched({element:e,content:t}){this.scope.containsElement(e)&&this.connectTarget(e,t)}tokenUnmatched({element:e,content:t}){this.disconnectTarget(e,t)}connectTarget(e,t){var n;this.targetsByName.has(t,e)||(this.targetsByName.add(t,e),null===(n=this.tokenListObserver)||void 0===n||n.pause((()=>this.delegate.targetConnected(e,t))))}disconnectTarget(e,t){var n;this.targetsByName.has(t,e)&&(this.targetsByName.delete(t,e),null===(n=this.tokenListObserver)||void 0===n||n.pause((()=>this.delegate.targetDisconnected(e,t))))}disconnectAllTargets(){for(const e of this.targetsByName.keys)for(const t of this.targetsByName.getValuesForKey(e))this.disconnectTarget(t,e)}get attributeName(){return`data-${this.context.identifier}-target`}get element(){return this.context.element}get scope(){return this.context.scope}}function q(e,t){const n=function(e){const t=[];for(;e;)t.push(e),e=Object.getPrototypeOf(e);return t.reverse()}(e);return Array.from(n.reduce(((e,n)=>(function(e,t){const n=e[t];return Array.isArray(n)?n:[]}(n,t).forEach((t=>e.add(t))),e)),new Set))}class z{constructor(e,t){this.started=!1,this.context=e,this.delegate=t,this.outletsByName=new P,this.outletElementsByName=new P,this.selectorObserverMap=new Map,this.attributeObserverMap=new Map}start(){this.started||(this.outletDefinitions.forEach((e=>{this.setupSelectorObserverForOutlet(e),this.setupAttributeObserverForOutlet(e)})),this.started=!0,this.dependentContexts.forEach((e=>e.refresh())))}refresh(){this.selectorObserverMap.forEach((e=>e.refresh())),this.attributeObserverMap.forEach((e=>e.refresh()))}stop(){this.started&&(this.started=!1,this.disconnectAllOutlets(),this.stopSelectorObservers(),this.stopAttributeObservers())}stopSelectorObservers(){this.selectorObserverMap.size>0&&(this.selectorObserverMap.forEach((e=>e.stop())),this.selectorObserverMap.clear())}stopAttributeObservers(){this.attributeObserverMap.size>0&&(this.attributeObserverMap.forEach((e=>e.stop())),this.attributeObserverMap.clear())}selectorMatched(e,t,{outletName:n}){const s=this.getOutlet(e,n);s&&this.connectOutlet(s,e,n)}selectorUnmatched(e,t,{outletName:n}){const s=this.getOutletFromMap(e,n);s&&this.disconnectOutlet(s,e,n)}selectorMatchElement(e,{outletName:t}){const n=this.selector(t),s=this.hasOutlet(e,t),r=e.matches(`[${this.schema.controllerAttribute}~=${t}]`);return!!n&&(s&&r&&e.matches(n))}elementMatchedAttribute(e,t){const n=this.getOutletNameFromOutletAttributeName(t);n&&this.updateSelectorObserverForOutlet(n)}elementAttributeValueChanged(e,t){const n=this.getOutletNameFromOutletAttributeName(t);n&&this.updateSelectorObserverForOutlet(n)}elementUnmatchedAttribute(e,t){const n=this.getOutletNameFromOutletAttributeName(t);n&&this.updateSelectorObserverForOutlet(n)}connectOutlet(e,t,n){var s;this.outletElementsByName.has(n,t)||(this.outletsByName.add(n,e),this.outletElementsByName.add(n,t),null===(s=this.selectorObserverMap.get(n))||void 0===s||s.pause((()=>this.delegate.outletConnected(e,t,n))))}disconnectOutlet(e,t,n){var s;this.outletElementsByName.has(n,t)&&(this.outletsByName.delete(n,e),this.outletElementsByName.delete(n,t),null===(s=this.selectorObserverMap.get(n))||void 0===s||s.pause((()=>this.delegate.outletDisconnected(e,t,n))))}disconnectAllOutlets(){for(const e of this.outletElementsByName.keys)for(const t of this.outletElementsByName.getValuesForKey(e))for(const n of this.outletsByName.getValuesForKey(e))this.disconnectOutlet(n,t,e)}updateSelectorObserverForOutlet(e){const t=this.selectorObserverMap.get(e);t&&(t.selector=this.selector(e))}setupSelectorObserverForOutlet(e){const t=this.selector(e),n=new V(document.body,t,this,{outletName:e});this.selectorObserverMap.set(e,n),n.start()}setupAttributeObserverForOutlet(e){const t=this.attributeNameForOutletName(e),n=new R(this.scope.element,t,this);this.attributeObserverMap.set(e,n),n.start()}selector(e){return this.scope.outlets.getSelectorForOutletName(e)}attributeNameForOutletName(e){return this.scope.schema.outletAttributeForScope(this.identifier,e)}getOutletNameFromOutletAttributeName(e){return this.outletDefinitions.find((t=>this.attributeNameForOutletName(t)===e))}get outletDependencies(){const e=new P;return this.router.modules.forEach((t=>{q(t.definition.controllerConstructor,"outlets").forEach((n=>e.add(n,t.identifier)))})),e}get outletDefinitions(){return this.outletDependencies.getKeysForValue(this.identifier)}get dependentControllerIdentifiers(){return this.outletDependencies.getValuesForKey(this.identifier)}get dependentContexts(){const e=this.dependentControllerIdentifiers;return this.router.contexts.filter((t=>e.includes(t.identifier)))}hasOutlet(e,t){return!!this.getOutlet(e,t)||!!this.getOutletFromMap(e,t)}getOutlet(e,t){return this.application.getControllerForElementAndIdentifier(e,t)}getOutletFromMap(e,t){return this.outletsByName.getValuesForKey(t).find((t=>t.element===e))}get scope(){return this.context.scope}get schema(){return this.context.schema}get identifier(){return this.context.identifier}get application(){return this.context.application}get router(){return this.application.router}}class G{constructor(e,t){this.logDebugActivity=(e,t={})=>{const{identifier:n,controller:s,element:r}=this;t=Object.assign({identifier:n,controller:s,element:r},t),this.application.logDebugActivity(this.identifier,e,t)},this.module=e,this.scope=t,this.controller=new e.controllerConstructor(this),this.bindingObserver=new _(this,this.dispatcher),this.valueObserver=new H(this,this.controller),this.targetObserver=new W(this,this),this.outletObserver=new z(this,this);try{this.controller.initialize(),this.logDebugActivity("initialize")}catch(e){this.handleError(e,"initializing controller")}}connect(){this.bindingObserver.start(),this.valueObserver.start(),this.targetObserver.start(),this.outletObserver.start();try{this.controller.connect(),this.logDebugActivity("connect")}catch(e){this.handleError(e,"connecting controller")}}refresh(){this.outletObserver.refresh()}disconnect(){try{this.controller.disconnect(),this.logDebugActivity("disconnect")}catch(e){this.handleError(e,"disconnecting controller")}this.outletObserver.stop(),this.targetObserver.stop(),this.valueObserver.stop(),this.bindingObserver.stop()}get application(){return this.module.application}get identifier(){return this.module.identifier}get schema(){return this.application.schema}get dispatcher(){return this.application.dispatcher}get element(){return this.scope.element}get parentElement(){return this.element.parentElement}handleError(e,t,n={}){const{identifier:s,controller:r,element:i}=this;n=Object.assign({identifier:s,controller:r,element:i},n),this.application.handleError(e,`Error ${t}`,n)}targetConnected(e,t){this.invokeControllerMethod(`${t}TargetConnected`,e)}targetDisconnected(e,t){this.invokeControllerMethod(`${t}TargetDisconnected`,e)}outletConnected(e,t,n){this.invokeControllerMethod(`${C(n)}OutletConnected`,e,t)}outletDisconnected(e,t,n){this.invokeControllerMethod(`${C(n)}OutletDisconnected`,e,t)}invokeControllerMethod(e,...t){const n=this.controller;"function"==typeof n[e]&&n[e](...t)}}function J(e){return function(e,t){const n=Q(e),s=function(e,t){return Z(t).reduce(((n,s)=>{const r=function(e,t,n){const s=Object.getOwnPropertyDescriptor(e,n);if(!s||!("value"in s)){const e=Object.getOwnPropertyDescriptor(t,n).value;return s&&(e.get=s.get||e.get,e.set=s.set||e.set),e}}(e,t,s);return r&&Object.assign(n,{[s]:r}),n}),{})}(e.prototype,t);return Object.defineProperties(n.prototype,s),n}(e,function(e){const t=q(e,"blessings");return t.reduce(((t,n)=>{const s=n(e);for(const e in s){const n=t[e]||{};t[e]=Object.assign(n,s[e])}return t}),{})}(e))}const Z="function"==typeof Object.getOwnPropertySymbols?e=>[...Object.getOwnPropertyNames(e),...Object.getOwnPropertySymbols(e)]:Object.getOwnPropertyNames,Q=(()=>{function e(e){function t(){return Reflect.construct(e,arguments,new.target)}return t.prototype=Object.create(e.prototype,{constructor:{value:t}}),Reflect.setPrototypeOf(t,e),t}try{return function(){const t=e((function(){this.a.call(this)}));t.prototype.a=function(){},new t}(),e}catch(e){return e=>class extends e{}}})();class X{constructor(e,t){this.application=e,this.definition=function(e){return{identifier:e.identifier,controllerConstructor:J(e.controllerConstructor)}}(t),this.contextsByScope=new WeakMap,this.connectedContexts=new Set}get identifier(){return this.definition.identifier}get controllerConstructor(){return this.definition.controllerConstructor}get contexts(){return Array.from(this.connectedContexts)}connectContextForScope(e){const t=this.fetchContextForScope(e);this.connectedContexts.add(t),t.connect()}disconnectContextForScope(e){const t=this.contextsByScope.get(e);t&&(this.connectedContexts.delete(t),t.disconnect())}fetchContextForScope(e){let t=this.contextsByScope.get(e);return t||(t=new G(this,e),this.contextsByScope.set(e,t)),t}}class Y{constructor(e){this.scope=e}has(e){return this.data.has(this.getDataKey(e))}get(e){return this.getAll(e)[0]}getAll(e){const t=this.data.get(this.getDataKey(e))||"";return t.match(/[^\s]+/g)||[]}getAttributeName(e){return this.data.getAttributeNameForKey(this.getDataKey(e))}getDataKey(e){return`${e}-class`}get data(){return this.scope.data}}class ee{constructor(e){this.scope=e}get element(){return this.scope.element}get identifier(){return this.scope.identifier}get(e){const t=this.getAttributeNameForKey(e);return this.element.getAttribute(t)}set(e,t){const n=this.getAttributeNameForKey(e);return this.element.setAttribute(n,t),this.get(e)}has(e){const t=this.getAttributeNameForKey(e);return this.element.hasAttribute(t)}delete(e){if(this.has(e)){const t=this.getAttributeNameForKey(e);return this.element.removeAttribute(t),!0}return!1}getAttributeNameForKey(e){return`data-${this.identifier}-${t=e,t.replace(/([A-Z])/g,((e,t)=>`-${t.toLowerCase()}`))}`;var t}}class te{constructor(e){this.warnedKeysByObject=new WeakMap,this.logger=e}warn(e,t,n){let s=this.warnedKeysByObject.get(e);s||(s=new Set,this.warnedKeysByObject.set(e,s)),s.has(t)||(s.add(t),this.logger.warn(n,e))}}function ne(e,t){return`[${e}~="${t}"]`}class se{constructor(e){this.scope=e}get element(){return this.scope.element}get identifier(){return this.scope.identifier}get schema(){return this.scope.schema}has(e){return null!=this.find(e)}find(...e){return e.reduce(((e,t)=>e||this.findTarget(t)||this.findLegacyTarget(t)),void 0)}findAll(...e){return e.reduce(((e,t)=>[...e,...this.findAllTargets(t),...this.findAllLegacyTargets(t)]),[])}findTarget(e){const t=this.getSelectorForTargetName(e);return this.scope.findElement(t)}findAllTargets(e){const t=this.getSelectorForTargetName(e);return this.scope.findAllElements(t)}getSelectorForTargetName(e){return ne(this.schema.targetAttributeForScope(this.identifier),e)}findLegacyTarget(e){const t=this.getLegacySelectorForTargetName(e);return this.deprecate(this.scope.findElement(t),e)}findAllLegacyTargets(e){const t=this.getLegacySelectorForTargetName(e);return this.scope.findAllElements(t).map((t=>this.deprecate(t,e)))}getLegacySelectorForTargetName(e){const t=`${this.identifier}.${e}`;return ne(this.schema.targetAttribute,t)}deprecate(e,t){if(e){const{identifier:n}=this,s=this.schema.targetAttribute,r=this.schema.targetAttributeForScope(n);this.guide.warn(e,`target:${t}`,`Please replace ${s}="${n}.${t}" with ${r}="${t}". The ${s} attribute is deprecated and will be removed in a future version of Stimulus.`)}return e}get guide(){return this.scope.guide}}class re{constructor(e,t){this.scope=e,this.controllerElement=t}get element(){return this.scope.element}get identifier(){return this.scope.identifier}get schema(){return this.scope.schema}has(e){return null!=this.find(e)}find(...e){return e.reduce(((e,t)=>e||this.findOutlet(t)),void 0)}findAll(...e){return e.reduce(((e,t)=>[...e,...this.findAllOutlets(t)]),[])}getSelectorForOutletName(e){const t=this.schema.outletAttributeForScope(this.identifier,e);return this.controllerElement.getAttribute(t)}findOutlet(e){const t=this.getSelectorForOutletName(e);if(t)return this.findElement(t,e)}findAllOutlets(e){const t=this.getSelectorForOutletName(e);return t?this.findAllElements(t,e):[]}findElement(e,t){return this.scope.queryElements(e).filter((n=>this.matchesElement(n,e,t)))[0]}findAllElements(e,t){return this.scope.queryElements(e).filter((n=>this.matchesElement(n,e,t)))}matchesElement(e,t,n){const s=e.getAttribute(this.scope.schema.controllerAttribute)||"";return e.matches(t)&&s.split(" ").includes(n)}}class ie{constructor(e,t,n,s){this.targets=new se(this),this.classes=new Y(this),this.data=new ee(this),this.containsElement=e=>e.closest(this.controllerSelector)===this.element,this.schema=e,this.element=t,this.identifier=n,this.guide=new te(s),this.outlets=new re(this.documentScope,t)}findElement(e){return this.element.matches(e)?this.element:this.queryElements(e).find(this.containsElement)}findAllElements(e){return[...this.element.matches(e)?[this.element]:[],...this.queryElements(e).filter(this.containsElement)]}queryElements(e){return Array.from(this.element.querySelectorAll(e))}get controllerSelector(){return ne(this.schema.controllerAttribute,this.identifier)}get isDocumentScope(){return this.element===document.documentElement}get documentScope(){return this.isDocumentScope?this:new ie(this.schema,document.documentElement,this.identifier,this.guide.logger)}}class oe{constructor(e,t,n){this.element=e,this.schema=t,this.delegate=n,this.valueListObserver=new U(this.element,this.controllerAttribute,this),this.scopesByIdentifierByElement=new WeakMap,this.scopeReferenceCounts=new WeakMap}start(){this.valueListObserver.start()}stop(){this.valueListObserver.stop()}get controllerAttribute(){return this.schema.controllerAttribute}parseValueForToken(e){const{element:t,content:n}=e;return this.parseValueForElementAndIdentifier(t,n)}parseValueForElementAndIdentifier(e,t){const n=this.fetchScopesByIdentifierForElement(e);let s=n.get(t);return s||(s=this.delegate.createScopeForElementAndIdentifier(e,t),n.set(t,s)),s}elementMatchedValue(e,t){const n=(this.scopeReferenceCounts.get(t)||0)+1;this.scopeReferenceCounts.set(t,n),1==n&&this.delegate.scopeConnected(t)}elementUnmatchedValue(e,t){const n=this.scopeReferenceCounts.get(t);n&&(this.scopeReferenceCounts.set(t,n-1),1==n&&this.delegate.scopeDisconnected(t))}fetchScopesByIdentifierForElement(e){let t=this.scopesByIdentifierByElement.get(e);return t||(t=new Map,this.scopesByIdentifierByElement.set(e,t)),t}}class ae{constructor(e){this.application=e,this.scopeObserver=new oe(this.element,this.schema,this),this.scopesByIdentifier=new P,this.modulesByIdentifier=new Map}get element(){return this.application.element}get schema(){return this.application.schema}get logger(){return this.application.logger}get controllerAttribute(){return this.schema.controllerAttribute}get modules(){return Array.from(this.modulesByIdentifier.values())}get contexts(){return this.modules.reduce(((e,t)=>e.concat(t.contexts)),[])}start(){this.scopeObserver.start()}stop(){this.scopeObserver.stop()}loadDefinition(e){this.unloadIdentifier(e.identifier);const t=new X(this.application,e);this.connectModule(t);const n=e.controllerConstructor.afterLoad;n&&n.call(e.controllerConstructor,e.identifier,this.application)}unloadIdentifier(e){const t=this.modulesByIdentifier.get(e);t&&this.disconnectModule(t)}getContextForElementAndIdentifier(e,t){const n=this.modulesByIdentifier.get(t);if(n)return n.contexts.find((t=>t.element==e))}proposeToConnectScopeForElementAndIdentifier(e,t){const n=this.scopeObserver.parseValueForElementAndIdentifier(e,t);n?this.scopeObserver.elementMatchedValue(n.element,n):console.error(`Couldn't find or create scope for identifier: "${t}" and element:`,e)}handleError(e,t,n){this.application.handleError(e,t,n)}createScopeForElementAndIdentifier(e,t){return new ie(this.schema,e,t,this.logger)}scopeConnected(e){this.scopesByIdentifier.add(e.identifier,e);const t=this.modulesByIdentifier.get(e.identifier);t&&t.connectContextForScope(e)}scopeDisconnected(e){this.scopesByIdentifier.delete(e.identifier,e);const t=this.modulesByIdentifier.get(e.identifier);t&&t.disconnectContextForScope(e)}connectModule(e){this.modulesByIdentifier.set(e.identifier,e);this.scopesByIdentifier.getValuesForKey(e.identifier).forEach((t=>e.connectContextForScope(t)))}disconnectModule(e){this.modulesByIdentifier.delete(e.identifier);this.scopesByIdentifier.getValuesForKey(e.identifier).forEach((t=>e.disconnectContextForScope(t)))}}const ce={controllerAttribute:"data-controller",actionAttribute:"data-action",targetAttribute:"data-target",targetAttributeForScope:e=>`data-${e}-target`,outletAttributeForScope:(e,t)=>`data-${e}-${t}-outlet`,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"},le("abcdefghijklmnopqrstuvwxyz".split("").map((e=>[e,e])))),le("0123456789".split("").map((e=>[e,e]))))};function le(e){return e.reduce(((e,[t,n])=>Object.assign(Object.assign({},e),{[t]:n})),{})}class he{constructor(e=document.documentElement,t=ce){this.logger=console,this.debug=!1,this.logDebugActivity=(e,t,n={})=>{this.debug&&this.logFormattedMessage(e,t,n)},this.element=e,this.schema=t,this.dispatcher=new w(this),this.router=new ae(this),this.actionDescriptorFilters=Object.assign({},k)}static start(e,t){const n=new this(e,t);return n.start(),n}async start(){await new Promise((e=>{"loading"==document.readyState?document.addEventListener("DOMContentLoaded",(()=>e())):e()})),this.logDebugActivity("application","starting"),this.dispatcher.start(),this.router.start(),this.logDebugActivity("application","start")}stop(){this.logDebugActivity("application","stopping"),this.dispatcher.stop(),this.router.stop(),this.logDebugActivity("application","stop")}register(e,t){this.load({identifier:e,controllerConstructor:t})}registerActionOption(e,t){this.actionDescriptorFilters[e]=t}load(e,...t){(Array.isArray(e)?e:[e,...t]).forEach((e=>{e.controllerConstructor.shouldLoad&&this.router.loadDefinition(e)}))}unload(e,...t){(Array.isArray(e)?e:[e,...t]).forEach((e=>this.router.unloadIdentifier(e)))}get controllers(){return this.router.contexts.map((e=>e.controller))}getControllerForElementAndIdentifier(e,t){const n=this.router.getContextForElementAndIdentifier(e,t);return n?n.controller:null}handleError(e,t,n){var s;this.logger.error("%s\n\n%o\n\n%o",t,e,n),null===(s=window.onerror)||void 0===s||s.call(window,t,"",0,0,e)}logFormattedMessage(e,t,n={}){n=Object.assign({application:this},n),this.logger.groupCollapsed(`${e} #${t}`),this.logger.log("details:",Object.assign({},n)),this.logger.groupEnd()}}class ue{static async reload(e){const t=await y();return new ue(t,e).reload()}constructor(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:/./;this.document=e,this.filePattern=t,this.application=window.Stimulus||he.start()}async reload(){O("Reload Stimulus controllers..."),this.application.stop(),await this.#e(),this.#t(),this.application.start()}async#e(){await Promise.all(this.#n.map((async e=>this.#s(e))))}get#n(){return this.controllerPathsToReload=this.controllerPathsToReload||this.#r.filter((e=>this.#i(e))),this.controllerPathsToReload}get#r(){return Object.keys(this.#o).filter((e=>e.endsWith("_controller")))}#i(e){return this.filePattern.test(e)}get#o(){return this.pathsByModule=this.pathsByModule||this.#a(),this.pathsByModule}#a(){const e=this.document.querySelector("script[type=importmap]");return JSON.parse(e.text).imports}async#s(e){O(`\t${e}`);const t=this.#c(e),n=v(this.#l(e)),s=await import(n);this.#h(t,s)}#t(){this.#u.forEach((e=>this.#d(e.identifier)))}get#u(){return this.#m?[]:this.application.controllers.filter((e=>this.filePattern.test(`${e.identifier}_controller`)))}get#m(){return this.#n.length>0}#l(e){return this.#o[e]}#c(e){return e.replace(/^.*\//,"").replace("_controller","").replace(/\//g,"--").replace(/_/g,"-")}#h(e,t){this.application.unload(e),this.application.register(e,t.default)}#d(e){O(`\tRemoving controller ${e}`),this.application.unload(e)}}class de{static async reload(){return(new de).reload()}async reload(){const e=await this.#p();await this.#g(e)}async#p(){O("Reload html...");const e=await y();return this.#f(e.body),e}#f(e){A.morph(document.body,e)}async#g(e){return new ue(e).reload()}}class me{static async reload(){for(var e=arguments.length,t=new Array(e),n=0;n0&&void 0!==arguments[0]?arguments[0]:/./;this.filePattern=e}async reload(){O("Reload css..."),await Promise.all(await this.#b())}async#b(){return(await this.#v()).map((e=>this.#y(e)))}async#v(){const e=await y();return Array.from(e.head.querySelectorAll("link[rel='stylesheet']"))}#y(e){return this.#A(e)?this.#O(e):Promise.resolve()}#A(e){return this.filePattern.test(e.getAttribute("href"))}async#O(e){return new Promise((t=>{const n=e.getAttribute("href"),s=this.#E(e)||this.#w(e);s.setAttribute("href",v(e.getAttribute("href"))),s.onload=()=>{O(`\t${n}`),t()}}))}#E(e){return this.#k.find((t=>f(e.href)===f(t.href)))}get#k(){return Array.from(document.querySelectorAll("link[rel='stylesheet']"))}#w(e){return document.head.append(e),e}}g.subscriptions.create({channel:"Hotwire::Spark::Channel"},{connected(){document.body.setAttribute("data-hotwire-spark-ready","")},async received(e){try{await this.dispatch(e)}catch(t){console.log(`Error on ${e.action}`,t)}},dispatch(e){let{action:t,path:n}=e;const s=function(e){return e.split("/").pop().split(".")[0]}(n);switch(t){case"reload_html":return this.reloadHtml();case"reload_css":return this.reloadCss(s);case"reload_stimulus":return this.reloadStimulus(s);default:throw new Error(`Unknown action: ${t}`)}},reloadHtml:()=>de.reload(),reloadCss:e=>me.reload(new RegExp(e)),reloadStimulus:e=>ue.reload(new RegExp(e))});const pe={config:{loggingEnabled:!1}};return document.addEventListener("DOMContentLoaded",(function(){var e;pe.config.loggingEnabled=(e="logging",document.querySelector(`meta[name="hotwire-spark:${e}"]`)?.content)})),pe}(); +var HotwireSpark=function(){"use strict";var e={logger:"undefined"!=typeof console?console:void 0,WebSocket:"undefined"!=typeof WebSocket?WebSocket:void 0},t={log(...t){this.enabled&&(t.push(Date.now()),e.logger.log("[ActionCable]",...t))}};const n=()=>(new Date).getTime(),o=e=>(n()-e)/1e3;class i{constructor(e){this.visibilityDidChange=this.visibilityDidChange.bind(this),this.connection=e,this.reconnectAttempts=0}start(){this.isRunning()||(this.startedAt=n(),delete this.stoppedAt,this.startPolling(),addEventListener("visibilitychange",this.visibilityDidChange),t.log(`ConnectionMonitor started. stale threshold = ${this.constructor.staleThreshold} s`))}stop(){this.isRunning()&&(this.stoppedAt=n(),this.stopPolling(),removeEventListener("visibilitychange",this.visibilityDidChange),t.log("ConnectionMonitor stopped"))}isRunning(){return this.startedAt&&!this.stoppedAt}recordMessage(){this.pingedAt=n()}recordConnect(){this.reconnectAttempts=0,delete this.disconnectedAt,t.log("ConnectionMonitor recorded connect")}recordDisconnect(){this.disconnectedAt=n(),t.log("ConnectionMonitor recorded disconnect")}startPolling(){this.stopPolling(),this.poll()}stopPolling(){clearTimeout(this.pollTimeout)}poll(){this.pollTimeout=setTimeout((()=>{this.reconnectIfStale(),this.poll()}),this.getPollInterval())}getPollInterval(){const{staleThreshold:e,reconnectionBackoffRate:t}=this.constructor;return 1e3*e*Math.pow(1+t,Math.min(this.reconnectAttempts,10))*(1+(0===this.reconnectAttempts?1:t)*Math.random())}reconnectIfStale(){this.connectionIsStale()&&(t.log(`ConnectionMonitor detected stale connection. reconnectAttempts = ${this.reconnectAttempts}, time stale = ${o(this.refreshedAt)} s, stale threshold = ${this.constructor.staleThreshold} s`),this.reconnectAttempts++,this.disconnectedRecently()?t.log(`ConnectionMonitor skipping reopening recent disconnect. time disconnected = ${o(this.disconnectedAt)} s`):(t.log("ConnectionMonitor reopening"),this.connection.reopen()))}get refreshedAt(){return this.pingedAt?this.pingedAt:this.startedAt}connectionIsStale(){return o(this.refreshedAt)>this.constructor.staleThreshold}disconnectedRecently(){return this.disconnectedAt&&o(this.disconnectedAt){!this.connectionIsStale()&&this.connection.isOpen()||(t.log(`ConnectionMonitor reopening stale connection on visibilitychange. visibilityState = ${document.visibilityState}`),this.connection.reopen())}),200)}}i.staleThreshold=6,i.reconnectionBackoffRate=.15;var r={message_types:{welcome:"welcome",disconnect:"disconnect",ping:"ping",confirmation:"confirm_subscription",rejection:"reject_subscription"},disconnect_reasons:{unauthorized:"unauthorized",invalid_request:"invalid_request",server_restart:"server_restart",remote:"remote"},default_mount_path:"/cable",protocols:["actioncable-v1-json","actioncable-unsupported"]};const{message_types:s,protocols:l}=r,c=l.slice(0,l.length-1),a=[].indexOf;class u{constructor(e){this.open=this.open.bind(this),this.consumer=e,this.subscriptions=this.consumer.subscriptions,this.monitor=new i(this),this.disconnected=!0}send(e){return!!this.isOpen()&&(this.webSocket.send(JSON.stringify(e)),!0)}open(){if(this.isActive())return t.log(`Attempted to open WebSocket, but existing socket is ${this.getState()}`),!1;{const n=[...l,...this.consumer.subprotocols||[]];return t.log(`Opening WebSocket, current state is ${this.getState()}, subprotocols: ${n}`),this.webSocket&&this.uninstallEventHandlers(),this.webSocket=new e.WebSocket(this.consumer.url,n),this.installEventHandlers(),this.monitor.start(),!0}}close({allowReconnect:e}={allowReconnect:!0}){if(e||this.monitor.stop(),this.isOpen())return this.webSocket.close()}reopen(){if(t.log(`Reopening WebSocket, current state is ${this.getState()}`),!this.isActive())return this.open();try{return this.close()}catch(e){t.log("Failed to reopen WebSocket",e)}finally{t.log(`Reopening WebSocket in ${this.constructor.reopenDelay}ms`),setTimeout(this.open,this.constructor.reopenDelay)}}getProtocol(){if(this.webSocket)return this.webSocket.protocol}isOpen(){return this.isState("open")}isActive(){return this.isState("open","connecting")}triedToReconnect(){return this.monitor.reconnectAttempts>0}isProtocolSupported(){return a.call(c,this.getProtocol())>=0}isState(...e){return a.call(e,this.getState())>=0}getState(){if(this.webSocket)for(let t in e.WebSocket)if(e.WebSocket[t]===this.webSocket.readyState)return t.toLowerCase();return null}installEventHandlers(){for(let e in this.events){const t=this.events[e].bind(this);this.webSocket[`on${e}`]=t}}uninstallEventHandlers(){for(let e in this.events)this.webSocket[`on${e}`]=function(){}}}u.reopenDelay=500,u.prototype.events={message(e){if(!this.isProtocolSupported())return;const{identifier:n,message:o,reason:i,reconnect:r,type:l}=JSON.parse(e.data);switch(this.monitor.recordMessage(),l){case s.welcome:return this.triedToReconnect()&&(this.reconnectAttempted=!0),this.monitor.recordConnect(),this.subscriptions.reload();case s.disconnect:return t.log(`Disconnecting. Reason: ${i}`),this.close({allowReconnect:r});case s.ping:return null;case s.confirmation:return this.subscriptions.confirmSubscription(n),this.reconnectAttempted?(this.reconnectAttempted=!1,this.subscriptions.notify(n,"connected",{reconnected:!0})):this.subscriptions.notify(n,"connected",{reconnected:!1});case s.rejection:return this.subscriptions.reject(n);default:return this.subscriptions.notify(n,"received",o)}},open(){if(t.log(`WebSocket onopen event, using '${this.getProtocol()}' subprotocol`),this.disconnected=!1,!this.isProtocolSupported())return t.log("Protocol is unsupported. Stopping monitor and disconnecting."),this.close({allowReconnect:!1})},close(e){if(t.log("WebSocket onclose event"),!this.disconnected)return this.disconnected=!0,this.monitor.recordDisconnect(),this.subscriptions.notifyAll("disconnected",{willAttemptReconnect:this.monitor.isRunning()})},error(){t.log("WebSocket onerror event")}};class d{constructor(e,t={},n){this.consumer=e,this.identifier=JSON.stringify(t),function(e,t){if(null!=t)for(let n in t){const o=t[n];e[n]=o}}(this,n)}perform(e,t={}){return t.action=e,this.send(t)}send(e){return this.consumer.send({command:"message",identifier:this.identifier,data:JSON.stringify(e)})}unsubscribe(){return this.consumer.subscriptions.remove(this)}}class h{constructor(e){this.subscriptions=e,this.pendingSubscriptions=[]}guarantee(e){-1==this.pendingSubscriptions.indexOf(e)?(t.log(`SubscriptionGuarantor guaranteeing ${e.identifier}`),this.pendingSubscriptions.push(e)):t.log(`SubscriptionGuarantor already guaranteeing ${e.identifier}`),this.startGuaranteeing()}forget(e){t.log(`SubscriptionGuarantor forgetting ${e.identifier}`),this.pendingSubscriptions=this.pendingSubscriptions.filter((t=>t!==e))}startGuaranteeing(){this.stopGuaranteeing(),this.retrySubscribing()}stopGuaranteeing(){clearTimeout(this.retryTimeout)}retrySubscribing(){this.retryTimeout=setTimeout((()=>{this.subscriptions&&"function"==typeof this.subscriptions.subscribe&&this.pendingSubscriptions.map((e=>{t.log(`SubscriptionGuarantor resubscribing ${e.identifier}`),this.subscriptions.subscribe(e)}))}),500)}}class p{constructor(e){this.consumer=e,this.guarantor=new h(this),this.subscriptions=[]}create(e,t){const n="object"==typeof e?e:{channel:e},o=new d(this.consumer,n,t);return this.add(o)}add(e){return this.subscriptions.push(e),this.consumer.ensureActiveConnection(),this.notify(e,"initialized"),this.subscribe(e),e}remove(e){return this.forget(e),this.findAll(e.identifier).length||this.sendCommand(e,"unsubscribe"),e}reject(e){return this.findAll(e).map((e=>(this.forget(e),this.notify(e,"rejected"),e)))}forget(e){return this.guarantor.forget(e),this.subscriptions=this.subscriptions.filter((t=>t!==e)),e}findAll(e){return this.subscriptions.filter((t=>t.identifier===e))}reload(){return this.subscriptions.map((e=>this.subscribe(e)))}notifyAll(e,...t){return this.subscriptions.map((n=>this.notify(n,e,...t)))}notify(e,t,...n){let o;return o="string"==typeof e?this.findAll(e):[e],o.map((e=>"function"==typeof e[t]?e[t](...n):void 0))}subscribe(e){this.sendCommand(e,"subscribe")&&this.guarantor.guarantee(e)}confirmSubscription(e){t.log(`Subscription confirmed ${e}`),this.findAll(e).map((e=>this.guarantor.forget(e)))}sendCommand(e,t){const{identifier:n}=e;return this.consumer.send({command:t,identifier:n})}}class f{constructor(e){this._url=e,this.subscriptions=new p(this),this.connection=new u(this),this.subprotocols=[]}get url(){return function(e){"function"==typeof e&&(e=e());if(e&&!/^wss?:/i.test(e)){const t=document.createElement("a");return t.href=e,t.href=t.href,t.protocol=t.protocol.replace("http","ws"),t.href}return e}(this._url)}send(e){return this.connection.send(e)}connect(){return this.connection.open()}disconnect(){return this.connection.close({allowReconnect:!1})}ensureActiveConnection(){if(!this.connection.isActive())return this.connection.open()}addSubProtocol(e){this.subprotocols=[...this.subprotocols,e]}}var m=function(e=function(e){const t=document.head.querySelector(`meta[name='action-cable-${e}']`);if(t)return t.getAttribute("content")}("url")||r.default_mount_path){return new f(e)}("/hotwire-spark");function g(e){return e.replace(/-[a-z0-9]+\.(\w+)(\?.*)?$/,".$1")}function b(e,t){const n=new URL(e,window.location.origin);return Object.entries(t).forEach((e=>{let[t,o]=e;n.searchParams.set(t,o)})),n.toString()}function v(e){return b(e,{reload:Date.now()})}async function y(){let e=v(b(window.location.href,{hotwire_spark:"true"}));const t=await fetch(e,{headers:{Accept:"text/html"}});if(!t.ok)throw new Error(`${t.status} when fetching ${e}`);const n=await t.text();return(new DOMParser).parseFromString(n,"text/html")}var S=function(){let e=new Set,t={morphStyle:"outerHTML",callbacks:{beforeNodeAdded:a,afterNodeAdded:a,beforeNodeMorphed:a,afterNodeMorphed:a,beforeNodeRemoved:a,afterNodeRemoved:a,beforeAttributeUpdated:a},head:{style:"merge",shouldPreserve:function(e){return"true"===e.getAttribute("im-preserve")},shouldReAppend:function(e){return"true"===e.getAttribute("im-re-append")},shouldRemove:a,afterHeadMorphed:a}};function n(e,t,o){if(o.head.block){let i=e.querySelector("head"),r=t.querySelector("head");if(i&&r){let s=c(r,i,o);return void Promise.all(s).then((function(){n(e,t,Object.assign(o,{head:{block:!1,ignore:!0}}))}))}}if("innerHTML"===o.morphStyle)return r(t,e,o),e.children;if("outerHTML"===o.morphStyle||null==o.morphStyle){let n=function(e,t,n){let o;o=e.firstChild;let i=o,r=0;for(;o;){let e=m(o,t,n);e>r&&(i=o,r=e),o=o.nextSibling}return i}(t,e,o),r=n?.previousSibling,s=n?.nextSibling,l=i(e,n,o);return n?function(e,t,n){let o=[],i=[];for(;null!=e;)o.push(e),e=e.previousSibling;for(;o.length>0;){let e=o.pop();i.push(e),t.parentElement.insertBefore(e,t)}i.push(t);for(;null!=n;)o.push(n),i.push(n),n=n.nextSibling;for(;o.length>0;)t.parentElement.insertBefore(o.pop(),t.nextSibling);return i}(r,l,s):[]}throw"Do not understand how to morph style "+o.morphStyle}function o(e,t){return t.ignoreActiveValue&&e===document.activeElement}function i(e,t,n){if(!n.ignoreActive||e!==document.activeElement)return null==t?!1===n.callbacks.beforeNodeRemoved(e)?e:(e.remove(),n.callbacks.afterNodeRemoved(e),null):d(e,t)?(!1===n.callbacks.beforeNodeMorphed(e,t)||(e instanceof HTMLHeadElement&&n.head.ignore||(e instanceof HTMLHeadElement&&"morph"!==n.head.style?c(t,e,n):(!function(e,t,n){let i=e.nodeType;if(1===i){const o=e.attributes,i=t.attributes;for(const e of o)s(e.name,t,"update",n)||t.getAttribute(e.name)!==e.value&&t.setAttribute(e.name,e.value);for(let o=i.length-1;0<=o;o--){const r=i[o];s(r.name,t,"remove",n)||(e.hasAttribute(r.name)||t.removeAttribute(r.name))}}8!==i&&3!==i||t.nodeValue!==e.nodeValue&&(t.nodeValue=e.nodeValue);o(t,n)||function(e,t,n){if(e instanceof HTMLInputElement&&t instanceof HTMLInputElement&&"file"!==e.type){let o=e.value,i=t.value;l(e,t,"checked",n),l(e,t,"disabled",n),e.hasAttribute("value")?o!==i&&(s("value",t,"update",n)||(t.setAttribute("value",o),t.value=o)):s("value",t,"remove",n)||(t.value="",t.removeAttribute("value"))}else if(e instanceof HTMLOptionElement)l(e,t,"selected",n);else if(e instanceof HTMLTextAreaElement&&t instanceof HTMLTextAreaElement){let o=e.value,i=t.value;if(s("value",t,"update",n))return;o!==i&&(t.value=o),t.firstChild&&t.firstChild.nodeValue!==o&&(t.firstChild.nodeValue=o)}}(e,t,n)}(t,e,n),o(e,n)||r(t,e,n))),n.callbacks.afterNodeMorphed(e,t)),e):!1===n.callbacks.beforeNodeRemoved(e)||!1===n.callbacks.beforeNodeAdded(t)?e:(e.parentElement.replaceChild(t,e),n.callbacks.afterNodeAdded(t),n.callbacks.afterNodeRemoved(e),t)}function r(e,t,n){let o,r=e.firstChild,s=t.firstChild;for(;r;){if(o=r,r=o.nextSibling,null==s){if(!1===n.callbacks.beforeNodeAdded(o))return;t.appendChild(o),n.callbacks.afterNodeAdded(o),y(n,o);continue}if(u(o,s,n)){i(s,o,n),s=s.nextSibling,y(n,o);continue}let l=p(e,t,o,s,n);if(l){s=h(s,l,n),i(l,o,n),y(n,o);continue}let c=f(e,t,o,s,n);if(c)s=h(s,c,n),i(c,o,n),y(n,o);else{if(!1===n.callbacks.beforeNodeAdded(o))return;t.insertBefore(o,s),n.callbacks.afterNodeAdded(o),y(n,o)}}for(;null!==s;){let e=s;s=s.nextSibling,g(e,n)}}function s(e,t,n,o){return!("value"!==e||!o.ignoreActiveValue||t!==document.activeElement)||!1===o.callbacks.beforeAttributeUpdated(e,t,n)}function l(e,t,n,o){if(e[n]!==t[n]){let i=s(n,t,"update",o);i||(t[n]=e[n]),e[n]?i||t.setAttribute(n,e[n]):s(n,t,"remove",o)||t.removeAttribute(n)}}function c(e,t,n){let o=[],i=[],r=[],s=[],l=n.head.style,c=new Map;for(const t of e.children)c.set(t.outerHTML,t);for(const e of t.children){let t=c.has(e.outerHTML),o=n.head.shouldReAppend(e),a=n.head.shouldPreserve(e);t||a?o?i.push(e):(c.delete(e.outerHTML),r.push(e)):"append"===l?o&&(i.push(e),s.push(e)):!1!==n.head.shouldRemove(e)&&i.push(e)}s.push(...c.values());let a=[];for(const e of s){let i=document.createRange().createContextualFragment(e.outerHTML).firstChild;if(!1!==n.callbacks.beforeNodeAdded(i)){if(i.href||i.src){let e=null,t=new Promise((function(t){e=t}));i.addEventListener("load",(function(){e()})),a.push(t)}t.appendChild(i),n.callbacks.afterNodeAdded(i),o.push(i)}}for(const e of i)!1!==n.callbacks.beforeNodeRemoved(e)&&(t.removeChild(e),n.callbacks.afterNodeRemoved(e));return n.head.afterHeadMorphed(t,{added:o,kept:r,removed:i}),a}function a(){}function u(e,t,n){return null!=e&&null!=t&&(e.nodeType===t.nodeType&&e.tagName===t.tagName&&(""!==e.id&&e.id===t.id||S(n,e,t)>0))}function d(e,t){return null!=e&&null!=t&&(e.nodeType===t.nodeType&&e.tagName===t.tagName)}function h(e,t,n){for(;e!==t;){let t=e;e=e.nextSibling,g(t,n)}return y(n,t),t.nextSibling}function p(e,t,n,o,i){let r=S(i,n,t);if(r>0){let t=o,s=0;for(;null!=t;){if(u(n,t,i))return t;if(s+=S(i,t,e),s>r)return null;t=t.nextSibling}}return null}function f(e,t,n,o,i){let r=o,s=n.nextSibling,l=0;for(;null!=r;){if(S(i,r,e)>0)return null;if(d(n,r))return r;if(d(s,r)&&(l++,s=s.nextSibling,l>=2))return null;r=r.nextSibling}return r}function m(e,t,n){return d(e,t)?.5+S(n,e,t):0}function g(e,t){y(t,e),!1!==t.callbacks.beforeNodeRemoved(e)&&(e.remove(),t.callbacks.afterNodeRemoved(e))}function b(e,t){return!e.deadIds.has(t)}function v(t,n,o){return(t.idMap.get(o)||e).has(n)}function y(t,n){let o=t.idMap.get(n)||e;for(const e of o)t.deadIds.add(e)}function S(t,n,o){let i=t.idMap.get(n)||e,r=0;for(const e of i)b(t,e)&&v(t,e,o)&&++r;return r}function A(e,t){let n=e.parentElement,o=e.querySelectorAll("[id]");for(const e of o){let o=e;for(;o!==n&&null!=o;){let n=t.get(o);null==n&&(n=new Set,t.set(o,n)),n.add(e.id),o=o.parentElement}}}function w(e,t){let n=new Map;return A(e,n),A(t,n),n}return{morph:function(e,o,i={}){e instanceof Document&&(e=e.documentElement),"string"==typeof o&&(o=function(e){let t=new DOMParser,n=e.replace(/]*>|>)([\s\S]*?)<\/svg>/gim,"");if(n.match(/<\/html>/)||n.match(/<\/head>/)||n.match(/<\/body>/)){let o=t.parseFromString(e,"text/html");if(n.match(/<\/html>/))return o.generatedByIdiomorph=!0,o;{let e=o.firstChild;return e?(e.generatedByIdiomorph=!0,e):null}}{let n=t.parseFromString("","text/html").body.querySelector("template").content;return n.generatedByIdiomorph=!0,n}}(o));let r=function(e){if(null==e){return document.createElement("div")}if(e.generatedByIdiomorph)return e;if(e instanceof Node){const t=document.createElement("div");return t.append(e),t}{const t=document.createElement("div");for(const n of[...e])t.append(n);return t}}(o),s=function(e,n,o){return o=function(e){let n={};return Object.assign(n,t),Object.assign(n,e),n.callbacks={},Object.assign(n.callbacks,t.callbacks),Object.assign(n.callbacks,e.callbacks),n.head={},Object.assign(n.head,t.head),Object.assign(n.head,e.head),n}(o),{target:e,newContent:n,config:o,morphStyle:o.morphStyle,ignoreActive:o.ignoreActive,ignoreActiveValue:o.ignoreActiveValue,idMap:w(e,n),deadIds:new Set,callbacks:o.callbacks,head:o.head}}(e,r,i);return n(e,r,s)},defaults:t}}();function A(){if(R.config.loggingEnabled){for(var e=arguments.length,t=new Array(e),n=0;n1&&void 0!==arguments[1]?arguments[1]:/./;this.document=e,this.filePattern=t,this.application=window.Stimulus}async reload(){A("Reload Stimulus controllers..."),this.application.stop(),await this.#e(),this.#t(),this.application.start()}async#e(){await Promise.all(this.#n.map((async e=>this.#o(e))))}get#n(){return this.controllerPathsToReload=this.controllerPathsToReload||this.#i.filter((e=>this.#r(e))),this.controllerPathsToReload}get#i(){return Object.keys(this.#s).filter((e=>e.endsWith("_controller")))}#r(e){return this.filePattern.test(e)}get#s(){return this.pathsByModule=this.pathsByModule||this.#l(),this.pathsByModule}#l(){const e=this.document.querySelector("script[type=importmap]");return JSON.parse(e.text).imports}async#o(e){A(`\t${e}`);const t=this.#c(e),n=v(this.#a(e)),o=await import(n);this.#u(t,o)}#t(){this.#d.forEach((e=>this.#h(e.identifier)))}get#d(){return this.#p?[]:this.application.controllers.filter((e=>this.filePattern.test(`${e.identifier}_controller`)))}get#p(){return this.#n.length>0}#a(e){return this.#s[e]}#c(e){return e.replace(/^.*\//,"").replace("_controller","").replace(/\//g,"--").replace(/_/g,"-")}#u(e,t){this.application.unload(e),this.application.register(e,t.default)}#h(e){A(`\tRemoving controller ${e}`),this.application.unload(e)}}class k{static async reload(){return(new k).reload()}async reload(){const e=await this.#f();await this.#m(e)}async#f(){A("Reload html...");const e=await y();return this.#g(e.body),e}#g(e){S.morph(document.body,e)}async#m(e){return new w(e).reload()}}class C{static async reload(){for(var e=arguments.length,t=new Array(e),n=0;n0&&void 0!==arguments[0]?arguments[0]:/./;this.filePattern=e}async reload(){A("Reload css..."),await Promise.all(await this.#b())}async#b(){return(await this.#v()).map((e=>this.#y(e)))}async#v(){const e=await y();return Array.from(e.head.querySelectorAll("link[rel='stylesheet']"))}#y(e){return this.#S(e)?this.#A(e):Promise.resolve()}#S(e){return this.filePattern.test(e.getAttribute("href"))}async#A(e){return new Promise((t=>{const n=e.getAttribute("href"),o=this.#w(e)||this.#k(e);o.setAttribute("href",v(e.getAttribute("href"))),o.onload=()=>{A(`\t${n}`),t()}}))}#w(e){return this.#C.find((t=>g(e.href)===g(t.href)))}get#C(){return Array.from(document.querySelectorAll("link[rel='stylesheet']"))}#k(e){return document.head.append(e),e}}m.subscriptions.create({channel:"Hotwire::Spark::Channel"},{connected(){document.body.setAttribute("data-hotwire-spark-ready","")},async received(e){try{await this.dispatch(e)}catch(t){console.log(`Error on ${e.action}`,t)}},dispatch(e){let{action:t,path:n}=e;const o=function(e){return e.split("/").pop().split(".")[0]}(n);switch(t){case"reload_html":return this.reloadHtml();case"reload_css":return this.reloadCss(o);case"reload_stimulus":return this.reloadStimulus(o);default:throw new Error(`Unknown action: ${t}`)}},reloadHtml:()=>k.reload(),reloadCss:e=>C.reload(new RegExp(e)),reloadStimulus:e=>w.reload(new RegExp(e))});const R={config:{loggingEnabled:!1}};return document.addEventListener("DOMContentLoaded",(function(){var e;R.config.loggingEnabled=(e="logging",document.querySelector(`meta[name="hotwire-spark:${e}"]`)?.content)})),R}(); //# sourceMappingURL=hotwire_spark.min.js.map diff --git a/app/assets/javascripts/hotwire_spark.min.js.map b/app/assets/javascripts/hotwire_spark.min.js.map index 320b32b..727afd2 100644 --- a/app/assets/javascripts/hotwire_spark.min.js.map +++ b/app/assets/javascripts/hotwire_spark.min.js.map @@ -1 +1 @@ -{"version":3,"file":"hotwire_spark.min.js","sources":["../../../node_modules/@rails/actioncable/app/assets/javascripts/actioncable.esm.js","../../javascript/hotwire/spark/channels/consumer.js","../../javascript/hotwire/spark/helpers.js","../../../node_modules/idiomorph/dist/idiomorph.esm.js","../../javascript/hotwire/spark/logger.js","../../../node_modules/@hotwired/stimulus/dist/stimulus.js","../../javascript/hotwire/spark/reloaders/stimulus_reloader.js","../../javascript/hotwire/spark/reloaders/html_reloader.js","../../javascript/hotwire/spark/reloaders/css_reloader.js","../../javascript/hotwire/spark/channels/monitoring_channel.js","../../javascript/hotwire/spark/index.js"],"sourcesContent":["var adapters = {\n logger: typeof console !== \"undefined\" ? console : undefined,\n WebSocket: typeof WebSocket !== \"undefined\" ? WebSocket : undefined\n};\n\nvar logger = {\n log(...messages) {\n if (this.enabled) {\n messages.push(Date.now());\n adapters.logger.log(\"[ActionCable]\", ...messages);\n }\n }\n};\n\nconst now = () => (new Date).getTime();\n\nconst secondsSince = time => (now() - time) / 1e3;\n\nclass ConnectionMonitor {\n constructor(connection) {\n this.visibilityDidChange = this.visibilityDidChange.bind(this);\n this.connection = connection;\n this.reconnectAttempts = 0;\n }\n start() {\n if (!this.isRunning()) {\n this.startedAt = now();\n delete this.stoppedAt;\n this.startPolling();\n addEventListener(\"visibilitychange\", this.visibilityDidChange);\n logger.log(`ConnectionMonitor started. stale threshold = ${this.constructor.staleThreshold} s`);\n }\n }\n stop() {\n if (this.isRunning()) {\n this.stoppedAt = now();\n this.stopPolling();\n removeEventListener(\"visibilitychange\", this.visibilityDidChange);\n logger.log(\"ConnectionMonitor stopped\");\n }\n }\n isRunning() {\n return this.startedAt && !this.stoppedAt;\n }\n recordMessage() {\n this.pingedAt = now();\n }\n recordConnect() {\n this.reconnectAttempts = 0;\n delete this.disconnectedAt;\n logger.log(\"ConnectionMonitor recorded connect\");\n }\n recordDisconnect() {\n this.disconnectedAt = now();\n logger.log(\"ConnectionMonitor recorded disconnect\");\n }\n startPolling() {\n this.stopPolling();\n this.poll();\n }\n stopPolling() {\n clearTimeout(this.pollTimeout);\n }\n poll() {\n this.pollTimeout = setTimeout((() => {\n this.reconnectIfStale();\n this.poll();\n }), this.getPollInterval());\n }\n getPollInterval() {\n const {staleThreshold: staleThreshold, reconnectionBackoffRate: reconnectionBackoffRate} = this.constructor;\n const backoff = Math.pow(1 + reconnectionBackoffRate, Math.min(this.reconnectAttempts, 10));\n const jitterMax = this.reconnectAttempts === 0 ? 1 : reconnectionBackoffRate;\n const jitter = jitterMax * Math.random();\n return staleThreshold * 1e3 * backoff * (1 + jitter);\n }\n reconnectIfStale() {\n if (this.connectionIsStale()) {\n logger.log(`ConnectionMonitor detected stale connection. reconnectAttempts = ${this.reconnectAttempts}, time stale = ${secondsSince(this.refreshedAt)} s, stale threshold = ${this.constructor.staleThreshold} s`);\n this.reconnectAttempts++;\n if (this.disconnectedRecently()) {\n logger.log(`ConnectionMonitor skipping reopening recent disconnect. time disconnected = ${secondsSince(this.disconnectedAt)} s`);\n } else {\n logger.log(\"ConnectionMonitor reopening\");\n this.connection.reopen();\n }\n }\n }\n get refreshedAt() {\n return this.pingedAt ? this.pingedAt : this.startedAt;\n }\n connectionIsStale() {\n return secondsSince(this.refreshedAt) > this.constructor.staleThreshold;\n }\n disconnectedRecently() {\n return this.disconnectedAt && secondsSince(this.disconnectedAt) < this.constructor.staleThreshold;\n }\n visibilityDidChange() {\n if (document.visibilityState === \"visible\") {\n setTimeout((() => {\n if (this.connectionIsStale() || !this.connection.isOpen()) {\n logger.log(`ConnectionMonitor reopening stale connection on visibilitychange. visibilityState = ${document.visibilityState}`);\n this.connection.reopen();\n }\n }), 200);\n }\n }\n}\n\nConnectionMonitor.staleThreshold = 6;\n\nConnectionMonitor.reconnectionBackoffRate = .15;\n\nvar INTERNAL = {\n message_types: {\n welcome: \"welcome\",\n disconnect: \"disconnect\",\n ping: \"ping\",\n confirmation: \"confirm_subscription\",\n rejection: \"reject_subscription\"\n },\n disconnect_reasons: {\n unauthorized: \"unauthorized\",\n invalid_request: \"invalid_request\",\n server_restart: \"server_restart\",\n remote: \"remote\"\n },\n default_mount_path: \"/cable\",\n protocols: [ \"actioncable-v1-json\", \"actioncable-unsupported\" ]\n};\n\nconst {message_types: message_types, protocols: protocols} = INTERNAL;\n\nconst supportedProtocols = protocols.slice(0, protocols.length - 1);\n\nconst indexOf = [].indexOf;\n\nclass Connection {\n constructor(consumer) {\n this.open = this.open.bind(this);\n this.consumer = consumer;\n this.subscriptions = this.consumer.subscriptions;\n this.monitor = new ConnectionMonitor(this);\n this.disconnected = true;\n }\n send(data) {\n if (this.isOpen()) {\n this.webSocket.send(JSON.stringify(data));\n return true;\n } else {\n return false;\n }\n }\n open() {\n if (this.isActive()) {\n logger.log(`Attempted to open WebSocket, but existing socket is ${this.getState()}`);\n return false;\n } else {\n const socketProtocols = [ ...protocols, ...this.consumer.subprotocols || [] ];\n logger.log(`Opening WebSocket, current state is ${this.getState()}, subprotocols: ${socketProtocols}`);\n if (this.webSocket) {\n this.uninstallEventHandlers();\n }\n this.webSocket = new adapters.WebSocket(this.consumer.url, socketProtocols);\n this.installEventHandlers();\n this.monitor.start();\n return true;\n }\n }\n close({allowReconnect: allowReconnect} = {\n allowReconnect: true\n }) {\n if (!allowReconnect) {\n this.monitor.stop();\n }\n if (this.isOpen()) {\n return this.webSocket.close();\n }\n }\n reopen() {\n logger.log(`Reopening WebSocket, current state is ${this.getState()}`);\n if (this.isActive()) {\n try {\n return this.close();\n } catch (error) {\n logger.log(\"Failed to reopen WebSocket\", error);\n } finally {\n logger.log(`Reopening WebSocket in ${this.constructor.reopenDelay}ms`);\n setTimeout(this.open, this.constructor.reopenDelay);\n }\n } else {\n return this.open();\n }\n }\n getProtocol() {\n if (this.webSocket) {\n return this.webSocket.protocol;\n }\n }\n isOpen() {\n return this.isState(\"open\");\n }\n isActive() {\n return this.isState(\"open\", \"connecting\");\n }\n triedToReconnect() {\n return this.monitor.reconnectAttempts > 0;\n }\n isProtocolSupported() {\n return indexOf.call(supportedProtocols, this.getProtocol()) >= 0;\n }\n isState(...states) {\n return indexOf.call(states, this.getState()) >= 0;\n }\n getState() {\n if (this.webSocket) {\n for (let state in adapters.WebSocket) {\n if (adapters.WebSocket[state] === this.webSocket.readyState) {\n return state.toLowerCase();\n }\n }\n }\n return null;\n }\n installEventHandlers() {\n for (let eventName in this.events) {\n const handler = this.events[eventName].bind(this);\n this.webSocket[`on${eventName}`] = handler;\n }\n }\n uninstallEventHandlers() {\n for (let eventName in this.events) {\n this.webSocket[`on${eventName}`] = function() {};\n }\n }\n}\n\nConnection.reopenDelay = 500;\n\nConnection.prototype.events = {\n message(event) {\n if (!this.isProtocolSupported()) {\n return;\n }\n const {identifier: identifier, message: message, reason: reason, reconnect: reconnect, type: type} = JSON.parse(event.data);\n this.monitor.recordMessage();\n switch (type) {\n case message_types.welcome:\n if (this.triedToReconnect()) {\n this.reconnectAttempted = true;\n }\n this.monitor.recordConnect();\n return this.subscriptions.reload();\n\n case message_types.disconnect:\n logger.log(`Disconnecting. Reason: ${reason}`);\n return this.close({\n allowReconnect: reconnect\n });\n\n case message_types.ping:\n return null;\n\n case message_types.confirmation:\n this.subscriptions.confirmSubscription(identifier);\n if (this.reconnectAttempted) {\n this.reconnectAttempted = false;\n return this.subscriptions.notify(identifier, \"connected\", {\n reconnected: true\n });\n } else {\n return this.subscriptions.notify(identifier, \"connected\", {\n reconnected: false\n });\n }\n\n case message_types.rejection:\n return this.subscriptions.reject(identifier);\n\n default:\n return this.subscriptions.notify(identifier, \"received\", message);\n }\n },\n open() {\n logger.log(`WebSocket onopen event, using '${this.getProtocol()}' subprotocol`);\n this.disconnected = false;\n if (!this.isProtocolSupported()) {\n logger.log(\"Protocol is unsupported. Stopping monitor and disconnecting.\");\n return this.close({\n allowReconnect: false\n });\n }\n },\n close(event) {\n logger.log(\"WebSocket onclose event\");\n if (this.disconnected) {\n return;\n }\n this.disconnected = true;\n this.monitor.recordDisconnect();\n return this.subscriptions.notifyAll(\"disconnected\", {\n willAttemptReconnect: this.monitor.isRunning()\n });\n },\n error() {\n logger.log(\"WebSocket onerror event\");\n }\n};\n\nconst extend = function(object, properties) {\n if (properties != null) {\n for (let key in properties) {\n const value = properties[key];\n object[key] = value;\n }\n }\n return object;\n};\n\nclass Subscription {\n constructor(consumer, params = {}, mixin) {\n this.consumer = consumer;\n this.identifier = JSON.stringify(params);\n extend(this, mixin);\n }\n perform(action, data = {}) {\n data.action = action;\n return this.send(data);\n }\n send(data) {\n return this.consumer.send({\n command: \"message\",\n identifier: this.identifier,\n data: JSON.stringify(data)\n });\n }\n unsubscribe() {\n return this.consumer.subscriptions.remove(this);\n }\n}\n\nclass SubscriptionGuarantor {\n constructor(subscriptions) {\n this.subscriptions = subscriptions;\n this.pendingSubscriptions = [];\n }\n guarantee(subscription) {\n if (this.pendingSubscriptions.indexOf(subscription) == -1) {\n logger.log(`SubscriptionGuarantor guaranteeing ${subscription.identifier}`);\n this.pendingSubscriptions.push(subscription);\n } else {\n logger.log(`SubscriptionGuarantor already guaranteeing ${subscription.identifier}`);\n }\n this.startGuaranteeing();\n }\n forget(subscription) {\n logger.log(`SubscriptionGuarantor forgetting ${subscription.identifier}`);\n this.pendingSubscriptions = this.pendingSubscriptions.filter((s => s !== subscription));\n }\n startGuaranteeing() {\n this.stopGuaranteeing();\n this.retrySubscribing();\n }\n stopGuaranteeing() {\n clearTimeout(this.retryTimeout);\n }\n retrySubscribing() {\n this.retryTimeout = setTimeout((() => {\n if (this.subscriptions && typeof this.subscriptions.subscribe === \"function\") {\n this.pendingSubscriptions.map((subscription => {\n logger.log(`SubscriptionGuarantor resubscribing ${subscription.identifier}`);\n this.subscriptions.subscribe(subscription);\n }));\n }\n }), 500);\n }\n}\n\nclass Subscriptions {\n constructor(consumer) {\n this.consumer = consumer;\n this.guarantor = new SubscriptionGuarantor(this);\n this.subscriptions = [];\n }\n create(channelName, mixin) {\n const channel = channelName;\n const params = typeof channel === \"object\" ? channel : {\n channel: channel\n };\n const subscription = new Subscription(this.consumer, params, mixin);\n return this.add(subscription);\n }\n add(subscription) {\n this.subscriptions.push(subscription);\n this.consumer.ensureActiveConnection();\n this.notify(subscription, \"initialized\");\n this.subscribe(subscription);\n return subscription;\n }\n remove(subscription) {\n this.forget(subscription);\n if (!this.findAll(subscription.identifier).length) {\n this.sendCommand(subscription, \"unsubscribe\");\n }\n return subscription;\n }\n reject(identifier) {\n return this.findAll(identifier).map((subscription => {\n this.forget(subscription);\n this.notify(subscription, \"rejected\");\n return subscription;\n }));\n }\n forget(subscription) {\n this.guarantor.forget(subscription);\n this.subscriptions = this.subscriptions.filter((s => s !== subscription));\n return subscription;\n }\n findAll(identifier) {\n return this.subscriptions.filter((s => s.identifier === identifier));\n }\n reload() {\n return this.subscriptions.map((subscription => this.subscribe(subscription)));\n }\n notifyAll(callbackName, ...args) {\n return this.subscriptions.map((subscription => this.notify(subscription, callbackName, ...args)));\n }\n notify(subscription, callbackName, ...args) {\n let subscriptions;\n if (typeof subscription === \"string\") {\n subscriptions = this.findAll(subscription);\n } else {\n subscriptions = [ subscription ];\n }\n return subscriptions.map((subscription => typeof subscription[callbackName] === \"function\" ? subscription[callbackName](...args) : undefined));\n }\n subscribe(subscription) {\n if (this.sendCommand(subscription, \"subscribe\")) {\n this.guarantor.guarantee(subscription);\n }\n }\n confirmSubscription(identifier) {\n logger.log(`Subscription confirmed ${identifier}`);\n this.findAll(identifier).map((subscription => this.guarantor.forget(subscription)));\n }\n sendCommand(subscription, command) {\n const {identifier: identifier} = subscription;\n return this.consumer.send({\n command: command,\n identifier: identifier\n });\n }\n}\n\nclass Consumer {\n constructor(url) {\n this._url = url;\n this.subscriptions = new Subscriptions(this);\n this.connection = new Connection(this);\n this.subprotocols = [];\n }\n get url() {\n return createWebSocketURL(this._url);\n }\n send(data) {\n return this.connection.send(data);\n }\n connect() {\n return this.connection.open();\n }\n disconnect() {\n return this.connection.close({\n allowReconnect: false\n });\n }\n ensureActiveConnection() {\n if (!this.connection.isActive()) {\n return this.connection.open();\n }\n }\n addSubProtocol(subprotocol) {\n this.subprotocols = [ ...this.subprotocols, subprotocol ];\n }\n}\n\nfunction createWebSocketURL(url) {\n if (typeof url === \"function\") {\n url = url();\n }\n if (url && !/^wss?:/i.test(url)) {\n const a = document.createElement(\"a\");\n a.href = url;\n a.href = a.href;\n a.protocol = a.protocol.replace(\"http\", \"ws\");\n return a.href;\n } else {\n return url;\n }\n}\n\nfunction createConsumer(url = getConfig(\"url\") || INTERNAL.default_mount_path) {\n return new Consumer(url);\n}\n\nfunction getConfig(name) {\n const element = document.head.querySelector(`meta[name='action-cable-${name}']`);\n if (element) {\n return element.getAttribute(\"content\");\n }\n}\n\nexport { Connection, ConnectionMonitor, Consumer, INTERNAL, Subscription, SubscriptionGuarantor, Subscriptions, adapters, createConsumer, createWebSocketURL, getConfig, logger };\n","import { createConsumer } from \"@rails/actioncable\"\n\nexport default createConsumer(\"/hotwire-spark\")\n","export function assetNameFromPath(path) {\n return path.split(\"/\").pop().split(\".\")[0]\n}\n\nexport function pathWithoutAssetDigest(path) {\n return path.replace(/-[a-z0-9]+\\.(\\w+)(\\?.*)?$/, \".$1\")\n}\n\nexport function urlWithParams(urlString, params) {\n const url = new URL(urlString, window.location.origin)\n Object.entries(params).forEach(([ key, value ]) => {\n url.searchParams.set(key, value)\n })\n return url.toString()\n}\n\nexport function cacheBustedUrl(urlString) {\n return urlWithParams(urlString, { reload: Date.now() })\n}\n\nexport async function reloadHtmlDocument() {\n let currentUrl = cacheBustedUrl(urlWithParams(window.location.href, { hotwire_spark: \"true\" }))\n const response = await fetch(currentUrl, { headers: { \"Accept\": \"text/html\" }})\n\n if (!response.ok) {\n throw new Error(`${response.status} when fetching ${currentUrl}`)\n }\n\n const fetchedHTML = await response.text()\n const parser = new DOMParser()\n return parser.parseFromString(fetchedHTML, \"text/html\")\n}\n\nexport function getConfigurationProperty(name) {\n return document.querySelector(`meta[name=\"hotwire-spark:${name}\"]`)?.content\n}\n\n","// base IIFE to define idiomorph\nvar Idiomorph = (function () {\n 'use strict';\n\n //=============================================================================\n // AND NOW IT BEGINS...\n //=============================================================================\n let EMPTY_SET = new Set();\n\n // default configuration values, updatable by users now\n let defaults = {\n morphStyle: \"outerHTML\",\n callbacks : {\n beforeNodeAdded: noOp,\n afterNodeAdded: noOp,\n beforeNodeMorphed: noOp,\n afterNodeMorphed: noOp,\n beforeNodeRemoved: noOp,\n afterNodeRemoved: noOp,\n beforeAttributeUpdated: noOp,\n\n },\n head: {\n style: 'merge',\n shouldPreserve: function (elt) {\n return elt.getAttribute(\"im-preserve\") === \"true\";\n },\n shouldReAppend: function (elt) {\n return elt.getAttribute(\"im-re-append\") === \"true\";\n },\n shouldRemove: noOp,\n afterHeadMorphed: noOp,\n }\n };\n\n //=============================================================================\n // Core Morphing Algorithm - morph, morphNormalizedContent, morphOldNodeTo, morphChildren\n //=============================================================================\n function morph(oldNode, newContent, config = {}) {\n\n if (oldNode instanceof Document) {\n oldNode = oldNode.documentElement;\n }\n\n if (typeof newContent === 'string') {\n newContent = parseContent(newContent);\n }\n\n let normalizedContent = normalizeContent(newContent);\n\n let ctx = createMorphContext(oldNode, normalizedContent, config);\n\n return morphNormalizedContent(oldNode, normalizedContent, ctx);\n }\n\n function morphNormalizedContent(oldNode, normalizedNewContent, ctx) {\n if (ctx.head.block) {\n let oldHead = oldNode.querySelector('head');\n let newHead = normalizedNewContent.querySelector('head');\n if (oldHead && newHead) {\n let promises = handleHeadElement(newHead, oldHead, ctx);\n // when head promises resolve, call morph again, ignoring the head tag\n Promise.all(promises).then(function () {\n morphNormalizedContent(oldNode, normalizedNewContent, Object.assign(ctx, {\n head: {\n block: false,\n ignore: true\n }\n }));\n });\n return;\n }\n }\n\n if (ctx.morphStyle === \"innerHTML\") {\n\n // innerHTML, so we are only updating the children\n morphChildren(normalizedNewContent, oldNode, ctx);\n return oldNode.children;\n\n } else if (ctx.morphStyle === \"outerHTML\" || ctx.morphStyle == null) {\n // otherwise find the best element match in the new content, morph that, and merge its siblings\n // into either side of the best match\n let bestMatch = findBestNodeMatch(normalizedNewContent, oldNode, ctx);\n\n // stash the siblings that will need to be inserted on either side of the best match\n let previousSibling = bestMatch?.previousSibling;\n let nextSibling = bestMatch?.nextSibling;\n\n // morph it\n let morphedNode = morphOldNodeTo(oldNode, bestMatch, ctx);\n\n if (bestMatch) {\n // if there was a best match, merge the siblings in too and return the\n // whole bunch\n return insertSiblings(previousSibling, morphedNode, nextSibling);\n } else {\n // otherwise nothing was added to the DOM\n return []\n }\n } else {\n throw \"Do not understand how to morph style \" + ctx.morphStyle;\n }\n }\n\n\n /**\n * @param possibleActiveElement\n * @param ctx\n * @returns {boolean}\n */\n function ignoreValueOfActiveElement(possibleActiveElement, ctx) {\n return ctx.ignoreActiveValue && possibleActiveElement === document.activeElement;\n }\n\n /**\n * @param oldNode root node to merge content into\n * @param newContent new content to merge\n * @param ctx the merge context\n * @returns {Element} the element that ended up in the DOM\n */\n function morphOldNodeTo(oldNode, newContent, ctx) {\n if (ctx.ignoreActive && oldNode === document.activeElement) {\n // don't morph focused element\n } else if (newContent == null) {\n if (ctx.callbacks.beforeNodeRemoved(oldNode) === false) return oldNode;\n\n oldNode.remove();\n ctx.callbacks.afterNodeRemoved(oldNode);\n return null;\n } else if (!isSoftMatch(oldNode, newContent)) {\n if (ctx.callbacks.beforeNodeRemoved(oldNode) === false) return oldNode;\n if (ctx.callbacks.beforeNodeAdded(newContent) === false) return oldNode;\n\n oldNode.parentElement.replaceChild(newContent, oldNode);\n ctx.callbacks.afterNodeAdded(newContent);\n ctx.callbacks.afterNodeRemoved(oldNode);\n return newContent;\n } else {\n if (ctx.callbacks.beforeNodeMorphed(oldNode, newContent) === false) return oldNode;\n\n if (oldNode instanceof HTMLHeadElement && ctx.head.ignore) {\n // ignore the head element\n } else if (oldNode instanceof HTMLHeadElement && ctx.head.style !== \"morph\") {\n handleHeadElement(newContent, oldNode, ctx);\n } else {\n syncNodeFrom(newContent, oldNode, ctx);\n if (!ignoreValueOfActiveElement(oldNode, ctx)) {\n morphChildren(newContent, oldNode, ctx);\n }\n }\n ctx.callbacks.afterNodeMorphed(oldNode, newContent);\n return oldNode;\n }\n }\n\n /**\n * This is the core algorithm for matching up children. The idea is to use id sets to try to match up\n * nodes as faithfully as possible. We greedily match, which allows us to keep the algorithm fast, but\n * by using id sets, we are able to better match up with content deeper in the DOM.\n *\n * Basic algorithm is, for each node in the new content:\n *\n * - if we have reached the end of the old parent, append the new content\n * - if the new content has an id set match with the current insertion point, morph\n * - search for an id set match\n * - if id set match found, morph\n * - otherwise search for a \"soft\" match\n * - if a soft match is found, morph\n * - otherwise, prepend the new node before the current insertion point\n *\n * The two search algorithms terminate if competing node matches appear to outweigh what can be achieved\n * with the current node. See findIdSetMatch() and findSoftMatch() for details.\n *\n * @param {Element} newParent the parent element of the new content\n * @param {Element } oldParent the old content that we are merging the new content into\n * @param ctx the merge context\n */\n function morphChildren(newParent, oldParent, ctx) {\n\n let nextNewChild = newParent.firstChild;\n let insertionPoint = oldParent.firstChild;\n let newChild;\n\n // run through all the new content\n while (nextNewChild) {\n\n newChild = nextNewChild;\n nextNewChild = newChild.nextSibling;\n\n // if we are at the end of the exiting parent's children, just append\n if (insertionPoint == null) {\n if (ctx.callbacks.beforeNodeAdded(newChild) === false) return;\n\n oldParent.appendChild(newChild);\n ctx.callbacks.afterNodeAdded(newChild);\n removeIdsFromConsideration(ctx, newChild);\n continue;\n }\n\n // if the current node has an id set match then morph\n if (isIdSetMatch(newChild, insertionPoint, ctx)) {\n morphOldNodeTo(insertionPoint, newChild, ctx);\n insertionPoint = insertionPoint.nextSibling;\n removeIdsFromConsideration(ctx, newChild);\n continue;\n }\n\n // otherwise search forward in the existing old children for an id set match\n let idSetMatch = findIdSetMatch(newParent, oldParent, newChild, insertionPoint, ctx);\n\n // if we found a potential match, remove the nodes until that point and morph\n if (idSetMatch) {\n insertionPoint = removeNodesBetween(insertionPoint, idSetMatch, ctx);\n morphOldNodeTo(idSetMatch, newChild, ctx);\n removeIdsFromConsideration(ctx, newChild);\n continue;\n }\n\n // no id set match found, so scan forward for a soft match for the current node\n let softMatch = findSoftMatch(newParent, oldParent, newChild, insertionPoint, ctx);\n\n // if we found a soft match for the current node, morph\n if (softMatch) {\n insertionPoint = removeNodesBetween(insertionPoint, softMatch, ctx);\n morphOldNodeTo(softMatch, newChild, ctx);\n removeIdsFromConsideration(ctx, newChild);\n continue;\n }\n\n // abandon all hope of morphing, just insert the new child before the insertion point\n // and move on\n if (ctx.callbacks.beforeNodeAdded(newChild) === false) return;\n\n oldParent.insertBefore(newChild, insertionPoint);\n ctx.callbacks.afterNodeAdded(newChild);\n removeIdsFromConsideration(ctx, newChild);\n }\n\n // remove any remaining old nodes that didn't match up with new content\n while (insertionPoint !== null) {\n\n let tempNode = insertionPoint;\n insertionPoint = insertionPoint.nextSibling;\n removeNode(tempNode, ctx);\n }\n }\n\n //=============================================================================\n // Attribute Syncing Code\n //=============================================================================\n\n /**\n * @param attr {String} the attribute to be mutated\n * @param to {Element} the element that is going to be updated\n * @param updateType {(\"update\"|\"remove\")}\n * @param ctx the merge context\n * @returns {boolean} true if the attribute should be ignored, false otherwise\n */\n function ignoreAttribute(attr, to, updateType, ctx) {\n if(attr === 'value' && ctx.ignoreActiveValue && to === document.activeElement){\n return true;\n }\n return ctx.callbacks.beforeAttributeUpdated(attr, to, updateType) === false;\n }\n\n /**\n * syncs a given node with another node, copying over all attributes and\n * inner element state from the 'from' node to the 'to' node\n *\n * @param {Element} from the element to copy attributes & state from\n * @param {Element} to the element to copy attributes & state to\n * @param ctx the merge context\n */\n function syncNodeFrom(from, to, ctx) {\n let type = from.nodeType\n\n // if is an element type, sync the attributes from the\n // new node into the new node\n if (type === 1 /* element type */) {\n const fromAttributes = from.attributes;\n const toAttributes = to.attributes;\n for (const fromAttribute of fromAttributes) {\n if (ignoreAttribute(fromAttribute.name, to, 'update', ctx)) {\n continue;\n }\n if (to.getAttribute(fromAttribute.name) !== fromAttribute.value) {\n to.setAttribute(fromAttribute.name, fromAttribute.value);\n }\n }\n // iterate backwards to avoid skipping over items when a delete occurs\n for (let i = toAttributes.length - 1; 0 <= i; i--) {\n const toAttribute = toAttributes[i];\n if (ignoreAttribute(toAttribute.name, to, 'remove', ctx)) {\n continue;\n }\n if (!from.hasAttribute(toAttribute.name)) {\n to.removeAttribute(toAttribute.name);\n }\n }\n }\n\n // sync text nodes\n if (type === 8 /* comment */ || type === 3 /* text */) {\n if (to.nodeValue !== from.nodeValue) {\n to.nodeValue = from.nodeValue;\n }\n }\n\n if (!ignoreValueOfActiveElement(to, ctx)) {\n // sync input values\n syncInputValue(from, to, ctx);\n }\n }\n\n /**\n * @param from {Element} element to sync the value from\n * @param to {Element} element to sync the value to\n * @param attributeName {String} the attribute name\n * @param ctx the merge context\n */\n function syncBooleanAttribute(from, to, attributeName, ctx) {\n if (from[attributeName] !== to[attributeName]) {\n let ignoreUpdate = ignoreAttribute(attributeName, to, 'update', ctx);\n if (!ignoreUpdate) {\n to[attributeName] = from[attributeName];\n }\n if (from[attributeName]) {\n if (!ignoreUpdate) {\n to.setAttribute(attributeName, from[attributeName]);\n }\n } else {\n if (!ignoreAttribute(attributeName, to, 'remove', ctx)) {\n to.removeAttribute(attributeName);\n }\n }\n }\n }\n\n /**\n * NB: many bothans died to bring us information:\n *\n * https://github.com/patrick-steele-idem/morphdom/blob/master/src/specialElHandlers.js\n * https://github.com/choojs/nanomorph/blob/master/lib/morph.jsL113\n *\n * @param from {Element} the element to sync the input value from\n * @param to {Element} the element to sync the input value to\n * @param ctx the merge context\n */\n function syncInputValue(from, to, ctx) {\n if (from instanceof HTMLInputElement &&\n to instanceof HTMLInputElement &&\n from.type !== 'file') {\n\n let fromValue = from.value;\n let toValue = to.value;\n\n // sync boolean attributes\n syncBooleanAttribute(from, to, 'checked', ctx);\n syncBooleanAttribute(from, to, 'disabled', ctx);\n\n if (!from.hasAttribute('value')) {\n if (!ignoreAttribute('value', to, 'remove', ctx)) {\n to.value = '';\n to.removeAttribute('value');\n }\n } else if (fromValue !== toValue) {\n if (!ignoreAttribute('value', to, 'update', ctx)) {\n to.setAttribute('value', fromValue);\n to.value = fromValue;\n }\n }\n } else if (from instanceof HTMLOptionElement) {\n syncBooleanAttribute(from, to, 'selected', ctx)\n } else if (from instanceof HTMLTextAreaElement && to instanceof HTMLTextAreaElement) {\n let fromValue = from.value;\n let toValue = to.value;\n if (ignoreAttribute('value', to, 'update', ctx)) {\n return;\n }\n if (fromValue !== toValue) {\n to.value = fromValue;\n }\n if (to.firstChild && to.firstChild.nodeValue !== fromValue) {\n to.firstChild.nodeValue = fromValue\n }\n }\n }\n\n //=============================================================================\n // the HEAD tag can be handled specially, either w/ a 'merge' or 'append' style\n //=============================================================================\n function handleHeadElement(newHeadTag, currentHead, ctx) {\n\n let added = []\n let removed = []\n let preserved = []\n let nodesToAppend = []\n\n let headMergeStyle = ctx.head.style;\n\n // put all new head elements into a Map, by their outerHTML\n let srcToNewHeadNodes = new Map();\n for (const newHeadChild of newHeadTag.children) {\n srcToNewHeadNodes.set(newHeadChild.outerHTML, newHeadChild);\n }\n\n // for each elt in the current head\n for (const currentHeadElt of currentHead.children) {\n\n // If the current head element is in the map\n let inNewContent = srcToNewHeadNodes.has(currentHeadElt.outerHTML);\n let isReAppended = ctx.head.shouldReAppend(currentHeadElt);\n let isPreserved = ctx.head.shouldPreserve(currentHeadElt);\n if (inNewContent || isPreserved) {\n if (isReAppended) {\n // remove the current version and let the new version replace it and re-execute\n removed.push(currentHeadElt);\n } else {\n // this element already exists and should not be re-appended, so remove it from\n // the new content map, preserving it in the DOM\n srcToNewHeadNodes.delete(currentHeadElt.outerHTML);\n preserved.push(currentHeadElt);\n }\n } else {\n if (headMergeStyle === \"append\") {\n // we are appending and this existing element is not new content\n // so if and only if it is marked for re-append do we do anything\n if (isReAppended) {\n removed.push(currentHeadElt);\n nodesToAppend.push(currentHeadElt);\n }\n } else {\n // if this is a merge, we remove this content since it is not in the new head\n if (ctx.head.shouldRemove(currentHeadElt) !== false) {\n removed.push(currentHeadElt);\n }\n }\n }\n }\n\n // Push the remaining new head elements in the Map into the\n // nodes to append to the head tag\n nodesToAppend.push(...srcToNewHeadNodes.values());\n log(\"to append: \", nodesToAppend);\n\n let promises = [];\n for (const newNode of nodesToAppend) {\n log(\"adding: \", newNode);\n let newElt = document.createRange().createContextualFragment(newNode.outerHTML).firstChild;\n log(newElt);\n if (ctx.callbacks.beforeNodeAdded(newElt) !== false) {\n if (newElt.href || newElt.src) {\n let resolve = null;\n let promise = new Promise(function (_resolve) {\n resolve = _resolve;\n });\n newElt.addEventListener('load', function () {\n resolve();\n });\n promises.push(promise);\n }\n currentHead.appendChild(newElt);\n ctx.callbacks.afterNodeAdded(newElt);\n added.push(newElt);\n }\n }\n\n // remove all removed elements, after we have appended the new elements to avoid\n // additional network requests for things like style sheets\n for (const removedElement of removed) {\n if (ctx.callbacks.beforeNodeRemoved(removedElement) !== false) {\n currentHead.removeChild(removedElement);\n ctx.callbacks.afterNodeRemoved(removedElement);\n }\n }\n\n ctx.head.afterHeadMorphed(currentHead, {added: added, kept: preserved, removed: removed});\n return promises;\n }\n\n //=============================================================================\n // Misc\n //=============================================================================\n\n function log() {\n //console.log(arguments);\n }\n\n function noOp() {\n }\n\n /*\n Deep merges the config object and the Idiomoroph.defaults object to\n produce a final configuration object\n */\n function mergeDefaults(config) {\n let finalConfig = {};\n // copy top level stuff into final config\n Object.assign(finalConfig, defaults);\n Object.assign(finalConfig, config);\n\n // copy callbacks into final config (do this to deep merge the callbacks)\n finalConfig.callbacks = {};\n Object.assign(finalConfig.callbacks, defaults.callbacks);\n Object.assign(finalConfig.callbacks, config.callbacks);\n\n // copy head config into final config (do this to deep merge the head)\n finalConfig.head = {};\n Object.assign(finalConfig.head, defaults.head);\n Object.assign(finalConfig.head, config.head);\n return finalConfig;\n }\n\n function createMorphContext(oldNode, newContent, config) {\n config = mergeDefaults(config);\n return {\n target: oldNode,\n newContent: newContent,\n config: config,\n morphStyle: config.morphStyle,\n ignoreActive: config.ignoreActive,\n ignoreActiveValue: config.ignoreActiveValue,\n idMap: createIdMap(oldNode, newContent),\n deadIds: new Set(),\n callbacks: config.callbacks,\n head: config.head\n }\n }\n\n function isIdSetMatch(node1, node2, ctx) {\n if (node1 == null || node2 == null) {\n return false;\n }\n if (node1.nodeType === node2.nodeType && node1.tagName === node2.tagName) {\n if (node1.id !== \"\" && node1.id === node2.id) {\n return true;\n } else {\n return getIdIntersectionCount(ctx, node1, node2) > 0;\n }\n }\n return false;\n }\n\n function isSoftMatch(node1, node2) {\n if (node1 == null || node2 == null) {\n return false;\n }\n return node1.nodeType === node2.nodeType && node1.tagName === node2.tagName\n }\n\n function removeNodesBetween(startInclusive, endExclusive, ctx) {\n while (startInclusive !== endExclusive) {\n let tempNode = startInclusive;\n startInclusive = startInclusive.nextSibling;\n removeNode(tempNode, ctx);\n }\n removeIdsFromConsideration(ctx, endExclusive);\n return endExclusive.nextSibling;\n }\n\n //=============================================================================\n // Scans forward from the insertionPoint in the old parent looking for a potential id match\n // for the newChild. We stop if we find a potential id match for the new child OR\n // if the number of potential id matches we are discarding is greater than the\n // potential id matches for the new child\n //=============================================================================\n function findIdSetMatch(newContent, oldParent, newChild, insertionPoint, ctx) {\n\n // max id matches we are willing to discard in our search\n let newChildPotentialIdCount = getIdIntersectionCount(ctx, newChild, oldParent);\n\n let potentialMatch = null;\n\n // only search forward if there is a possibility of an id match\n if (newChildPotentialIdCount > 0) {\n let potentialMatch = insertionPoint;\n // if there is a possibility of an id match, scan forward\n // keep track of the potential id match count we are discarding (the\n // newChildPotentialIdCount must be greater than this to make it likely\n // worth it)\n let otherMatchCount = 0;\n while (potentialMatch != null) {\n\n // If we have an id match, return the current potential match\n if (isIdSetMatch(newChild, potentialMatch, ctx)) {\n return potentialMatch;\n }\n\n // computer the other potential matches of this new content\n otherMatchCount += getIdIntersectionCount(ctx, potentialMatch, newContent);\n if (otherMatchCount > newChildPotentialIdCount) {\n // if we have more potential id matches in _other_ content, we\n // do not have a good candidate for an id match, so return null\n return null;\n }\n\n // advanced to the next old content child\n potentialMatch = potentialMatch.nextSibling;\n }\n }\n return potentialMatch;\n }\n\n //=============================================================================\n // Scans forward from the insertionPoint in the old parent looking for a potential soft match\n // for the newChild. We stop if we find a potential soft match for the new child OR\n // if we find a potential id match in the old parents children OR if we find two\n // potential soft matches for the next two pieces of new content\n //=============================================================================\n function findSoftMatch(newContent, oldParent, newChild, insertionPoint, ctx) {\n\n let potentialSoftMatch = insertionPoint;\n let nextSibling = newChild.nextSibling;\n let siblingSoftMatchCount = 0;\n\n while (potentialSoftMatch != null) {\n\n if (getIdIntersectionCount(ctx, potentialSoftMatch, newContent) > 0) {\n // the current potential soft match has a potential id set match with the remaining new\n // content so bail out of looking\n return null;\n }\n\n // if we have a soft match with the current node, return it\n if (isSoftMatch(newChild, potentialSoftMatch)) {\n return potentialSoftMatch;\n }\n\n if (isSoftMatch(nextSibling, potentialSoftMatch)) {\n // the next new node has a soft match with this node, so\n // increment the count of future soft matches\n siblingSoftMatchCount++;\n nextSibling = nextSibling.nextSibling;\n\n // If there are two future soft matches, bail to allow the siblings to soft match\n // so that we don't consume future soft matches for the sake of the current node\n if (siblingSoftMatchCount >= 2) {\n return null;\n }\n }\n\n // advanced to the next old content child\n potentialSoftMatch = potentialSoftMatch.nextSibling;\n }\n\n return potentialSoftMatch;\n }\n\n function parseContent(newContent) {\n let parser = new DOMParser();\n\n // remove svgs to avoid false-positive matches on head, etc.\n let contentWithSvgsRemoved = newContent.replace(/]*>|>)([\\s\\S]*?)<\\/svg>/gim, '');\n\n // if the newContent contains a html, head or body tag, we can simply parse it w/o wrapping\n if (contentWithSvgsRemoved.match(/<\\/html>/) || contentWithSvgsRemoved.match(/<\\/head>/) || contentWithSvgsRemoved.match(/<\\/body>/)) {\n let content = parser.parseFromString(newContent, \"text/html\");\n // if it is a full HTML document, return the document itself as the parent container\n if (contentWithSvgsRemoved.match(/<\\/html>/)) {\n content.generatedByIdiomorph = true;\n return content;\n } else {\n // otherwise return the html element as the parent container\n let htmlElement = content.firstChild;\n if (htmlElement) {\n htmlElement.generatedByIdiomorph = true;\n return htmlElement;\n } else {\n return null;\n }\n }\n } else {\n // if it is partial HTML, wrap it in a template tag to provide a parent element and also to help\n // deal with touchy tags like tr, tbody, etc.\n let responseDoc = parser.parseFromString(\"\", \"text/html\");\n let content = responseDoc.body.querySelector('template').content;\n content.generatedByIdiomorph = true;\n return content\n }\n }\n\n function normalizeContent(newContent) {\n if (newContent == null) {\n // noinspection UnnecessaryLocalVariableJS\n const dummyParent = document.createElement('div');\n return dummyParent;\n } else if (newContent.generatedByIdiomorph) {\n // the template tag created by idiomorph parsing can serve as a dummy parent\n return newContent;\n } else if (newContent instanceof Node) {\n // a single node is added as a child to a dummy parent\n const dummyParent = document.createElement('div');\n dummyParent.append(newContent);\n return dummyParent;\n } else {\n // all nodes in the array or HTMLElement collection are consolidated under\n // a single dummy parent element\n const dummyParent = document.createElement('div');\n for (const elt of [...newContent]) {\n dummyParent.append(elt);\n }\n return dummyParent;\n }\n }\n\n function insertSiblings(previousSibling, morphedNode, nextSibling) {\n let stack = []\n let added = []\n while (previousSibling != null) {\n stack.push(previousSibling);\n previousSibling = previousSibling.previousSibling;\n }\n while (stack.length > 0) {\n let node = stack.pop();\n added.push(node); // push added preceding siblings on in order and insert\n morphedNode.parentElement.insertBefore(node, morphedNode);\n }\n added.push(morphedNode);\n while (nextSibling != null) {\n stack.push(nextSibling);\n added.push(nextSibling); // here we are going in order, so push on as we scan, rather than add\n nextSibling = nextSibling.nextSibling;\n }\n while (stack.length > 0) {\n morphedNode.parentElement.insertBefore(stack.pop(), morphedNode.nextSibling);\n }\n return added;\n }\n\n function findBestNodeMatch(newContent, oldNode, ctx) {\n let currentElement;\n currentElement = newContent.firstChild;\n let bestElement = currentElement;\n let score = 0;\n while (currentElement) {\n let newScore = scoreElement(currentElement, oldNode, ctx);\n if (newScore > score) {\n bestElement = currentElement;\n score = newScore;\n }\n currentElement = currentElement.nextSibling;\n }\n return bestElement;\n }\n\n function scoreElement(node1, node2, ctx) {\n if (isSoftMatch(node1, node2)) {\n return .5 + getIdIntersectionCount(ctx, node1, node2);\n }\n return 0;\n }\n\n function removeNode(tempNode, ctx) {\n removeIdsFromConsideration(ctx, tempNode)\n if (ctx.callbacks.beforeNodeRemoved(tempNode) === false) return;\n\n tempNode.remove();\n ctx.callbacks.afterNodeRemoved(tempNode);\n }\n\n //=============================================================================\n // ID Set Functions\n //=============================================================================\n\n function isIdInConsideration(ctx, id) {\n return !ctx.deadIds.has(id);\n }\n\n function idIsWithinNode(ctx, id, targetNode) {\n let idSet = ctx.idMap.get(targetNode) || EMPTY_SET;\n return idSet.has(id);\n }\n\n function removeIdsFromConsideration(ctx, node) {\n let idSet = ctx.idMap.get(node) || EMPTY_SET;\n for (const id of idSet) {\n ctx.deadIds.add(id);\n }\n }\n\n function getIdIntersectionCount(ctx, node1, node2) {\n let sourceSet = ctx.idMap.get(node1) || EMPTY_SET;\n let matchCount = 0;\n for (const id of sourceSet) {\n // a potential match is an id in the source and potentialIdsSet, but\n // that has not already been merged into the DOM\n if (isIdInConsideration(ctx, id) && idIsWithinNode(ctx, id, node2)) {\n ++matchCount;\n }\n }\n return matchCount;\n }\n\n /**\n * A bottom up algorithm that finds all elements with ids inside of the node\n * argument and populates id sets for those nodes and all their parents, generating\n * a set of ids contained within all nodes for the entire hierarchy in the DOM\n *\n * @param node {Element}\n * @param {Map>} idMap\n */\n function populateIdMapForNode(node, idMap) {\n let nodeParent = node.parentElement;\n // find all elements with an id property\n let idElements = node.querySelectorAll('[id]');\n for (const elt of idElements) {\n let current = elt;\n // walk up the parent hierarchy of that element, adding the id\n // of element to the parent's id set\n while (current !== nodeParent && current != null) {\n let idSet = idMap.get(current);\n // if the id set doesn't exist, create it and insert it in the map\n if (idSet == null) {\n idSet = new Set();\n idMap.set(current, idSet);\n }\n idSet.add(elt.id);\n current = current.parentElement;\n }\n }\n }\n\n /**\n * This function computes a map of nodes to all ids contained within that node (inclusive of the\n * node). This map can be used to ask if two nodes have intersecting sets of ids, which allows\n * for a looser definition of \"matching\" than tradition id matching, and allows child nodes\n * to contribute to a parent nodes matching.\n *\n * @param {Element} oldContent the old content that will be morphed\n * @param {Element} newContent the new content to morph to\n * @returns {Map>} a map of nodes to id sets for the\n */\n function createIdMap(oldContent, newContent) {\n let idMap = new Map();\n populateIdMapForNode(oldContent, idMap);\n populateIdMapForNode(newContent, idMap);\n return idMap;\n }\n\n //=============================================================================\n // This is what ends up becoming the Idiomorph global object\n //=============================================================================\n return {\n morph,\n defaults\n }\n })();\n\nexport {Idiomorph};\n","import HotwireSpark from \"./index.js\"\n\nexport function log(...args) {\n if (HotwireSpark.config.loggingEnabled) {\n console.log(`[hotwire_spark]`, ...args)\n }\n}\n\n","/*\nStimulus 3.2.1\nCopyright © 2023 Basecamp, LLC\n */\nclass EventListener {\n constructor(eventTarget, eventName, eventOptions) {\n this.eventTarget = eventTarget;\n this.eventName = eventName;\n this.eventOptions = eventOptions;\n this.unorderedBindings = new Set();\n }\n connect() {\n this.eventTarget.addEventListener(this.eventName, this, this.eventOptions);\n }\n disconnect() {\n this.eventTarget.removeEventListener(this.eventName, this, this.eventOptions);\n }\n bindingConnected(binding) {\n this.unorderedBindings.add(binding);\n }\n bindingDisconnected(binding) {\n this.unorderedBindings.delete(binding);\n }\n handleEvent(event) {\n const extendedEvent = extendEvent(event);\n for (const binding of this.bindings) {\n if (extendedEvent.immediatePropagationStopped) {\n break;\n }\n else {\n binding.handleEvent(extendedEvent);\n }\n }\n }\n hasBindings() {\n return this.unorderedBindings.size > 0;\n }\n get bindings() {\n return Array.from(this.unorderedBindings).sort((left, right) => {\n const leftIndex = left.index, rightIndex = right.index;\n return leftIndex < rightIndex ? -1 : leftIndex > rightIndex ? 1 : 0;\n });\n }\n}\nfunction extendEvent(event) {\n if (\"immediatePropagationStopped\" in event) {\n return event;\n }\n else {\n const { stopImmediatePropagation } = event;\n return Object.assign(event, {\n immediatePropagationStopped: false,\n stopImmediatePropagation() {\n this.immediatePropagationStopped = true;\n stopImmediatePropagation.call(this);\n },\n });\n }\n}\n\nclass Dispatcher {\n constructor(application) {\n this.application = application;\n this.eventListenerMaps = new Map();\n this.started = false;\n }\n start() {\n if (!this.started) {\n this.started = true;\n this.eventListeners.forEach((eventListener) => eventListener.connect());\n }\n }\n stop() {\n if (this.started) {\n this.started = false;\n this.eventListeners.forEach((eventListener) => eventListener.disconnect());\n }\n }\n get eventListeners() {\n return Array.from(this.eventListenerMaps.values()).reduce((listeners, map) => listeners.concat(Array.from(map.values())), []);\n }\n bindingConnected(binding) {\n this.fetchEventListenerForBinding(binding).bindingConnected(binding);\n }\n bindingDisconnected(binding, clearEventListeners = false) {\n this.fetchEventListenerForBinding(binding).bindingDisconnected(binding);\n if (clearEventListeners)\n this.clearEventListenersForBinding(binding);\n }\n handleError(error, message, detail = {}) {\n this.application.handleError(error, `Error ${message}`, detail);\n }\n clearEventListenersForBinding(binding) {\n const eventListener = this.fetchEventListenerForBinding(binding);\n if (!eventListener.hasBindings()) {\n eventListener.disconnect();\n this.removeMappedEventListenerFor(binding);\n }\n }\n removeMappedEventListenerFor(binding) {\n const { eventTarget, eventName, eventOptions } = binding;\n const eventListenerMap = this.fetchEventListenerMapForEventTarget(eventTarget);\n const cacheKey = this.cacheKey(eventName, eventOptions);\n eventListenerMap.delete(cacheKey);\n if (eventListenerMap.size == 0)\n this.eventListenerMaps.delete(eventTarget);\n }\n fetchEventListenerForBinding(binding) {\n const { eventTarget, eventName, eventOptions } = binding;\n return this.fetchEventListener(eventTarget, eventName, eventOptions);\n }\n fetchEventListener(eventTarget, eventName, eventOptions) {\n const eventListenerMap = this.fetchEventListenerMapForEventTarget(eventTarget);\n const cacheKey = this.cacheKey(eventName, eventOptions);\n let eventListener = eventListenerMap.get(cacheKey);\n if (!eventListener) {\n eventListener = this.createEventListener(eventTarget, eventName, eventOptions);\n eventListenerMap.set(cacheKey, eventListener);\n }\n return eventListener;\n }\n createEventListener(eventTarget, eventName, eventOptions) {\n const eventListener = new EventListener(eventTarget, eventName, eventOptions);\n if (this.started) {\n eventListener.connect();\n }\n return eventListener;\n }\n fetchEventListenerMapForEventTarget(eventTarget) {\n let eventListenerMap = this.eventListenerMaps.get(eventTarget);\n if (!eventListenerMap) {\n eventListenerMap = new Map();\n this.eventListenerMaps.set(eventTarget, eventListenerMap);\n }\n return eventListenerMap;\n }\n cacheKey(eventName, eventOptions) {\n const parts = [eventName];\n Object.keys(eventOptions)\n .sort()\n .forEach((key) => {\n parts.push(`${eventOptions[key] ? \"\" : \"!\"}${key}`);\n });\n return parts.join(\":\");\n }\n}\n\nconst defaultActionDescriptorFilters = {\n stop({ event, value }) {\n if (value)\n event.stopPropagation();\n return true;\n },\n prevent({ event, value }) {\n if (value)\n event.preventDefault();\n return true;\n },\n self({ event, value, element }) {\n if (value) {\n return element === event.target;\n }\n else {\n return true;\n }\n },\n};\nconst descriptorPattern = /^(?:(?:([^.]+?)\\+)?(.+?)(?:\\.(.+?))?(?:@(window|document))?->)?(.+?)(?:#([^:]+?))(?::(.+))?$/;\nfunction parseActionDescriptorString(descriptorString) {\n const source = descriptorString.trim();\n const matches = source.match(descriptorPattern) || [];\n let eventName = matches[2];\n let keyFilter = matches[3];\n if (keyFilter && ![\"keydown\", \"keyup\", \"keypress\"].includes(eventName)) {\n eventName += `.${keyFilter}`;\n keyFilter = \"\";\n }\n return {\n eventTarget: parseEventTarget(matches[4]),\n eventName,\n eventOptions: matches[7] ? parseEventOptions(matches[7]) : {},\n identifier: matches[5],\n methodName: matches[6],\n keyFilter: matches[1] || keyFilter,\n };\n}\nfunction parseEventTarget(eventTargetName) {\n if (eventTargetName == \"window\") {\n return window;\n }\n else if (eventTargetName == \"document\") {\n return document;\n }\n}\nfunction parseEventOptions(eventOptions) {\n return eventOptions\n .split(\":\")\n .reduce((options, token) => Object.assign(options, { [token.replace(/^!/, \"\")]: !/^!/.test(token) }), {});\n}\nfunction stringifyEventTarget(eventTarget) {\n if (eventTarget == window) {\n return \"window\";\n }\n else if (eventTarget == document) {\n return \"document\";\n }\n}\n\nfunction camelize(value) {\n return value.replace(/(?:[_-])([a-z0-9])/g, (_, char) => char.toUpperCase());\n}\nfunction namespaceCamelize(value) {\n return camelize(value.replace(/--/g, \"-\").replace(/__/g, \"_\"));\n}\nfunction capitalize(value) {\n return value.charAt(0).toUpperCase() + value.slice(1);\n}\nfunction dasherize(value) {\n return value.replace(/([A-Z])/g, (_, char) => `-${char.toLowerCase()}`);\n}\nfunction tokenize(value) {\n return value.match(/[^\\s]+/g) || [];\n}\n\nfunction isSomething(object) {\n return object !== null && object !== undefined;\n}\nfunction hasProperty(object, property) {\n return Object.prototype.hasOwnProperty.call(object, property);\n}\n\nconst allModifiers = [\"meta\", \"ctrl\", \"alt\", \"shift\"];\nclass Action {\n constructor(element, index, descriptor, schema) {\n this.element = element;\n this.index = index;\n this.eventTarget = descriptor.eventTarget || element;\n this.eventName = descriptor.eventName || getDefaultEventNameForElement(element) || error(\"missing event name\");\n this.eventOptions = descriptor.eventOptions || {};\n this.identifier = descriptor.identifier || error(\"missing identifier\");\n this.methodName = descriptor.methodName || error(\"missing method name\");\n this.keyFilter = descriptor.keyFilter || \"\";\n this.schema = schema;\n }\n static forToken(token, schema) {\n return new this(token.element, token.index, parseActionDescriptorString(token.content), schema);\n }\n toString() {\n const eventFilter = this.keyFilter ? `.${this.keyFilter}` : \"\";\n const eventTarget = this.eventTargetName ? `@${this.eventTargetName}` : \"\";\n return `${this.eventName}${eventFilter}${eventTarget}->${this.identifier}#${this.methodName}`;\n }\n shouldIgnoreKeyboardEvent(event) {\n if (!this.keyFilter) {\n return false;\n }\n const filters = this.keyFilter.split(\"+\");\n if (this.keyFilterDissatisfied(event, filters)) {\n return true;\n }\n const standardFilter = filters.filter((key) => !allModifiers.includes(key))[0];\n if (!standardFilter) {\n return false;\n }\n if (!hasProperty(this.keyMappings, standardFilter)) {\n error(`contains unknown key filter: ${this.keyFilter}`);\n }\n return this.keyMappings[standardFilter].toLowerCase() !== event.key.toLowerCase();\n }\n shouldIgnoreMouseEvent(event) {\n if (!this.keyFilter) {\n return false;\n }\n const filters = [this.keyFilter];\n if (this.keyFilterDissatisfied(event, filters)) {\n return true;\n }\n return false;\n }\n get params() {\n const params = {};\n const pattern = new RegExp(`^data-${this.identifier}-(.+)-param$`, \"i\");\n for (const { name, value } of Array.from(this.element.attributes)) {\n const match = name.match(pattern);\n const key = match && match[1];\n if (key) {\n params[camelize(key)] = typecast(value);\n }\n }\n return params;\n }\n get eventTargetName() {\n return stringifyEventTarget(this.eventTarget);\n }\n get keyMappings() {\n return this.schema.keyMappings;\n }\n keyFilterDissatisfied(event, filters) {\n const [meta, ctrl, alt, shift] = allModifiers.map((modifier) => filters.includes(modifier));\n return event.metaKey !== meta || event.ctrlKey !== ctrl || event.altKey !== alt || event.shiftKey !== shift;\n }\n}\nconst defaultEventNames = {\n a: () => \"click\",\n button: () => \"click\",\n form: () => \"submit\",\n details: () => \"toggle\",\n input: (e) => (e.getAttribute(\"type\") == \"submit\" ? \"click\" : \"input\"),\n select: () => \"change\",\n textarea: () => \"input\",\n};\nfunction getDefaultEventNameForElement(element) {\n const tagName = element.tagName.toLowerCase();\n if (tagName in defaultEventNames) {\n return defaultEventNames[tagName](element);\n }\n}\nfunction error(message) {\n throw new Error(message);\n}\nfunction typecast(value) {\n try {\n return JSON.parse(value);\n }\n catch (o_O) {\n return value;\n }\n}\n\nclass Binding {\n constructor(context, action) {\n this.context = context;\n this.action = action;\n }\n get index() {\n return this.action.index;\n }\n get eventTarget() {\n return this.action.eventTarget;\n }\n get eventOptions() {\n return this.action.eventOptions;\n }\n get identifier() {\n return this.context.identifier;\n }\n handleEvent(event) {\n const actionEvent = this.prepareActionEvent(event);\n if (this.willBeInvokedByEvent(event) && this.applyEventModifiers(actionEvent)) {\n this.invokeWithEvent(actionEvent);\n }\n }\n get eventName() {\n return this.action.eventName;\n }\n get method() {\n const method = this.controller[this.methodName];\n if (typeof method == \"function\") {\n return method;\n }\n throw new Error(`Action \"${this.action}\" references undefined method \"${this.methodName}\"`);\n }\n applyEventModifiers(event) {\n const { element } = this.action;\n const { actionDescriptorFilters } = this.context.application;\n const { controller } = this.context;\n let passes = true;\n for (const [name, value] of Object.entries(this.eventOptions)) {\n if (name in actionDescriptorFilters) {\n const filter = actionDescriptorFilters[name];\n passes = passes && filter({ name, value, event, element, controller });\n }\n else {\n continue;\n }\n }\n return passes;\n }\n prepareActionEvent(event) {\n return Object.assign(event, { params: this.action.params });\n }\n invokeWithEvent(event) {\n const { target, currentTarget } = event;\n try {\n this.method.call(this.controller, event);\n this.context.logDebugActivity(this.methodName, { event, target, currentTarget, action: this.methodName });\n }\n catch (error) {\n const { identifier, controller, element, index } = this;\n const detail = { identifier, controller, element, index, event };\n this.context.handleError(error, `invoking action \"${this.action}\"`, detail);\n }\n }\n willBeInvokedByEvent(event) {\n const eventTarget = event.target;\n if (event instanceof KeyboardEvent && this.action.shouldIgnoreKeyboardEvent(event)) {\n return false;\n }\n if (event instanceof MouseEvent && this.action.shouldIgnoreMouseEvent(event)) {\n return false;\n }\n if (this.element === eventTarget) {\n return true;\n }\n else if (eventTarget instanceof Element && this.element.contains(eventTarget)) {\n return this.scope.containsElement(eventTarget);\n }\n else {\n return this.scope.containsElement(this.action.element);\n }\n }\n get controller() {\n return this.context.controller;\n }\n get methodName() {\n return this.action.methodName;\n }\n get element() {\n return this.scope.element;\n }\n get scope() {\n return this.context.scope;\n }\n}\n\nclass ElementObserver {\n constructor(element, delegate) {\n this.mutationObserverInit = { attributes: true, childList: true, subtree: true };\n this.element = element;\n this.started = false;\n this.delegate = delegate;\n this.elements = new Set();\n this.mutationObserver = new MutationObserver((mutations) => this.processMutations(mutations));\n }\n start() {\n if (!this.started) {\n this.started = true;\n this.mutationObserver.observe(this.element, this.mutationObserverInit);\n this.refresh();\n }\n }\n pause(callback) {\n if (this.started) {\n this.mutationObserver.disconnect();\n this.started = false;\n }\n callback();\n if (!this.started) {\n this.mutationObserver.observe(this.element, this.mutationObserverInit);\n this.started = true;\n }\n }\n stop() {\n if (this.started) {\n this.mutationObserver.takeRecords();\n this.mutationObserver.disconnect();\n this.started = false;\n }\n }\n refresh() {\n if (this.started) {\n const matches = new Set(this.matchElementsInTree());\n for (const element of Array.from(this.elements)) {\n if (!matches.has(element)) {\n this.removeElement(element);\n }\n }\n for (const element of Array.from(matches)) {\n this.addElement(element);\n }\n }\n }\n processMutations(mutations) {\n if (this.started) {\n for (const mutation of mutations) {\n this.processMutation(mutation);\n }\n }\n }\n processMutation(mutation) {\n if (mutation.type == \"attributes\") {\n this.processAttributeChange(mutation.target, mutation.attributeName);\n }\n else if (mutation.type == \"childList\") {\n this.processRemovedNodes(mutation.removedNodes);\n this.processAddedNodes(mutation.addedNodes);\n }\n }\n processAttributeChange(element, attributeName) {\n if (this.elements.has(element)) {\n if (this.delegate.elementAttributeChanged && this.matchElement(element)) {\n this.delegate.elementAttributeChanged(element, attributeName);\n }\n else {\n this.removeElement(element);\n }\n }\n else if (this.matchElement(element)) {\n this.addElement(element);\n }\n }\n processRemovedNodes(nodes) {\n for (const node of Array.from(nodes)) {\n const element = this.elementFromNode(node);\n if (element) {\n this.processTree(element, this.removeElement);\n }\n }\n }\n processAddedNodes(nodes) {\n for (const node of Array.from(nodes)) {\n const element = this.elementFromNode(node);\n if (element && this.elementIsActive(element)) {\n this.processTree(element, this.addElement);\n }\n }\n }\n matchElement(element) {\n return this.delegate.matchElement(element);\n }\n matchElementsInTree(tree = this.element) {\n return this.delegate.matchElementsInTree(tree);\n }\n processTree(tree, processor) {\n for (const element of this.matchElementsInTree(tree)) {\n processor.call(this, element);\n }\n }\n elementFromNode(node) {\n if (node.nodeType == Node.ELEMENT_NODE) {\n return node;\n }\n }\n elementIsActive(element) {\n if (element.isConnected != this.element.isConnected) {\n return false;\n }\n else {\n return this.element.contains(element);\n }\n }\n addElement(element) {\n if (!this.elements.has(element)) {\n if (this.elementIsActive(element)) {\n this.elements.add(element);\n if (this.delegate.elementMatched) {\n this.delegate.elementMatched(element);\n }\n }\n }\n }\n removeElement(element) {\n if (this.elements.has(element)) {\n this.elements.delete(element);\n if (this.delegate.elementUnmatched) {\n this.delegate.elementUnmatched(element);\n }\n }\n }\n}\n\nclass AttributeObserver {\n constructor(element, attributeName, delegate) {\n this.attributeName = attributeName;\n this.delegate = delegate;\n this.elementObserver = new ElementObserver(element, this);\n }\n get element() {\n return this.elementObserver.element;\n }\n get selector() {\n return `[${this.attributeName}]`;\n }\n start() {\n this.elementObserver.start();\n }\n pause(callback) {\n this.elementObserver.pause(callback);\n }\n stop() {\n this.elementObserver.stop();\n }\n refresh() {\n this.elementObserver.refresh();\n }\n get started() {\n return this.elementObserver.started;\n }\n matchElement(element) {\n return element.hasAttribute(this.attributeName);\n }\n matchElementsInTree(tree) {\n const match = this.matchElement(tree) ? [tree] : [];\n const matches = Array.from(tree.querySelectorAll(this.selector));\n return match.concat(matches);\n }\n elementMatched(element) {\n if (this.delegate.elementMatchedAttribute) {\n this.delegate.elementMatchedAttribute(element, this.attributeName);\n }\n }\n elementUnmatched(element) {\n if (this.delegate.elementUnmatchedAttribute) {\n this.delegate.elementUnmatchedAttribute(element, this.attributeName);\n }\n }\n elementAttributeChanged(element, attributeName) {\n if (this.delegate.elementAttributeValueChanged && this.attributeName == attributeName) {\n this.delegate.elementAttributeValueChanged(element, attributeName);\n }\n }\n}\n\nfunction add(map, key, value) {\n fetch(map, key).add(value);\n}\nfunction del(map, key, value) {\n fetch(map, key).delete(value);\n prune(map, key);\n}\nfunction fetch(map, key) {\n let values = map.get(key);\n if (!values) {\n values = new Set();\n map.set(key, values);\n }\n return values;\n}\nfunction prune(map, key) {\n const values = map.get(key);\n if (values != null && values.size == 0) {\n map.delete(key);\n }\n}\n\nclass Multimap {\n constructor() {\n this.valuesByKey = new Map();\n }\n get keys() {\n return Array.from(this.valuesByKey.keys());\n }\n get values() {\n const sets = Array.from(this.valuesByKey.values());\n return sets.reduce((values, set) => values.concat(Array.from(set)), []);\n }\n get size() {\n const sets = Array.from(this.valuesByKey.values());\n return sets.reduce((size, set) => size + set.size, 0);\n }\n add(key, value) {\n add(this.valuesByKey, key, value);\n }\n delete(key, value) {\n del(this.valuesByKey, key, value);\n }\n has(key, value) {\n const values = this.valuesByKey.get(key);\n return values != null && values.has(value);\n }\n hasKey(key) {\n return this.valuesByKey.has(key);\n }\n hasValue(value) {\n const sets = Array.from(this.valuesByKey.values());\n return sets.some((set) => set.has(value));\n }\n getValuesForKey(key) {\n const values = this.valuesByKey.get(key);\n return values ? Array.from(values) : [];\n }\n getKeysForValue(value) {\n return Array.from(this.valuesByKey)\n .filter(([_key, values]) => values.has(value))\n .map(([key, _values]) => key);\n }\n}\n\nclass IndexedMultimap extends Multimap {\n constructor() {\n super();\n this.keysByValue = new Map();\n }\n get values() {\n return Array.from(this.keysByValue.keys());\n }\n add(key, value) {\n super.add(key, value);\n add(this.keysByValue, value, key);\n }\n delete(key, value) {\n super.delete(key, value);\n del(this.keysByValue, value, key);\n }\n hasValue(value) {\n return this.keysByValue.has(value);\n }\n getKeysForValue(value) {\n const set = this.keysByValue.get(value);\n return set ? Array.from(set) : [];\n }\n}\n\nclass SelectorObserver {\n constructor(element, selector, delegate, details) {\n this._selector = selector;\n this.details = details;\n this.elementObserver = new ElementObserver(element, this);\n this.delegate = delegate;\n this.matchesByElement = new Multimap();\n }\n get started() {\n return this.elementObserver.started;\n }\n get selector() {\n return this._selector;\n }\n set selector(selector) {\n this._selector = selector;\n this.refresh();\n }\n start() {\n this.elementObserver.start();\n }\n pause(callback) {\n this.elementObserver.pause(callback);\n }\n stop() {\n this.elementObserver.stop();\n }\n refresh() {\n this.elementObserver.refresh();\n }\n get element() {\n return this.elementObserver.element;\n }\n matchElement(element) {\n const { selector } = this;\n if (selector) {\n const matches = element.matches(selector);\n if (this.delegate.selectorMatchElement) {\n return matches && this.delegate.selectorMatchElement(element, this.details);\n }\n return matches;\n }\n else {\n return false;\n }\n }\n matchElementsInTree(tree) {\n const { selector } = this;\n if (selector) {\n const match = this.matchElement(tree) ? [tree] : [];\n const matches = Array.from(tree.querySelectorAll(selector)).filter((match) => this.matchElement(match));\n return match.concat(matches);\n }\n else {\n return [];\n }\n }\n elementMatched(element) {\n const { selector } = this;\n if (selector) {\n this.selectorMatched(element, selector);\n }\n }\n elementUnmatched(element) {\n const selectors = this.matchesByElement.getKeysForValue(element);\n for (const selector of selectors) {\n this.selectorUnmatched(element, selector);\n }\n }\n elementAttributeChanged(element, _attributeName) {\n const { selector } = this;\n if (selector) {\n const matches = this.matchElement(element);\n const matchedBefore = this.matchesByElement.has(selector, element);\n if (matches && !matchedBefore) {\n this.selectorMatched(element, selector);\n }\n else if (!matches && matchedBefore) {\n this.selectorUnmatched(element, selector);\n }\n }\n }\n selectorMatched(element, selector) {\n this.delegate.selectorMatched(element, selector, this.details);\n this.matchesByElement.add(selector, element);\n }\n selectorUnmatched(element, selector) {\n this.delegate.selectorUnmatched(element, selector, this.details);\n this.matchesByElement.delete(selector, element);\n }\n}\n\nclass StringMapObserver {\n constructor(element, delegate) {\n this.element = element;\n this.delegate = delegate;\n this.started = false;\n this.stringMap = new Map();\n this.mutationObserver = new MutationObserver((mutations) => this.processMutations(mutations));\n }\n start() {\n if (!this.started) {\n this.started = true;\n this.mutationObserver.observe(this.element, { attributes: true, attributeOldValue: true });\n this.refresh();\n }\n }\n stop() {\n if (this.started) {\n this.mutationObserver.takeRecords();\n this.mutationObserver.disconnect();\n this.started = false;\n }\n }\n refresh() {\n if (this.started) {\n for (const attributeName of this.knownAttributeNames) {\n this.refreshAttribute(attributeName, null);\n }\n }\n }\n processMutations(mutations) {\n if (this.started) {\n for (const mutation of mutations) {\n this.processMutation(mutation);\n }\n }\n }\n processMutation(mutation) {\n const attributeName = mutation.attributeName;\n if (attributeName) {\n this.refreshAttribute(attributeName, mutation.oldValue);\n }\n }\n refreshAttribute(attributeName, oldValue) {\n const key = this.delegate.getStringMapKeyForAttribute(attributeName);\n if (key != null) {\n if (!this.stringMap.has(attributeName)) {\n this.stringMapKeyAdded(key, attributeName);\n }\n const value = this.element.getAttribute(attributeName);\n if (this.stringMap.get(attributeName) != value) {\n this.stringMapValueChanged(value, key, oldValue);\n }\n if (value == null) {\n const oldValue = this.stringMap.get(attributeName);\n this.stringMap.delete(attributeName);\n if (oldValue)\n this.stringMapKeyRemoved(key, attributeName, oldValue);\n }\n else {\n this.stringMap.set(attributeName, value);\n }\n }\n }\n stringMapKeyAdded(key, attributeName) {\n if (this.delegate.stringMapKeyAdded) {\n this.delegate.stringMapKeyAdded(key, attributeName);\n }\n }\n stringMapValueChanged(value, key, oldValue) {\n if (this.delegate.stringMapValueChanged) {\n this.delegate.stringMapValueChanged(value, key, oldValue);\n }\n }\n stringMapKeyRemoved(key, attributeName, oldValue) {\n if (this.delegate.stringMapKeyRemoved) {\n this.delegate.stringMapKeyRemoved(key, attributeName, oldValue);\n }\n }\n get knownAttributeNames() {\n return Array.from(new Set(this.currentAttributeNames.concat(this.recordedAttributeNames)));\n }\n get currentAttributeNames() {\n return Array.from(this.element.attributes).map((attribute) => attribute.name);\n }\n get recordedAttributeNames() {\n return Array.from(this.stringMap.keys());\n }\n}\n\nclass TokenListObserver {\n constructor(element, attributeName, delegate) {\n this.attributeObserver = new AttributeObserver(element, attributeName, this);\n this.delegate = delegate;\n this.tokensByElement = new Multimap();\n }\n get started() {\n return this.attributeObserver.started;\n }\n start() {\n this.attributeObserver.start();\n }\n pause(callback) {\n this.attributeObserver.pause(callback);\n }\n stop() {\n this.attributeObserver.stop();\n }\n refresh() {\n this.attributeObserver.refresh();\n }\n get element() {\n return this.attributeObserver.element;\n }\n get attributeName() {\n return this.attributeObserver.attributeName;\n }\n elementMatchedAttribute(element) {\n this.tokensMatched(this.readTokensForElement(element));\n }\n elementAttributeValueChanged(element) {\n const [unmatchedTokens, matchedTokens] = this.refreshTokensForElement(element);\n this.tokensUnmatched(unmatchedTokens);\n this.tokensMatched(matchedTokens);\n }\n elementUnmatchedAttribute(element) {\n this.tokensUnmatched(this.tokensByElement.getValuesForKey(element));\n }\n tokensMatched(tokens) {\n tokens.forEach((token) => this.tokenMatched(token));\n }\n tokensUnmatched(tokens) {\n tokens.forEach((token) => this.tokenUnmatched(token));\n }\n tokenMatched(token) {\n this.delegate.tokenMatched(token);\n this.tokensByElement.add(token.element, token);\n }\n tokenUnmatched(token) {\n this.delegate.tokenUnmatched(token);\n this.tokensByElement.delete(token.element, token);\n }\n refreshTokensForElement(element) {\n const previousTokens = this.tokensByElement.getValuesForKey(element);\n const currentTokens = this.readTokensForElement(element);\n const firstDifferingIndex = zip(previousTokens, currentTokens).findIndex(([previousToken, currentToken]) => !tokensAreEqual(previousToken, currentToken));\n if (firstDifferingIndex == -1) {\n return [[], []];\n }\n else {\n return [previousTokens.slice(firstDifferingIndex), currentTokens.slice(firstDifferingIndex)];\n }\n }\n readTokensForElement(element) {\n const attributeName = this.attributeName;\n const tokenString = element.getAttribute(attributeName) || \"\";\n return parseTokenString(tokenString, element, attributeName);\n }\n}\nfunction parseTokenString(tokenString, element, attributeName) {\n return tokenString\n .trim()\n .split(/\\s+/)\n .filter((content) => content.length)\n .map((content, index) => ({ element, attributeName, content, index }));\n}\nfunction zip(left, right) {\n const length = Math.max(left.length, right.length);\n return Array.from({ length }, (_, index) => [left[index], right[index]]);\n}\nfunction tokensAreEqual(left, right) {\n return left && right && left.index == right.index && left.content == right.content;\n}\n\nclass ValueListObserver {\n constructor(element, attributeName, delegate) {\n this.tokenListObserver = new TokenListObserver(element, attributeName, this);\n this.delegate = delegate;\n this.parseResultsByToken = new WeakMap();\n this.valuesByTokenByElement = new WeakMap();\n }\n get started() {\n return this.tokenListObserver.started;\n }\n start() {\n this.tokenListObserver.start();\n }\n stop() {\n this.tokenListObserver.stop();\n }\n refresh() {\n this.tokenListObserver.refresh();\n }\n get element() {\n return this.tokenListObserver.element;\n }\n get attributeName() {\n return this.tokenListObserver.attributeName;\n }\n tokenMatched(token) {\n const { element } = token;\n const { value } = this.fetchParseResultForToken(token);\n if (value) {\n this.fetchValuesByTokenForElement(element).set(token, value);\n this.delegate.elementMatchedValue(element, value);\n }\n }\n tokenUnmatched(token) {\n const { element } = token;\n const { value } = this.fetchParseResultForToken(token);\n if (value) {\n this.fetchValuesByTokenForElement(element).delete(token);\n this.delegate.elementUnmatchedValue(element, value);\n }\n }\n fetchParseResultForToken(token) {\n let parseResult = this.parseResultsByToken.get(token);\n if (!parseResult) {\n parseResult = this.parseToken(token);\n this.parseResultsByToken.set(token, parseResult);\n }\n return parseResult;\n }\n fetchValuesByTokenForElement(element) {\n let valuesByToken = this.valuesByTokenByElement.get(element);\n if (!valuesByToken) {\n valuesByToken = new Map();\n this.valuesByTokenByElement.set(element, valuesByToken);\n }\n return valuesByToken;\n }\n parseToken(token) {\n try {\n const value = this.delegate.parseValueForToken(token);\n return { value };\n }\n catch (error) {\n return { error };\n }\n }\n}\n\nclass BindingObserver {\n constructor(context, delegate) {\n this.context = context;\n this.delegate = delegate;\n this.bindingsByAction = new Map();\n }\n start() {\n if (!this.valueListObserver) {\n this.valueListObserver = new ValueListObserver(this.element, this.actionAttribute, this);\n this.valueListObserver.start();\n }\n }\n stop() {\n if (this.valueListObserver) {\n this.valueListObserver.stop();\n delete this.valueListObserver;\n this.disconnectAllActions();\n }\n }\n get element() {\n return this.context.element;\n }\n get identifier() {\n return this.context.identifier;\n }\n get actionAttribute() {\n return this.schema.actionAttribute;\n }\n get schema() {\n return this.context.schema;\n }\n get bindings() {\n return Array.from(this.bindingsByAction.values());\n }\n connectAction(action) {\n const binding = new Binding(this.context, action);\n this.bindingsByAction.set(action, binding);\n this.delegate.bindingConnected(binding);\n }\n disconnectAction(action) {\n const binding = this.bindingsByAction.get(action);\n if (binding) {\n this.bindingsByAction.delete(action);\n this.delegate.bindingDisconnected(binding);\n }\n }\n disconnectAllActions() {\n this.bindings.forEach((binding) => this.delegate.bindingDisconnected(binding, true));\n this.bindingsByAction.clear();\n }\n parseValueForToken(token) {\n const action = Action.forToken(token, this.schema);\n if (action.identifier == this.identifier) {\n return action;\n }\n }\n elementMatchedValue(element, action) {\n this.connectAction(action);\n }\n elementUnmatchedValue(element, action) {\n this.disconnectAction(action);\n }\n}\n\nclass ValueObserver {\n constructor(context, receiver) {\n this.context = context;\n this.receiver = receiver;\n this.stringMapObserver = new StringMapObserver(this.element, this);\n this.valueDescriptorMap = this.controller.valueDescriptorMap;\n }\n start() {\n this.stringMapObserver.start();\n this.invokeChangedCallbacksForDefaultValues();\n }\n stop() {\n this.stringMapObserver.stop();\n }\n get element() {\n return this.context.element;\n }\n get controller() {\n return this.context.controller;\n }\n getStringMapKeyForAttribute(attributeName) {\n if (attributeName in this.valueDescriptorMap) {\n return this.valueDescriptorMap[attributeName].name;\n }\n }\n stringMapKeyAdded(key, attributeName) {\n const descriptor = this.valueDescriptorMap[attributeName];\n if (!this.hasValue(key)) {\n this.invokeChangedCallback(key, descriptor.writer(this.receiver[key]), descriptor.writer(descriptor.defaultValue));\n }\n }\n stringMapValueChanged(value, name, oldValue) {\n const descriptor = this.valueDescriptorNameMap[name];\n if (value === null)\n return;\n if (oldValue === null) {\n oldValue = descriptor.writer(descriptor.defaultValue);\n }\n this.invokeChangedCallback(name, value, oldValue);\n }\n stringMapKeyRemoved(key, attributeName, oldValue) {\n const descriptor = this.valueDescriptorNameMap[key];\n if (this.hasValue(key)) {\n this.invokeChangedCallback(key, descriptor.writer(this.receiver[key]), oldValue);\n }\n else {\n this.invokeChangedCallback(key, descriptor.writer(descriptor.defaultValue), oldValue);\n }\n }\n invokeChangedCallbacksForDefaultValues() {\n for (const { key, name, defaultValue, writer } of this.valueDescriptors) {\n if (defaultValue != undefined && !this.controller.data.has(key)) {\n this.invokeChangedCallback(name, writer(defaultValue), undefined);\n }\n }\n }\n invokeChangedCallback(name, rawValue, rawOldValue) {\n const changedMethodName = `${name}Changed`;\n const changedMethod = this.receiver[changedMethodName];\n if (typeof changedMethod == \"function\") {\n const descriptor = this.valueDescriptorNameMap[name];\n try {\n const value = descriptor.reader(rawValue);\n let oldValue = rawOldValue;\n if (rawOldValue) {\n oldValue = descriptor.reader(rawOldValue);\n }\n changedMethod.call(this.receiver, value, oldValue);\n }\n catch (error) {\n if (error instanceof TypeError) {\n error.message = `Stimulus Value \"${this.context.identifier}.${descriptor.name}\" - ${error.message}`;\n }\n throw error;\n }\n }\n }\n get valueDescriptors() {\n const { valueDescriptorMap } = this;\n return Object.keys(valueDescriptorMap).map((key) => valueDescriptorMap[key]);\n }\n get valueDescriptorNameMap() {\n const descriptors = {};\n Object.keys(this.valueDescriptorMap).forEach((key) => {\n const descriptor = this.valueDescriptorMap[key];\n descriptors[descriptor.name] = descriptor;\n });\n return descriptors;\n }\n hasValue(attributeName) {\n const descriptor = this.valueDescriptorNameMap[attributeName];\n const hasMethodName = `has${capitalize(descriptor.name)}`;\n return this.receiver[hasMethodName];\n }\n}\n\nclass TargetObserver {\n constructor(context, delegate) {\n this.context = context;\n this.delegate = delegate;\n this.targetsByName = new Multimap();\n }\n start() {\n if (!this.tokenListObserver) {\n this.tokenListObserver = new TokenListObserver(this.element, this.attributeName, this);\n this.tokenListObserver.start();\n }\n }\n stop() {\n if (this.tokenListObserver) {\n this.disconnectAllTargets();\n this.tokenListObserver.stop();\n delete this.tokenListObserver;\n }\n }\n tokenMatched({ element, content: name }) {\n if (this.scope.containsElement(element)) {\n this.connectTarget(element, name);\n }\n }\n tokenUnmatched({ element, content: name }) {\n this.disconnectTarget(element, name);\n }\n connectTarget(element, name) {\n var _a;\n if (!this.targetsByName.has(name, element)) {\n this.targetsByName.add(name, element);\n (_a = this.tokenListObserver) === null || _a === void 0 ? void 0 : _a.pause(() => this.delegate.targetConnected(element, name));\n }\n }\n disconnectTarget(element, name) {\n var _a;\n if (this.targetsByName.has(name, element)) {\n this.targetsByName.delete(name, element);\n (_a = this.tokenListObserver) === null || _a === void 0 ? void 0 : _a.pause(() => this.delegate.targetDisconnected(element, name));\n }\n }\n disconnectAllTargets() {\n for (const name of this.targetsByName.keys) {\n for (const element of this.targetsByName.getValuesForKey(name)) {\n this.disconnectTarget(element, name);\n }\n }\n }\n get attributeName() {\n return `data-${this.context.identifier}-target`;\n }\n get element() {\n return this.context.element;\n }\n get scope() {\n return this.context.scope;\n }\n}\n\nfunction readInheritableStaticArrayValues(constructor, propertyName) {\n const ancestors = getAncestorsForConstructor(constructor);\n return Array.from(ancestors.reduce((values, constructor) => {\n getOwnStaticArrayValues(constructor, propertyName).forEach((name) => values.add(name));\n return values;\n }, new Set()));\n}\nfunction readInheritableStaticObjectPairs(constructor, propertyName) {\n const ancestors = getAncestorsForConstructor(constructor);\n return ancestors.reduce((pairs, constructor) => {\n pairs.push(...getOwnStaticObjectPairs(constructor, propertyName));\n return pairs;\n }, []);\n}\nfunction getAncestorsForConstructor(constructor) {\n const ancestors = [];\n while (constructor) {\n ancestors.push(constructor);\n constructor = Object.getPrototypeOf(constructor);\n }\n return ancestors.reverse();\n}\nfunction getOwnStaticArrayValues(constructor, propertyName) {\n const definition = constructor[propertyName];\n return Array.isArray(definition) ? definition : [];\n}\nfunction getOwnStaticObjectPairs(constructor, propertyName) {\n const definition = constructor[propertyName];\n return definition ? Object.keys(definition).map((key) => [key, definition[key]]) : [];\n}\n\nclass OutletObserver {\n constructor(context, delegate) {\n this.started = false;\n this.context = context;\n this.delegate = delegate;\n this.outletsByName = new Multimap();\n this.outletElementsByName = new Multimap();\n this.selectorObserverMap = new Map();\n this.attributeObserverMap = new Map();\n }\n start() {\n if (!this.started) {\n this.outletDefinitions.forEach((outletName) => {\n this.setupSelectorObserverForOutlet(outletName);\n this.setupAttributeObserverForOutlet(outletName);\n });\n this.started = true;\n this.dependentContexts.forEach((context) => context.refresh());\n }\n }\n refresh() {\n this.selectorObserverMap.forEach((observer) => observer.refresh());\n this.attributeObserverMap.forEach((observer) => observer.refresh());\n }\n stop() {\n if (this.started) {\n this.started = false;\n this.disconnectAllOutlets();\n this.stopSelectorObservers();\n this.stopAttributeObservers();\n }\n }\n stopSelectorObservers() {\n if (this.selectorObserverMap.size > 0) {\n this.selectorObserverMap.forEach((observer) => observer.stop());\n this.selectorObserverMap.clear();\n }\n }\n stopAttributeObservers() {\n if (this.attributeObserverMap.size > 0) {\n this.attributeObserverMap.forEach((observer) => observer.stop());\n this.attributeObserverMap.clear();\n }\n }\n selectorMatched(element, _selector, { outletName }) {\n const outlet = this.getOutlet(element, outletName);\n if (outlet) {\n this.connectOutlet(outlet, element, outletName);\n }\n }\n selectorUnmatched(element, _selector, { outletName }) {\n const outlet = this.getOutletFromMap(element, outletName);\n if (outlet) {\n this.disconnectOutlet(outlet, element, outletName);\n }\n }\n selectorMatchElement(element, { outletName }) {\n const selector = this.selector(outletName);\n const hasOutlet = this.hasOutlet(element, outletName);\n const hasOutletController = element.matches(`[${this.schema.controllerAttribute}~=${outletName}]`);\n if (selector) {\n return hasOutlet && hasOutletController && element.matches(selector);\n }\n else {\n return false;\n }\n }\n elementMatchedAttribute(_element, attributeName) {\n const outletName = this.getOutletNameFromOutletAttributeName(attributeName);\n if (outletName) {\n this.updateSelectorObserverForOutlet(outletName);\n }\n }\n elementAttributeValueChanged(_element, attributeName) {\n const outletName = this.getOutletNameFromOutletAttributeName(attributeName);\n if (outletName) {\n this.updateSelectorObserverForOutlet(outletName);\n }\n }\n elementUnmatchedAttribute(_element, attributeName) {\n const outletName = this.getOutletNameFromOutletAttributeName(attributeName);\n if (outletName) {\n this.updateSelectorObserverForOutlet(outletName);\n }\n }\n connectOutlet(outlet, element, outletName) {\n var _a;\n if (!this.outletElementsByName.has(outletName, element)) {\n this.outletsByName.add(outletName, outlet);\n this.outletElementsByName.add(outletName, element);\n (_a = this.selectorObserverMap.get(outletName)) === null || _a === void 0 ? void 0 : _a.pause(() => this.delegate.outletConnected(outlet, element, outletName));\n }\n }\n disconnectOutlet(outlet, element, outletName) {\n var _a;\n if (this.outletElementsByName.has(outletName, element)) {\n this.outletsByName.delete(outletName, outlet);\n this.outletElementsByName.delete(outletName, element);\n (_a = this.selectorObserverMap\n .get(outletName)) === null || _a === void 0 ? void 0 : _a.pause(() => this.delegate.outletDisconnected(outlet, element, outletName));\n }\n }\n disconnectAllOutlets() {\n for (const outletName of this.outletElementsByName.keys) {\n for (const element of this.outletElementsByName.getValuesForKey(outletName)) {\n for (const outlet of this.outletsByName.getValuesForKey(outletName)) {\n this.disconnectOutlet(outlet, element, outletName);\n }\n }\n }\n }\n updateSelectorObserverForOutlet(outletName) {\n const observer = this.selectorObserverMap.get(outletName);\n if (observer) {\n observer.selector = this.selector(outletName);\n }\n }\n setupSelectorObserverForOutlet(outletName) {\n const selector = this.selector(outletName);\n const selectorObserver = new SelectorObserver(document.body, selector, this, { outletName });\n this.selectorObserverMap.set(outletName, selectorObserver);\n selectorObserver.start();\n }\n setupAttributeObserverForOutlet(outletName) {\n const attributeName = this.attributeNameForOutletName(outletName);\n const attributeObserver = new AttributeObserver(this.scope.element, attributeName, this);\n this.attributeObserverMap.set(outletName, attributeObserver);\n attributeObserver.start();\n }\n selector(outletName) {\n return this.scope.outlets.getSelectorForOutletName(outletName);\n }\n attributeNameForOutletName(outletName) {\n return this.scope.schema.outletAttributeForScope(this.identifier, outletName);\n }\n getOutletNameFromOutletAttributeName(attributeName) {\n return this.outletDefinitions.find((outletName) => this.attributeNameForOutletName(outletName) === attributeName);\n }\n get outletDependencies() {\n const dependencies = new Multimap();\n this.router.modules.forEach((module) => {\n const constructor = module.definition.controllerConstructor;\n const outlets = readInheritableStaticArrayValues(constructor, \"outlets\");\n outlets.forEach((outlet) => dependencies.add(outlet, module.identifier));\n });\n return dependencies;\n }\n get outletDefinitions() {\n return this.outletDependencies.getKeysForValue(this.identifier);\n }\n get dependentControllerIdentifiers() {\n return this.outletDependencies.getValuesForKey(this.identifier);\n }\n get dependentContexts() {\n const identifiers = this.dependentControllerIdentifiers;\n return this.router.contexts.filter((context) => identifiers.includes(context.identifier));\n }\n hasOutlet(element, outletName) {\n return !!this.getOutlet(element, outletName) || !!this.getOutletFromMap(element, outletName);\n }\n getOutlet(element, outletName) {\n return this.application.getControllerForElementAndIdentifier(element, outletName);\n }\n getOutletFromMap(element, outletName) {\n return this.outletsByName.getValuesForKey(outletName).find((outlet) => outlet.element === element);\n }\n get scope() {\n return this.context.scope;\n }\n get schema() {\n return this.context.schema;\n }\n get identifier() {\n return this.context.identifier;\n }\n get application() {\n return this.context.application;\n }\n get router() {\n return this.application.router;\n }\n}\n\nclass Context {\n constructor(module, scope) {\n this.logDebugActivity = (functionName, detail = {}) => {\n const { identifier, controller, element } = this;\n detail = Object.assign({ identifier, controller, element }, detail);\n this.application.logDebugActivity(this.identifier, functionName, detail);\n };\n this.module = module;\n this.scope = scope;\n this.controller = new module.controllerConstructor(this);\n this.bindingObserver = new BindingObserver(this, this.dispatcher);\n this.valueObserver = new ValueObserver(this, this.controller);\n this.targetObserver = new TargetObserver(this, this);\n this.outletObserver = new OutletObserver(this, this);\n try {\n this.controller.initialize();\n this.logDebugActivity(\"initialize\");\n }\n catch (error) {\n this.handleError(error, \"initializing controller\");\n }\n }\n connect() {\n this.bindingObserver.start();\n this.valueObserver.start();\n this.targetObserver.start();\n this.outletObserver.start();\n try {\n this.controller.connect();\n this.logDebugActivity(\"connect\");\n }\n catch (error) {\n this.handleError(error, \"connecting controller\");\n }\n }\n refresh() {\n this.outletObserver.refresh();\n }\n disconnect() {\n try {\n this.controller.disconnect();\n this.logDebugActivity(\"disconnect\");\n }\n catch (error) {\n this.handleError(error, \"disconnecting controller\");\n }\n this.outletObserver.stop();\n this.targetObserver.stop();\n this.valueObserver.stop();\n this.bindingObserver.stop();\n }\n get application() {\n return this.module.application;\n }\n get identifier() {\n return this.module.identifier;\n }\n get schema() {\n return this.application.schema;\n }\n get dispatcher() {\n return this.application.dispatcher;\n }\n get element() {\n return this.scope.element;\n }\n get parentElement() {\n return this.element.parentElement;\n }\n handleError(error, message, detail = {}) {\n const { identifier, controller, element } = this;\n detail = Object.assign({ identifier, controller, element }, detail);\n this.application.handleError(error, `Error ${message}`, detail);\n }\n targetConnected(element, name) {\n this.invokeControllerMethod(`${name}TargetConnected`, element);\n }\n targetDisconnected(element, name) {\n this.invokeControllerMethod(`${name}TargetDisconnected`, element);\n }\n outletConnected(outlet, element, name) {\n this.invokeControllerMethod(`${namespaceCamelize(name)}OutletConnected`, outlet, element);\n }\n outletDisconnected(outlet, element, name) {\n this.invokeControllerMethod(`${namespaceCamelize(name)}OutletDisconnected`, outlet, element);\n }\n invokeControllerMethod(methodName, ...args) {\n const controller = this.controller;\n if (typeof controller[methodName] == \"function\") {\n controller[methodName](...args);\n }\n }\n}\n\nfunction bless(constructor) {\n return shadow(constructor, getBlessedProperties(constructor));\n}\nfunction shadow(constructor, properties) {\n const shadowConstructor = extend(constructor);\n const shadowProperties = getShadowProperties(constructor.prototype, properties);\n Object.defineProperties(shadowConstructor.prototype, shadowProperties);\n return shadowConstructor;\n}\nfunction getBlessedProperties(constructor) {\n const blessings = readInheritableStaticArrayValues(constructor, \"blessings\");\n return blessings.reduce((blessedProperties, blessing) => {\n const properties = blessing(constructor);\n for (const key in properties) {\n const descriptor = blessedProperties[key] || {};\n blessedProperties[key] = Object.assign(descriptor, properties[key]);\n }\n return blessedProperties;\n }, {});\n}\nfunction getShadowProperties(prototype, properties) {\n return getOwnKeys(properties).reduce((shadowProperties, key) => {\n const descriptor = getShadowedDescriptor(prototype, properties, key);\n if (descriptor) {\n Object.assign(shadowProperties, { [key]: descriptor });\n }\n return shadowProperties;\n }, {});\n}\nfunction getShadowedDescriptor(prototype, properties, key) {\n const shadowingDescriptor = Object.getOwnPropertyDescriptor(prototype, key);\n const shadowedByValue = shadowingDescriptor && \"value\" in shadowingDescriptor;\n if (!shadowedByValue) {\n const descriptor = Object.getOwnPropertyDescriptor(properties, key).value;\n if (shadowingDescriptor) {\n descriptor.get = shadowingDescriptor.get || descriptor.get;\n descriptor.set = shadowingDescriptor.set || descriptor.set;\n }\n return descriptor;\n }\n}\nconst getOwnKeys = (() => {\n if (typeof Object.getOwnPropertySymbols == \"function\") {\n return (object) => [...Object.getOwnPropertyNames(object), ...Object.getOwnPropertySymbols(object)];\n }\n else {\n return Object.getOwnPropertyNames;\n }\n})();\nconst extend = (() => {\n function extendWithReflect(constructor) {\n function extended() {\n return Reflect.construct(constructor, arguments, new.target);\n }\n extended.prototype = Object.create(constructor.prototype, {\n constructor: { value: extended },\n });\n Reflect.setPrototypeOf(extended, constructor);\n return extended;\n }\n function testReflectExtension() {\n const a = function () {\n this.a.call(this);\n };\n const b = extendWithReflect(a);\n b.prototype.a = function () { };\n return new b();\n }\n try {\n testReflectExtension();\n return extendWithReflect;\n }\n catch (error) {\n return (constructor) => class extended extends constructor {\n };\n }\n})();\n\nfunction blessDefinition(definition) {\n return {\n identifier: definition.identifier,\n controllerConstructor: bless(definition.controllerConstructor),\n };\n}\n\nclass Module {\n constructor(application, definition) {\n this.application = application;\n this.definition = blessDefinition(definition);\n this.contextsByScope = new WeakMap();\n this.connectedContexts = new Set();\n }\n get identifier() {\n return this.definition.identifier;\n }\n get controllerConstructor() {\n return this.definition.controllerConstructor;\n }\n get contexts() {\n return Array.from(this.connectedContexts);\n }\n connectContextForScope(scope) {\n const context = this.fetchContextForScope(scope);\n this.connectedContexts.add(context);\n context.connect();\n }\n disconnectContextForScope(scope) {\n const context = this.contextsByScope.get(scope);\n if (context) {\n this.connectedContexts.delete(context);\n context.disconnect();\n }\n }\n fetchContextForScope(scope) {\n let context = this.contextsByScope.get(scope);\n if (!context) {\n context = new Context(this, scope);\n this.contextsByScope.set(scope, context);\n }\n return context;\n }\n}\n\nclass ClassMap {\n constructor(scope) {\n this.scope = scope;\n }\n has(name) {\n return this.data.has(this.getDataKey(name));\n }\n get(name) {\n return this.getAll(name)[0];\n }\n getAll(name) {\n const tokenString = this.data.get(this.getDataKey(name)) || \"\";\n return tokenize(tokenString);\n }\n getAttributeName(name) {\n return this.data.getAttributeNameForKey(this.getDataKey(name));\n }\n getDataKey(name) {\n return `${name}-class`;\n }\n get data() {\n return this.scope.data;\n }\n}\n\nclass DataMap {\n constructor(scope) {\n this.scope = scope;\n }\n get element() {\n return this.scope.element;\n }\n get identifier() {\n return this.scope.identifier;\n }\n get(key) {\n const name = this.getAttributeNameForKey(key);\n return this.element.getAttribute(name);\n }\n set(key, value) {\n const name = this.getAttributeNameForKey(key);\n this.element.setAttribute(name, value);\n return this.get(key);\n }\n has(key) {\n const name = this.getAttributeNameForKey(key);\n return this.element.hasAttribute(name);\n }\n delete(key) {\n if (this.has(key)) {\n const name = this.getAttributeNameForKey(key);\n this.element.removeAttribute(name);\n return true;\n }\n else {\n return false;\n }\n }\n getAttributeNameForKey(key) {\n return `data-${this.identifier}-${dasherize(key)}`;\n }\n}\n\nclass Guide {\n constructor(logger) {\n this.warnedKeysByObject = new WeakMap();\n this.logger = logger;\n }\n warn(object, key, message) {\n let warnedKeys = this.warnedKeysByObject.get(object);\n if (!warnedKeys) {\n warnedKeys = new Set();\n this.warnedKeysByObject.set(object, warnedKeys);\n }\n if (!warnedKeys.has(key)) {\n warnedKeys.add(key);\n this.logger.warn(message, object);\n }\n }\n}\n\nfunction attributeValueContainsToken(attributeName, token) {\n return `[${attributeName}~=\"${token}\"]`;\n}\n\nclass TargetSet {\n constructor(scope) {\n this.scope = scope;\n }\n get element() {\n return this.scope.element;\n }\n get identifier() {\n return this.scope.identifier;\n }\n get schema() {\n return this.scope.schema;\n }\n has(targetName) {\n return this.find(targetName) != null;\n }\n find(...targetNames) {\n return targetNames.reduce((target, targetName) => target || this.findTarget(targetName) || this.findLegacyTarget(targetName), undefined);\n }\n findAll(...targetNames) {\n return targetNames.reduce((targets, targetName) => [\n ...targets,\n ...this.findAllTargets(targetName),\n ...this.findAllLegacyTargets(targetName),\n ], []);\n }\n findTarget(targetName) {\n const selector = this.getSelectorForTargetName(targetName);\n return this.scope.findElement(selector);\n }\n findAllTargets(targetName) {\n const selector = this.getSelectorForTargetName(targetName);\n return this.scope.findAllElements(selector);\n }\n getSelectorForTargetName(targetName) {\n const attributeName = this.schema.targetAttributeForScope(this.identifier);\n return attributeValueContainsToken(attributeName, targetName);\n }\n findLegacyTarget(targetName) {\n const selector = this.getLegacySelectorForTargetName(targetName);\n return this.deprecate(this.scope.findElement(selector), targetName);\n }\n findAllLegacyTargets(targetName) {\n const selector = this.getLegacySelectorForTargetName(targetName);\n return this.scope.findAllElements(selector).map((element) => this.deprecate(element, targetName));\n }\n getLegacySelectorForTargetName(targetName) {\n const targetDescriptor = `${this.identifier}.${targetName}`;\n return attributeValueContainsToken(this.schema.targetAttribute, targetDescriptor);\n }\n deprecate(element, targetName) {\n if (element) {\n const { identifier } = this;\n const attributeName = this.schema.targetAttribute;\n const revisedAttributeName = this.schema.targetAttributeForScope(identifier);\n this.guide.warn(element, `target:${targetName}`, `Please replace ${attributeName}=\"${identifier}.${targetName}\" with ${revisedAttributeName}=\"${targetName}\". ` +\n `The ${attributeName} attribute is deprecated and will be removed in a future version of Stimulus.`);\n }\n return element;\n }\n get guide() {\n return this.scope.guide;\n }\n}\n\nclass OutletSet {\n constructor(scope, controllerElement) {\n this.scope = scope;\n this.controllerElement = controllerElement;\n }\n get element() {\n return this.scope.element;\n }\n get identifier() {\n return this.scope.identifier;\n }\n get schema() {\n return this.scope.schema;\n }\n has(outletName) {\n return this.find(outletName) != null;\n }\n find(...outletNames) {\n return outletNames.reduce((outlet, outletName) => outlet || this.findOutlet(outletName), undefined);\n }\n findAll(...outletNames) {\n return outletNames.reduce((outlets, outletName) => [...outlets, ...this.findAllOutlets(outletName)], []);\n }\n getSelectorForOutletName(outletName) {\n const attributeName = this.schema.outletAttributeForScope(this.identifier, outletName);\n return this.controllerElement.getAttribute(attributeName);\n }\n findOutlet(outletName) {\n const selector = this.getSelectorForOutletName(outletName);\n if (selector)\n return this.findElement(selector, outletName);\n }\n findAllOutlets(outletName) {\n const selector = this.getSelectorForOutletName(outletName);\n return selector ? this.findAllElements(selector, outletName) : [];\n }\n findElement(selector, outletName) {\n const elements = this.scope.queryElements(selector);\n return elements.filter((element) => this.matchesElement(element, selector, outletName))[0];\n }\n findAllElements(selector, outletName) {\n const elements = this.scope.queryElements(selector);\n return elements.filter((element) => this.matchesElement(element, selector, outletName));\n }\n matchesElement(element, selector, outletName) {\n const controllerAttribute = element.getAttribute(this.scope.schema.controllerAttribute) || \"\";\n return element.matches(selector) && controllerAttribute.split(\" \").includes(outletName);\n }\n}\n\nclass Scope {\n constructor(schema, element, identifier, logger) {\n this.targets = new TargetSet(this);\n this.classes = new ClassMap(this);\n this.data = new DataMap(this);\n this.containsElement = (element) => {\n return element.closest(this.controllerSelector) === this.element;\n };\n this.schema = schema;\n this.element = element;\n this.identifier = identifier;\n this.guide = new Guide(logger);\n this.outlets = new OutletSet(this.documentScope, element);\n }\n findElement(selector) {\n return this.element.matches(selector) ? this.element : this.queryElements(selector).find(this.containsElement);\n }\n findAllElements(selector) {\n return [\n ...(this.element.matches(selector) ? [this.element] : []),\n ...this.queryElements(selector).filter(this.containsElement),\n ];\n }\n queryElements(selector) {\n return Array.from(this.element.querySelectorAll(selector));\n }\n get controllerSelector() {\n return attributeValueContainsToken(this.schema.controllerAttribute, this.identifier);\n }\n get isDocumentScope() {\n return this.element === document.documentElement;\n }\n get documentScope() {\n return this.isDocumentScope\n ? this\n : new Scope(this.schema, document.documentElement, this.identifier, this.guide.logger);\n }\n}\n\nclass ScopeObserver {\n constructor(element, schema, delegate) {\n this.element = element;\n this.schema = schema;\n this.delegate = delegate;\n this.valueListObserver = new ValueListObserver(this.element, this.controllerAttribute, this);\n this.scopesByIdentifierByElement = new WeakMap();\n this.scopeReferenceCounts = new WeakMap();\n }\n start() {\n this.valueListObserver.start();\n }\n stop() {\n this.valueListObserver.stop();\n }\n get controllerAttribute() {\n return this.schema.controllerAttribute;\n }\n parseValueForToken(token) {\n const { element, content: identifier } = token;\n return this.parseValueForElementAndIdentifier(element, identifier);\n }\n parseValueForElementAndIdentifier(element, identifier) {\n const scopesByIdentifier = this.fetchScopesByIdentifierForElement(element);\n let scope = scopesByIdentifier.get(identifier);\n if (!scope) {\n scope = this.delegate.createScopeForElementAndIdentifier(element, identifier);\n scopesByIdentifier.set(identifier, scope);\n }\n return scope;\n }\n elementMatchedValue(element, value) {\n const referenceCount = (this.scopeReferenceCounts.get(value) || 0) + 1;\n this.scopeReferenceCounts.set(value, referenceCount);\n if (referenceCount == 1) {\n this.delegate.scopeConnected(value);\n }\n }\n elementUnmatchedValue(element, value) {\n const referenceCount = this.scopeReferenceCounts.get(value);\n if (referenceCount) {\n this.scopeReferenceCounts.set(value, referenceCount - 1);\n if (referenceCount == 1) {\n this.delegate.scopeDisconnected(value);\n }\n }\n }\n fetchScopesByIdentifierForElement(element) {\n let scopesByIdentifier = this.scopesByIdentifierByElement.get(element);\n if (!scopesByIdentifier) {\n scopesByIdentifier = new Map();\n this.scopesByIdentifierByElement.set(element, scopesByIdentifier);\n }\n return scopesByIdentifier;\n }\n}\n\nclass Router {\n constructor(application) {\n this.application = application;\n this.scopeObserver = new ScopeObserver(this.element, this.schema, this);\n this.scopesByIdentifier = new Multimap();\n this.modulesByIdentifier = new Map();\n }\n get element() {\n return this.application.element;\n }\n get schema() {\n return this.application.schema;\n }\n get logger() {\n return this.application.logger;\n }\n get controllerAttribute() {\n return this.schema.controllerAttribute;\n }\n get modules() {\n return Array.from(this.modulesByIdentifier.values());\n }\n get contexts() {\n return this.modules.reduce((contexts, module) => contexts.concat(module.contexts), []);\n }\n start() {\n this.scopeObserver.start();\n }\n stop() {\n this.scopeObserver.stop();\n }\n loadDefinition(definition) {\n this.unloadIdentifier(definition.identifier);\n const module = new Module(this.application, definition);\n this.connectModule(module);\n const afterLoad = definition.controllerConstructor.afterLoad;\n if (afterLoad) {\n afterLoad.call(definition.controllerConstructor, definition.identifier, this.application);\n }\n }\n unloadIdentifier(identifier) {\n const module = this.modulesByIdentifier.get(identifier);\n if (module) {\n this.disconnectModule(module);\n }\n }\n getContextForElementAndIdentifier(element, identifier) {\n const module = this.modulesByIdentifier.get(identifier);\n if (module) {\n return module.contexts.find((context) => context.element == element);\n }\n }\n proposeToConnectScopeForElementAndIdentifier(element, identifier) {\n const scope = this.scopeObserver.parseValueForElementAndIdentifier(element, identifier);\n if (scope) {\n this.scopeObserver.elementMatchedValue(scope.element, scope);\n }\n else {\n console.error(`Couldn't find or create scope for identifier: \"${identifier}\" and element:`, element);\n }\n }\n handleError(error, message, detail) {\n this.application.handleError(error, message, detail);\n }\n createScopeForElementAndIdentifier(element, identifier) {\n return new Scope(this.schema, element, identifier, this.logger);\n }\n scopeConnected(scope) {\n this.scopesByIdentifier.add(scope.identifier, scope);\n const module = this.modulesByIdentifier.get(scope.identifier);\n if (module) {\n module.connectContextForScope(scope);\n }\n }\n scopeDisconnected(scope) {\n this.scopesByIdentifier.delete(scope.identifier, scope);\n const module = this.modulesByIdentifier.get(scope.identifier);\n if (module) {\n module.disconnectContextForScope(scope);\n }\n }\n connectModule(module) {\n this.modulesByIdentifier.set(module.identifier, module);\n const scopes = this.scopesByIdentifier.getValuesForKey(module.identifier);\n scopes.forEach((scope) => module.connectContextForScope(scope));\n }\n disconnectModule(module) {\n this.modulesByIdentifier.delete(module.identifier);\n const scopes = this.scopesByIdentifier.getValuesForKey(module.identifier);\n scopes.forEach((scope) => module.disconnectContextForScope(scope));\n }\n}\n\nconst defaultSchema = {\n controllerAttribute: \"data-controller\",\n actionAttribute: \"data-action\",\n targetAttribute: \"data-target\",\n targetAttributeForScope: (identifier) => `data-${identifier}-target`,\n outletAttributeForScope: (identifier, outlet) => `data-${identifier}-${outlet}-outlet`,\n 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]))),\n};\nfunction objectFromEntries(array) {\n return array.reduce((memo, [k, v]) => (Object.assign(Object.assign({}, memo), { [k]: v })), {});\n}\n\nclass Application {\n constructor(element = document.documentElement, schema = defaultSchema) {\n this.logger = console;\n this.debug = false;\n this.logDebugActivity = (identifier, functionName, detail = {}) => {\n if (this.debug) {\n this.logFormattedMessage(identifier, functionName, detail);\n }\n };\n this.element = element;\n this.schema = schema;\n this.dispatcher = new Dispatcher(this);\n this.router = new Router(this);\n this.actionDescriptorFilters = Object.assign({}, defaultActionDescriptorFilters);\n }\n static start(element, schema) {\n const application = new this(element, schema);\n application.start();\n return application;\n }\n async start() {\n await domReady();\n this.logDebugActivity(\"application\", \"starting\");\n this.dispatcher.start();\n this.router.start();\n this.logDebugActivity(\"application\", \"start\");\n }\n stop() {\n this.logDebugActivity(\"application\", \"stopping\");\n this.dispatcher.stop();\n this.router.stop();\n this.logDebugActivity(\"application\", \"stop\");\n }\n register(identifier, controllerConstructor) {\n this.load({ identifier, controllerConstructor });\n }\n registerActionOption(name, filter) {\n this.actionDescriptorFilters[name] = filter;\n }\n load(head, ...rest) {\n const definitions = Array.isArray(head) ? head : [head, ...rest];\n definitions.forEach((definition) => {\n if (definition.controllerConstructor.shouldLoad) {\n this.router.loadDefinition(definition);\n }\n });\n }\n unload(head, ...rest) {\n const identifiers = Array.isArray(head) ? head : [head, ...rest];\n identifiers.forEach((identifier) => this.router.unloadIdentifier(identifier));\n }\n get controllers() {\n return this.router.contexts.map((context) => context.controller);\n }\n getControllerForElementAndIdentifier(element, identifier) {\n const context = this.router.getContextForElementAndIdentifier(element, identifier);\n return context ? context.controller : null;\n }\n handleError(error, message, detail) {\n var _a;\n this.logger.error(`%s\\n\\n%o\\n\\n%o`, message, error, detail);\n (_a = window.onerror) === null || _a === void 0 ? void 0 : _a.call(window, message, \"\", 0, 0, error);\n }\n logFormattedMessage(identifier, functionName, detail = {}) {\n detail = Object.assign({ application: this }, detail);\n this.logger.groupCollapsed(`${identifier} #${functionName}`);\n this.logger.log(\"details:\", Object.assign({}, detail));\n this.logger.groupEnd();\n }\n}\nfunction domReady() {\n return new Promise((resolve) => {\n if (document.readyState == \"loading\") {\n document.addEventListener(\"DOMContentLoaded\", () => resolve());\n }\n else {\n resolve();\n }\n });\n}\n\nfunction ClassPropertiesBlessing(constructor) {\n const classes = readInheritableStaticArrayValues(constructor, \"classes\");\n return classes.reduce((properties, classDefinition) => {\n return Object.assign(properties, propertiesForClassDefinition(classDefinition));\n }, {});\n}\nfunction propertiesForClassDefinition(key) {\n return {\n [`${key}Class`]: {\n get() {\n const { classes } = this;\n if (classes.has(key)) {\n return classes.get(key);\n }\n else {\n const attribute = classes.getAttributeName(key);\n throw new Error(`Missing attribute \"${attribute}\"`);\n }\n },\n },\n [`${key}Classes`]: {\n get() {\n return this.classes.getAll(key);\n },\n },\n [`has${capitalize(key)}Class`]: {\n get() {\n return this.classes.has(key);\n },\n },\n };\n}\n\nfunction OutletPropertiesBlessing(constructor) {\n const outlets = readInheritableStaticArrayValues(constructor, \"outlets\");\n return outlets.reduce((properties, outletDefinition) => {\n return Object.assign(properties, propertiesForOutletDefinition(outletDefinition));\n }, {});\n}\nfunction getOutletController(controller, element, identifier) {\n return controller.application.getControllerForElementAndIdentifier(element, identifier);\n}\nfunction getControllerAndEnsureConnectedScope(controller, element, outletName) {\n let outletController = getOutletController(controller, element, outletName);\n if (outletController)\n return outletController;\n controller.application.router.proposeToConnectScopeForElementAndIdentifier(element, outletName);\n outletController = getOutletController(controller, element, outletName);\n if (outletController)\n return outletController;\n}\nfunction propertiesForOutletDefinition(name) {\n const camelizedName = namespaceCamelize(name);\n return {\n [`${camelizedName}Outlet`]: {\n get() {\n const outletElement = this.outlets.find(name);\n const selector = this.outlets.getSelectorForOutletName(name);\n if (outletElement) {\n const outletController = getControllerAndEnsureConnectedScope(this, outletElement, name);\n if (outletController)\n return outletController;\n throw new Error(`The provided outlet element is missing an outlet controller \"${name}\" instance for host controller \"${this.identifier}\"`);\n }\n throw new Error(`Missing outlet element \"${name}\" for host controller \"${this.identifier}\". Stimulus couldn't find a matching outlet element using selector \"${selector}\".`);\n },\n },\n [`${camelizedName}Outlets`]: {\n get() {\n const outlets = this.outlets.findAll(name);\n if (outlets.length > 0) {\n return outlets\n .map((outletElement) => {\n const outletController = getControllerAndEnsureConnectedScope(this, outletElement, name);\n if (outletController)\n return outletController;\n console.warn(`The provided outlet element is missing an outlet controller \"${name}\" instance for host controller \"${this.identifier}\"`, outletElement);\n })\n .filter((controller) => controller);\n }\n return [];\n },\n },\n [`${camelizedName}OutletElement`]: {\n get() {\n const outletElement = this.outlets.find(name);\n const selector = this.outlets.getSelectorForOutletName(name);\n if (outletElement) {\n return outletElement;\n }\n else {\n throw new Error(`Missing outlet element \"${name}\" for host controller \"${this.identifier}\". Stimulus couldn't find a matching outlet element using selector \"${selector}\".`);\n }\n },\n },\n [`${camelizedName}OutletElements`]: {\n get() {\n return this.outlets.findAll(name);\n },\n },\n [`has${capitalize(camelizedName)}Outlet`]: {\n get() {\n return this.outlets.has(name);\n },\n },\n };\n}\n\nfunction TargetPropertiesBlessing(constructor) {\n const targets = readInheritableStaticArrayValues(constructor, \"targets\");\n return targets.reduce((properties, targetDefinition) => {\n return Object.assign(properties, propertiesForTargetDefinition(targetDefinition));\n }, {});\n}\nfunction propertiesForTargetDefinition(name) {\n return {\n [`${name}Target`]: {\n get() {\n const target = this.targets.find(name);\n if (target) {\n return target;\n }\n else {\n throw new Error(`Missing target element \"${name}\" for \"${this.identifier}\" controller`);\n }\n },\n },\n [`${name}Targets`]: {\n get() {\n return this.targets.findAll(name);\n },\n },\n [`has${capitalize(name)}Target`]: {\n get() {\n return this.targets.has(name);\n },\n },\n };\n}\n\nfunction ValuePropertiesBlessing(constructor) {\n const valueDefinitionPairs = readInheritableStaticObjectPairs(constructor, \"values\");\n const propertyDescriptorMap = {\n valueDescriptorMap: {\n get() {\n return valueDefinitionPairs.reduce((result, valueDefinitionPair) => {\n const valueDescriptor = parseValueDefinitionPair(valueDefinitionPair, this.identifier);\n const attributeName = this.data.getAttributeNameForKey(valueDescriptor.key);\n return Object.assign(result, { [attributeName]: valueDescriptor });\n }, {});\n },\n },\n };\n return valueDefinitionPairs.reduce((properties, valueDefinitionPair) => {\n return Object.assign(properties, propertiesForValueDefinitionPair(valueDefinitionPair));\n }, propertyDescriptorMap);\n}\nfunction propertiesForValueDefinitionPair(valueDefinitionPair, controller) {\n const definition = parseValueDefinitionPair(valueDefinitionPair, controller);\n const { key, name, reader: read, writer: write } = definition;\n return {\n [name]: {\n get() {\n const value = this.data.get(key);\n if (value !== null) {\n return read(value);\n }\n else {\n return definition.defaultValue;\n }\n },\n set(value) {\n if (value === undefined) {\n this.data.delete(key);\n }\n else {\n this.data.set(key, write(value));\n }\n },\n },\n [`has${capitalize(name)}`]: {\n get() {\n return this.data.has(key) || definition.hasCustomDefaultValue;\n },\n },\n };\n}\nfunction parseValueDefinitionPair([token, typeDefinition], controller) {\n return valueDescriptorForTokenAndTypeDefinition({\n controller,\n token,\n typeDefinition,\n });\n}\nfunction parseValueTypeConstant(constant) {\n switch (constant) {\n case Array:\n return \"array\";\n case Boolean:\n return \"boolean\";\n case Number:\n return \"number\";\n case Object:\n return \"object\";\n case String:\n return \"string\";\n }\n}\nfunction parseValueTypeDefault(defaultValue) {\n switch (typeof defaultValue) {\n case \"boolean\":\n return \"boolean\";\n case \"number\":\n return \"number\";\n case \"string\":\n return \"string\";\n }\n if (Array.isArray(defaultValue))\n return \"array\";\n if (Object.prototype.toString.call(defaultValue) === \"[object Object]\")\n return \"object\";\n}\nfunction parseValueTypeObject(payload) {\n const { controller, token, typeObject } = payload;\n const hasType = isSomething(typeObject.type);\n const hasDefault = isSomething(typeObject.default);\n const fullObject = hasType && hasDefault;\n const onlyType = hasType && !hasDefault;\n const onlyDefault = !hasType && hasDefault;\n const typeFromObject = parseValueTypeConstant(typeObject.type);\n const typeFromDefaultValue = parseValueTypeDefault(payload.typeObject.default);\n if (onlyType)\n return typeFromObject;\n if (onlyDefault)\n return typeFromDefaultValue;\n if (typeFromObject !== typeFromDefaultValue) {\n const propertyPath = controller ? `${controller}.${token}` : token;\n throw new Error(`The specified default value for the Stimulus Value \"${propertyPath}\" must match the defined type \"${typeFromObject}\". The provided default value of \"${typeObject.default}\" is of type \"${typeFromDefaultValue}\".`);\n }\n if (fullObject)\n return typeFromObject;\n}\nfunction parseValueTypeDefinition(payload) {\n const { controller, token, typeDefinition } = payload;\n const typeObject = { controller, token, typeObject: typeDefinition };\n const typeFromObject = parseValueTypeObject(typeObject);\n const typeFromDefaultValue = parseValueTypeDefault(typeDefinition);\n const typeFromConstant = parseValueTypeConstant(typeDefinition);\n const type = typeFromObject || typeFromDefaultValue || typeFromConstant;\n if (type)\n return type;\n const propertyPath = controller ? `${controller}.${typeDefinition}` : token;\n throw new Error(`Unknown value type \"${propertyPath}\" for \"${token}\" value`);\n}\nfunction defaultValueForDefinition(typeDefinition) {\n const constant = parseValueTypeConstant(typeDefinition);\n if (constant)\n return defaultValuesByType[constant];\n const hasDefault = hasProperty(typeDefinition, \"default\");\n const hasType = hasProperty(typeDefinition, \"type\");\n const typeObject = typeDefinition;\n if (hasDefault)\n return typeObject.default;\n if (hasType) {\n const { type } = typeObject;\n const constantFromType = parseValueTypeConstant(type);\n if (constantFromType)\n return defaultValuesByType[constantFromType];\n }\n return typeDefinition;\n}\nfunction valueDescriptorForTokenAndTypeDefinition(payload) {\n const { token, typeDefinition } = payload;\n const key = `${dasherize(token)}-value`;\n const type = parseValueTypeDefinition(payload);\n return {\n type,\n key,\n name: camelize(key),\n get defaultValue() {\n return defaultValueForDefinition(typeDefinition);\n },\n get hasCustomDefaultValue() {\n return parseValueTypeDefault(typeDefinition) !== undefined;\n },\n reader: readers[type],\n writer: writers[type] || writers.default,\n };\n}\nconst defaultValuesByType = {\n get array() {\n return [];\n },\n boolean: false,\n number: 0,\n get object() {\n return {};\n },\n string: \"\",\n};\nconst readers = {\n array(value) {\n const array = JSON.parse(value);\n if (!Array.isArray(array)) {\n throw new TypeError(`expected value of type \"array\" but instead got value \"${value}\" of type \"${parseValueTypeDefault(array)}\"`);\n }\n return array;\n },\n boolean(value) {\n return !(value == \"0\" || String(value).toLowerCase() == \"false\");\n },\n number(value) {\n return Number(value.replace(/_/g, \"\"));\n },\n object(value) {\n const object = JSON.parse(value);\n if (object === null || typeof object != \"object\" || Array.isArray(object)) {\n throw new TypeError(`expected value of type \"object\" but instead got value \"${value}\" of type \"${parseValueTypeDefault(object)}\"`);\n }\n return object;\n },\n string(value) {\n return value;\n },\n};\nconst writers = {\n default: writeString,\n array: writeJSON,\n object: writeJSON,\n};\nfunction writeJSON(value) {\n return JSON.stringify(value);\n}\nfunction writeString(value) {\n return `${value}`;\n}\n\nclass Controller {\n constructor(context) {\n this.context = context;\n }\n static get shouldLoad() {\n return true;\n }\n static afterLoad(_identifier, _application) {\n return;\n }\n get application() {\n return this.context.application;\n }\n get scope() {\n return this.context.scope;\n }\n get element() {\n return this.scope.element;\n }\n get identifier() {\n return this.scope.identifier;\n }\n get targets() {\n return this.scope.targets;\n }\n get outlets() {\n return this.scope.outlets;\n }\n get classes() {\n return this.scope.classes;\n }\n get data() {\n return this.scope.data;\n }\n initialize() {\n }\n connect() {\n }\n disconnect() {\n }\n dispatch(eventName, { target = this.element, detail = {}, prefix = this.identifier, bubbles = true, cancelable = true, } = {}) {\n const type = prefix ? `${prefix}:${eventName}` : eventName;\n const event = new CustomEvent(type, { detail, bubbles, cancelable });\n target.dispatchEvent(event);\n return event;\n }\n}\nController.blessings = [\n ClassPropertiesBlessing,\n TargetPropertiesBlessing,\n ValuePropertiesBlessing,\n OutletPropertiesBlessing,\n];\nController.targets = [];\nController.outlets = [];\nController.values = {};\n\nexport { Application, AttributeObserver, Context, Controller, ElementObserver, IndexedMultimap, Multimap, SelectorObserver, StringMapObserver, TokenListObserver, ValueListObserver, add, defaultSchema, del, fetch, prune };\n","import { Application } from \"@hotwired/stimulus\"\nimport { log } from \"../logger.js\"\nimport { cacheBustedUrl, reloadHtmlDocument } from \"../helpers.js\"\n\nexport class StimulusReloader {\n static async reload(filePattern) {\n const document = await reloadHtmlDocument()\n return new StimulusReloader(document, filePattern).reload()\n }\n\n constructor(document, filePattern = /./) {\n this.document = document\n this.filePattern = filePattern\n this.application = window.Stimulus || Application.start()\n }\n\n async reload() {\n log(\"Reload Stimulus controllers...\")\n\n this.application.stop()\n\n await this.#reloadChangedStimulusControllers()\n this.#unloadDeletedStimulusControllers()\n\n this.application.start()\n }\n\n async #reloadChangedStimulusControllers() {\n await Promise.all(\n this.#stimulusControllerPathsToReload.map(async moduleName => this.#reloadStimulusController(moduleName))\n )\n }\n\n get #stimulusControllerPathsToReload() {\n this.controllerPathsToReload = this.controllerPathsToReload || this.#stimulusControllerPaths.filter(path => this.#shouldReloadController(path))\n return this.controllerPathsToReload\n }\n\n get #stimulusControllerPaths() {\n return Object.keys(this.#stimulusPathsByModule).filter(path => path.endsWith(\"_controller\"))\n }\n\n #shouldReloadController(path) {\n return this.filePattern.test(path)\n }\n\n get #stimulusPathsByModule() {\n this.pathsByModule = this.pathsByModule || this.#parseImportmapJson()\n return this.pathsByModule\n }\n\n #parseImportmapJson() {\n const importmapScript = this.document.querySelector(\"script[type=importmap]\")\n return JSON.parse(importmapScript.text).imports\n }\n\n async #reloadStimulusController(moduleName) {\n log(`\\t${moduleName}`)\n\n const controllerName = this.#extractControllerName(moduleName)\n const path = cacheBustedUrl(this.#pathForModuleName(moduleName))\n\n const module = await import(path)\n\n this.#registerController(controllerName, module)\n }\n\n #unloadDeletedStimulusControllers() {\n this.#controllersToUnload.forEach(controller => this.#deregisterController(controller.identifier))\n }\n\n get #controllersToUnload() {\n if (this.#didChangeTriggerAReload) {\n return []\n } else {\n return this.application.controllers.filter(controller => this.filePattern.test(`${controller.identifier}_controller`))\n }\n }\n\n get #didChangeTriggerAReload() {\n return this.#stimulusControllerPathsToReload.length > 0\n }\n\n #pathForModuleName(moduleName) {\n return this.#stimulusPathsByModule[moduleName]\n }\n\n #extractControllerName(path) {\n return path\n .replace(/^.*\\//, \"\")\n .replace(\"_controller\", \"\")\n .replace(/\\//g, \"--\")\n .replace(/_/g, \"-\")\n }\n\n #registerController(name, module) {\n this.application.unload(name)\n this.application.register(name, module.default)\n }\n\n #deregisterController(name) {\n log(`\\tRemoving controller ${name}`)\n this.application.unload(name)\n }\n}\n","import { Idiomorph } from \"idiomorph/dist/idiomorph.esm.js\"\nimport { log } from \"../logger.js\"\nimport { reloadHtmlDocument } from \"../helpers.js\"\nimport { StimulusReloader } from \"./stimulus_reloader.js\"\n\nexport class HtmlReloader {\n static async reload() {\n return new HtmlReloader().reload()\n }\n\n async reload() {\n const reloadedDocument = await this.#reloadHtml()\n await this.#reloadStimulus(reloadedDocument)\n }\n\n async #reloadHtml() {\n log(\"Reload html...\")\n\n const reloadedDocument = await reloadHtmlDocument()\n this.#updateBody(reloadedDocument.body)\n return reloadedDocument\n }\n\n #updateBody(newBody) {\n Idiomorph.morph(document.body, newBody)\n }\n\n async #reloadStimulus(reloadedDocument) {\n return new StimulusReloader(reloadedDocument).reload()\n }\n}\n","import { log } from \"../logger.js\"\nimport { cacheBustedUrl, reloadHtmlDocument, pathWithoutAssetDigest } from \"../helpers.js\"\n\nexport class CssReloader {\n static async reload(...params) {\n return new CssReloader(...params).reload()\n }\n\n constructor(filePattern = /./) {\n this.filePattern = filePattern\n }\n\n async reload() {\n log(\"Reload css...\")\n await Promise.all(await this.#reloadAllLinks())\n }\n\n async #reloadAllLinks() {\n const cssLinks = await this.#loadNewCssLinks();\n return cssLinks.map(link => this.#reloadLinkIfNeeded(link))\n }\n\n async #loadNewCssLinks() {\n const reloadedDocument = await reloadHtmlDocument()\n return Array.from(reloadedDocument.head.querySelectorAll(\"link[rel='stylesheet']\"))\n }\n\n #reloadLinkIfNeeded(link) {\n if (this.#shouldReloadLink(link)) {\n return this.#reloadLink(link)\n } else {\n return Promise.resolve()\n }\n }\n\n #shouldReloadLink(link) {\n return this.filePattern.test(link.getAttribute(\"href\"))\n }\n\n async #reloadLink(link) {\n return new Promise(resolve => {\n const href = link.getAttribute(\"href\")\n const newLink = this.#findExistingLinkFor(link) || this.#appendNewLink(link)\n\n newLink.setAttribute(\"href\", cacheBustedUrl(link.getAttribute(\"href\")))\n newLink.onload = () => {\n log(`\\t${href}`)\n resolve()\n }\n })\n }\n\n #findExistingLinkFor(link) {\n return this.#cssLinks.find(newLink => pathWithoutAssetDigest(link.href) === pathWithoutAssetDigest(newLink.href))\n }\n\n get #cssLinks() {\n return Array.from(document.querySelectorAll(\"link[rel='stylesheet']\"))\n }\n\n #appendNewLink(link) {\n document.head.append(link)\n return link\n }\n}\n","import consumer from \"./consumer\"\nimport { assetNameFromPath } from \"../helpers.js\";\nimport { HtmlReloader } from \"../reloaders/html_reloader.js\";\nimport { CssReloader } from \"../reloaders/css_reloader.js\";\nimport { StimulusReloader } from \"../reloaders/stimulus_reloader.js\";\n\nconsumer.subscriptions.create({ channel: \"Hotwire::Spark::Channel\" }, {\n connected() {\n document.body.setAttribute(\"data-hotwire-spark-ready\", \"\")\n },\n\n async received(message) {\n try {\n await this.dispatch(message)\n } catch(error) {\n console.log(`Error on ${message.action}`, error)\n }\n },\n\n dispatch({ action, path }) {\n const fileName = assetNameFromPath(path)\n\n switch(action) {\n case \"reload_html\":\n return this.reloadHtml()\n case \"reload_css\":\n return this.reloadCss(fileName)\n case \"reload_stimulus\":\n return this.reloadStimulus(fileName)\n default:\n throw new Error(`Unknown action: ${action}`)\n }\n },\n\n reloadHtml() {\n return HtmlReloader.reload()\n },\n\n reloadCss(fileName) {\n return CssReloader.reload(new RegExp(fileName))\n },\n\n reloadStimulus(fileName) {\n return StimulusReloader.reload(new RegExp(fileName))\n }\n})\n\n","import \"./channels/monitoring_channel.js\"\nimport { getConfigurationProperty } from \"./helpers.js\";\n\nconst HotwireSpark = {\n config: {\n loggingEnabled: false \n }\n}\n\ndocument.addEventListener(\"DOMContentLoaded\", function() {\n HotwireSpark.config.loggingEnabled = getConfigurationProperty(\"logging\");\n})\n\nexport default HotwireSpark\n"],"names":["adapters","logger","console","undefined","WebSocket","log","messages","this","enabled","push","Date","now","getTime","secondsSince","time","ConnectionMonitor","constructor","connection","visibilityDidChange","bind","reconnectAttempts","start","isRunning","startedAt","stoppedAt","startPolling","addEventListener","staleThreshold","stop","stopPolling","removeEventListener","recordMessage","pingedAt","recordConnect","disconnectedAt","recordDisconnect","poll","clearTimeout","pollTimeout","setTimeout","reconnectIfStale","getPollInterval","reconnectionBackoffRate","Math","pow","min","random","connectionIsStale","refreshedAt","disconnectedRecently","reopen","document","visibilityState","isOpen","INTERNAL","message_types","welcome","disconnect","ping","confirmation","rejection","disconnect_reasons","unauthorized","invalid_request","server_restart","remote","default_mount_path","protocols","supportedProtocols","slice","length","indexOf","Connection","consumer","open","subscriptions","monitor","disconnected","send","data","webSocket","JSON","stringify","isActive","getState","socketProtocols","subprotocols","uninstallEventHandlers","url","installEventHandlers","close","allowReconnect","error","reopenDelay","getProtocol","protocol","isState","triedToReconnect","isProtocolSupported","call","states","state","readyState","toLowerCase","eventName","events","handler","prototype","message","event","identifier","reason","reconnect","type","parse","reconnectAttempted","reload","confirmSubscription","notify","reconnected","reject","notifyAll","willAttemptReconnect","Subscription","params","mixin","object","properties","key","value","extend","perform","action","command","unsubscribe","remove","SubscriptionGuarantor","pendingSubscriptions","guarantee","subscription","startGuaranteeing","forget","filter","s","stopGuaranteeing","retrySubscribing","retryTimeout","subscribe","map","Subscriptions","guarantor","create","channelName","channel","add","ensureActiveConnection","findAll","sendCommand","callbackName","args","Consumer","_url","test","a","createElement","href","replace","createWebSocketURL","connect","addSubProtocol","subprotocol","createConsumer","name","element","head","querySelector","getAttribute","getConfig","pathWithoutAssetDigest","path","urlWithParams","urlString","URL","window","location","origin","Object","entries","forEach","_ref","searchParams","set","toString","cacheBustedUrl","async","reloadHtmlDocument","currentUrl","hotwire_spark","response","fetch","headers","Accept","ok","Error","status","fetchedHTML","text","DOMParser","parseFromString","Idiomorph","EMPTY_SET","Set","defaults","morphStyle","callbacks","beforeNodeAdded","noOp","afterNodeAdded","beforeNodeMorphed","afterNodeMorphed","beforeNodeRemoved","afterNodeRemoved","beforeAttributeUpdated","style","shouldPreserve","elt","shouldReAppend","shouldRemove","afterHeadMorphed","morphNormalizedContent","oldNode","normalizedNewContent","ctx","block","oldHead","newHead","promises","handleHeadElement","Promise","all","then","assign","ignore","morphChildren","children","bestMatch","newContent","currentElement","firstChild","bestElement","score","newScore","scoreElement","nextSibling","findBestNodeMatch","previousSibling","morphedNode","morphOldNodeTo","stack","added","node","pop","parentElement","insertBefore","insertSiblings","ignoreValueOfActiveElement","possibleActiveElement","ignoreActiveValue","activeElement","ignoreActive","isSoftMatch","HTMLHeadElement","from","to","nodeType","fromAttributes","attributes","toAttributes","fromAttribute","ignoreAttribute","setAttribute","i","toAttribute","hasAttribute","removeAttribute","nodeValue","HTMLInputElement","fromValue","toValue","syncBooleanAttribute","HTMLOptionElement","HTMLTextAreaElement","syncInputValue","syncNodeFrom","replaceChild","newParent","oldParent","newChild","nextNewChild","insertionPoint","appendChild","removeIdsFromConsideration","isIdSetMatch","idSetMatch","findIdSetMatch","removeNodesBetween","softMatch","findSoftMatch","tempNode","removeNode","attr","updateType","attributeName","ignoreUpdate","newHeadTag","currentHead","removed","preserved","nodesToAppend","headMergeStyle","srcToNewHeadNodes","Map","newHeadChild","outerHTML","currentHeadElt","inNewContent","has","isReAppended","isPreserved","delete","values","newNode","newElt","createRange","createContextualFragment","src","resolve","promise","_resolve","removedElement","removeChild","kept","node1","node2","tagName","id","getIdIntersectionCount","startInclusive","endExclusive","newChildPotentialIdCount","potentialMatch","otherMatchCount","potentialSoftMatch","siblingSoftMatchCount","isIdInConsideration","deadIds","idIsWithinNode","targetNode","idMap","get","idSet","sourceSet","matchCount","populateIdMapForNode","nodeParent","idElements","querySelectorAll","current","createIdMap","oldContent","morph","config","Document","documentElement","parser","contentWithSvgsRemoved","match","content","generatedByIdiomorph","htmlElement","body","parseContent","normalizedContent","Node","dummyParent","append","normalizeContent","finalConfig","mergeDefaults","target","createMorphContext","HotwireSpark","loggingEnabled","_len","arguments","Array","_key","EventListener","eventTarget","eventOptions","unorderedBindings","bindingConnected","binding","bindingDisconnected","handleEvent","extendedEvent","stopImmediatePropagation","immediatePropagationStopped","extendEvent","bindings","hasBindings","size","sort","left","right","leftIndex","index","rightIndex","Dispatcher","application","eventListenerMaps","started","eventListeners","eventListener","reduce","listeners","concat","fetchEventListenerForBinding","clearEventListeners","clearEventListenersForBinding","handleError","detail","removeMappedEventListenerFor","eventListenerMap","fetchEventListenerMapForEventTarget","cacheKey","fetchEventListener","createEventListener","parts","keys","join","defaultActionDescriptorFilters","stopPropagation","prevent","preventDefault","self","descriptorPattern","parseEventTarget","eventTargetName","camelize","_","char","toUpperCase","namespaceCamelize","allModifiers","Action","descriptor","schema","defaultEventNames","getDefaultEventNameForElement","methodName","keyFilter","forToken","token","descriptorString","matches","trim","includes","split","options","parseActionDescriptorString","eventFilter","shouldIgnoreKeyboardEvent","filters","keyFilterDissatisfied","standardFilter","keyMappings","property","hasOwnProperty","shouldIgnoreMouseEvent","pattern","RegExp","typecast","meta","ctrl","alt","shift","modifier","metaKey","ctrlKey","altKey","shiftKey","button","form","details","input","e","select","textarea","o_O","Binding","context","actionEvent","prepareActionEvent","willBeInvokedByEvent","applyEventModifiers","invokeWithEvent","method","controller","actionDescriptorFilters","passes","currentTarget","logDebugActivity","KeyboardEvent","MouseEvent","Element","contains","scope","containsElement","ElementObserver","delegate","mutationObserverInit","childList","subtree","elements","mutationObserver","MutationObserver","mutations","processMutations","observe","refresh","pause","callback","takeRecords","matchElementsInTree","removeElement","addElement","mutation","processMutation","processAttributeChange","processRemovedNodes","removedNodes","processAddedNodes","addedNodes","elementAttributeChanged","matchElement","nodes","elementFromNode","processTree","elementIsActive","tree","processor","ELEMENT_NODE","isConnected","elementMatched","elementUnmatched","AttributeObserver","elementObserver","selector","elementMatchedAttribute","elementUnmatchedAttribute","elementAttributeValueChanged","Multimap","valuesByKey","prune","del","hasKey","hasValue","some","getValuesForKey","getKeysForValue","_values","SelectorObserver","_selector","matchesByElement","selectorMatchElement","selectorMatched","selectors","selectorUnmatched","_attributeName","matchedBefore","StringMapObserver","stringMap","attributeOldValue","knownAttributeNames","refreshAttribute","oldValue","getStringMapKeyForAttribute","stringMapKeyAdded","stringMapValueChanged","stringMapKeyRemoved","currentAttributeNames","recordedAttributeNames","attribute","TokenListObserver","attributeObserver","tokensByElement","tokensMatched","readTokensForElement","unmatchedTokens","matchedTokens","refreshTokensForElement","tokensUnmatched","tokens","tokenMatched","tokenUnmatched","previousTokens","currentTokens","firstDifferingIndex","max","zip","findIndex","previousToken","currentToken","tokenString","parseTokenString","ValueListObserver","tokenListObserver","parseResultsByToken","WeakMap","valuesByTokenByElement","fetchParseResultForToken","fetchValuesByTokenForElement","elementMatchedValue","elementUnmatchedValue","parseResult","parseToken","valuesByToken","parseValueForToken","BindingObserver","bindingsByAction","valueListObserver","actionAttribute","disconnectAllActions","connectAction","disconnectAction","clear","ValueObserver","receiver","stringMapObserver","valueDescriptorMap","invokeChangedCallbacksForDefaultValues","invokeChangedCallback","writer","defaultValue","valueDescriptorNameMap","valueDescriptors","rawValue","rawOldValue","changedMethodName","changedMethod","reader","TypeError","descriptors","hasMethodName","charAt","TargetObserver","targetsByName","disconnectAllTargets","connectTarget","disconnectTarget","_a","targetConnected","targetDisconnected","readInheritableStaticArrayValues","propertyName","ancestors","getPrototypeOf","reverse","getAncestorsForConstructor","definition","isArray","getOwnStaticArrayValues","OutletObserver","outletsByName","outletElementsByName","selectorObserverMap","attributeObserverMap","outletDefinitions","outletName","setupSelectorObserverForOutlet","setupAttributeObserverForOutlet","dependentContexts","observer","disconnectAllOutlets","stopSelectorObservers","stopAttributeObservers","outlet","getOutlet","connectOutlet","getOutletFromMap","disconnectOutlet","hasOutlet","hasOutletController","controllerAttribute","_element","getOutletNameFromOutletAttributeName","updateSelectorObserverForOutlet","outletConnected","outletDisconnected","selectorObserver","attributeNameForOutletName","outlets","getSelectorForOutletName","outletAttributeForScope","find","outletDependencies","dependencies","router","modules","module","controllerConstructor","dependentControllerIdentifiers","identifiers","contexts","getControllerForElementAndIdentifier","Context","functionName","bindingObserver","dispatcher","valueObserver","targetObserver","outletObserver","initialize","invokeControllerMethod","bless","shadowConstructor","shadowProperties","getOwnKeys","shadowingDescriptor","getOwnPropertyDescriptor","getShadowedDescriptor","getShadowProperties","defineProperties","shadow","blessings","blessedProperties","blessing","getBlessedProperties","getOwnPropertySymbols","getOwnPropertyNames","extendWithReflect","extended","Reflect","construct","setPrototypeOf","b","testReflectExtension","Module","blessDefinition","contextsByScope","connectedContexts","connectContextForScope","fetchContextForScope","disconnectContextForScope","ClassMap","getDataKey","getAll","getAttributeName","getAttributeNameForKey","DataMap","Guide","warnedKeysByObject","warn","warnedKeys","attributeValueContainsToken","TargetSet","targetName","targetNames","findTarget","findLegacyTarget","targets","findAllTargets","findAllLegacyTargets","getSelectorForTargetName","findElement","findAllElements","targetAttributeForScope","getLegacySelectorForTargetName","deprecate","targetDescriptor","targetAttribute","revisedAttributeName","guide","OutletSet","controllerElement","outletNames","findOutlet","findAllOutlets","queryElements","matchesElement","Scope","classes","closest","controllerSelector","documentScope","isDocumentScope","ScopeObserver","scopesByIdentifierByElement","scopeReferenceCounts","parseValueForElementAndIdentifier","scopesByIdentifier","fetchScopesByIdentifierForElement","createScopeForElementAndIdentifier","referenceCount","scopeConnected","scopeDisconnected","Router","scopeObserver","modulesByIdentifier","loadDefinition","unloadIdentifier","connectModule","afterLoad","disconnectModule","getContextForElementAndIdentifier","proposeToConnectScopeForElementAndIdentifier","defaultSchema","enter","tab","esc","space","up","down","home","end","page_up","page_down","objectFromEntries","c","n","array","memo","k","v","Application","debug","logFormattedMessage","register","load","registerActionOption","rest","shouldLoad","unload","controllers","onerror","groupCollapsed","groupEnd","StimulusReloader","filePattern","Stimulus","reloadChangedStimulusControllers","unloadDeletedStimulusControllers","stimulusControllerPathsToReload","reloadStimulusController","moduleName","controllerPathsToReload","stimulusControllerPaths","shouldReloadController","stimulusPathsByModule","endsWith","pathsByModule","parseImportmapJson","importmapScript","imports","controllerName","extractControllerName","pathForModuleName","import","registerController","controllersToUnload","deregisterController","didChangeTriggerAReload","default","HtmlReloader","reloadedDocument","reloadHtml","reloadStimulus","updateBody","newBody","CssReloader","reloadAllLinks","loadNewCssLinks","link","reloadLinkIfNeeded","shouldReloadLink","reloadLink","newLink","findExistingLinkFor","appendNewLink","onload","cssLinks","connected","received","dispatch","fileName","assetNameFromPath","reloadCss"],"mappings":"yCAAA,IAAIA,EAAW,CACbC,OAA2B,oBAAZC,QAA0BA,aAAUC,EACnDC,UAAgC,oBAAdA,UAA4BA,eAAYD,GAGxDF,EAAS,CACX,GAAAI,IAAOC,GACDC,KAAKC,UACPF,EAASG,KAAKC,KAAKC,OACnBX,EAASC,OAAOI,IAAI,mBAAoBC,GAE9C,GAGA,MAAMK,EAAM,KAAM,IAAK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A2gB,CAAeN,GAEb,OADAh0B,SAAS2H,KAAKmN,OAAOkf,GACdA,CACT,ECzDF1yB,EAASE,cAAc4E,OAAO,CAAEE,QAAS,2BAA6B,CACpEmuB,SAAAA,GACEz0B,SAASyU,KAAKpG,aAAa,2BAA4B,GACxD,EAED,cAAMqmB,CAASjxB,GACb,UACQrG,KAAKu3B,SAASlxB,EACrB,CAAC,MAAMhB,GACN1F,QAAQG,IAAI,YAAYuG,EAAQwB,SAAUxC,EAC5C,CACD,EAEDkyB,QAAAA,CAAQjsB,GAAmB,IAAlBzD,OAAEA,EAAM+C,KAAEA,GAAMU,EACvB,MAAMksB,EPpBH,SAA2B5sB,GAChC,OAAOA,EAAKiS,MAAM,KAAK/M,MAAM+M,MAAM,KAAK,EAC1C,COkBqB4a,CAAkB7sB,GAEnC,OAAO/C,GACL,IAAK,cACH,OAAO7H,KAAKq2B,aACd,IAAK,aACH,OAAOr2B,KAAK03B,UAAUF,GACxB,IAAK,kBACH,OAAOx3B,KAAKs2B,eAAekB,GAC7B,QACE,MAAM,IAAIprB,MAAM,mBAAmBvE,KAExC,EAEDwuB,WAAUA,IACDF,GAAatvB,SAGtB6wB,UAAUF,GACDf,GAAY5vB,OAAO,IAAI6W,OAAO8Z,IAGvClB,eAAekB,GACN/C,GAAiB5tB,OAAO,IAAI6W,OAAO8Z,MCxC9C,MAAMxf,GAAe,CACnBpB,OAAQ,CACNqB,gBAAgB,WAIpBrV,SAASzB,iBAAiB,oBAAoB,WRwBvC,IAAkCkJ,EQvBvC2N,GAAapB,OAAOqB,gBRuBmB5N,EQvBuB,URwBvDzH,SAAS4H,cAAc,4BAA4BH,QAAW6M,QQvBvE","x_google_ignoreList":[0,3,5]} \ No newline at end of file +{"version":3,"file":"hotwire_spark.min.js","sources":["../../../node_modules/@rails/actioncable/app/assets/javascripts/actioncable.esm.js","../../javascript/hotwire/spark/channels/consumer.js","../../javascript/hotwire/spark/helpers.js","../../../node_modules/idiomorph/dist/idiomorph.esm.js","../../javascript/hotwire/spark/logger.js","../../javascript/hotwire/spark/reloaders/stimulus_reloader.js","../../javascript/hotwire/spark/reloaders/html_reloader.js","../../javascript/hotwire/spark/reloaders/css_reloader.js","../../javascript/hotwire/spark/channels/monitoring_channel.js","../../javascript/hotwire/spark/index.js"],"sourcesContent":["var adapters = {\n logger: typeof console !== \"undefined\" ? console : undefined,\n WebSocket: typeof WebSocket !== \"undefined\" ? WebSocket : undefined\n};\n\nvar logger = {\n log(...messages) {\n if (this.enabled) {\n messages.push(Date.now());\n adapters.logger.log(\"[ActionCable]\", ...messages);\n }\n }\n};\n\nconst now = () => (new Date).getTime();\n\nconst secondsSince = time => (now() - time) / 1e3;\n\nclass ConnectionMonitor {\n constructor(connection) {\n this.visibilityDidChange = this.visibilityDidChange.bind(this);\n this.connection = connection;\n this.reconnectAttempts = 0;\n }\n start() {\n if (!this.isRunning()) {\n this.startedAt = now();\n delete this.stoppedAt;\n this.startPolling();\n addEventListener(\"visibilitychange\", this.visibilityDidChange);\n logger.log(`ConnectionMonitor started. stale threshold = ${this.constructor.staleThreshold} s`);\n }\n }\n stop() {\n if (this.isRunning()) {\n this.stoppedAt = now();\n this.stopPolling();\n removeEventListener(\"visibilitychange\", this.visibilityDidChange);\n logger.log(\"ConnectionMonitor stopped\");\n }\n }\n isRunning() {\n return this.startedAt && !this.stoppedAt;\n }\n recordMessage() {\n this.pingedAt = now();\n }\n recordConnect() {\n this.reconnectAttempts = 0;\n delete this.disconnectedAt;\n logger.log(\"ConnectionMonitor recorded connect\");\n }\n recordDisconnect() {\n this.disconnectedAt = now();\n logger.log(\"ConnectionMonitor recorded disconnect\");\n }\n startPolling() {\n this.stopPolling();\n this.poll();\n }\n stopPolling() {\n clearTimeout(this.pollTimeout);\n }\n poll() {\n this.pollTimeout = setTimeout((() => {\n this.reconnectIfStale();\n this.poll();\n }), this.getPollInterval());\n }\n getPollInterval() {\n const {staleThreshold: staleThreshold, reconnectionBackoffRate: reconnectionBackoffRate} = this.constructor;\n const backoff = Math.pow(1 + reconnectionBackoffRate, Math.min(this.reconnectAttempts, 10));\n const jitterMax = this.reconnectAttempts === 0 ? 1 : reconnectionBackoffRate;\n const jitter = jitterMax * Math.random();\n return staleThreshold * 1e3 * backoff * (1 + jitter);\n }\n reconnectIfStale() {\n if (this.connectionIsStale()) {\n logger.log(`ConnectionMonitor detected stale connection. reconnectAttempts = ${this.reconnectAttempts}, time stale = ${secondsSince(this.refreshedAt)} s, stale threshold = ${this.constructor.staleThreshold} s`);\n this.reconnectAttempts++;\n if (this.disconnectedRecently()) {\n logger.log(`ConnectionMonitor skipping reopening recent disconnect. time disconnected = ${secondsSince(this.disconnectedAt)} s`);\n } else {\n logger.log(\"ConnectionMonitor reopening\");\n this.connection.reopen();\n }\n }\n }\n get refreshedAt() {\n return this.pingedAt ? this.pingedAt : this.startedAt;\n }\n connectionIsStale() {\n return secondsSince(this.refreshedAt) > this.constructor.staleThreshold;\n }\n disconnectedRecently() {\n return this.disconnectedAt && secondsSince(this.disconnectedAt) < this.constructor.staleThreshold;\n }\n visibilityDidChange() {\n if (document.visibilityState === \"visible\") {\n setTimeout((() => {\n if (this.connectionIsStale() || !this.connection.isOpen()) {\n logger.log(`ConnectionMonitor reopening stale connection on visibilitychange. visibilityState = ${document.visibilityState}`);\n this.connection.reopen();\n }\n }), 200);\n }\n }\n}\n\nConnectionMonitor.staleThreshold = 6;\n\nConnectionMonitor.reconnectionBackoffRate = .15;\n\nvar INTERNAL = {\n message_types: {\n welcome: \"welcome\",\n disconnect: \"disconnect\",\n ping: \"ping\",\n confirmation: \"confirm_subscription\",\n rejection: \"reject_subscription\"\n },\n disconnect_reasons: {\n unauthorized: \"unauthorized\",\n invalid_request: \"invalid_request\",\n server_restart: \"server_restart\",\n remote: \"remote\"\n },\n default_mount_path: \"/cable\",\n protocols: [ \"actioncable-v1-json\", \"actioncable-unsupported\" ]\n};\n\nconst {message_types: message_types, protocols: protocols} = INTERNAL;\n\nconst supportedProtocols = protocols.slice(0, protocols.length - 1);\n\nconst indexOf = [].indexOf;\n\nclass Connection {\n constructor(consumer) {\n this.open = this.open.bind(this);\n this.consumer = consumer;\n this.subscriptions = this.consumer.subscriptions;\n this.monitor = new ConnectionMonitor(this);\n this.disconnected = true;\n }\n send(data) {\n if (this.isOpen()) {\n this.webSocket.send(JSON.stringify(data));\n return true;\n } else {\n return false;\n }\n }\n open() {\n if (this.isActive()) {\n logger.log(`Attempted to open WebSocket, but existing socket is ${this.getState()}`);\n return false;\n } else {\n const socketProtocols = [ ...protocols, ...this.consumer.subprotocols || [] ];\n logger.log(`Opening WebSocket, current state is ${this.getState()}, subprotocols: ${socketProtocols}`);\n if (this.webSocket) {\n this.uninstallEventHandlers();\n }\n this.webSocket = new adapters.WebSocket(this.consumer.url, socketProtocols);\n this.installEventHandlers();\n this.monitor.start();\n return true;\n }\n }\n close({allowReconnect: allowReconnect} = {\n allowReconnect: true\n }) {\n if (!allowReconnect) {\n this.monitor.stop();\n }\n if (this.isOpen()) {\n return this.webSocket.close();\n }\n }\n reopen() {\n logger.log(`Reopening WebSocket, current state is ${this.getState()}`);\n if (this.isActive()) {\n try {\n return this.close();\n } catch (error) {\n logger.log(\"Failed to reopen WebSocket\", error);\n } finally {\n logger.log(`Reopening WebSocket in ${this.constructor.reopenDelay}ms`);\n setTimeout(this.open, this.constructor.reopenDelay);\n }\n } else {\n return this.open();\n }\n }\n getProtocol() {\n if (this.webSocket) {\n return this.webSocket.protocol;\n }\n }\n isOpen() {\n return this.isState(\"open\");\n }\n isActive() {\n return this.isState(\"open\", \"connecting\");\n }\n triedToReconnect() {\n return this.monitor.reconnectAttempts > 0;\n }\n isProtocolSupported() {\n return indexOf.call(supportedProtocols, this.getProtocol()) >= 0;\n }\n isState(...states) {\n return indexOf.call(states, this.getState()) >= 0;\n }\n getState() {\n if (this.webSocket) {\n for (let state in adapters.WebSocket) {\n if (adapters.WebSocket[state] === this.webSocket.readyState) {\n return state.toLowerCase();\n }\n }\n }\n return null;\n }\n installEventHandlers() {\n for (let eventName in this.events) {\n const handler = this.events[eventName].bind(this);\n this.webSocket[`on${eventName}`] = handler;\n }\n }\n uninstallEventHandlers() {\n for (let eventName in this.events) {\n this.webSocket[`on${eventName}`] = function() {};\n }\n }\n}\n\nConnection.reopenDelay = 500;\n\nConnection.prototype.events = {\n message(event) {\n if (!this.isProtocolSupported()) {\n return;\n }\n const {identifier: identifier, message: message, reason: reason, reconnect: reconnect, type: type} = JSON.parse(event.data);\n this.monitor.recordMessage();\n switch (type) {\n case message_types.welcome:\n if (this.triedToReconnect()) {\n this.reconnectAttempted = true;\n }\n this.monitor.recordConnect();\n return this.subscriptions.reload();\n\n case message_types.disconnect:\n logger.log(`Disconnecting. Reason: ${reason}`);\n return this.close({\n allowReconnect: reconnect\n });\n\n case message_types.ping:\n return null;\n\n case message_types.confirmation:\n this.subscriptions.confirmSubscription(identifier);\n if (this.reconnectAttempted) {\n this.reconnectAttempted = false;\n return this.subscriptions.notify(identifier, \"connected\", {\n reconnected: true\n });\n } else {\n return this.subscriptions.notify(identifier, \"connected\", {\n reconnected: false\n });\n }\n\n case message_types.rejection:\n return this.subscriptions.reject(identifier);\n\n default:\n return this.subscriptions.notify(identifier, \"received\", message);\n }\n },\n open() {\n logger.log(`WebSocket onopen event, using '${this.getProtocol()}' subprotocol`);\n this.disconnected = false;\n if (!this.isProtocolSupported()) {\n logger.log(\"Protocol is unsupported. Stopping monitor and disconnecting.\");\n return this.close({\n allowReconnect: false\n });\n }\n },\n close(event) {\n logger.log(\"WebSocket onclose event\");\n if (this.disconnected) {\n return;\n }\n this.disconnected = true;\n this.monitor.recordDisconnect();\n return this.subscriptions.notifyAll(\"disconnected\", {\n willAttemptReconnect: this.monitor.isRunning()\n });\n },\n error() {\n logger.log(\"WebSocket onerror event\");\n }\n};\n\nconst extend = function(object, properties) {\n if (properties != null) {\n for (let key in properties) {\n const value = properties[key];\n object[key] = value;\n }\n }\n return object;\n};\n\nclass Subscription {\n constructor(consumer, params = {}, mixin) {\n this.consumer = consumer;\n this.identifier = JSON.stringify(params);\n extend(this, mixin);\n }\n perform(action, data = {}) {\n data.action = action;\n return this.send(data);\n }\n send(data) {\n return this.consumer.send({\n command: \"message\",\n identifier: this.identifier,\n data: JSON.stringify(data)\n });\n }\n unsubscribe() {\n return this.consumer.subscriptions.remove(this);\n }\n}\n\nclass SubscriptionGuarantor {\n constructor(subscriptions) {\n this.subscriptions = subscriptions;\n this.pendingSubscriptions = [];\n }\n guarantee(subscription) {\n if (this.pendingSubscriptions.indexOf(subscription) == -1) {\n logger.log(`SubscriptionGuarantor guaranteeing ${subscription.identifier}`);\n this.pendingSubscriptions.push(subscription);\n } else {\n logger.log(`SubscriptionGuarantor already guaranteeing ${subscription.identifier}`);\n }\n this.startGuaranteeing();\n }\n forget(subscription) {\n logger.log(`SubscriptionGuarantor forgetting ${subscription.identifier}`);\n this.pendingSubscriptions = this.pendingSubscriptions.filter((s => s !== subscription));\n }\n startGuaranteeing() {\n this.stopGuaranteeing();\n this.retrySubscribing();\n }\n stopGuaranteeing() {\n clearTimeout(this.retryTimeout);\n }\n retrySubscribing() {\n this.retryTimeout = setTimeout((() => {\n if (this.subscriptions && typeof this.subscriptions.subscribe === \"function\") {\n this.pendingSubscriptions.map((subscription => {\n logger.log(`SubscriptionGuarantor resubscribing ${subscription.identifier}`);\n this.subscriptions.subscribe(subscription);\n }));\n }\n }), 500);\n }\n}\n\nclass Subscriptions {\n constructor(consumer) {\n this.consumer = consumer;\n this.guarantor = new SubscriptionGuarantor(this);\n this.subscriptions = [];\n }\n create(channelName, mixin) {\n const channel = channelName;\n const params = typeof channel === \"object\" ? channel : {\n channel: channel\n };\n const subscription = new Subscription(this.consumer, params, mixin);\n return this.add(subscription);\n }\n add(subscription) {\n this.subscriptions.push(subscription);\n this.consumer.ensureActiveConnection();\n this.notify(subscription, \"initialized\");\n this.subscribe(subscription);\n return subscription;\n }\n remove(subscription) {\n this.forget(subscription);\n if (!this.findAll(subscription.identifier).length) {\n this.sendCommand(subscription, \"unsubscribe\");\n }\n return subscription;\n }\n reject(identifier) {\n return this.findAll(identifier).map((subscription => {\n this.forget(subscription);\n this.notify(subscription, \"rejected\");\n return subscription;\n }));\n }\n forget(subscription) {\n this.guarantor.forget(subscription);\n this.subscriptions = this.subscriptions.filter((s => s !== subscription));\n return subscription;\n }\n findAll(identifier) {\n return this.subscriptions.filter((s => s.identifier === identifier));\n }\n reload() {\n return this.subscriptions.map((subscription => this.subscribe(subscription)));\n }\n notifyAll(callbackName, ...args) {\n return this.subscriptions.map((subscription => this.notify(subscription, callbackName, ...args)));\n }\n notify(subscription, callbackName, ...args) {\n let subscriptions;\n if (typeof subscription === \"string\") {\n subscriptions = this.findAll(subscription);\n } else {\n subscriptions = [ subscription ];\n }\n return subscriptions.map((subscription => typeof subscription[callbackName] === \"function\" ? subscription[callbackName](...args) : undefined));\n }\n subscribe(subscription) {\n if (this.sendCommand(subscription, \"subscribe\")) {\n this.guarantor.guarantee(subscription);\n }\n }\n confirmSubscription(identifier) {\n logger.log(`Subscription confirmed ${identifier}`);\n this.findAll(identifier).map((subscription => this.guarantor.forget(subscription)));\n }\n sendCommand(subscription, command) {\n const {identifier: identifier} = subscription;\n return this.consumer.send({\n command: command,\n identifier: identifier\n });\n }\n}\n\nclass Consumer {\n constructor(url) {\n this._url = url;\n this.subscriptions = new Subscriptions(this);\n this.connection = new Connection(this);\n this.subprotocols = [];\n }\n get url() {\n return createWebSocketURL(this._url);\n }\n send(data) {\n return this.connection.send(data);\n }\n connect() {\n return this.connection.open();\n }\n disconnect() {\n return this.connection.close({\n allowReconnect: false\n });\n }\n ensureActiveConnection() {\n if (!this.connection.isActive()) {\n return this.connection.open();\n }\n }\n addSubProtocol(subprotocol) {\n this.subprotocols = [ ...this.subprotocols, subprotocol ];\n }\n}\n\nfunction createWebSocketURL(url) {\n if (typeof url === \"function\") {\n url = url();\n }\n if (url && !/^wss?:/i.test(url)) {\n const a = document.createElement(\"a\");\n a.href = url;\n a.href = a.href;\n a.protocol = a.protocol.replace(\"http\", \"ws\");\n return a.href;\n } else {\n return url;\n }\n}\n\nfunction createConsumer(url = getConfig(\"url\") || INTERNAL.default_mount_path) {\n return new Consumer(url);\n}\n\nfunction getConfig(name) {\n const element = document.head.querySelector(`meta[name='action-cable-${name}']`);\n if (element) {\n return element.getAttribute(\"content\");\n }\n}\n\nexport { Connection, ConnectionMonitor, Consumer, INTERNAL, Subscription, SubscriptionGuarantor, Subscriptions, adapters, createConsumer, createWebSocketURL, getConfig, logger };\n","import { createConsumer } from \"@rails/actioncable\"\n\nexport default createConsumer(\"/hotwire-spark\")\n","export function assetNameFromPath(path) {\n return path.split(\"/\").pop().split(\".\")[0]\n}\n\nexport function pathWithoutAssetDigest(path) {\n return path.replace(/-[a-z0-9]+\\.(\\w+)(\\?.*)?$/, \".$1\")\n}\n\nexport function urlWithParams(urlString, params) {\n const url = new URL(urlString, window.location.origin)\n Object.entries(params).forEach(([ key, value ]) => {\n url.searchParams.set(key, value)\n })\n return url.toString()\n}\n\nexport function cacheBustedUrl(urlString) {\n return urlWithParams(urlString, { reload: Date.now() })\n}\n\nexport async function reloadHtmlDocument() {\n let currentUrl = cacheBustedUrl(urlWithParams(window.location.href, { hotwire_spark: \"true\" }))\n const response = await fetch(currentUrl, { headers: { \"Accept\": \"text/html\" }})\n\n if (!response.ok) {\n throw new Error(`${response.status} when fetching ${currentUrl}`)\n }\n\n const fetchedHTML = await response.text()\n const parser = new DOMParser()\n return parser.parseFromString(fetchedHTML, \"text/html\")\n}\n\nexport function getConfigurationProperty(name) {\n return document.querySelector(`meta[name=\"hotwire-spark:${name}\"]`)?.content\n}\n\n","// base IIFE to define idiomorph\nvar Idiomorph = (function () {\n 'use strict';\n\n //=============================================================================\n // AND NOW IT BEGINS...\n //=============================================================================\n let EMPTY_SET = new Set();\n\n // default configuration values, updatable by users now\n let defaults = {\n morphStyle: \"outerHTML\",\n callbacks : {\n beforeNodeAdded: noOp,\n afterNodeAdded: noOp,\n beforeNodeMorphed: noOp,\n afterNodeMorphed: noOp,\n beforeNodeRemoved: noOp,\n afterNodeRemoved: noOp,\n beforeAttributeUpdated: noOp,\n\n },\n head: {\n style: 'merge',\n shouldPreserve: function (elt) {\n return elt.getAttribute(\"im-preserve\") === \"true\";\n },\n shouldReAppend: function (elt) {\n return elt.getAttribute(\"im-re-append\") === \"true\";\n },\n shouldRemove: noOp,\n afterHeadMorphed: noOp,\n }\n };\n\n //=============================================================================\n // Core Morphing Algorithm - morph, morphNormalizedContent, morphOldNodeTo, morphChildren\n //=============================================================================\n function morph(oldNode, newContent, config = {}) {\n\n if (oldNode instanceof Document) {\n oldNode = oldNode.documentElement;\n }\n\n if (typeof newContent === 'string') {\n newContent = parseContent(newContent);\n }\n\n let normalizedContent = normalizeContent(newContent);\n\n let ctx = createMorphContext(oldNode, normalizedContent, config);\n\n return morphNormalizedContent(oldNode, normalizedContent, ctx);\n }\n\n function morphNormalizedContent(oldNode, normalizedNewContent, ctx) {\n if (ctx.head.block) {\n let oldHead = oldNode.querySelector('head');\n let newHead = normalizedNewContent.querySelector('head');\n if (oldHead && newHead) {\n let promises = handleHeadElement(newHead, oldHead, ctx);\n // when head promises resolve, call morph again, ignoring the head tag\n Promise.all(promises).then(function () {\n morphNormalizedContent(oldNode, normalizedNewContent, Object.assign(ctx, {\n head: {\n block: false,\n ignore: true\n }\n }));\n });\n return;\n }\n }\n\n if (ctx.morphStyle === \"innerHTML\") {\n\n // innerHTML, so we are only updating the children\n morphChildren(normalizedNewContent, oldNode, ctx);\n return oldNode.children;\n\n } else if (ctx.morphStyle === \"outerHTML\" || ctx.morphStyle == null) {\n // otherwise find the best element match in the new content, morph that, and merge its siblings\n // into either side of the best match\n let bestMatch = findBestNodeMatch(normalizedNewContent, oldNode, ctx);\n\n // stash the siblings that will need to be inserted on either side of the best match\n let previousSibling = bestMatch?.previousSibling;\n let nextSibling = bestMatch?.nextSibling;\n\n // morph it\n let morphedNode = morphOldNodeTo(oldNode, bestMatch, ctx);\n\n if (bestMatch) {\n // if there was a best match, merge the siblings in too and return the\n // whole bunch\n return insertSiblings(previousSibling, morphedNode, nextSibling);\n } else {\n // otherwise nothing was added to the DOM\n return []\n }\n } else {\n throw \"Do not understand how to morph style \" + ctx.morphStyle;\n }\n }\n\n\n /**\n * @param possibleActiveElement\n * @param ctx\n * @returns {boolean}\n */\n function ignoreValueOfActiveElement(possibleActiveElement, ctx) {\n return ctx.ignoreActiveValue && possibleActiveElement === document.activeElement;\n }\n\n /**\n * @param oldNode root node to merge content into\n * @param newContent new content to merge\n * @param ctx the merge context\n * @returns {Element} the element that ended up in the DOM\n */\n function morphOldNodeTo(oldNode, newContent, ctx) {\n if (ctx.ignoreActive && oldNode === document.activeElement) {\n // don't morph focused element\n } else if (newContent == null) {\n if (ctx.callbacks.beforeNodeRemoved(oldNode) === false) return oldNode;\n\n oldNode.remove();\n ctx.callbacks.afterNodeRemoved(oldNode);\n return null;\n } else if (!isSoftMatch(oldNode, newContent)) {\n if (ctx.callbacks.beforeNodeRemoved(oldNode) === false) return oldNode;\n if (ctx.callbacks.beforeNodeAdded(newContent) === false) return oldNode;\n\n oldNode.parentElement.replaceChild(newContent, oldNode);\n ctx.callbacks.afterNodeAdded(newContent);\n ctx.callbacks.afterNodeRemoved(oldNode);\n return newContent;\n } else {\n if (ctx.callbacks.beforeNodeMorphed(oldNode, newContent) === false) return oldNode;\n\n if (oldNode instanceof HTMLHeadElement && ctx.head.ignore) {\n // ignore the head element\n } else if (oldNode instanceof HTMLHeadElement && ctx.head.style !== \"morph\") {\n handleHeadElement(newContent, oldNode, ctx);\n } else {\n syncNodeFrom(newContent, oldNode, ctx);\n if (!ignoreValueOfActiveElement(oldNode, ctx)) {\n morphChildren(newContent, oldNode, ctx);\n }\n }\n ctx.callbacks.afterNodeMorphed(oldNode, newContent);\n return oldNode;\n }\n }\n\n /**\n * This is the core algorithm for matching up children. The idea is to use id sets to try to match up\n * nodes as faithfully as possible. We greedily match, which allows us to keep the algorithm fast, but\n * by using id sets, we are able to better match up with content deeper in the DOM.\n *\n * Basic algorithm is, for each node in the new content:\n *\n * - if we have reached the end of the old parent, append the new content\n * - if the new content has an id set match with the current insertion point, morph\n * - search for an id set match\n * - if id set match found, morph\n * - otherwise search for a \"soft\" match\n * - if a soft match is found, morph\n * - otherwise, prepend the new node before the current insertion point\n *\n * The two search algorithms terminate if competing node matches appear to outweigh what can be achieved\n * with the current node. See findIdSetMatch() and findSoftMatch() for details.\n *\n * @param {Element} newParent the parent element of the new content\n * @param {Element } oldParent the old content that we are merging the new content into\n * @param ctx the merge context\n */\n function morphChildren(newParent, oldParent, ctx) {\n\n let nextNewChild = newParent.firstChild;\n let insertionPoint = oldParent.firstChild;\n let newChild;\n\n // run through all the new content\n while (nextNewChild) {\n\n newChild = nextNewChild;\n nextNewChild = newChild.nextSibling;\n\n // if we are at the end of the exiting parent's children, just append\n if (insertionPoint == null) {\n if (ctx.callbacks.beforeNodeAdded(newChild) === false) return;\n\n oldParent.appendChild(newChild);\n ctx.callbacks.afterNodeAdded(newChild);\n removeIdsFromConsideration(ctx, newChild);\n continue;\n }\n\n // if the current node has an id set match then morph\n if (isIdSetMatch(newChild, insertionPoint, ctx)) {\n morphOldNodeTo(insertionPoint, newChild, ctx);\n insertionPoint = insertionPoint.nextSibling;\n removeIdsFromConsideration(ctx, newChild);\n continue;\n }\n\n // otherwise search forward in the existing old children for an id set match\n let idSetMatch = findIdSetMatch(newParent, oldParent, newChild, insertionPoint, ctx);\n\n // if we found a potential match, remove the nodes until that point and morph\n if (idSetMatch) {\n insertionPoint = removeNodesBetween(insertionPoint, idSetMatch, ctx);\n morphOldNodeTo(idSetMatch, newChild, ctx);\n removeIdsFromConsideration(ctx, newChild);\n continue;\n }\n\n // no id set match found, so scan forward for a soft match for the current node\n let softMatch = findSoftMatch(newParent, oldParent, newChild, insertionPoint, ctx);\n\n // if we found a soft match for the current node, morph\n if (softMatch) {\n insertionPoint = removeNodesBetween(insertionPoint, softMatch, ctx);\n morphOldNodeTo(softMatch, newChild, ctx);\n removeIdsFromConsideration(ctx, newChild);\n continue;\n }\n\n // abandon all hope of morphing, just insert the new child before the insertion point\n // and move on\n if (ctx.callbacks.beforeNodeAdded(newChild) === false) return;\n\n oldParent.insertBefore(newChild, insertionPoint);\n ctx.callbacks.afterNodeAdded(newChild);\n removeIdsFromConsideration(ctx, newChild);\n }\n\n // remove any remaining old nodes that didn't match up with new content\n while (insertionPoint !== null) {\n\n let tempNode = insertionPoint;\n insertionPoint = insertionPoint.nextSibling;\n removeNode(tempNode, ctx);\n }\n }\n\n //=============================================================================\n // Attribute Syncing Code\n //=============================================================================\n\n /**\n * @param attr {String} the attribute to be mutated\n * @param to {Element} the element that is going to be updated\n * @param updateType {(\"update\"|\"remove\")}\n * @param ctx the merge context\n * @returns {boolean} true if the attribute should be ignored, false otherwise\n */\n function ignoreAttribute(attr, to, updateType, ctx) {\n if(attr === 'value' && ctx.ignoreActiveValue && to === document.activeElement){\n return true;\n }\n return ctx.callbacks.beforeAttributeUpdated(attr, to, updateType) === false;\n }\n\n /**\n * syncs a given node with another node, copying over all attributes and\n * inner element state from the 'from' node to the 'to' node\n *\n * @param {Element} from the element to copy attributes & state from\n * @param {Element} to the element to copy attributes & state to\n * @param ctx the merge context\n */\n function syncNodeFrom(from, to, ctx) {\n let type = from.nodeType\n\n // if is an element type, sync the attributes from the\n // new node into the new node\n if (type === 1 /* element type */) {\n const fromAttributes = from.attributes;\n const toAttributes = to.attributes;\n for (const fromAttribute of fromAttributes) {\n if (ignoreAttribute(fromAttribute.name, to, 'update', ctx)) {\n continue;\n }\n if (to.getAttribute(fromAttribute.name) !== fromAttribute.value) {\n to.setAttribute(fromAttribute.name, fromAttribute.value);\n }\n }\n // iterate backwards to avoid skipping over items when a delete occurs\n for (let i = toAttributes.length - 1; 0 <= i; i--) {\n const toAttribute = toAttributes[i];\n if (ignoreAttribute(toAttribute.name, to, 'remove', ctx)) {\n continue;\n }\n if (!from.hasAttribute(toAttribute.name)) {\n to.removeAttribute(toAttribute.name);\n }\n }\n }\n\n // sync text nodes\n if (type === 8 /* comment */ || type === 3 /* text */) {\n if (to.nodeValue !== from.nodeValue) {\n to.nodeValue = from.nodeValue;\n }\n }\n\n if (!ignoreValueOfActiveElement(to, ctx)) {\n // sync input values\n syncInputValue(from, to, ctx);\n }\n }\n\n /**\n * @param from {Element} element to sync the value from\n * @param to {Element} element to sync the value to\n * @param attributeName {String} the attribute name\n * @param ctx the merge context\n */\n function syncBooleanAttribute(from, to, attributeName, ctx) {\n if (from[attributeName] !== to[attributeName]) {\n let ignoreUpdate = ignoreAttribute(attributeName, to, 'update', ctx);\n if (!ignoreUpdate) {\n to[attributeName] = from[attributeName];\n }\n if (from[attributeName]) {\n if (!ignoreUpdate) {\n to.setAttribute(attributeName, from[attributeName]);\n }\n } else {\n if (!ignoreAttribute(attributeName, to, 'remove', ctx)) {\n to.removeAttribute(attributeName);\n }\n }\n }\n }\n\n /**\n * NB: many bothans died to bring us information:\n *\n * https://github.com/patrick-steele-idem/morphdom/blob/master/src/specialElHandlers.js\n * https://github.com/choojs/nanomorph/blob/master/lib/morph.jsL113\n *\n * @param from {Element} the element to sync the input value from\n * @param to {Element} the element to sync the input value to\n * @param ctx the merge context\n */\n function syncInputValue(from, to, ctx) {\n if (from instanceof HTMLInputElement &&\n to instanceof HTMLInputElement &&\n from.type !== 'file') {\n\n let fromValue = from.value;\n let toValue = to.value;\n\n // sync boolean attributes\n syncBooleanAttribute(from, to, 'checked', ctx);\n syncBooleanAttribute(from, to, 'disabled', ctx);\n\n if (!from.hasAttribute('value')) {\n if (!ignoreAttribute('value', to, 'remove', ctx)) {\n to.value = '';\n to.removeAttribute('value');\n }\n } else if (fromValue !== toValue) {\n if (!ignoreAttribute('value', to, 'update', ctx)) {\n to.setAttribute('value', fromValue);\n to.value = fromValue;\n }\n }\n } else if (from instanceof HTMLOptionElement) {\n syncBooleanAttribute(from, to, 'selected', ctx)\n } else if (from instanceof HTMLTextAreaElement && to instanceof HTMLTextAreaElement) {\n let fromValue = from.value;\n let toValue = to.value;\n if (ignoreAttribute('value', to, 'update', ctx)) {\n return;\n }\n if (fromValue !== toValue) {\n to.value = fromValue;\n }\n if (to.firstChild && to.firstChild.nodeValue !== fromValue) {\n to.firstChild.nodeValue = fromValue\n }\n }\n }\n\n //=============================================================================\n // the HEAD tag can be handled specially, either w/ a 'merge' or 'append' style\n //=============================================================================\n function handleHeadElement(newHeadTag, currentHead, ctx) {\n\n let added = []\n let removed = []\n let preserved = []\n let nodesToAppend = []\n\n let headMergeStyle = ctx.head.style;\n\n // put all new head elements into a Map, by their outerHTML\n let srcToNewHeadNodes = new Map();\n for (const newHeadChild of newHeadTag.children) {\n srcToNewHeadNodes.set(newHeadChild.outerHTML, newHeadChild);\n }\n\n // for each elt in the current head\n for (const currentHeadElt of currentHead.children) {\n\n // If the current head element is in the map\n let inNewContent = srcToNewHeadNodes.has(currentHeadElt.outerHTML);\n let isReAppended = ctx.head.shouldReAppend(currentHeadElt);\n let isPreserved = ctx.head.shouldPreserve(currentHeadElt);\n if (inNewContent || isPreserved) {\n if (isReAppended) {\n // remove the current version and let the new version replace it and re-execute\n removed.push(currentHeadElt);\n } else {\n // this element already exists and should not be re-appended, so remove it from\n // the new content map, preserving it in the DOM\n srcToNewHeadNodes.delete(currentHeadElt.outerHTML);\n preserved.push(currentHeadElt);\n }\n } else {\n if (headMergeStyle === \"append\") {\n // we are appending and this existing element is not new content\n // so if and only if it is marked for re-append do we do anything\n if (isReAppended) {\n removed.push(currentHeadElt);\n nodesToAppend.push(currentHeadElt);\n }\n } else {\n // if this is a merge, we remove this content since it is not in the new head\n if (ctx.head.shouldRemove(currentHeadElt) !== false) {\n removed.push(currentHeadElt);\n }\n }\n }\n }\n\n // Push the remaining new head elements in the Map into the\n // nodes to append to the head tag\n nodesToAppend.push(...srcToNewHeadNodes.values());\n log(\"to append: \", nodesToAppend);\n\n let promises = [];\n for (const newNode of nodesToAppend) {\n log(\"adding: \", newNode);\n let newElt = document.createRange().createContextualFragment(newNode.outerHTML).firstChild;\n log(newElt);\n if (ctx.callbacks.beforeNodeAdded(newElt) !== false) {\n if (newElt.href || newElt.src) {\n let resolve = null;\n let promise = new Promise(function (_resolve) {\n resolve = _resolve;\n });\n newElt.addEventListener('load', function () {\n resolve();\n });\n promises.push(promise);\n }\n currentHead.appendChild(newElt);\n ctx.callbacks.afterNodeAdded(newElt);\n added.push(newElt);\n }\n }\n\n // remove all removed elements, after we have appended the new elements to avoid\n // additional network requests for things like style sheets\n for (const removedElement of removed) {\n if (ctx.callbacks.beforeNodeRemoved(removedElement) !== false) {\n currentHead.removeChild(removedElement);\n ctx.callbacks.afterNodeRemoved(removedElement);\n }\n }\n\n ctx.head.afterHeadMorphed(currentHead, {added: added, kept: preserved, removed: removed});\n return promises;\n }\n\n //=============================================================================\n // Misc\n //=============================================================================\n\n function log() {\n //console.log(arguments);\n }\n\n function noOp() {\n }\n\n /*\n Deep merges the config object and the Idiomoroph.defaults object to\n produce a final configuration object\n */\n function mergeDefaults(config) {\n let finalConfig = {};\n // copy top level stuff into final config\n Object.assign(finalConfig, defaults);\n Object.assign(finalConfig, config);\n\n // copy callbacks into final config (do this to deep merge the callbacks)\n finalConfig.callbacks = {};\n Object.assign(finalConfig.callbacks, defaults.callbacks);\n Object.assign(finalConfig.callbacks, config.callbacks);\n\n // copy head config into final config (do this to deep merge the head)\n finalConfig.head = {};\n Object.assign(finalConfig.head, defaults.head);\n Object.assign(finalConfig.head, config.head);\n return finalConfig;\n }\n\n function createMorphContext(oldNode, newContent, config) {\n config = mergeDefaults(config);\n return {\n target: oldNode,\n newContent: newContent,\n config: config,\n morphStyle: config.morphStyle,\n ignoreActive: config.ignoreActive,\n ignoreActiveValue: config.ignoreActiveValue,\n idMap: createIdMap(oldNode, newContent),\n deadIds: new Set(),\n callbacks: config.callbacks,\n head: config.head\n }\n }\n\n function isIdSetMatch(node1, node2, ctx) {\n if (node1 == null || node2 == null) {\n return false;\n }\n if (node1.nodeType === node2.nodeType && node1.tagName === node2.tagName) {\n if (node1.id !== \"\" && node1.id === node2.id) {\n return true;\n } else {\n return getIdIntersectionCount(ctx, node1, node2) > 0;\n }\n }\n return false;\n }\n\n function isSoftMatch(node1, node2) {\n if (node1 == null || node2 == null) {\n return false;\n }\n return node1.nodeType === node2.nodeType && node1.tagName === node2.tagName\n }\n\n function removeNodesBetween(startInclusive, endExclusive, ctx) {\n while (startInclusive !== endExclusive) {\n let tempNode = startInclusive;\n startInclusive = startInclusive.nextSibling;\n removeNode(tempNode, ctx);\n }\n removeIdsFromConsideration(ctx, endExclusive);\n return endExclusive.nextSibling;\n }\n\n //=============================================================================\n // Scans forward from the insertionPoint in the old parent looking for a potential id match\n // for the newChild. We stop if we find a potential id match for the new child OR\n // if the number of potential id matches we are discarding is greater than the\n // potential id matches for the new child\n //=============================================================================\n function findIdSetMatch(newContent, oldParent, newChild, insertionPoint, ctx) {\n\n // max id matches we are willing to discard in our search\n let newChildPotentialIdCount = getIdIntersectionCount(ctx, newChild, oldParent);\n\n let potentialMatch = null;\n\n // only search forward if there is a possibility of an id match\n if (newChildPotentialIdCount > 0) {\n let potentialMatch = insertionPoint;\n // if there is a possibility of an id match, scan forward\n // keep track of the potential id match count we are discarding (the\n // newChildPotentialIdCount must be greater than this to make it likely\n // worth it)\n let otherMatchCount = 0;\n while (potentialMatch != null) {\n\n // If we have an id match, return the current potential match\n if (isIdSetMatch(newChild, potentialMatch, ctx)) {\n return potentialMatch;\n }\n\n // computer the other potential matches of this new content\n otherMatchCount += getIdIntersectionCount(ctx, potentialMatch, newContent);\n if (otherMatchCount > newChildPotentialIdCount) {\n // if we have more potential id matches in _other_ content, we\n // do not have a good candidate for an id match, so return null\n return null;\n }\n\n // advanced to the next old content child\n potentialMatch = potentialMatch.nextSibling;\n }\n }\n return potentialMatch;\n }\n\n //=============================================================================\n // Scans forward from the insertionPoint in the old parent looking for a potential soft match\n // for the newChild. We stop if we find a potential soft match for the new child OR\n // if we find a potential id match in the old parents children OR if we find two\n // potential soft matches for the next two pieces of new content\n //=============================================================================\n function findSoftMatch(newContent, oldParent, newChild, insertionPoint, ctx) {\n\n let potentialSoftMatch = insertionPoint;\n let nextSibling = newChild.nextSibling;\n let siblingSoftMatchCount = 0;\n\n while (potentialSoftMatch != null) {\n\n if (getIdIntersectionCount(ctx, potentialSoftMatch, newContent) > 0) {\n // the current potential soft match has a potential id set match with the remaining new\n // content so bail out of looking\n return null;\n }\n\n // if we have a soft match with the current node, return it\n if (isSoftMatch(newChild, potentialSoftMatch)) {\n return potentialSoftMatch;\n }\n\n if (isSoftMatch(nextSibling, potentialSoftMatch)) {\n // the next new node has a soft match with this node, so\n // increment the count of future soft matches\n siblingSoftMatchCount++;\n nextSibling = nextSibling.nextSibling;\n\n // If there are two future soft matches, bail to allow the siblings to soft match\n // so that we don't consume future soft matches for the sake of the current node\n if (siblingSoftMatchCount >= 2) {\n return null;\n }\n }\n\n // advanced to the next old content child\n potentialSoftMatch = potentialSoftMatch.nextSibling;\n }\n\n return potentialSoftMatch;\n }\n\n function parseContent(newContent) {\n let parser = new DOMParser();\n\n // remove svgs to avoid false-positive matches on head, etc.\n let contentWithSvgsRemoved = newContent.replace(/]*>|>)([\\s\\S]*?)<\\/svg>/gim, '');\n\n // if the newContent contains a html, head or body tag, we can simply parse it w/o wrapping\n if (contentWithSvgsRemoved.match(/<\\/html>/) || contentWithSvgsRemoved.match(/<\\/head>/) || contentWithSvgsRemoved.match(/<\\/body>/)) {\n let content = parser.parseFromString(newContent, \"text/html\");\n // if it is a full HTML document, return the document itself as the parent container\n if (contentWithSvgsRemoved.match(/<\\/html>/)) {\n content.generatedByIdiomorph = true;\n return content;\n } else {\n // otherwise return the html element as the parent container\n let htmlElement = content.firstChild;\n if (htmlElement) {\n htmlElement.generatedByIdiomorph = true;\n return htmlElement;\n } else {\n return null;\n }\n }\n } else {\n // if it is partial HTML, wrap it in a template tag to provide a parent element and also to help\n // deal with touchy tags like tr, tbody, etc.\n let responseDoc = parser.parseFromString(\"\", \"text/html\");\n let content = responseDoc.body.querySelector('template').content;\n content.generatedByIdiomorph = true;\n return content\n }\n }\n\n function normalizeContent(newContent) {\n if (newContent == null) {\n // noinspection UnnecessaryLocalVariableJS\n const dummyParent = document.createElement('div');\n return dummyParent;\n } else if (newContent.generatedByIdiomorph) {\n // the template tag created by idiomorph parsing can serve as a dummy parent\n return newContent;\n } else if (newContent instanceof Node) {\n // a single node is added as a child to a dummy parent\n const dummyParent = document.createElement('div');\n dummyParent.append(newContent);\n return dummyParent;\n } else {\n // all nodes in the array or HTMLElement collection are consolidated under\n // a single dummy parent element\n const dummyParent = document.createElement('div');\n for (const elt of [...newContent]) {\n dummyParent.append(elt);\n }\n return dummyParent;\n }\n }\n\n function insertSiblings(previousSibling, morphedNode, nextSibling) {\n let stack = []\n let added = []\n while (previousSibling != null) {\n stack.push(previousSibling);\n previousSibling = previousSibling.previousSibling;\n }\n while (stack.length > 0) {\n let node = stack.pop();\n added.push(node); // push added preceding siblings on in order and insert\n morphedNode.parentElement.insertBefore(node, morphedNode);\n }\n added.push(morphedNode);\n while (nextSibling != null) {\n stack.push(nextSibling);\n added.push(nextSibling); // here we are going in order, so push on as we scan, rather than add\n nextSibling = nextSibling.nextSibling;\n }\n while (stack.length > 0) {\n morphedNode.parentElement.insertBefore(stack.pop(), morphedNode.nextSibling);\n }\n return added;\n }\n\n function findBestNodeMatch(newContent, oldNode, ctx) {\n let currentElement;\n currentElement = newContent.firstChild;\n let bestElement = currentElement;\n let score = 0;\n while (currentElement) {\n let newScore = scoreElement(currentElement, oldNode, ctx);\n if (newScore > score) {\n bestElement = currentElement;\n score = newScore;\n }\n currentElement = currentElement.nextSibling;\n }\n return bestElement;\n }\n\n function scoreElement(node1, node2, ctx) {\n if (isSoftMatch(node1, node2)) {\n return .5 + getIdIntersectionCount(ctx, node1, node2);\n }\n return 0;\n }\n\n function removeNode(tempNode, ctx) {\n removeIdsFromConsideration(ctx, tempNode)\n if (ctx.callbacks.beforeNodeRemoved(tempNode) === false) return;\n\n tempNode.remove();\n ctx.callbacks.afterNodeRemoved(tempNode);\n }\n\n //=============================================================================\n // ID Set Functions\n //=============================================================================\n\n function isIdInConsideration(ctx, id) {\n return !ctx.deadIds.has(id);\n }\n\n function idIsWithinNode(ctx, id, targetNode) {\n let idSet = ctx.idMap.get(targetNode) || EMPTY_SET;\n return idSet.has(id);\n }\n\n function removeIdsFromConsideration(ctx, node) {\n let idSet = ctx.idMap.get(node) || EMPTY_SET;\n for (const id of idSet) {\n ctx.deadIds.add(id);\n }\n }\n\n function getIdIntersectionCount(ctx, node1, node2) {\n let sourceSet = ctx.idMap.get(node1) || EMPTY_SET;\n let matchCount = 0;\n for (const id of sourceSet) {\n // a potential match is an id in the source and potentialIdsSet, but\n // that has not already been merged into the DOM\n if (isIdInConsideration(ctx, id) && idIsWithinNode(ctx, id, node2)) {\n ++matchCount;\n }\n }\n return matchCount;\n }\n\n /**\n * A bottom up algorithm that finds all elements with ids inside of the node\n * argument and populates id sets for those nodes and all their parents, generating\n * a set of ids contained within all nodes for the entire hierarchy in the DOM\n *\n * @param node {Element}\n * @param {Map>} idMap\n */\n function populateIdMapForNode(node, idMap) {\n let nodeParent = node.parentElement;\n // find all elements with an id property\n let idElements = node.querySelectorAll('[id]');\n for (const elt of idElements) {\n let current = elt;\n // walk up the parent hierarchy of that element, adding the id\n // of element to the parent's id set\n while (current !== nodeParent && current != null) {\n let idSet = idMap.get(current);\n // if the id set doesn't exist, create it and insert it in the map\n if (idSet == null) {\n idSet = new Set();\n idMap.set(current, idSet);\n }\n idSet.add(elt.id);\n current = current.parentElement;\n }\n }\n }\n\n /**\n * This function computes a map of nodes to all ids contained within that node (inclusive of the\n * node). This map can be used to ask if two nodes have intersecting sets of ids, which allows\n * for a looser definition of \"matching\" than tradition id matching, and allows child nodes\n * to contribute to a parent nodes matching.\n *\n * @param {Element} oldContent the old content that will be morphed\n * @param {Element} newContent the new content to morph to\n * @returns {Map>} a map of nodes to id sets for the\n */\n function createIdMap(oldContent, newContent) {\n let idMap = new Map();\n populateIdMapForNode(oldContent, idMap);\n populateIdMapForNode(newContent, idMap);\n return idMap;\n }\n\n //=============================================================================\n // This is what ends up becoming the Idiomorph global object\n //=============================================================================\n return {\n morph,\n defaults\n }\n })();\n\nexport {Idiomorph};\n","import HotwireSpark from \"./index.js\"\n\nexport function log(...args) {\n if (HotwireSpark.config.loggingEnabled) {\n console.log(`[hotwire_spark]`, ...args)\n }\n}\n\n","import { log } from \"../logger.js\"\nimport { cacheBustedUrl, reloadHtmlDocument } from \"../helpers.js\"\n\nexport class StimulusReloader {\n static async reload(filePattern) {\n const document = await reloadHtmlDocument()\n return new StimulusReloader(document, filePattern).reload()\n }\n\n constructor(document, filePattern = /./) {\n this.document = document\n this.filePattern = filePattern\n this.application = window.Stimulus\n }\n\n async reload() {\n log(\"Reload Stimulus controllers...\")\n\n this.application.stop()\n\n await this.#reloadChangedStimulusControllers()\n this.#unloadDeletedStimulusControllers()\n\n this.application.start()\n }\n\n async #reloadChangedStimulusControllers() {\n await Promise.all(\n this.#stimulusControllerPathsToReload.map(async moduleName => this.#reloadStimulusController(moduleName))\n )\n }\n\n get #stimulusControllerPathsToReload() {\n this.controllerPathsToReload = this.controllerPathsToReload || this.#stimulusControllerPaths.filter(path => this.#shouldReloadController(path))\n return this.controllerPathsToReload\n }\n\n get #stimulusControllerPaths() {\n return Object.keys(this.#stimulusPathsByModule).filter(path => path.endsWith(\"_controller\"))\n }\n\n #shouldReloadController(path) {\n return this.filePattern.test(path)\n }\n\n get #stimulusPathsByModule() {\n this.pathsByModule = this.pathsByModule || this.#parseImportmapJson()\n return this.pathsByModule\n }\n\n #parseImportmapJson() {\n const importmapScript = this.document.querySelector(\"script[type=importmap]\")\n return JSON.parse(importmapScript.text).imports\n }\n\n async #reloadStimulusController(moduleName) {\n log(`\\t${moduleName}`)\n\n const controllerName = this.#extractControllerName(moduleName)\n const path = cacheBustedUrl(this.#pathForModuleName(moduleName))\n\n const module = await import(path)\n\n this.#registerController(controllerName, module)\n }\n\n #unloadDeletedStimulusControllers() {\n this.#controllersToUnload.forEach(controller => this.#deregisterController(controller.identifier))\n }\n\n get #controllersToUnload() {\n if (this.#didChangeTriggerAReload) {\n return []\n } else {\n return this.application.controllers.filter(controller => this.filePattern.test(`${controller.identifier}_controller`))\n }\n }\n\n get #didChangeTriggerAReload() {\n return this.#stimulusControllerPathsToReload.length > 0\n }\n\n #pathForModuleName(moduleName) {\n return this.#stimulusPathsByModule[moduleName]\n }\n\n #extractControllerName(path) {\n return path\n .replace(/^.*\\//, \"\")\n .replace(\"_controller\", \"\")\n .replace(/\\//g, \"--\")\n .replace(/_/g, \"-\")\n }\n\n #registerController(name, module) {\n this.application.unload(name)\n this.application.register(name, module.default)\n }\n\n #deregisterController(name) {\n log(`\\tRemoving controller ${name}`)\n this.application.unload(name)\n }\n}\n","import { Idiomorph } from \"idiomorph/dist/idiomorph.esm.js\"\nimport { log } from \"../logger.js\"\nimport { reloadHtmlDocument } from \"../helpers.js\"\nimport { StimulusReloader } from \"./stimulus_reloader.js\"\n\nexport class HtmlReloader {\n static async reload() {\n return new HtmlReloader().reload()\n }\n\n async reload() {\n const reloadedDocument = await this.#reloadHtml()\n await this.#reloadStimulus(reloadedDocument)\n }\n\n async #reloadHtml() {\n log(\"Reload html...\")\n\n const reloadedDocument = await reloadHtmlDocument()\n this.#updateBody(reloadedDocument.body)\n return reloadedDocument\n }\n\n #updateBody(newBody) {\n Idiomorph.morph(document.body, newBody)\n }\n\n async #reloadStimulus(reloadedDocument) {\n return new StimulusReloader(reloadedDocument).reload()\n }\n}\n","import { log } from \"../logger.js\"\nimport { cacheBustedUrl, reloadHtmlDocument, pathWithoutAssetDigest } from \"../helpers.js\"\n\nexport class CssReloader {\n static async reload(...params) {\n return new CssReloader(...params).reload()\n }\n\n constructor(filePattern = /./) {\n this.filePattern = filePattern\n }\n\n async reload() {\n log(\"Reload css...\")\n await Promise.all(await this.#reloadAllLinks())\n }\n\n async #reloadAllLinks() {\n const cssLinks = await this.#loadNewCssLinks();\n return cssLinks.map(link => this.#reloadLinkIfNeeded(link))\n }\n\n async #loadNewCssLinks() {\n const reloadedDocument = await reloadHtmlDocument()\n return Array.from(reloadedDocument.head.querySelectorAll(\"link[rel='stylesheet']\"))\n }\n\n #reloadLinkIfNeeded(link) {\n if (this.#shouldReloadLink(link)) {\n return this.#reloadLink(link)\n } else {\n return Promise.resolve()\n }\n }\n\n #shouldReloadLink(link) {\n return this.filePattern.test(link.getAttribute(\"href\"))\n }\n\n async #reloadLink(link) {\n return new Promise(resolve => {\n const href = link.getAttribute(\"href\")\n const newLink = this.#findExistingLinkFor(link) || this.#appendNewLink(link)\n\n newLink.setAttribute(\"href\", cacheBustedUrl(link.getAttribute(\"href\")))\n newLink.onload = () => {\n log(`\\t${href}`)\n resolve()\n }\n })\n }\n\n #findExistingLinkFor(link) {\n return this.#cssLinks.find(newLink => pathWithoutAssetDigest(link.href) === pathWithoutAssetDigest(newLink.href))\n }\n\n get #cssLinks() {\n return Array.from(document.querySelectorAll(\"link[rel='stylesheet']\"))\n }\n\n #appendNewLink(link) {\n document.head.append(link)\n return link\n }\n}\n","import consumer from \"./consumer\"\nimport { assetNameFromPath } from \"../helpers.js\";\nimport { HtmlReloader } from \"../reloaders/html_reloader.js\";\nimport { CssReloader } from \"../reloaders/css_reloader.js\";\nimport { StimulusReloader } from \"../reloaders/stimulus_reloader.js\";\n\nconsumer.subscriptions.create({ channel: \"Hotwire::Spark::Channel\" }, {\n connected() {\n document.body.setAttribute(\"data-hotwire-spark-ready\", \"\")\n },\n\n async received(message) {\n try {\n await this.dispatch(message)\n } catch(error) {\n console.log(`Error on ${message.action}`, error)\n }\n },\n\n dispatch({ action, path }) {\n const fileName = assetNameFromPath(path)\n\n switch(action) {\n case \"reload_html\":\n return this.reloadHtml()\n case \"reload_css\":\n return this.reloadCss(fileName)\n case \"reload_stimulus\":\n return this.reloadStimulus(fileName)\n default:\n throw new Error(`Unknown action: ${action}`)\n }\n },\n\n reloadHtml() {\n return HtmlReloader.reload()\n },\n\n reloadCss(fileName) {\n return CssReloader.reload(new RegExp(fileName))\n },\n\n reloadStimulus(fileName) {\n return StimulusReloader.reload(new RegExp(fileName))\n }\n})\n\n","import \"./channels/monitoring_channel.js\"\nimport { getConfigurationProperty } from \"./helpers.js\";\n\nconst HotwireSpark = {\n config: {\n loggingEnabled: false \n }\n}\n\ndocument.addEventListener(\"DOMContentLoaded\", function() {\n HotwireSpark.config.loggingEnabled = getConfigurationProperty(\"logging\");\n})\n\nexport default HotwireSpark\n"],"names":["adapters","logger","console","undefined","WebSocket","log","messages","this","enabled","push","Date","now","getTime","secondsSince","time","ConnectionMonitor","constructor","connection","visibilityDidChange","bind","reconnectAttempts","start","isRunning","startedAt","stoppedAt","startPolling","addEventListener","staleThreshold","stop","stopPolling","removeEventListener","recordMessage","pingedAt","recordConnect","disconnectedAt","recordDisconnect","poll","clearTimeout","pollTimeout","setTimeout","reconnectIfStale","getPollInterval","reconnectionBackoffRate","Math","pow","min","random","connectionIsStale","refreshedAt","disconnectedRecently","reopen","document","visibilityState","isOpen","INTERNAL","message_types","welcome","disconnect","ping","confirmation","rejection","disconnect_reasons","unauthorized","invalid_request","server_restart","remote","default_mount_path","protocols","supportedProtocols","slice","length","indexOf","Connection","consumer","open","subscriptions","monitor","disconnected","send","data","webSocket","JSON","stringify","isActive","getState","socketProtocols","subprotocols","uninstallEventHandlers","url","installEventHandlers","close","allowReconnect","error","reopenDelay","getProtocol","protocol","isState","triedToReconnect","isProtocolSupported","call","states","state","readyState","toLowerCase","eventName","events","handler","prototype","message","event","identifier","reason","reconnect","type","parse","reconnectAttempted","reload","confirmSubscription","notify","reconnected","reject","notifyAll","willAttemptReconnect","Subscription","params","mixin","object","properties","key","value","extend","perform","action","command","unsubscribe","remove","SubscriptionGuarantor","pendingSubscriptions","guarantee","subscription","startGuaranteeing","forget","filter","s","stopGuaranteeing","retrySubscribing","retryTimeout","subscribe","map","Subscriptions","guarantor","create","channelName","channel","add","ensureActiveConnection","findAll","sendCommand","callbackName","args","Consumer","_url","test","a","createElement","href","replace","createWebSocketURL","connect","addSubProtocol","subprotocol","createConsumer","name","element","head","querySelector","getAttribute","getConfig","pathWithoutAssetDigest","path","urlWithParams","urlString","URL","window","location","origin","Object","entries","forEach","_ref","searchParams","set","toString","cacheBustedUrl","async","reloadHtmlDocument","currentUrl","hotwire_spark","response","fetch","headers","Accept","ok","Error","status","fetchedHTML","text","DOMParser","parseFromString","Idiomorph","EMPTY_SET","Set","defaults","morphStyle","callbacks","beforeNodeAdded","noOp","afterNodeAdded","beforeNodeMorphed","afterNodeMorphed","beforeNodeRemoved","afterNodeRemoved","beforeAttributeUpdated","style","shouldPreserve","elt","shouldReAppend","shouldRemove","afterHeadMorphed","morphNormalizedContent","oldNode","normalizedNewContent","ctx","block","oldHead","newHead","promises","handleHeadElement","Promise","all","then","assign","ignore","morphChildren","children","bestMatch","newContent","currentElement","firstChild","bestElement","score","newScore","scoreElement","nextSibling","findBestNodeMatch","previousSibling","morphedNode","morphOldNodeTo","stack","added","node","pop","parentElement","insertBefore","insertSiblings","ignoreValueOfActiveElement","possibleActiveElement","ignoreActiveValue","activeElement","ignoreActive","isSoftMatch","HTMLHeadElement","from","to","nodeType","fromAttributes","attributes","toAttributes","fromAttribute","ignoreAttribute","setAttribute","i","toAttribute","hasAttribute","removeAttribute","nodeValue","HTMLInputElement","fromValue","toValue","syncBooleanAttribute","HTMLOptionElement","HTMLTextAreaElement","syncInputValue","syncNodeFrom","replaceChild","newParent","oldParent","newChild","nextNewChild","insertionPoint","appendChild","removeIdsFromConsideration","isIdSetMatch","idSetMatch","findIdSetMatch","removeNodesBetween","softMatch","findSoftMatch","tempNode","removeNode","attr","updateType","attributeName","ignoreUpdate","newHeadTag","currentHead","removed","preserved","nodesToAppend","headMergeStyle","srcToNewHeadNodes","Map","newHeadChild","outerHTML","currentHeadElt","inNewContent","has","isReAppended","isPreserved","delete","values","newNode","newElt","createRange","createContextualFragment","src","resolve","promise","_resolve","removedElement","removeChild","kept","node1","node2","tagName","id","getIdIntersectionCount","startInclusive","endExclusive","newChildPotentialIdCount","potentialMatch","otherMatchCount","potentialSoftMatch","siblingSoftMatchCount","isIdInConsideration","deadIds","idIsWithinNode","targetNode","idMap","get","idSet","sourceSet","matchCount","populateIdMapForNode","nodeParent","idElements","querySelectorAll","current","createIdMap","oldContent","morph","config","Document","documentElement","parser","contentWithSvgsRemoved","match","content","generatedByIdiomorph","htmlElement","body","parseContent","normalizedContent","Node","dummyParent","append","normalizeContent","finalConfig","mergeDefaults","target","createMorphContext","HotwireSpark","loggingEnabled","_len","arguments","Array","_key","StimulusReloader","filePattern","application","Stimulus","reloadChangedStimulusControllers","unloadDeletedStimulusControllers","stimulusControllerPathsToReload","reloadStimulusController","moduleName","controllerPathsToReload","stimulusControllerPaths","shouldReloadController","keys","stimulusPathsByModule","endsWith","pathsByModule","parseImportmapJson","importmapScript","imports","controllerName","extractControllerName","pathForModuleName","module","import","registerController","controllersToUnload","controller","deregisterController","didChangeTriggerAReload","controllers","unload","register","default","HtmlReloader","reloadedDocument","reloadHtml","reloadStimulus","updateBody","newBody","CssReloader","reloadAllLinks","loadNewCssLinks","link","reloadLinkIfNeeded","shouldReloadLink","reloadLink","newLink","findExistingLinkFor","appendNewLink","onload","cssLinks","find","connected","received","dispatch","fileName","split","assetNameFromPath","reloadCss","RegExp"],"mappings":"yCAAA,IAAIA,EAAW,CACbC,OAA2B,oBAAZC,QAA0BA,aAAUC,EACnDC,UAAgC,oBAAdA,UAA4BA,eAAYD,GAGxDF,EAAS,CACX,GAAAI,IAAOC,GACDC,KAAKC,UACPF,EAASG,KAAKC,KAAKC,OACnBX,EAASC,OAAOI,IAAI,mBAAoBC,GAE9C,GAGA,MAAMK,EAAM,KAAM,IAAKD,MAAME,UAEvBC,EAAeC,IAASH,IAAQG,GAAQ,IAE9C,MAAMC,EACJ,WAAAC,CAAYC,GACVV,KAAKW,oBAAsBX,KAAKW,oB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GACb,UACQrG,KAAK4b,SAASvV,EACrB,CAAC,MAAMhB,GACN1F,QAAQG,IAAI,YAAYuG,EAAQwB,SAAUxC,EAC5C,CACD,EAEDuW,QAAAA,CAAQtQ,GAAmB,IAAlBzD,OAAEA,EAAM+C,KAAEA,GAAMU,EACvB,MAAMuQ,ENpBH,SAA2BjR,GAChC,OAAOA,EAAKkR,MAAM,KAAKhM,MAAMgM,MAAM,KAAK,EAC1C,CMkBqBC,CAAkBnR,GAEnC,OAAO/C,GACL,IAAK,cACH,OAAO7H,KAAKya,aACd,IAAK,aACH,OAAOza,KAAKgc,UAAUH,GACxB,IAAK,kBACH,OAAO7b,KAAK0a,eAAemB,GAC7B,QACE,MAAM,IAAIzP,MAAM,mBAAmBvE,KAExC,EAED4S,WAAUA,IACDF,EAAa1T,SAGtBmV,UAAUH,GACDhB,EAAYhU,OAAO,IAAIoV,OAAOJ,IAGvCnB,eAAemB,GACNvD,EAAiBzR,OAAO,IAAIoV,OAAOJ,MCxC9C,MAAM7D,EAAe,CACnBpB,OAAQ,CACNqB,gBAAgB,WAIpBrV,SAASzB,iBAAiB,oBAAoB,WPwBvC,IAAkCkJ,EOvBvC2N,EAAapB,OAAOqB,gBPuBmB5N,EOvBuB,UPwBvDzH,SAAS4H,cAAc,4BAA4BH,QAAW6M,QOvBvE","x_google_ignoreList":[0,3]} \ No newline at end of file diff --git a/app/javascript/hotwire/spark/reloaders/stimulus_reloader.js b/app/javascript/hotwire/spark/reloaders/stimulus_reloader.js index 60e3749..c6b878c 100644 --- a/app/javascript/hotwire/spark/reloaders/stimulus_reloader.js +++ b/app/javascript/hotwire/spark/reloaders/stimulus_reloader.js @@ -1,4 +1,3 @@ -import { Application } from "@hotwired/stimulus" import { log } from "../logger.js" import { cacheBustedUrl, reloadHtmlDocument } from "../helpers.js" @@ -11,7 +10,7 @@ export class StimulusReloader { constructor(document, filePattern = /./) { this.document = document this.filePattern = filePattern - this.application = window.Stimulus || Application.start() + this.application = window.Stimulus } async reload() {