UNPKG

stimulus

Version:

Stimulus JavaScript framework

1,344 lines (1,323 loc) 99.6 kB
(function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) : typeof define === 'function' && define.amd ? define(['exports'], factory) : (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.Stimulus = {})); })(this, (function (exports) { 'use strict'; /* 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 isSomething(object) { return object !== null && object !== undefined; } 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(map, key).add(value); } function del(map, key, value) { fetch(map, key).delete(value); prune(map, key); } function fetch(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 IndexedMultimap extends Multimap { constructor() { super(); this.keysByValue = new Map(); } get values() { return Array.from(this.keysByValue.keys()); } add(key, value) { super.add(key, value); add(this.keysByValue, value, key); } delete(key, value) { super.delete(key, value); del(this.keysByValue, value, key); } hasValue(value) { return this.keysByValue.has(value); } getKeysForValue(value) { const set = this.keysByValue.get(value); return set ? Array.from(set) : []; } } 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 readInheritableStaticObjectPairs(constructor, propertyName) { const ancestors = getAncestorsForConstructor(constructor); return ancestors.reduce((pairs, constructor) => { pairs.push(...getOwnStaticObjectPairs(constructor, propertyName)); return pairs; }, []); } 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 : []; } function getOwnStaticObjectPairs(constructor, propertyName) { const definition = constructor[propertyName]; return definition ? Object.keys(definition).map((key) => [key, definition[key]]) : []; } 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);