{"version":3,"file":"index-BEA4R4g9.js","sources":["../../../node_modules/@hotwired/stimulus/dist/stimulus.js","../../../app/packs/scripts/controllers/address_controller.js","../../../node_modules/imask/esm/core/utils.js","../../../node_modules/imask/esm/core/action-details.js","../../../node_modules/imask/esm/core/holder.js","../../../node_modules/imask/esm/masked/factory.js","../../../node_modules/imask/esm/controls/mask-element.js","../../../node_modules/imask/esm/controls/html-mask-element.js","../../../node_modules/imask/esm/controls/html-input-mask-element.js","../../../node_modules/imask/esm/controls/html-contenteditable-mask-element.js","../../../node_modules/imask/esm/controls/input-history.js","../../../node_modules/imask/esm/controls/input.js","../../../node_modules/imask/esm/core/change-details.js","../../../node_modules/imask/esm/core/continuous-tail-details.js","../../../node_modules/imask/esm/masked/base.js","../../../node_modules/imask/esm/masked/pattern/chunk-tail-details.js","../../../node_modules/imask/esm/masked/pattern/cursor.js","../../../node_modules/imask/esm/masked/pattern/fixed-definition.js","../../../node_modules/imask/esm/masked/pattern/input-definition.js","../../../node_modules/imask/esm/masked/regexp.js","../../../node_modules/imask/esm/masked/pattern.js","../../../node_modules/imask/esm/masked/range.js","../../../node_modules/imask/esm/masked/date.js","../../../node_modules/imask/esm/masked/dynamic.js","../../../node_modules/imask/esm/masked/enum.js","../../../node_modules/imask/esm/masked/function.js","../../../node_modules/imask/esm/masked/number.js","../../../node_modules/imask/esm/masked/pipe.js","../../../node_modules/imask/esm/masked/repeat.js","../../../node_modules/imask/esm/index.js","../../../app/packs/scripts/controllers/amount_input_controller.js","../../../node_modules/typed.js/dist/typed.module.js","../../../app/packs/scripts/controllers/animate_text_controller.js","../../../app/packs/scripts/controllers/audio_clips_player_controller.js","../../../node_modules/sortablejs/modular/sortable.esm.js","../../../node_modules/@rails/request.js/src/fetch_response.js","../../../node_modules/@rails/request.js/src/request_interceptor.js","../../../node_modules/@rails/request.js/src/lib/utils.js","../../../node_modules/@rails/request.js/src/fetch_request.js","../../../node_modules/@rails/request.js/src/verbs.js","../../../node_modules/stimulus-sortable/dist/stimulus-sortable.es.js","../../../node_modules/rails-ujs/lib/assets/compiled/rails-ujs.js","../../../app/packs/scripts/controllers/audio_controller.js","../../../node_modules/@easepick/datetime/dist/index.esm.js","../../../app/packs/scripts/controllers/booking_form_controller.js","../../../app/packs/scripts/controllers/bulk_checker_controller.js","../../../node_modules/@fancyapps/ui/dist/fancybox.esm.js","../../../app/packs/scripts/controllers/carousel_controller.js","../../../app/packs/scripts/controllers/category_dropdown_controller.js","../../../app/packs/scripts/controllers/category_select_controller.js","../../../app/packs/scripts/controllers/checkbox_controller.js","../../../app/packs/scripts/vendor/auto_complete.min.js","../../../app/packs/scripts/backend/_city_picker.js","../../../app/packs/scripts/controllers/city_picker_controller.js","../../../app/packs/scripts/controllers/clickable_row_controller.js","../../../app/packs/scripts/controllers/counter_controller.js","../../../node_modules/@easepick/bundle/dist/index.esm.js","../../../node_modules/@easepick/base-plugin/dist/index.esm.js","../../../node_modules/@easepick/lock-plugin/dist/index.esm.js","../../../app/packs/scripts/controllers/datepicker_controller.js","../../../app/packs/scripts/controllers/enquiry_state_change_controller.js","../../../app/packs/scripts/controllers/facebook_share_controller.js","../../../app/packs/scripts/controllers/fancybox_controller.js","../../../app/packs/scripts/controllers/filter_controller.js","../../../app/packs/scripts/controllers/gallery_controller.js","../../../app/packs/scripts/controllers/google_maps_controller.js","../../../app/packs/scripts/controllers/lightbox_controller.js","../../../app/packs/scripts/backend/files_upload.js","../../../app/packs/scripts/backend/text_validator.js","../../../app/packs/scripts/controllers/message_controller.js","../../../app/packs/scripts/controllers/movie_controller.js","../../../node_modules/stimulus-rails-nested-form/dist/stimulus-rails-nested-form.es.js","../../../app/packs/scripts/controllers/nested_form_controller.js","../../../app/packs/scripts/controllers/official_member_badge_controller.js","../../../app/packs/scripts/controllers/package_price_controller.js","../../../node_modules/intl-tel-input/build/js/intlTelInput.js","../../../node_modules/intl-tel-input/index.js","../../../node_modules/intl-tel-input/build/js/utils.js","../../../app/packs/scripts/controllers/phone_number_input_controller.js","../../../app/packs/scripts/backend/phone_validator.js","../../../app/packs/scripts/controllers/phone_validator_controller.js","../../../app/packs/scripts/controllers/photo_controller.js","../../../app/packs/scripts/controllers/photos_form_controller.js","../../../app/packs/scripts/controllers/redirect_on_change_controller.js","../../../node_modules/knockout/build/output/knockout-latest.js","../../../node_modules/jquery/dist/jquery.js","../../../app/packs/scripts/models/reply.js","../../../app/packs/scripts/controllers/reply_controller.js","../../../app/packs/scripts/controllers/reviews_form_controller.js","../../../app/packs/scripts/controllers/singular_phone_number_input_controller.js","../../../app/packs/scripts/controllers/sort_items_controller.js","../../../app/packs/scripts/controllers/tabs_controller.js","../../../app/packs/scripts/controllers/toggle_content_controller.js","../../../app/packs/scripts/controllers/toggler_controller.js","../../../app/packs/scripts/controllers/upload_widget_controller.js","../../../app/packs/scripts/controllers/venue_enquiry_controller.js","../../../app/packs/scripts/controllers/visibility_toggle_controller.js","../../../node_modules/stimulus-vite-helpers/dist/index.js"],"sourcesContent":["/*\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","/* global window */\n\nimport { Controller } from '@hotwired/stimulus';\n\n// Targets\n//\n// * input: The input field that will be used for the autocomplete.\n//\n// * postalCode: The value of this element will be set to the postal code of the\n// place selected in the autocomplete dropdown.\nexport default class extends Controller {\n static targets = [\n \"input\",\n \"postalCode\",\n ];\n\n triggerDropdown() {\n this.inputTarget.blur();\n this.inputTarget.focus();\n }\n\n addressGoogleCallback () {\n window.googleMapsIsLoaded = true;\n\n this.setup();\n\n if (this.isInputElementFocused()) {\n setTimeout(this.triggerDropdown.bind(this), 100);\n }\n }\n\n connect () {\n window.addressGoogleCallback = this.addressGoogleCallback.bind(this);\n }\n\n isInputElementFocused () {\n return document.activeElement === this.inputTarget\n }\n\n setup () {\n if (!window.googleMapsIsLoaded) {\n setTimeout(this.loadAutoComplete.bind(this), 100);\n } else {\n if (!this.autocomplete) {\n this.autocomplete = new google.maps.places.Autocomplete(this.inputTarget, this.autocompleteOptions());\n this.autocomplete.addListener(\n \"place_changed\",\n this.handlePlaceChanged.bind(this)\n );\n }\n }\n }\n\n autocompleteOptions () {\n var countryCode = this.element.dataset.countryCode;\n var language = this.element.dataset.language;\n var resultTypes = this.element.dataset.types;\n var types = [];\n\n if (resultTypes != \"\") {\n types = [resultTypes];\n }\n\n var options = {\n componentRestrictions: {\n country: countryCode\n },\n fields: [\n \"address_components\",\n \"geometry\"\n ],\n language: language,\n types: types\n }\n\n return options\n }\n\n // This is called when a user selects a place in the dropdown.\n handlePlaceChanged() {\n const place = this.autocomplete.getPlace();\n if (!place) { return }\n\n const addressComponents = place.address_components;\n\n if (this.hasPostalCodeTarget) {\n const postalCode = addressComponents.find(component => component.types.includes(\"postal_code\"));\n this.postalCodeTarget.value = postalCode ? postalCode.long_name : \"\";\n }\n }\n\n loadAutoComplete () {\n if (!window.googleMapsIsLoaded) {\n const element = this.element;\n const { googlekey, region } = element.dataset;\n\n if (!document.getElementById('google-maps-sdk')) {\n var script = document.createElement('script');\n\n const urlOptions = `key=${googlekey}&libraries=places&callback=window.addressGoogleCallback®ion=${region}`\n\n script.id = 'google-maps-sdk';\n script.setAttribute('async', 'true');\n script.setAttribute('defer', 'true');\n script.src = `//maps.googleapis.com/maps/api/js?${urlOptions}`;\n\n document.body.append(script);\n }\n }\n }\n\n dontSubmit (input) {\n // dont submit the form when pressing enter in the autocomplete field\n google.maps.event.addDomListener(input, \"keydown\", function(e) {\n if (e.keyCode == 13) {\n e.preventDefault();\n }\n });\n }\n}\n","/** Checks if value is string */\nfunction isString(str) {\n return typeof str === 'string' || str instanceof String;\n}\n\n/** Checks if value is object */\nfunction isObject(obj) {\n var _obj$constructor;\n return typeof obj === 'object' && obj != null && (obj == null || (_obj$constructor = obj.constructor) == null ? void 0 : _obj$constructor.name) === 'Object';\n}\nfunction pick(obj, keys) {\n if (Array.isArray(keys)) return pick(obj, (_, k) => keys.includes(k));\n return Object.entries(obj).reduce((acc, _ref) => {\n let [k, v] = _ref;\n if (keys(v, k)) acc[k] = v;\n return acc;\n }, {});\n}\n\n/** Direction */\nconst DIRECTION = {\n NONE: 'NONE',\n LEFT: 'LEFT',\n FORCE_LEFT: 'FORCE_LEFT',\n RIGHT: 'RIGHT',\n FORCE_RIGHT: 'FORCE_RIGHT'\n};\n\n/** Direction */\n\nfunction forceDirection(direction) {\n switch (direction) {\n case DIRECTION.LEFT:\n return DIRECTION.FORCE_LEFT;\n case DIRECTION.RIGHT:\n return DIRECTION.FORCE_RIGHT;\n default:\n return direction;\n }\n}\n\n/** Escapes regular expression control chars */\nfunction escapeRegExp(str) {\n return str.replace(/([.*+?^=!:${}()|[\\]/\\\\])/g, '\\\\$1');\n}\n\n// cloned from https://github.com/epoberezkin/fast-deep-equal with small changes\nfunction objectIncludes(b, a) {\n if (a === b) return true;\n const arrA = Array.isArray(a),\n arrB = Array.isArray(b);\n let i;\n if (arrA && arrB) {\n if (a.length != b.length) return false;\n for (i = 0; i < a.length; i++) if (!objectIncludes(a[i], b[i])) return false;\n return true;\n }\n if (arrA != arrB) return false;\n if (a && b && typeof a === 'object' && typeof b === 'object') {\n const dateA = a instanceof Date,\n dateB = b instanceof Date;\n if (dateA && dateB) return a.getTime() == b.getTime();\n if (dateA != dateB) return false;\n const regexpA = a instanceof RegExp,\n regexpB = b instanceof RegExp;\n if (regexpA && regexpB) return a.toString() == b.toString();\n if (regexpA != regexpB) return false;\n const keys = Object.keys(a);\n // if (keys.length !== Object.keys(b).length) return false;\n\n for (i = 0; i < keys.length; i++) if (!Object.prototype.hasOwnProperty.call(b, keys[i])) return false;\n for (i = 0; i < keys.length; i++) if (!objectIncludes(b[keys[i]], a[keys[i]])) return false;\n return true;\n } else if (a && b && typeof a === 'function' && typeof b === 'function') {\n return a.toString() === b.toString();\n }\n return false;\n}\n\n/** Selection range */\n\nexport { DIRECTION, escapeRegExp, forceDirection, isObject, isString, objectIncludes, pick };\n","import { DIRECTION } from './utils.js';\n\n/** Provides details of changing input */\nclass ActionDetails {\n /** Current input value */\n\n /** Current cursor position */\n\n /** Old input value */\n\n /** Old selection */\n\n constructor(opts) {\n Object.assign(this, opts);\n\n // double check if left part was changed (autofilling, other non-standard input triggers)\n while (this.value.slice(0, this.startChangePos) !== this.oldValue.slice(0, this.startChangePos)) {\n --this.oldSelection.start;\n }\n if (this.insertedCount) {\n // double check right part\n while (this.value.slice(this.cursorPos) !== this.oldValue.slice(this.oldSelection.end)) {\n if (this.value.length - this.cursorPos < this.oldValue.length - this.oldSelection.end) ++this.oldSelection.end;else ++this.cursorPos;\n }\n }\n }\n\n /** Start changing position */\n get startChangePos() {\n return Math.min(this.cursorPos, this.oldSelection.start);\n }\n\n /** Inserted symbols count */\n get insertedCount() {\n return this.cursorPos - this.startChangePos;\n }\n\n /** Inserted symbols */\n get inserted() {\n return this.value.substr(this.startChangePos, this.insertedCount);\n }\n\n /** Removed symbols count */\n get removedCount() {\n // Math.max for opposite operation\n return Math.max(this.oldSelection.end - this.startChangePos ||\n // for Delete\n this.oldValue.length - this.value.length, 0);\n }\n\n /** Removed symbols */\n get removed() {\n return this.oldValue.substr(this.startChangePos, this.removedCount);\n }\n\n /** Unchanged head symbols */\n get head() {\n return this.value.substring(0, this.startChangePos);\n }\n\n /** Unchanged tail symbols */\n get tail() {\n return this.value.substring(this.startChangePos + this.insertedCount);\n }\n\n /** Remove direction */\n get removeDirection() {\n if (!this.removedCount || this.insertedCount) return DIRECTION.NONE;\n\n // align right if delete at right\n return (this.oldSelection.end === this.cursorPos || this.oldSelection.start === this.cursorPos) &&\n // if not range removed (event with backspace)\n this.oldSelection.end === this.oldSelection.start ? DIRECTION.RIGHT : DIRECTION.LEFT;\n }\n}\n\nexport { ActionDetails as default };\n","/** Applies mask on element */\nfunction IMask(el, opts) {\n // currently available only for input-like elements\n return new IMask.InputMask(el, opts);\n}\n\nexport { IMask as default };\n","import { isString, isObject, pick } from '../core/utils.js';\nimport IMask from '../core/holder.js';\n\n// TODO can't use overloads here because of https://github.com/microsoft/TypeScript/issues/50754\n// export function maskedClass(mask: string): typeof MaskedPattern;\n// export function maskedClass(mask: DateConstructor): typeof MaskedDate;\n// export function maskedClass(mask: NumberConstructor): typeof MaskedNumber;\n// export function maskedClass(mask: Array | ArrayConstructor): typeof MaskedDynamic;\n// export function maskedClass(mask: MaskedDate): typeof MaskedDate;\n// export function maskedClass(mask: MaskedNumber): typeof MaskedNumber;\n// export function maskedClass(mask: MaskedEnum): typeof MaskedEnum;\n// export function maskedClass(mask: MaskedRange): typeof MaskedRange;\n// export function maskedClass(mask: MaskedRegExp): typeof MaskedRegExp;\n// export function maskedClass(mask: MaskedFunction): typeof MaskedFunction;\n// export function maskedClass(mask: MaskedPattern): typeof MaskedPattern;\n// export function maskedClass(mask: MaskedDynamic): typeof MaskedDynamic;\n// export function maskedClass(mask: Masked): typeof Masked;\n// export function maskedClass(mask: typeof Masked): typeof Masked;\n// export function maskedClass(mask: typeof MaskedDate): typeof MaskedDate;\n// export function maskedClass(mask: typeof MaskedNumber): typeof MaskedNumber;\n// export function maskedClass(mask: typeof MaskedEnum): typeof MaskedEnum;\n// export function maskedClass(mask: typeof MaskedRange): typeof MaskedRange;\n// export function maskedClass(mask: typeof MaskedRegExp): typeof MaskedRegExp;\n// export function maskedClass(mask: typeof MaskedFunction): typeof MaskedFunction;\n// export function maskedClass(mask: typeof MaskedPattern): typeof MaskedPattern;\n// export function maskedClass(mask: typeof MaskedDynamic): typeof MaskedDynamic;\n// export function maskedClass (mask: Mask): Mask;\n// export function maskedClass(mask: RegExp): typeof MaskedRegExp;\n// export function maskedClass(mask: (value: string, ...args: any[]) => boolean): typeof MaskedFunction;\n\n/** Get Masked class by mask type */\nfunction maskedClass(mask) /* TODO */{\n if (mask == null) throw new Error('mask property should be defined');\n if (mask instanceof RegExp) return IMask.MaskedRegExp;\n if (isString(mask)) return IMask.MaskedPattern;\n if (mask === Date) return IMask.MaskedDate;\n if (mask === Number) return IMask.MaskedNumber;\n if (Array.isArray(mask) || mask === Array) return IMask.MaskedDynamic;\n if (IMask.Masked && mask.prototype instanceof IMask.Masked) return mask;\n if (IMask.Masked && mask instanceof IMask.Masked) return mask.constructor;\n if (mask instanceof Function) return IMask.MaskedFunction;\n console.warn('Mask not found for mask', mask); // eslint-disable-line no-console\n return IMask.Masked;\n}\nfunction normalizeOpts(opts) {\n if (!opts) throw new Error('Options in not defined');\n if (IMask.Masked) {\n if (opts.prototype instanceof IMask.Masked) return {\n mask: opts\n };\n\n /*\n handle cases like:\n 1) opts = Masked\n 2) opts = { mask: Masked, ...instanceOpts }\n */\n const {\n mask = undefined,\n ...instanceOpts\n } = opts instanceof IMask.Masked ? {\n mask: opts\n } : isObject(opts) && opts.mask instanceof IMask.Masked ? opts : {};\n if (mask) {\n const _mask = mask.mask;\n return {\n ...pick(mask, (_, k) => !k.startsWith('_')),\n mask: mask.constructor,\n _mask,\n ...instanceOpts\n };\n }\n }\n if (!isObject(opts)) return {\n mask: opts\n };\n return {\n ...opts\n };\n}\n\n// TODO can't use overloads here because of https://github.com/microsoft/TypeScript/issues/50754\n\n// From masked\n// export default function createMask (opts: Opts): ReturnMasked;\n// // From masked class\n// export default function createMask, ReturnMasked extends Masked=InstanceType> (opts: Opts): ReturnMasked;\n// export default function createMask, ReturnMasked extends MaskedDate=MaskedDate> (opts: Opts): ReturnMasked;\n// export default function createMask, ReturnMasked extends MaskedNumber=MaskedNumber> (opts: Opts): ReturnMasked;\n// export default function createMask, ReturnMasked extends MaskedEnum=MaskedEnum> (opts: Opts): ReturnMasked;\n// export default function createMask, ReturnMasked extends MaskedRange=MaskedRange> (opts: Opts): ReturnMasked;\n// export default function createMask, ReturnMasked extends MaskedRegExp=MaskedRegExp> (opts: Opts): ReturnMasked;\n// export default function createMask, ReturnMasked extends MaskedFunction=MaskedFunction> (opts: Opts): ReturnMasked;\n// export default function createMask, ReturnMasked extends MaskedPattern=MaskedPattern> (opts: Opts): ReturnMasked;\n// export default function createMask, ReturnMasked extends MaskedDynamic=MaskedDynamic> (opts: Opts): ReturnMasked;\n// // From mask opts\n// export default function createMask, ReturnMasked=Opts extends MaskedOptions ? M : never> (opts: Opts): ReturnMasked;\n// export default function createMask> (opts: Opts): ReturnMasked;\n// export default function createMask> (opts: Opts): ReturnMasked;\n// export default function createMask> (opts: Opts): ReturnMasked;\n// export default function createMask> (opts: Opts): ReturnMasked;\n// export default function createMask> (opts: Opts): ReturnMasked;\n// export default function createMask> (opts: Opts): ReturnMasked;\n// export default function createMask, ReturnMasked extends MaskedRegExp=MaskedRegExp> (opts: Opts): ReturnMasked;\n// export default function createMask, ReturnMasked extends MaskedFunction=MaskedFunction> (opts: Opts): ReturnMasked;\n\n/** Creates new {@link Masked} depending on mask type */\nfunction createMask(opts) {\n if (IMask.Masked && opts instanceof IMask.Masked) return opts;\n const nOpts = normalizeOpts(opts);\n const MaskedClass = maskedClass(nOpts.mask);\n if (!MaskedClass) throw new Error(\"Masked class is not found for provided mask \" + nOpts.mask + \", appropriate module needs to be imported manually before creating mask.\");\n if (nOpts.mask === MaskedClass) delete nOpts.mask;\n if (nOpts._mask) {\n nOpts.mask = nOpts._mask;\n delete nOpts._mask;\n }\n return new MaskedClass(nOpts);\n}\nIMask.createMask = createMask;\n\nexport { createMask as default, maskedClass, normalizeOpts };\n","import IMask from '../core/holder.js';\n\n/** Generic element API to use with mask */\nclass MaskElement {\n /** */\n\n /** */\n\n /** */\n\n /** Safely returns selection start */\n get selectionStart() {\n let start;\n try {\n start = this._unsafeSelectionStart;\n } catch {}\n return start != null ? start : this.value.length;\n }\n\n /** Safely returns selection end */\n get selectionEnd() {\n let end;\n try {\n end = this._unsafeSelectionEnd;\n } catch {}\n return end != null ? end : this.value.length;\n }\n\n /** Safely sets element selection */\n select(start, end) {\n if (start == null || end == null || start === this.selectionStart && end === this.selectionEnd) return;\n try {\n this._unsafeSelect(start, end);\n } catch {}\n }\n\n /** */\n get isActive() {\n return false;\n }\n /** */\n\n /** */\n\n /** */\n}\nIMask.MaskElement = MaskElement;\n\nexport { MaskElement as default };\n","import MaskElement from './mask-element.js';\nimport IMask from '../core/holder.js';\n\nconst KEY_Z = 90;\nconst KEY_Y = 89;\n\n/** Bridge between HTMLElement and {@link Masked} */\nclass HTMLMaskElement extends MaskElement {\n /** HTMLElement to use mask on */\n\n constructor(input) {\n super();\n this.input = input;\n this._onKeydown = this._onKeydown.bind(this);\n this._onInput = this._onInput.bind(this);\n this._onBeforeinput = this._onBeforeinput.bind(this);\n this._onCompositionEnd = this._onCompositionEnd.bind(this);\n }\n get rootElement() {\n var _this$input$getRootNo, _this$input$getRootNo2, _this$input;\n return (_this$input$getRootNo = (_this$input$getRootNo2 = (_this$input = this.input).getRootNode) == null ? void 0 : _this$input$getRootNo2.call(_this$input)) != null ? _this$input$getRootNo : document;\n }\n\n /** Is element in focus */\n get isActive() {\n return this.input === this.rootElement.activeElement;\n }\n\n /** Binds HTMLElement events to mask internal events */\n bindEvents(handlers) {\n this.input.addEventListener('keydown', this._onKeydown);\n this.input.addEventListener('input', this._onInput);\n this.input.addEventListener('beforeinput', this._onBeforeinput);\n this.input.addEventListener('compositionend', this._onCompositionEnd);\n this.input.addEventListener('drop', handlers.drop);\n this.input.addEventListener('click', handlers.click);\n this.input.addEventListener('focus', handlers.focus);\n this.input.addEventListener('blur', handlers.commit);\n this._handlers = handlers;\n }\n _onKeydown(e) {\n if (this._handlers.redo && (e.keyCode === KEY_Z && e.shiftKey && (e.metaKey || e.ctrlKey) || e.keyCode === KEY_Y && e.ctrlKey)) {\n e.preventDefault();\n return this._handlers.redo(e);\n }\n if (this._handlers.undo && e.keyCode === KEY_Z && (e.metaKey || e.ctrlKey)) {\n e.preventDefault();\n return this._handlers.undo(e);\n }\n if (!e.isComposing) this._handlers.selectionChange(e);\n }\n _onBeforeinput(e) {\n if (e.inputType === 'historyUndo' && this._handlers.undo) {\n e.preventDefault();\n return this._handlers.undo(e);\n }\n if (e.inputType === 'historyRedo' && this._handlers.redo) {\n e.preventDefault();\n return this._handlers.redo(e);\n }\n }\n _onCompositionEnd(e) {\n this._handlers.input(e);\n }\n _onInput(e) {\n if (!e.isComposing) this._handlers.input(e);\n }\n\n /** Unbinds HTMLElement events to mask internal events */\n unbindEvents() {\n this.input.removeEventListener('keydown', this._onKeydown);\n this.input.removeEventListener('input', this._onInput);\n this.input.removeEventListener('beforeinput', this._onBeforeinput);\n this.input.removeEventListener('compositionend', this._onCompositionEnd);\n this.input.removeEventListener('drop', this._handlers.drop);\n this.input.removeEventListener('click', this._handlers.click);\n this.input.removeEventListener('focus', this._handlers.focus);\n this.input.removeEventListener('blur', this._handlers.commit);\n this._handlers = {};\n }\n}\nIMask.HTMLMaskElement = HTMLMaskElement;\n\nexport { HTMLMaskElement as default };\n","import HTMLMaskElement from './html-mask-element.js';\nimport IMask from '../core/holder.js';\nimport './mask-element.js';\n\n/** Bridge between InputElement and {@link Masked} */\nclass HTMLInputMaskElement extends HTMLMaskElement {\n /** InputElement to use mask on */\n\n constructor(input) {\n super(input);\n this.input = input;\n }\n\n /** Returns InputElement selection start */\n get _unsafeSelectionStart() {\n return this.input.selectionStart != null ? this.input.selectionStart : this.value.length;\n }\n\n /** Returns InputElement selection end */\n get _unsafeSelectionEnd() {\n return this.input.selectionEnd;\n }\n\n /** Sets InputElement selection */\n _unsafeSelect(start, end) {\n this.input.setSelectionRange(start, end);\n }\n get value() {\n return this.input.value;\n }\n set value(value) {\n this.input.value = value;\n }\n}\nIMask.HTMLMaskElement = HTMLMaskElement;\n\nexport { HTMLInputMaskElement as default };\n","import HTMLMaskElement from './html-mask-element.js';\nimport IMask from '../core/holder.js';\nimport './mask-element.js';\n\nclass HTMLContenteditableMaskElement extends HTMLMaskElement {\n /** Returns HTMLElement selection start */\n get _unsafeSelectionStart() {\n const root = this.rootElement;\n const selection = root.getSelection && root.getSelection();\n const anchorOffset = selection && selection.anchorOffset;\n const focusOffset = selection && selection.focusOffset;\n if (focusOffset == null || anchorOffset == null || anchorOffset < focusOffset) {\n return anchorOffset;\n }\n return focusOffset;\n }\n\n /** Returns HTMLElement selection end */\n get _unsafeSelectionEnd() {\n const root = this.rootElement;\n const selection = root.getSelection && root.getSelection();\n const anchorOffset = selection && selection.anchorOffset;\n const focusOffset = selection && selection.focusOffset;\n if (focusOffset == null || anchorOffset == null || anchorOffset > focusOffset) {\n return anchorOffset;\n }\n return focusOffset;\n }\n\n /** Sets HTMLElement selection */\n _unsafeSelect(start, end) {\n if (!this.rootElement.createRange) return;\n const range = this.rootElement.createRange();\n range.setStart(this.input.firstChild || this.input, start);\n range.setEnd(this.input.lastChild || this.input, end);\n const root = this.rootElement;\n const selection = root.getSelection && root.getSelection();\n if (selection) {\n selection.removeAllRanges();\n selection.addRange(range);\n }\n }\n\n /** HTMLElement value */\n get value() {\n return this.input.textContent || '';\n }\n set value(value) {\n this.input.textContent = value;\n }\n}\nIMask.HTMLContenteditableMaskElement = HTMLContenteditableMaskElement;\n\nexport { HTMLContenteditableMaskElement as default };\n","class InputHistory {\n constructor() {\n this.states = [];\n this.currentIndex = 0;\n }\n get currentState() {\n return this.states[this.currentIndex];\n }\n get isEmpty() {\n return this.states.length === 0;\n }\n push(state) {\n // if current index points before the last element then remove the future\n if (this.currentIndex < this.states.length - 1) this.states.length = this.currentIndex + 1;\n this.states.push(state);\n if (this.states.length > InputHistory.MAX_LENGTH) this.states.shift();\n this.currentIndex = this.states.length - 1;\n }\n go(steps) {\n this.currentIndex = Math.min(Math.max(this.currentIndex + steps, 0), this.states.length - 1);\n return this.currentState;\n }\n undo() {\n return this.go(-1);\n }\n redo() {\n return this.go(+1);\n }\n clear() {\n this.states.length = 0;\n this.currentIndex = 0;\n }\n}\nInputHistory.MAX_LENGTH = 100;\n\nexport { InputHistory as default };\n","import { DIRECTION } from '../core/utils.js';\nimport ActionDetails from '../core/action-details.js';\nimport createMask, { maskedClass } from '../masked/factory.js';\nimport MaskElement from './mask-element.js';\nimport HTMLInputMaskElement from './html-input-mask-element.js';\nimport HTMLContenteditableMaskElement from './html-contenteditable-mask-element.js';\nimport IMask from '../core/holder.js';\nimport InputHistory from './input-history.js';\nimport './html-mask-element.js';\n\n/** Listens to element events and controls changes between element and {@link Masked} */\nclass InputMask {\n /**\n View element\n */\n\n /** Internal {@link Masked} model */\n\n constructor(el, opts) {\n this.el = el instanceof MaskElement ? el : el.isContentEditable && el.tagName !== 'INPUT' && el.tagName !== 'TEXTAREA' ? new HTMLContenteditableMaskElement(el) : new HTMLInputMaskElement(el);\n this.masked = createMask(opts);\n this._listeners = {};\n this._value = '';\n this._unmaskedValue = '';\n this._rawInputValue = '';\n this.history = new InputHistory();\n this._saveSelection = this._saveSelection.bind(this);\n this._onInput = this._onInput.bind(this);\n this._onChange = this._onChange.bind(this);\n this._onDrop = this._onDrop.bind(this);\n this._onFocus = this._onFocus.bind(this);\n this._onClick = this._onClick.bind(this);\n this._onUndo = this._onUndo.bind(this);\n this._onRedo = this._onRedo.bind(this);\n this.alignCursor = this.alignCursor.bind(this);\n this.alignCursorFriendly = this.alignCursorFriendly.bind(this);\n this._bindEvents();\n\n // refresh\n this.updateValue();\n this._onChange();\n }\n maskEquals(mask) {\n var _this$masked;\n return mask == null || ((_this$masked = this.masked) == null ? void 0 : _this$masked.maskEquals(mask));\n }\n\n /** Masked */\n get mask() {\n return this.masked.mask;\n }\n set mask(mask) {\n if (this.maskEquals(mask)) return;\n if (!(mask instanceof IMask.Masked) && this.masked.constructor === maskedClass(mask)) {\n // TODO \"any\" no idea\n this.masked.updateOptions({\n mask\n });\n return;\n }\n const masked = mask instanceof IMask.Masked ? mask : createMask({\n mask\n });\n masked.unmaskedValue = this.masked.unmaskedValue;\n this.masked = masked;\n }\n\n /** Raw value */\n get value() {\n return this._value;\n }\n set value(str) {\n if (this.value === str) return;\n this.masked.value = str;\n this.updateControl('auto');\n }\n\n /** Unmasked value */\n get unmaskedValue() {\n return this._unmaskedValue;\n }\n set unmaskedValue(str) {\n if (this.unmaskedValue === str) return;\n this.masked.unmaskedValue = str;\n this.updateControl('auto');\n }\n\n /** Raw input value */\n get rawInputValue() {\n return this._rawInputValue;\n }\n set rawInputValue(str) {\n if (this.rawInputValue === str) return;\n this.masked.rawInputValue = str;\n this.updateControl();\n this.alignCursor();\n }\n\n /** Typed unmasked value */\n get typedValue() {\n return this.masked.typedValue;\n }\n set typedValue(val) {\n if (this.masked.typedValueEquals(val)) return;\n this.masked.typedValue = val;\n this.updateControl('auto');\n }\n\n /** Display value */\n get displayValue() {\n return this.masked.displayValue;\n }\n\n /** Starts listening to element events */\n _bindEvents() {\n this.el.bindEvents({\n selectionChange: this._saveSelection,\n input: this._onInput,\n drop: this._onDrop,\n click: this._onClick,\n focus: this._onFocus,\n commit: this._onChange,\n undo: this._onUndo,\n redo: this._onRedo\n });\n }\n\n /** Stops listening to element events */\n _unbindEvents() {\n if (this.el) this.el.unbindEvents();\n }\n\n /** Fires custom event */\n _fireEvent(ev, e) {\n const listeners = this._listeners[ev];\n if (!listeners) return;\n listeners.forEach(l => l(e));\n }\n\n /** Current selection start */\n get selectionStart() {\n return this._cursorChanging ? this._changingCursorPos : this.el.selectionStart;\n }\n\n /** Current cursor position */\n get cursorPos() {\n return this._cursorChanging ? this._changingCursorPos : this.el.selectionEnd;\n }\n set cursorPos(pos) {\n if (!this.el || !this.el.isActive) return;\n this.el.select(pos, pos);\n this._saveSelection();\n }\n\n /** Stores current selection */\n _saveSelection( /* ev */\n ) {\n if (this.displayValue !== this.el.value) {\n console.warn('Element value was changed outside of mask. Syncronize mask using `mask.updateValue()` to work properly.'); // eslint-disable-line no-console\n }\n this._selection = {\n start: this.selectionStart,\n end: this.cursorPos\n };\n }\n\n /** Syncronizes model value from view */\n updateValue() {\n this.masked.value = this.el.value;\n this._value = this.masked.value;\n this._unmaskedValue = this.masked.unmaskedValue;\n this._rawInputValue = this.masked.rawInputValue;\n }\n\n /** Syncronizes view from model value, fires change events */\n updateControl(cursorPos) {\n const newUnmaskedValue = this.masked.unmaskedValue;\n const newValue = this.masked.value;\n const newRawInputValue = this.masked.rawInputValue;\n const newDisplayValue = this.displayValue;\n const isChanged = this.unmaskedValue !== newUnmaskedValue || this.value !== newValue || this._rawInputValue !== newRawInputValue;\n this._unmaskedValue = newUnmaskedValue;\n this._value = newValue;\n this._rawInputValue = newRawInputValue;\n if (this.el.value !== newDisplayValue) this.el.value = newDisplayValue;\n if (cursorPos === 'auto') this.alignCursor();else if (cursorPos != null) this.cursorPos = cursorPos;\n if (isChanged) this._fireChangeEvents();\n if (!this._historyChanging && (isChanged || this.history.isEmpty)) this.history.push({\n unmaskedValue: newUnmaskedValue,\n selection: {\n start: this.selectionStart,\n end: this.cursorPos\n }\n });\n }\n\n /** Updates options with deep equal check, recreates {@link Masked} model if mask type changes */\n updateOptions(opts) {\n const {\n mask,\n ...restOpts\n } = opts; // TODO types, yes, mask is optional\n\n const updateMask = !this.maskEquals(mask);\n const updateOpts = this.masked.optionsIsChanged(restOpts);\n if (updateMask) this.mask = mask;\n if (updateOpts) this.masked.updateOptions(restOpts); // TODO\n\n if (updateMask || updateOpts) this.updateControl();\n }\n\n /** Updates cursor */\n updateCursor(cursorPos) {\n if (cursorPos == null) return;\n this.cursorPos = cursorPos;\n\n // also queue change cursor for mobile browsers\n this._delayUpdateCursor(cursorPos);\n }\n\n /** Delays cursor update to support mobile browsers */\n _delayUpdateCursor(cursorPos) {\n this._abortUpdateCursor();\n this._changingCursorPos = cursorPos;\n this._cursorChanging = setTimeout(() => {\n if (!this.el) return; // if was destroyed\n this.cursorPos = this._changingCursorPos;\n this._abortUpdateCursor();\n }, 10);\n }\n\n /** Fires custom events */\n _fireChangeEvents() {\n this._fireEvent('accept', this._inputEvent);\n if (this.masked.isComplete) this._fireEvent('complete', this._inputEvent);\n }\n\n /** Aborts delayed cursor update */\n _abortUpdateCursor() {\n if (this._cursorChanging) {\n clearTimeout(this._cursorChanging);\n delete this._cursorChanging;\n }\n }\n\n /** Aligns cursor to nearest available position */\n alignCursor() {\n this.cursorPos = this.masked.nearestInputPos(this.masked.nearestInputPos(this.cursorPos, DIRECTION.LEFT));\n }\n\n /** Aligns cursor only if selection is empty */\n alignCursorFriendly() {\n if (this.selectionStart !== this.cursorPos) return; // skip if range is selected\n this.alignCursor();\n }\n\n /** Adds listener on custom event */\n on(ev, handler) {\n if (!this._listeners[ev]) this._listeners[ev] = [];\n this._listeners[ev].push(handler);\n return this;\n }\n\n /** Removes custom event listener */\n off(ev, handler) {\n if (!this._listeners[ev]) return this;\n if (!handler) {\n delete this._listeners[ev];\n return this;\n }\n const hIndex = this._listeners[ev].indexOf(handler);\n if (hIndex >= 0) this._listeners[ev].splice(hIndex, 1);\n return this;\n }\n\n /** Handles view input event */\n _onInput(e) {\n this._inputEvent = e;\n this._abortUpdateCursor();\n const details = new ActionDetails({\n // new state\n value: this.el.value,\n cursorPos: this.cursorPos,\n // old state\n oldValue: this.displayValue,\n oldSelection: this._selection\n });\n const oldRawValue = this.masked.rawInputValue;\n const offset = this.masked.splice(details.startChangePos, details.removed.length, details.inserted, details.removeDirection, {\n input: true,\n raw: true\n }).offset;\n\n // force align in remove direction only if no input chars were removed\n // otherwise we still need to align with NONE (to get out from fixed symbols for instance)\n const removeDirection = oldRawValue === this.masked.rawInputValue ? details.removeDirection : DIRECTION.NONE;\n let cursorPos = this.masked.nearestInputPos(details.startChangePos + offset, removeDirection);\n if (removeDirection !== DIRECTION.NONE) cursorPos = this.masked.nearestInputPos(cursorPos, DIRECTION.NONE);\n this.updateControl(cursorPos);\n delete this._inputEvent;\n }\n\n /** Handles view change event and commits model value */\n _onChange() {\n if (this.displayValue !== this.el.value) this.updateValue();\n this.masked.doCommit();\n this.updateControl();\n this._saveSelection();\n }\n\n /** Handles view drop event, prevents by default */\n _onDrop(ev) {\n ev.preventDefault();\n ev.stopPropagation();\n }\n\n /** Restore last selection on focus */\n _onFocus(ev) {\n this.alignCursorFriendly();\n }\n\n /** Restore last selection on focus */\n _onClick(ev) {\n this.alignCursorFriendly();\n }\n _onUndo() {\n this._applyHistoryState(this.history.undo());\n }\n _onRedo() {\n this._applyHistoryState(this.history.redo());\n }\n _applyHistoryState(state) {\n if (!state) return;\n this._historyChanging = true;\n this.unmaskedValue = state.unmaskedValue;\n this.el.select(state.selection.start, state.selection.end);\n this._saveSelection();\n this._historyChanging = false;\n }\n\n /** Unbind view events and removes element reference */\n destroy() {\n this._unbindEvents();\n this._listeners.length = 0;\n delete this.el;\n }\n}\nIMask.InputMask = InputMask;\n\nexport { InputMask as default };\n","import IMask from './holder.js';\n\n/** Provides details of changing model value */\nclass ChangeDetails {\n /** Inserted symbols */\n\n /** Additional offset if any changes occurred before tail */\n\n /** Raw inserted is used by dynamic mask */\n\n /** Can skip chars */\n\n static normalize(prep) {\n return Array.isArray(prep) ? prep : [prep, new ChangeDetails()];\n }\n constructor(details) {\n Object.assign(this, {\n inserted: '',\n rawInserted: '',\n tailShift: 0,\n skip: false\n }, details);\n }\n\n /** Aggregate changes */\n aggregate(details) {\n this.inserted += details.inserted;\n this.rawInserted += details.rawInserted;\n this.tailShift += details.tailShift;\n this.skip = this.skip || details.skip;\n return this;\n }\n\n /** Total offset considering all changes */\n get offset() {\n return this.tailShift + this.inserted.length;\n }\n get consumed() {\n return Boolean(this.rawInserted) || this.skip;\n }\n equals(details) {\n return this.inserted === details.inserted && this.tailShift === details.tailShift && this.rawInserted === details.rawInserted && this.skip === details.skip;\n }\n}\nIMask.ChangeDetails = ChangeDetails;\n\nexport { ChangeDetails as default };\n","/** Provides details of continuous extracted tail */\nclass ContinuousTailDetails {\n /** Tail value as string */\n\n /** Tail start position */\n\n /** Start position */\n\n constructor(value, from, stop) {\n if (value === void 0) {\n value = '';\n }\n if (from === void 0) {\n from = 0;\n }\n this.value = value;\n this.from = from;\n this.stop = stop;\n }\n toString() {\n return this.value;\n }\n extend(tail) {\n this.value += String(tail);\n }\n appendTo(masked) {\n return masked.append(this.toString(), {\n tail: true\n }).aggregate(masked._appendPlaceholder());\n }\n get state() {\n return {\n value: this.value,\n from: this.from,\n stop: this.stop\n };\n }\n set state(state) {\n Object.assign(this, state);\n }\n unshift(beforePos) {\n if (!this.value.length || beforePos != null && this.from >= beforePos) return '';\n const shiftChar = this.value[0];\n this.value = this.value.slice(1);\n return shiftChar;\n }\n shift() {\n if (!this.value.length) return '';\n const shiftChar = this.value[this.value.length - 1];\n this.value = this.value.slice(0, -1);\n return shiftChar;\n }\n}\n\nexport { ContinuousTailDetails as default };\n","import ChangeDetails from '../core/change-details.js';\nimport ContinuousTailDetails from '../core/continuous-tail-details.js';\nimport { isString, DIRECTION, objectIncludes, forceDirection } from '../core/utils.js';\nimport IMask from '../core/holder.js';\n\n/** Append flags */\n\n/** Extract flags */\n\n// see https://github.com/microsoft/TypeScript/issues/6223\n\n/** Provides common masking stuff */\nclass Masked {\n /** */\n\n /** */\n\n /** Transforms value before mask processing */\n\n /** Transforms each char before mask processing */\n\n /** Validates if value is acceptable */\n\n /** Does additional processing at the end of editing */\n\n /** Format typed value to string */\n\n /** Parse string to get typed value */\n\n /** Enable characters overwriting */\n\n /** */\n\n /** */\n\n /** */\n\n /** */\n\n constructor(opts) {\n this._value = '';\n this._update({\n ...Masked.DEFAULTS,\n ...opts\n });\n this._initialized = true;\n }\n\n /** Sets and applies new options */\n updateOptions(opts) {\n if (!this.optionsIsChanged(opts)) return;\n this.withValueRefresh(this._update.bind(this, opts));\n }\n\n /** Sets new options */\n _update(opts) {\n Object.assign(this, opts);\n }\n\n /** Mask state */\n get state() {\n return {\n _value: this.value,\n _rawInputValue: this.rawInputValue\n };\n }\n set state(state) {\n this._value = state._value;\n }\n\n /** Resets value */\n reset() {\n this._value = '';\n }\n get value() {\n return this._value;\n }\n set value(value) {\n this.resolve(value, {\n input: true\n });\n }\n\n /** Resolve new value */\n resolve(value, flags) {\n if (flags === void 0) {\n flags = {\n input: true\n };\n }\n this.reset();\n this.append(value, flags, '');\n this.doCommit();\n }\n get unmaskedValue() {\n return this.value;\n }\n set unmaskedValue(value) {\n this.resolve(value, {});\n }\n get typedValue() {\n return this.parse ? this.parse(this.value, this) : this.unmaskedValue;\n }\n set typedValue(value) {\n if (this.format) {\n this.value = this.format(value, this);\n } else {\n this.unmaskedValue = String(value);\n }\n }\n\n /** Value that includes raw user input */\n get rawInputValue() {\n return this.extractInput(0, this.displayValue.length, {\n raw: true\n });\n }\n set rawInputValue(value) {\n this.resolve(value, {\n raw: true\n });\n }\n get displayValue() {\n return this.value;\n }\n get isComplete() {\n return true;\n }\n get isFilled() {\n return this.isComplete;\n }\n\n /** Finds nearest input position in direction */\n nearestInputPos(cursorPos, direction) {\n return cursorPos;\n }\n totalInputPositions(fromPos, toPos) {\n if (fromPos === void 0) {\n fromPos = 0;\n }\n if (toPos === void 0) {\n toPos = this.displayValue.length;\n }\n return Math.min(this.displayValue.length, toPos - fromPos);\n }\n\n /** Extracts value in range considering flags */\n extractInput(fromPos, toPos, flags) {\n if (fromPos === void 0) {\n fromPos = 0;\n }\n if (toPos === void 0) {\n toPos = this.displayValue.length;\n }\n return this.displayValue.slice(fromPos, toPos);\n }\n\n /** Extracts tail in range */\n extractTail(fromPos, toPos) {\n if (fromPos === void 0) {\n fromPos = 0;\n }\n if (toPos === void 0) {\n toPos = this.displayValue.length;\n }\n return new ContinuousTailDetails(this.extractInput(fromPos, toPos), fromPos);\n }\n\n /** Appends tail */\n appendTail(tail) {\n if (isString(tail)) tail = new ContinuousTailDetails(String(tail));\n return tail.appendTo(this);\n }\n\n /** Appends char */\n _appendCharRaw(ch, flags) {\n if (!ch) return new ChangeDetails();\n this._value += ch;\n return new ChangeDetails({\n inserted: ch,\n rawInserted: ch\n });\n }\n\n /** Appends char */\n _appendChar(ch, flags, checkTail) {\n if (flags === void 0) {\n flags = {};\n }\n const consistentState = this.state;\n let details;\n [ch, details] = this.doPrepareChar(ch, flags);\n if (ch) {\n details = details.aggregate(this._appendCharRaw(ch, flags));\n\n // TODO handle `skip`?\n\n // try `autofix` lookahead\n if (!details.rawInserted && this.autofix === 'pad') {\n const noFixState = this.state;\n this.state = consistentState;\n let fixDetails = this.pad(flags);\n const chDetails = this._appendCharRaw(ch, flags);\n fixDetails = fixDetails.aggregate(chDetails);\n\n // if fix was applied or\n // if details are equal use skip restoring state optimization\n if (chDetails.rawInserted || fixDetails.equals(details)) {\n details = fixDetails;\n } else {\n this.state = noFixState;\n }\n }\n }\n if (details.inserted) {\n let consistentTail;\n let appended = this.doValidate(flags) !== false;\n if (appended && checkTail != null) {\n // validation ok, check tail\n const beforeTailState = this.state;\n if (this.overwrite === true) {\n consistentTail = checkTail.state;\n for (let i = 0; i < details.rawInserted.length; ++i) {\n checkTail.unshift(this.displayValue.length - details.tailShift);\n }\n }\n let tailDetails = this.appendTail(checkTail);\n appended = tailDetails.rawInserted.length === checkTail.toString().length;\n\n // not ok, try shift\n if (!(appended && tailDetails.inserted) && this.overwrite === 'shift') {\n this.state = beforeTailState;\n consistentTail = checkTail.state;\n for (let i = 0; i < details.rawInserted.length; ++i) {\n checkTail.shift();\n }\n tailDetails = this.appendTail(checkTail);\n appended = tailDetails.rawInserted.length === checkTail.toString().length;\n }\n\n // if ok, rollback state after tail\n if (appended && tailDetails.inserted) this.state = beforeTailState;\n }\n\n // revert all if something went wrong\n if (!appended) {\n details = new ChangeDetails();\n this.state = consistentState;\n if (checkTail && consistentTail) checkTail.state = consistentTail;\n }\n }\n return details;\n }\n\n /** Appends optional placeholder at the end */\n _appendPlaceholder() {\n return new ChangeDetails();\n }\n\n /** Appends optional eager placeholder at the end */\n _appendEager() {\n return new ChangeDetails();\n }\n\n /** Appends symbols considering flags */\n append(str, flags, tail) {\n if (!isString(str)) throw new Error('value should be string');\n const checkTail = isString(tail) ? new ContinuousTailDetails(String(tail)) : tail;\n if (flags != null && flags.tail) flags._beforeTailState = this.state;\n let details;\n [str, details] = this.doPrepare(str, flags);\n for (let ci = 0; ci < str.length; ++ci) {\n const d = this._appendChar(str[ci], flags, checkTail);\n if (!d.rawInserted && !this.doSkipInvalid(str[ci], flags, checkTail)) break;\n details.aggregate(d);\n }\n if ((this.eager === true || this.eager === 'append') && flags != null && flags.input && str) {\n details.aggregate(this._appendEager());\n }\n\n // append tail but aggregate only tailShift\n if (checkTail != null) {\n details.tailShift += this.appendTail(checkTail).tailShift;\n // TODO it's a good idea to clear state after appending ends\n // but it causes bugs when one append calls another (when dynamic dispatch set rawInputValue)\n // this._resetBeforeTailState();\n }\n return details;\n }\n remove(fromPos, toPos) {\n if (fromPos === void 0) {\n fromPos = 0;\n }\n if (toPos === void 0) {\n toPos = this.displayValue.length;\n }\n this._value = this.displayValue.slice(0, fromPos) + this.displayValue.slice(toPos);\n return new ChangeDetails();\n }\n\n /** Calls function and reapplies current value */\n withValueRefresh(fn) {\n if (this._refreshing || !this._initialized) return fn();\n this._refreshing = true;\n const rawInput = this.rawInputValue;\n const value = this.value;\n const ret = fn();\n this.rawInputValue = rawInput;\n // append lost trailing chars at the end\n if (this.value && this.value !== value && value.indexOf(this.value) === 0) {\n this.append(value.slice(this.displayValue.length), {}, '');\n this.doCommit();\n }\n delete this._refreshing;\n return ret;\n }\n runIsolated(fn) {\n if (this._isolated || !this._initialized) return fn(this);\n this._isolated = true;\n const state = this.state;\n const ret = fn(this);\n this.state = state;\n delete this._isolated;\n return ret;\n }\n doSkipInvalid(ch, flags, checkTail) {\n return Boolean(this.skipInvalid);\n }\n\n /** Prepares string before mask processing */\n doPrepare(str, flags) {\n if (flags === void 0) {\n flags = {};\n }\n return ChangeDetails.normalize(this.prepare ? this.prepare(str, this, flags) : str);\n }\n\n /** Prepares each char before mask processing */\n doPrepareChar(str, flags) {\n if (flags === void 0) {\n flags = {};\n }\n return ChangeDetails.normalize(this.prepareChar ? this.prepareChar(str, this, flags) : str);\n }\n\n /** Validates if value is acceptable */\n doValidate(flags) {\n return (!this.validate || this.validate(this.value, this, flags)) && (!this.parent || this.parent.doValidate(flags));\n }\n\n /** Does additional processing at the end of editing */\n doCommit() {\n if (this.commit) this.commit(this.value, this);\n }\n splice(start, deleteCount, inserted, removeDirection, flags) {\n if (inserted === void 0) {\n inserted = '';\n }\n if (removeDirection === void 0) {\n removeDirection = DIRECTION.NONE;\n }\n if (flags === void 0) {\n flags = {\n input: true\n };\n }\n const tailPos = start + deleteCount;\n const tail = this.extractTail(tailPos);\n const eagerRemove = this.eager === true || this.eager === 'remove';\n let oldRawValue;\n if (eagerRemove) {\n removeDirection = forceDirection(removeDirection);\n oldRawValue = this.extractInput(0, tailPos, {\n raw: true\n });\n }\n let startChangePos = start;\n const details = new ChangeDetails();\n\n // if it is just deletion without insertion\n if (removeDirection !== DIRECTION.NONE) {\n startChangePos = this.nearestInputPos(start, deleteCount > 1 && start !== 0 && !eagerRemove ? DIRECTION.NONE : removeDirection);\n\n // adjust tailShift if start was aligned\n details.tailShift = startChangePos - start;\n }\n details.aggregate(this.remove(startChangePos));\n if (eagerRemove && removeDirection !== DIRECTION.NONE && oldRawValue === this.rawInputValue) {\n if (removeDirection === DIRECTION.FORCE_LEFT) {\n let valLength;\n while (oldRawValue === this.rawInputValue && (valLength = this.displayValue.length)) {\n details.aggregate(new ChangeDetails({\n tailShift: -1\n })).aggregate(this.remove(valLength - 1));\n }\n } else if (removeDirection === DIRECTION.FORCE_RIGHT) {\n tail.unshift();\n }\n }\n return details.aggregate(this.append(inserted, flags, tail));\n }\n maskEquals(mask) {\n return this.mask === mask;\n }\n optionsIsChanged(opts) {\n return !objectIncludes(this, opts);\n }\n typedValueEquals(value) {\n const tval = this.typedValue;\n return value === tval || Masked.EMPTY_VALUES.includes(value) && Masked.EMPTY_VALUES.includes(tval) || (this.format ? this.format(value, this) === this.format(this.typedValue, this) : false);\n }\n pad(flags) {\n return new ChangeDetails();\n }\n}\nMasked.DEFAULTS = {\n skipInvalid: true\n};\nMasked.EMPTY_VALUES = [undefined, null, ''];\nIMask.Masked = Masked;\n\nexport { Masked as default };\n","import ChangeDetails from '../../core/change-details.js';\nimport { isString } from '../../core/utils.js';\nimport ContinuousTailDetails from '../../core/continuous-tail-details.js';\nimport IMask from '../../core/holder.js';\n\nclass ChunksTailDetails {\n /** */\n\n constructor(chunks, from) {\n if (chunks === void 0) {\n chunks = [];\n }\n if (from === void 0) {\n from = 0;\n }\n this.chunks = chunks;\n this.from = from;\n }\n toString() {\n return this.chunks.map(String).join('');\n }\n extend(tailChunk) {\n if (!String(tailChunk)) return;\n tailChunk = isString(tailChunk) ? new ContinuousTailDetails(String(tailChunk)) : tailChunk;\n const lastChunk = this.chunks[this.chunks.length - 1];\n const extendLast = lastChunk && (\n // if stops are same or tail has no stop\n lastChunk.stop === tailChunk.stop || tailChunk.stop == null) &&\n // if tail chunk goes just after last chunk\n tailChunk.from === lastChunk.from + lastChunk.toString().length;\n if (tailChunk instanceof ContinuousTailDetails) {\n // check the ability to extend previous chunk\n if (extendLast) {\n // extend previous chunk\n lastChunk.extend(tailChunk.toString());\n } else {\n // append new chunk\n this.chunks.push(tailChunk);\n }\n } else if (tailChunk instanceof ChunksTailDetails) {\n if (tailChunk.stop == null) {\n // unwrap floating chunks to parent, keeping `from` pos\n let firstTailChunk;\n while (tailChunk.chunks.length && tailChunk.chunks[0].stop == null) {\n firstTailChunk = tailChunk.chunks.shift(); // not possible to be `undefined` because length was checked above\n firstTailChunk.from += tailChunk.from;\n this.extend(firstTailChunk);\n }\n }\n\n // if tail chunk still has value\n if (tailChunk.toString()) {\n // if chunks contains stops, then popup stop to container\n tailChunk.stop = tailChunk.blockIndex;\n this.chunks.push(tailChunk);\n }\n }\n }\n appendTo(masked) {\n if (!(masked instanceof IMask.MaskedPattern)) {\n const tail = new ContinuousTailDetails(this.toString());\n return tail.appendTo(masked);\n }\n const details = new ChangeDetails();\n for (let ci = 0; ci < this.chunks.length; ++ci) {\n const chunk = this.chunks[ci];\n const lastBlockIter = masked._mapPosToBlock(masked.displayValue.length);\n const stop = chunk.stop;\n let chunkBlock;\n if (stop != null && (\n // if block not found or stop is behind lastBlock\n !lastBlockIter || lastBlockIter.index <= stop)) {\n if (chunk instanceof ChunksTailDetails ||\n // for continuous block also check if stop is exist\n masked._stops.indexOf(stop) >= 0) {\n details.aggregate(masked._appendPlaceholder(stop));\n }\n chunkBlock = chunk instanceof ChunksTailDetails && masked._blocks[stop];\n }\n if (chunkBlock) {\n const tailDetails = chunkBlock.appendTail(chunk);\n details.aggregate(tailDetails);\n\n // get not inserted chars\n const remainChars = chunk.toString().slice(tailDetails.rawInserted.length);\n if (remainChars) details.aggregate(masked.append(remainChars, {\n tail: true\n }));\n } else {\n details.aggregate(masked.append(chunk.toString(), {\n tail: true\n }));\n }\n }\n return details;\n }\n get state() {\n return {\n chunks: this.chunks.map(c => c.state),\n from: this.from,\n stop: this.stop,\n blockIndex: this.blockIndex\n };\n }\n set state(state) {\n const {\n chunks,\n ...props\n } = state;\n Object.assign(this, props);\n this.chunks = chunks.map(cstate => {\n const chunk = \"chunks\" in cstate ? new ChunksTailDetails() : new ContinuousTailDetails();\n chunk.state = cstate;\n return chunk;\n });\n }\n unshift(beforePos) {\n if (!this.chunks.length || beforePos != null && this.from >= beforePos) return '';\n const chunkShiftPos = beforePos != null ? beforePos - this.from : beforePos;\n let ci = 0;\n while (ci < this.chunks.length) {\n const chunk = this.chunks[ci];\n const shiftChar = chunk.unshift(chunkShiftPos);\n if (chunk.toString()) {\n // chunk still contains value\n // but not shifted - means no more available chars to shift\n if (!shiftChar) break;\n ++ci;\n } else {\n // clean if chunk has no value\n this.chunks.splice(ci, 1);\n }\n if (shiftChar) return shiftChar;\n }\n return '';\n }\n shift() {\n if (!this.chunks.length) return '';\n let ci = this.chunks.length - 1;\n while (0 <= ci) {\n const chunk = this.chunks[ci];\n const shiftChar = chunk.shift();\n if (chunk.toString()) {\n // chunk still contains value\n // but not shifted - means no more available chars to shift\n if (!shiftChar) break;\n --ci;\n } else {\n // clean if chunk has no value\n this.chunks.splice(ci, 1);\n }\n if (shiftChar) return shiftChar;\n }\n return '';\n }\n}\n\nexport { ChunksTailDetails as default };\n","import { DIRECTION } from '../../core/utils.js';\n\nclass PatternCursor {\n constructor(masked, pos) {\n this.masked = masked;\n this._log = [];\n const {\n offset,\n index\n } = masked._mapPosToBlock(pos) || (pos < 0 ?\n // first\n {\n index: 0,\n offset: 0\n } :\n // last\n {\n index: this.masked._blocks.length,\n offset: 0\n });\n this.offset = offset;\n this.index = index;\n this.ok = false;\n }\n get block() {\n return this.masked._blocks[this.index];\n }\n get pos() {\n return this.masked._blockStartPos(this.index) + this.offset;\n }\n get state() {\n return {\n index: this.index,\n offset: this.offset,\n ok: this.ok\n };\n }\n set state(s) {\n Object.assign(this, s);\n }\n pushState() {\n this._log.push(this.state);\n }\n popState() {\n const s = this._log.pop();\n if (s) this.state = s;\n return s;\n }\n bindBlock() {\n if (this.block) return;\n if (this.index < 0) {\n this.index = 0;\n this.offset = 0;\n }\n if (this.index >= this.masked._blocks.length) {\n this.index = this.masked._blocks.length - 1;\n this.offset = this.block.displayValue.length; // TODO this is stupid type error, `block` depends on index that was changed above\n }\n }\n _pushLeft(fn) {\n this.pushState();\n for (this.bindBlock(); 0 <= this.index; --this.index, this.offset = ((_this$block = this.block) == null ? void 0 : _this$block.displayValue.length) || 0) {\n var _this$block;\n if (fn()) return this.ok = true;\n }\n return this.ok = false;\n }\n _pushRight(fn) {\n this.pushState();\n for (this.bindBlock(); this.index < this.masked._blocks.length; ++this.index, this.offset = 0) {\n if (fn()) return this.ok = true;\n }\n return this.ok = false;\n }\n pushLeftBeforeFilled() {\n return this._pushLeft(() => {\n if (this.block.isFixed || !this.block.value) return;\n this.offset = this.block.nearestInputPos(this.offset, DIRECTION.FORCE_LEFT);\n if (this.offset !== 0) return true;\n });\n }\n pushLeftBeforeInput() {\n // cases:\n // filled input: 00|\n // optional empty input: 00[]|\n // nested block: XX<[]>|\n return this._pushLeft(() => {\n if (this.block.isFixed) return;\n this.offset = this.block.nearestInputPos(this.offset, DIRECTION.LEFT);\n return true;\n });\n }\n pushLeftBeforeRequired() {\n return this._pushLeft(() => {\n if (this.block.isFixed || this.block.isOptional && !this.block.value) return;\n this.offset = this.block.nearestInputPos(this.offset, DIRECTION.LEFT);\n return true;\n });\n }\n pushRightBeforeFilled() {\n return this._pushRight(() => {\n if (this.block.isFixed || !this.block.value) return;\n this.offset = this.block.nearestInputPos(this.offset, DIRECTION.FORCE_RIGHT);\n if (this.offset !== this.block.value.length) return true;\n });\n }\n pushRightBeforeInput() {\n return this._pushRight(() => {\n if (this.block.isFixed) return;\n\n // const o = this.offset;\n this.offset = this.block.nearestInputPos(this.offset, DIRECTION.NONE);\n // HACK cases like (STILL DOES NOT WORK FOR NESTED)\n // aa|X\n // aaX_ - this will not work\n // if (o && o === this.offset && this.block instanceof PatternInputDefinition) continue;\n return true;\n });\n }\n pushRightBeforeRequired() {\n return this._pushRight(() => {\n if (this.block.isFixed || this.block.isOptional && !this.block.value) return;\n\n // TODO check |[*]XX_\n this.offset = this.block.nearestInputPos(this.offset, DIRECTION.NONE);\n return true;\n });\n }\n}\n\nexport { PatternCursor as default };\n","import ChangeDetails from '../../core/change-details.js';\nimport { DIRECTION, isString } from '../../core/utils.js';\nimport ContinuousTailDetails from '../../core/continuous-tail-details.js';\nimport '../../core/holder.js';\n\nclass PatternFixedDefinition {\n /** */\n\n /** */\n\n /** */\n\n /** */\n\n /** */\n\n /** */\n\n constructor(opts) {\n Object.assign(this, opts);\n this._value = '';\n this.isFixed = true;\n }\n get value() {\n return this._value;\n }\n get unmaskedValue() {\n return this.isUnmasking ? this.value : '';\n }\n get rawInputValue() {\n return this._isRawInput ? this.value : '';\n }\n get displayValue() {\n return this.value;\n }\n reset() {\n this._isRawInput = false;\n this._value = '';\n }\n remove(fromPos, toPos) {\n if (fromPos === void 0) {\n fromPos = 0;\n }\n if (toPos === void 0) {\n toPos = this._value.length;\n }\n this._value = this._value.slice(0, fromPos) + this._value.slice(toPos);\n if (!this._value) this._isRawInput = false;\n return new ChangeDetails();\n }\n nearestInputPos(cursorPos, direction) {\n if (direction === void 0) {\n direction = DIRECTION.NONE;\n }\n const minPos = 0;\n const maxPos = this._value.length;\n switch (direction) {\n case DIRECTION.LEFT:\n case DIRECTION.FORCE_LEFT:\n return minPos;\n case DIRECTION.NONE:\n case DIRECTION.RIGHT:\n case DIRECTION.FORCE_RIGHT:\n default:\n return maxPos;\n }\n }\n totalInputPositions(fromPos, toPos) {\n if (fromPos === void 0) {\n fromPos = 0;\n }\n if (toPos === void 0) {\n toPos = this._value.length;\n }\n return this._isRawInput ? toPos - fromPos : 0;\n }\n extractInput(fromPos, toPos, flags) {\n if (fromPos === void 0) {\n fromPos = 0;\n }\n if (toPos === void 0) {\n toPos = this._value.length;\n }\n if (flags === void 0) {\n flags = {};\n }\n return flags.raw && this._isRawInput && this._value.slice(fromPos, toPos) || '';\n }\n get isComplete() {\n return true;\n }\n get isFilled() {\n return Boolean(this._value);\n }\n _appendChar(ch, flags) {\n if (flags === void 0) {\n flags = {};\n }\n if (this.isFilled) return new ChangeDetails();\n const appendEager = this.eager === true || this.eager === 'append';\n const appended = this.char === ch;\n const isResolved = appended && (this.isUnmasking || flags.input || flags.raw) && (!flags.raw || !appendEager) && !flags.tail;\n const details = new ChangeDetails({\n inserted: this.char,\n rawInserted: isResolved ? this.char : ''\n });\n this._value = this.char;\n this._isRawInput = isResolved && (flags.raw || flags.input);\n return details;\n }\n _appendEager() {\n return this._appendChar(this.char, {\n tail: true\n });\n }\n _appendPlaceholder() {\n const details = new ChangeDetails();\n if (this.isFilled) return details;\n this._value = details.inserted = this.char;\n return details;\n }\n extractTail() {\n return new ContinuousTailDetails('');\n }\n appendTail(tail) {\n if (isString(tail)) tail = new ContinuousTailDetails(String(tail));\n return tail.appendTo(this);\n }\n append(str, flags, tail) {\n const details = this._appendChar(str[0], flags);\n if (tail != null) {\n details.tailShift += this.appendTail(tail).tailShift;\n }\n return details;\n }\n doCommit() {}\n get state() {\n return {\n _value: this._value,\n _rawInputValue: this.rawInputValue\n };\n }\n set state(state) {\n this._value = state._value;\n this._isRawInput = Boolean(state._rawInputValue);\n }\n pad(flags) {\n return this._appendPlaceholder();\n }\n}\n\nexport { PatternFixedDefinition as default };\n","import createMask from '../factory.js';\nimport ChangeDetails from '../../core/change-details.js';\nimport { DIRECTION } from '../../core/utils.js';\nimport '../../core/holder.js';\n\nclass PatternInputDefinition {\n /** */\n\n /** */\n\n /** */\n\n /** */\n\n /** */\n\n /** */\n\n /** */\n\n /** */\n\n constructor(opts) {\n const {\n parent,\n isOptional,\n placeholderChar,\n displayChar,\n lazy,\n eager,\n ...maskOpts\n } = opts;\n this.masked = createMask(maskOpts);\n Object.assign(this, {\n parent,\n isOptional,\n placeholderChar,\n displayChar,\n lazy,\n eager\n });\n }\n reset() {\n this.isFilled = false;\n this.masked.reset();\n }\n remove(fromPos, toPos) {\n if (fromPos === void 0) {\n fromPos = 0;\n }\n if (toPos === void 0) {\n toPos = this.value.length;\n }\n if (fromPos === 0 && toPos >= 1) {\n this.isFilled = false;\n return this.masked.remove(fromPos, toPos);\n }\n return new ChangeDetails();\n }\n get value() {\n return this.masked.value || (this.isFilled && !this.isOptional ? this.placeholderChar : '');\n }\n get unmaskedValue() {\n return this.masked.unmaskedValue;\n }\n get rawInputValue() {\n return this.masked.rawInputValue;\n }\n get displayValue() {\n return this.masked.value && this.displayChar || this.value;\n }\n get isComplete() {\n return Boolean(this.masked.value) || this.isOptional;\n }\n _appendChar(ch, flags) {\n if (flags === void 0) {\n flags = {};\n }\n if (this.isFilled) return new ChangeDetails();\n const state = this.masked.state;\n // simulate input\n let details = this.masked._appendChar(ch, this.currentMaskFlags(flags));\n if (details.inserted && this.doValidate(flags) === false) {\n details = new ChangeDetails();\n this.masked.state = state;\n }\n if (!details.inserted && !this.isOptional && !this.lazy && !flags.input) {\n details.inserted = this.placeholderChar;\n }\n details.skip = !details.inserted && !this.isOptional;\n this.isFilled = Boolean(details.inserted);\n return details;\n }\n append(str, flags, tail) {\n // TODO probably should be done via _appendChar\n return this.masked.append(str, this.currentMaskFlags(flags), tail);\n }\n _appendPlaceholder() {\n if (this.isFilled || this.isOptional) return new ChangeDetails();\n this.isFilled = true;\n return new ChangeDetails({\n inserted: this.placeholderChar\n });\n }\n _appendEager() {\n return new ChangeDetails();\n }\n extractTail(fromPos, toPos) {\n return this.masked.extractTail(fromPos, toPos);\n }\n appendTail(tail) {\n return this.masked.appendTail(tail);\n }\n extractInput(fromPos, toPos, flags) {\n if (fromPos === void 0) {\n fromPos = 0;\n }\n if (toPos === void 0) {\n toPos = this.value.length;\n }\n return this.masked.extractInput(fromPos, toPos, flags);\n }\n nearestInputPos(cursorPos, direction) {\n if (direction === void 0) {\n direction = DIRECTION.NONE;\n }\n const minPos = 0;\n const maxPos = this.value.length;\n const boundPos = Math.min(Math.max(cursorPos, minPos), maxPos);\n switch (direction) {\n case DIRECTION.LEFT:\n case DIRECTION.FORCE_LEFT:\n return this.isComplete ? boundPos : minPos;\n case DIRECTION.RIGHT:\n case DIRECTION.FORCE_RIGHT:\n return this.isComplete ? boundPos : maxPos;\n case DIRECTION.NONE:\n default:\n return boundPos;\n }\n }\n totalInputPositions(fromPos, toPos) {\n if (fromPos === void 0) {\n fromPos = 0;\n }\n if (toPos === void 0) {\n toPos = this.value.length;\n }\n return this.value.slice(fromPos, toPos).length;\n }\n doValidate(flags) {\n return this.masked.doValidate(this.currentMaskFlags(flags)) && (!this.parent || this.parent.doValidate(this.currentMaskFlags(flags)));\n }\n doCommit() {\n this.masked.doCommit();\n }\n get state() {\n return {\n _value: this.value,\n _rawInputValue: this.rawInputValue,\n masked: this.masked.state,\n isFilled: this.isFilled\n };\n }\n set state(state) {\n this.masked.state = state.masked;\n this.isFilled = state.isFilled;\n }\n currentMaskFlags(flags) {\n var _flags$_beforeTailSta;\n return {\n ...flags,\n _beforeTailState: (flags == null || (_flags$_beforeTailSta = flags._beforeTailState) == null ? void 0 : _flags$_beforeTailSta.masked) || (flags == null ? void 0 : flags._beforeTailState)\n };\n }\n pad(flags) {\n return new ChangeDetails();\n }\n}\nPatternInputDefinition.DEFAULT_DEFINITIONS = {\n '0': /\\d/,\n 'a': /[\\u0041-\\u005A\\u0061-\\u007A\\u00AA\\u00B5\\u00BA\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02C1\\u02C6-\\u02D1\\u02E0-\\u02E4\\u02EC\\u02EE\\u0370-\\u0374\\u0376\\u0377\\u037A-\\u037D\\u0386\\u0388-\\u038A\\u038C\\u038E-\\u03A1\\u03A3-\\u03F5\\u03F7-\\u0481\\u048A-\\u0527\\u0531-\\u0556\\u0559\\u0561-\\u0587\\u05D0-\\u05EA\\u05F0-\\u05F2\\u0620-\\u064A\\u066E\\u066F\\u0671-\\u06D3\\u06D5\\u06E5\\u06E6\\u06EE\\u06EF\\u06FA-\\u06FC\\u06FF\\u0710\\u0712-\\u072F\\u074D-\\u07A5\\u07B1\\u07CA-\\u07EA\\u07F4\\u07F5\\u07FA\\u0800-\\u0815\\u081A\\u0824\\u0828\\u0840-\\u0858\\u08A0\\u08A2-\\u08AC\\u0904-\\u0939\\u093D\\u0950\\u0958-\\u0961\\u0971-\\u0977\\u0979-\\u097F\\u0985-\\u098C\\u098F\\u0990\\u0993-\\u09A8\\u09AA-\\u09B0\\u09B2\\u09B6-\\u09B9\\u09BD\\u09CE\\u09DC\\u09DD\\u09DF-\\u09E1\\u09F0\\u09F1\\u0A05-\\u0A0A\\u0A0F\\u0A10\\u0A13-\\u0A28\\u0A2A-\\u0A30\\u0A32\\u0A33\\u0A35\\u0A36\\u0A38\\u0A39\\u0A59-\\u0A5C\\u0A5E\\u0A72-\\u0A74\\u0A85-\\u0A8D\\u0A8F-\\u0A91\\u0A93-\\u0AA8\\u0AAA-\\u0AB0\\u0AB2\\u0AB3\\u0AB5-\\u0AB9\\u0ABD\\u0AD0\\u0AE0\\u0AE1\\u0B05-\\u0B0C\\u0B0F\\u0B10\\u0B13-\\u0B28\\u0B2A-\\u0B30\\u0B32\\u0B33\\u0B35-\\u0B39\\u0B3D\\u0B5C\\u0B5D\\u0B5F-\\u0B61\\u0B71\\u0B83\\u0B85-\\u0B8A\\u0B8E-\\u0B90\\u0B92-\\u0B95\\u0B99\\u0B9A\\u0B9C\\u0B9E\\u0B9F\\u0BA3\\u0BA4\\u0BA8-\\u0BAA\\u0BAE-\\u0BB9\\u0BD0\\u0C05-\\u0C0C\\u0C0E-\\u0C10\\u0C12-\\u0C28\\u0C2A-\\u0C33\\u0C35-\\u0C39\\u0C3D\\u0C58\\u0C59\\u0C60\\u0C61\\u0C85-\\u0C8C\\u0C8E-\\u0C90\\u0C92-\\u0CA8\\u0CAA-\\u0CB3\\u0CB5-\\u0CB9\\u0CBD\\u0CDE\\u0CE0\\u0CE1\\u0CF1\\u0CF2\\u0D05-\\u0D0C\\u0D0E-\\u0D10\\u0D12-\\u0D3A\\u0D3D\\u0D4E\\u0D60\\u0D61\\u0D7A-\\u0D7F\\u0D85-\\u0D96\\u0D9A-\\u0DB1\\u0DB3-\\u0DBB\\u0DBD\\u0DC0-\\u0DC6\\u0E01-\\u0E30\\u0E32\\u0E33\\u0E40-\\u0E46\\u0E81\\u0E82\\u0E84\\u0E87\\u0E88\\u0E8A\\u0E8D\\u0E94-\\u0E97\\u0E99-\\u0E9F\\u0EA1-\\u0EA3\\u0EA5\\u0EA7\\u0EAA\\u0EAB\\u0EAD-\\u0EB0\\u0EB2\\u0EB3\\u0EBD\\u0EC0-\\u0EC4\\u0EC6\\u0EDC-\\u0EDF\\u0F00\\u0F40-\\u0F47\\u0F49-\\u0F6C\\u0F88-\\u0F8C\\u1000-\\u102A\\u103F\\u1050-\\u1055\\u105A-\\u105D\\u1061\\u1065\\u1066\\u106E-\\u1070\\u1075-\\u1081\\u108E\\u10A0-\\u10C5\\u10C7\\u10CD\\u10D0-\\u10FA\\u10FC-\\u1248\\u124A-\\u124D\\u1250-\\u1256\\u1258\\u125A-\\u125D\\u1260-\\u1288\\u128A-\\u128D\\u1290-\\u12B0\\u12B2-\\u12B5\\u12B8-\\u12BE\\u12C0\\u12C2-\\u12C5\\u12C8-\\u12D6\\u12D8-\\u1310\\u1312-\\u1315\\u1318-\\u135A\\u1380-\\u138F\\u13A0-\\u13F4\\u1401-\\u166C\\u166F-\\u167F\\u1681-\\u169A\\u16A0-\\u16EA\\u1700-\\u170C\\u170E-\\u1711\\u1720-\\u1731\\u1740-\\u1751\\u1760-\\u176C\\u176E-\\u1770\\u1780-\\u17B3\\u17D7\\u17DC\\u1820-\\u1877\\u1880-\\u18A8\\u18AA\\u18B0-\\u18F5\\u1900-\\u191C\\u1950-\\u196D\\u1970-\\u1974\\u1980-\\u19AB\\u19C1-\\u19C7\\u1A00-\\u1A16\\u1A20-\\u1A54\\u1AA7\\u1B05-\\u1B33\\u1B45-\\u1B4B\\u1B83-\\u1BA0\\u1BAE\\u1BAF\\u1BBA-\\u1BE5\\u1C00-\\u1C23\\u1C4D-\\u1C4F\\u1C5A-\\u1C7D\\u1CE9-\\u1CEC\\u1CEE-\\u1CF1\\u1CF5\\u1CF6\\u1D00-\\u1DBF\\u1E00-\\u1F15\\u1F18-\\u1F1D\\u1F20-\\u1F45\\u1F48-\\u1F4D\\u1F50-\\u1F57\\u1F59\\u1F5B\\u1F5D\\u1F5F-\\u1F7D\\u1F80-\\u1FB4\\u1FB6-\\u1FBC\\u1FBE\\u1FC2-\\u1FC4\\u1FC6-\\u1FCC\\u1FD0-\\u1FD3\\u1FD6-\\u1FDB\\u1FE0-\\u1FEC\\u1FF2-\\u1FF4\\u1FF6-\\u1FFC\\u2071\\u207F\\u2090-\\u209C\\u2102\\u2107\\u210A-\\u2113\\u2115\\u2119-\\u211D\\u2124\\u2126\\u2128\\u212A-\\u212D\\u212F-\\u2139\\u213C-\\u213F\\u2145-\\u2149\\u214E\\u2183\\u2184\\u2C00-\\u2C2E\\u2C30-\\u2C5E\\u2C60-\\u2CE4\\u2CEB-\\u2CEE\\u2CF2\\u2CF3\\u2D00-\\u2D25\\u2D27\\u2D2D\\u2D30-\\u2D67\\u2D6F\\u2D80-\\u2D96\\u2DA0-\\u2DA6\\u2DA8-\\u2DAE\\u2DB0-\\u2DB6\\u2DB8-\\u2DBE\\u2DC0-\\u2DC6\\u2DC8-\\u2DCE\\u2DD0-\\u2DD6\\u2DD8-\\u2DDE\\u2E2F\\u3005\\u3006\\u3031-\\u3035\\u303B\\u303C\\u3041-\\u3096\\u309D-\\u309F\\u30A1-\\u30FA\\u30FC-\\u30FF\\u3105-\\u312D\\u3131-\\u318E\\u31A0-\\u31BA\\u31F0-\\u31FF\\u3400-\\u4DB5\\u4E00-\\u9FCC\\uA000-\\uA48C\\uA4D0-\\uA4FD\\uA500-\\uA60C\\uA610-\\uA61F\\uA62A\\uA62B\\uA640-\\uA66E\\uA67F-\\uA697\\uA6A0-\\uA6E5\\uA717-\\uA71F\\uA722-\\uA788\\uA78B-\\uA78E\\uA790-\\uA793\\uA7A0-\\uA7AA\\uA7F8-\\uA801\\uA803-\\uA805\\uA807-\\uA80A\\uA80C-\\uA822\\uA840-\\uA873\\uA882-\\uA8B3\\uA8F2-\\uA8F7\\uA8FB\\uA90A-\\uA925\\uA930-\\uA946\\uA960-\\uA97C\\uA984-\\uA9B2\\uA9CF\\uAA00-\\uAA28\\uAA40-\\uAA42\\uAA44-\\uAA4B\\uAA60-\\uAA76\\uAA7A\\uAA80-\\uAAAF\\uAAB1\\uAAB5\\uAAB6\\uAAB9-\\uAABD\\uAAC0\\uAAC2\\uAADB-\\uAADD\\uAAE0-\\uAAEA\\uAAF2-\\uAAF4\\uAB01-\\uAB06\\uAB09-\\uAB0E\\uAB11-\\uAB16\\uAB20-\\uAB26\\uAB28-\\uAB2E\\uABC0-\\uABE2\\uAC00-\\uD7A3\\uD7B0-\\uD7C6\\uD7CB-\\uD7FB\\uF900-\\uFA6D\\uFA70-\\uFAD9\\uFB00-\\uFB06\\uFB13-\\uFB17\\uFB1D\\uFB1F-\\uFB28\\uFB2A-\\uFB36\\uFB38-\\uFB3C\\uFB3E\\uFB40\\uFB41\\uFB43\\uFB44\\uFB46-\\uFBB1\\uFBD3-\\uFD3D\\uFD50-\\uFD8F\\uFD92-\\uFDC7\\uFDF0-\\uFDFB\\uFE70-\\uFE74\\uFE76-\\uFEFC\\uFF21-\\uFF3A\\uFF41-\\uFF5A\\uFF66-\\uFFBE\\uFFC2-\\uFFC7\\uFFCA-\\uFFCF\\uFFD2-\\uFFD7\\uFFDA-\\uFFDC]/,\n // http://stackoverflow.com/a/22075070\n '*': /./\n};\n\nexport { PatternInputDefinition as default };\n","import Masked from './base.js';\nimport IMask from '../core/holder.js';\nimport '../core/change-details.js';\nimport '../core/continuous-tail-details.js';\nimport '../core/utils.js';\n\n/** Masking by RegExp */\nclass MaskedRegExp extends Masked {\n /** */\n\n /** Enable characters overwriting */\n\n /** */\n\n /** */\n\n /** */\n\n updateOptions(opts) {\n super.updateOptions(opts);\n }\n _update(opts) {\n const mask = opts.mask;\n if (mask) opts.validate = value => value.search(mask) >= 0;\n super._update(opts);\n }\n}\nIMask.MaskedRegExp = MaskedRegExp;\n\nexport { MaskedRegExp as default };\n","import ChangeDetails from '../core/change-details.js';\nimport IMask from '../core/holder.js';\nimport { DIRECTION } from '../core/utils.js';\nimport Masked from './base.js';\nimport createMask, { normalizeOpts } from './factory.js';\nimport ChunksTailDetails from './pattern/chunk-tail-details.js';\nimport PatternCursor from './pattern/cursor.js';\nimport PatternFixedDefinition from './pattern/fixed-definition.js';\nimport PatternInputDefinition from './pattern/input-definition.js';\nimport './regexp.js';\nimport '../core/continuous-tail-details.js';\n\n/** Pattern mask */\nclass MaskedPattern extends Masked {\n /** */\n\n /** */\n\n /** Single char for empty input */\n\n /** Single char for filled input */\n\n /** Show placeholder only when needed */\n\n /** Enable characters overwriting */\n\n /** */\n\n /** */\n\n /** */\n\n constructor(opts) {\n super({\n ...MaskedPattern.DEFAULTS,\n ...opts,\n definitions: Object.assign({}, PatternInputDefinition.DEFAULT_DEFINITIONS, opts == null ? void 0 : opts.definitions)\n });\n }\n updateOptions(opts) {\n super.updateOptions(opts);\n }\n _update(opts) {\n opts.definitions = Object.assign({}, this.definitions, opts.definitions);\n super._update(opts);\n this._rebuildMask();\n }\n _rebuildMask() {\n const defs = this.definitions;\n this._blocks = [];\n this.exposeBlock = undefined;\n this._stops = [];\n this._maskedBlocks = {};\n const pattern = this.mask;\n if (!pattern || !defs) return;\n let unmaskingBlock = false;\n let optionalBlock = false;\n for (let i = 0; i < pattern.length; ++i) {\n if (this.blocks) {\n const p = pattern.slice(i);\n const bNames = Object.keys(this.blocks).filter(bName => p.indexOf(bName) === 0);\n // order by key length\n bNames.sort((a, b) => b.length - a.length);\n // use block name with max length\n const bName = bNames[0];\n if (bName) {\n const {\n expose,\n repeat,\n ...bOpts\n } = normalizeOpts(this.blocks[bName]); // TODO type Opts\n const blockOpts = {\n lazy: this.lazy,\n eager: this.eager,\n placeholderChar: this.placeholderChar,\n displayChar: this.displayChar,\n overwrite: this.overwrite,\n autofix: this.autofix,\n ...bOpts,\n repeat,\n parent: this\n };\n const maskedBlock = repeat != null ? new IMask.RepeatBlock(blockOpts /* TODO */) : createMask(blockOpts);\n if (maskedBlock) {\n this._blocks.push(maskedBlock);\n if (expose) this.exposeBlock = maskedBlock;\n\n // store block index\n if (!this._maskedBlocks[bName]) this._maskedBlocks[bName] = [];\n this._maskedBlocks[bName].push(this._blocks.length - 1);\n }\n i += bName.length - 1;\n continue;\n }\n }\n let char = pattern[i];\n let isInput = (char in defs);\n if (char === MaskedPattern.STOP_CHAR) {\n this._stops.push(this._blocks.length);\n continue;\n }\n if (char === '{' || char === '}') {\n unmaskingBlock = !unmaskingBlock;\n continue;\n }\n if (char === '[' || char === ']') {\n optionalBlock = !optionalBlock;\n continue;\n }\n if (char === MaskedPattern.ESCAPE_CHAR) {\n ++i;\n char = pattern[i];\n if (!char) break;\n isInput = false;\n }\n const def = isInput ? new PatternInputDefinition({\n isOptional: optionalBlock,\n lazy: this.lazy,\n eager: this.eager,\n placeholderChar: this.placeholderChar,\n displayChar: this.displayChar,\n ...normalizeOpts(defs[char]),\n parent: this\n }) : new PatternFixedDefinition({\n char,\n eager: this.eager,\n isUnmasking: unmaskingBlock\n });\n this._blocks.push(def);\n }\n }\n get state() {\n return {\n ...super.state,\n _blocks: this._blocks.map(b => b.state)\n };\n }\n set state(state) {\n if (!state) {\n this.reset();\n return;\n }\n const {\n _blocks,\n ...maskedState\n } = state;\n this._blocks.forEach((b, bi) => b.state = _blocks[bi]);\n super.state = maskedState;\n }\n reset() {\n super.reset();\n this._blocks.forEach(b => b.reset());\n }\n get isComplete() {\n return this.exposeBlock ? this.exposeBlock.isComplete : this._blocks.every(b => b.isComplete);\n }\n get isFilled() {\n return this._blocks.every(b => b.isFilled);\n }\n get isFixed() {\n return this._blocks.every(b => b.isFixed);\n }\n get isOptional() {\n return this._blocks.every(b => b.isOptional);\n }\n doCommit() {\n this._blocks.forEach(b => b.doCommit());\n super.doCommit();\n }\n get unmaskedValue() {\n return this.exposeBlock ? this.exposeBlock.unmaskedValue : this._blocks.reduce((str, b) => str += b.unmaskedValue, '');\n }\n set unmaskedValue(unmaskedValue) {\n if (this.exposeBlock) {\n const tail = this.extractTail(this._blockStartPos(this._blocks.indexOf(this.exposeBlock)) + this.exposeBlock.displayValue.length);\n this.exposeBlock.unmaskedValue = unmaskedValue;\n this.appendTail(tail);\n this.doCommit();\n } else super.unmaskedValue = unmaskedValue;\n }\n get value() {\n return this.exposeBlock ? this.exposeBlock.value :\n // TODO return _value when not in change?\n this._blocks.reduce((str, b) => str += b.value, '');\n }\n set value(value) {\n if (this.exposeBlock) {\n const tail = this.extractTail(this._blockStartPos(this._blocks.indexOf(this.exposeBlock)) + this.exposeBlock.displayValue.length);\n this.exposeBlock.value = value;\n this.appendTail(tail);\n this.doCommit();\n } else super.value = value;\n }\n get typedValue() {\n return this.exposeBlock ? this.exposeBlock.typedValue : super.typedValue;\n }\n set typedValue(value) {\n if (this.exposeBlock) {\n const tail = this.extractTail(this._blockStartPos(this._blocks.indexOf(this.exposeBlock)) + this.exposeBlock.displayValue.length);\n this.exposeBlock.typedValue = value;\n this.appendTail(tail);\n this.doCommit();\n } else super.typedValue = value;\n }\n get displayValue() {\n return this._blocks.reduce((str, b) => str += b.displayValue, '');\n }\n appendTail(tail) {\n return super.appendTail(tail).aggregate(this._appendPlaceholder());\n }\n _appendEager() {\n var _this$_mapPosToBlock;\n const details = new ChangeDetails();\n let startBlockIndex = (_this$_mapPosToBlock = this._mapPosToBlock(this.displayValue.length)) == null ? void 0 : _this$_mapPosToBlock.index;\n if (startBlockIndex == null) return details;\n\n // TODO test if it works for nested pattern masks\n if (this._blocks[startBlockIndex].isFilled) ++startBlockIndex;\n for (let bi = startBlockIndex; bi < this._blocks.length; ++bi) {\n const d = this._blocks[bi]._appendEager();\n if (!d.inserted) break;\n details.aggregate(d);\n }\n return details;\n }\n _appendCharRaw(ch, flags) {\n if (flags === void 0) {\n flags = {};\n }\n const blockIter = this._mapPosToBlock(this.displayValue.length);\n const details = new ChangeDetails();\n if (!blockIter) return details;\n for (let bi = blockIter.index, block; block = this._blocks[bi]; ++bi) {\n var _flags$_beforeTailSta;\n const blockDetails = block._appendChar(ch, {\n ...flags,\n _beforeTailState: (_flags$_beforeTailSta = flags._beforeTailState) == null || (_flags$_beforeTailSta = _flags$_beforeTailSta._blocks) == null ? void 0 : _flags$_beforeTailSta[bi]\n });\n details.aggregate(blockDetails);\n if (blockDetails.consumed) break; // go next char\n }\n return details;\n }\n extractTail(fromPos, toPos) {\n if (fromPos === void 0) {\n fromPos = 0;\n }\n if (toPos === void 0) {\n toPos = this.displayValue.length;\n }\n const chunkTail = new ChunksTailDetails();\n if (fromPos === toPos) return chunkTail;\n this._forEachBlocksInRange(fromPos, toPos, (b, bi, bFromPos, bToPos) => {\n const blockChunk = b.extractTail(bFromPos, bToPos);\n blockChunk.stop = this._findStopBefore(bi);\n blockChunk.from = this._blockStartPos(bi);\n if (blockChunk instanceof ChunksTailDetails) blockChunk.blockIndex = bi;\n chunkTail.extend(blockChunk);\n });\n return chunkTail;\n }\n extractInput(fromPos, toPos, flags) {\n if (fromPos === void 0) {\n fromPos = 0;\n }\n if (toPos === void 0) {\n toPos = this.displayValue.length;\n }\n if (flags === void 0) {\n flags = {};\n }\n if (fromPos === toPos) return '';\n let input = '';\n this._forEachBlocksInRange(fromPos, toPos, (b, _, fromPos, toPos) => {\n input += b.extractInput(fromPos, toPos, flags);\n });\n return input;\n }\n _findStopBefore(blockIndex) {\n let stopBefore;\n for (let si = 0; si < this._stops.length; ++si) {\n const stop = this._stops[si];\n if (stop <= blockIndex) stopBefore = stop;else break;\n }\n return stopBefore;\n }\n\n /** Appends placeholder depending on laziness */\n _appendPlaceholder(toBlockIndex) {\n const details = new ChangeDetails();\n if (this.lazy && toBlockIndex == null) return details;\n const startBlockIter = this._mapPosToBlock(this.displayValue.length);\n if (!startBlockIter) return details;\n const startBlockIndex = startBlockIter.index;\n const endBlockIndex = toBlockIndex != null ? toBlockIndex : this._blocks.length;\n this._blocks.slice(startBlockIndex, endBlockIndex).forEach(b => {\n if (!b.lazy || toBlockIndex != null) {\n var _blocks2;\n details.aggregate(b._appendPlaceholder((_blocks2 = b._blocks) == null ? void 0 : _blocks2.length));\n }\n });\n return details;\n }\n\n /** Finds block in pos */\n _mapPosToBlock(pos) {\n let accVal = '';\n for (let bi = 0; bi < this._blocks.length; ++bi) {\n const block = this._blocks[bi];\n const blockStartPos = accVal.length;\n accVal += block.displayValue;\n if (pos <= accVal.length) {\n return {\n index: bi,\n offset: pos - blockStartPos\n };\n }\n }\n }\n _blockStartPos(blockIndex) {\n return this._blocks.slice(0, blockIndex).reduce((pos, b) => pos += b.displayValue.length, 0);\n }\n _forEachBlocksInRange(fromPos, toPos, fn) {\n if (toPos === void 0) {\n toPos = this.displayValue.length;\n }\n const fromBlockIter = this._mapPosToBlock(fromPos);\n if (fromBlockIter) {\n const toBlockIter = this._mapPosToBlock(toPos);\n // process first block\n const isSameBlock = toBlockIter && fromBlockIter.index === toBlockIter.index;\n const fromBlockStartPos = fromBlockIter.offset;\n const fromBlockEndPos = toBlockIter && isSameBlock ? toBlockIter.offset : this._blocks[fromBlockIter.index].displayValue.length;\n fn(this._blocks[fromBlockIter.index], fromBlockIter.index, fromBlockStartPos, fromBlockEndPos);\n if (toBlockIter && !isSameBlock) {\n // process intermediate blocks\n for (let bi = fromBlockIter.index + 1; bi < toBlockIter.index; ++bi) {\n fn(this._blocks[bi], bi, 0, this._blocks[bi].displayValue.length);\n }\n\n // process last block\n fn(this._blocks[toBlockIter.index], toBlockIter.index, 0, toBlockIter.offset);\n }\n }\n }\n remove(fromPos, toPos) {\n if (fromPos === void 0) {\n fromPos = 0;\n }\n if (toPos === void 0) {\n toPos = this.displayValue.length;\n }\n const removeDetails = super.remove(fromPos, toPos);\n this._forEachBlocksInRange(fromPos, toPos, (b, _, bFromPos, bToPos) => {\n removeDetails.aggregate(b.remove(bFromPos, bToPos));\n });\n return removeDetails;\n }\n nearestInputPos(cursorPos, direction) {\n if (direction === void 0) {\n direction = DIRECTION.NONE;\n }\n if (!this._blocks.length) return 0;\n const cursor = new PatternCursor(this, cursorPos);\n if (direction === DIRECTION.NONE) {\n // -------------------------------------------------\n // NONE should only go out from fixed to the right!\n // -------------------------------------------------\n if (cursor.pushRightBeforeInput()) return cursor.pos;\n cursor.popState();\n if (cursor.pushLeftBeforeInput()) return cursor.pos;\n return this.displayValue.length;\n }\n\n // FORCE is only about a|* otherwise is 0\n if (direction === DIRECTION.LEFT || direction === DIRECTION.FORCE_LEFT) {\n // try to break fast when *|a\n if (direction === DIRECTION.LEFT) {\n cursor.pushRightBeforeFilled();\n if (cursor.ok && cursor.pos === cursorPos) return cursorPos;\n cursor.popState();\n }\n\n // forward flow\n cursor.pushLeftBeforeInput();\n cursor.pushLeftBeforeRequired();\n cursor.pushLeftBeforeFilled();\n\n // backward flow\n if (direction === DIRECTION.LEFT) {\n cursor.pushRightBeforeInput();\n cursor.pushRightBeforeRequired();\n if (cursor.ok && cursor.pos <= cursorPos) return cursor.pos;\n cursor.popState();\n if (cursor.ok && cursor.pos <= cursorPos) return cursor.pos;\n cursor.popState();\n }\n if (cursor.ok) return cursor.pos;\n if (direction === DIRECTION.FORCE_LEFT) return 0;\n cursor.popState();\n if (cursor.ok) return cursor.pos;\n cursor.popState();\n if (cursor.ok) return cursor.pos;\n return 0;\n }\n if (direction === DIRECTION.RIGHT || direction === DIRECTION.FORCE_RIGHT) {\n // forward flow\n cursor.pushRightBeforeInput();\n cursor.pushRightBeforeRequired();\n if (cursor.pushRightBeforeFilled()) return cursor.pos;\n if (direction === DIRECTION.FORCE_RIGHT) return this.displayValue.length;\n\n // backward flow\n cursor.popState();\n if (cursor.ok) return cursor.pos;\n cursor.popState();\n if (cursor.ok) return cursor.pos;\n return this.nearestInputPos(cursorPos, DIRECTION.LEFT);\n }\n return cursorPos;\n }\n totalInputPositions(fromPos, toPos) {\n if (fromPos === void 0) {\n fromPos = 0;\n }\n if (toPos === void 0) {\n toPos = this.displayValue.length;\n }\n let total = 0;\n this._forEachBlocksInRange(fromPos, toPos, (b, _, bFromPos, bToPos) => {\n total += b.totalInputPositions(bFromPos, bToPos);\n });\n return total;\n }\n\n /** Get block by name */\n maskedBlock(name) {\n return this.maskedBlocks(name)[0];\n }\n\n /** Get all blocks by name */\n maskedBlocks(name) {\n const indices = this._maskedBlocks[name];\n if (!indices) return [];\n return indices.map(gi => this._blocks[gi]);\n }\n pad(flags) {\n const details = new ChangeDetails();\n this._forEachBlocksInRange(0, this.displayValue.length, b => details.aggregate(b.pad(flags)));\n return details;\n }\n}\nMaskedPattern.DEFAULTS = {\n ...Masked.DEFAULTS,\n lazy: true,\n placeholderChar: '_'\n};\nMaskedPattern.STOP_CHAR = '`';\nMaskedPattern.ESCAPE_CHAR = '\\\\';\nMaskedPattern.InputDefinition = PatternInputDefinition;\nMaskedPattern.FixedDefinition = PatternFixedDefinition;\nIMask.MaskedPattern = MaskedPattern;\n\nexport { MaskedPattern as default };\n","import ChangeDetails from '../core/change-details.js';\nimport IMask from '../core/holder.js';\nimport MaskedPattern from './pattern.js';\nimport '../core/utils.js';\nimport './base.js';\nimport '../core/continuous-tail-details.js';\nimport './factory.js';\nimport './pattern/chunk-tail-details.js';\nimport './pattern/cursor.js';\nimport './pattern/fixed-definition.js';\nimport './pattern/input-definition.js';\nimport './regexp.js';\n\n/** Pattern which accepts ranges */\nclass MaskedRange extends MaskedPattern {\n /**\n Optionally sets max length of pattern.\n Used when pattern length is longer then `to` param length. Pads zeros at start in this case.\n */\n\n /** Min bound */\n\n /** Max bound */\n\n get _matchFrom() {\n return this.maxLength - String(this.from).length;\n }\n constructor(opts) {\n super(opts); // mask will be created in _update\n }\n updateOptions(opts) {\n super.updateOptions(opts);\n }\n _update(opts) {\n const {\n to = this.to || 0,\n from = this.from || 0,\n maxLength = this.maxLength || 0,\n autofix = this.autofix,\n ...patternOpts\n } = opts;\n this.to = to;\n this.from = from;\n this.maxLength = Math.max(String(to).length, maxLength);\n this.autofix = autofix;\n const fromStr = String(this.from).padStart(this.maxLength, '0');\n const toStr = String(this.to).padStart(this.maxLength, '0');\n let sameCharsCount = 0;\n while (sameCharsCount < toStr.length && toStr[sameCharsCount] === fromStr[sameCharsCount]) ++sameCharsCount;\n patternOpts.mask = toStr.slice(0, sameCharsCount).replace(/0/g, '\\\\0') + '0'.repeat(this.maxLength - sameCharsCount);\n super._update(patternOpts);\n }\n get isComplete() {\n return super.isComplete && Boolean(this.value);\n }\n boundaries(str) {\n let minstr = '';\n let maxstr = '';\n const [, placeholder, num] = str.match(/^(\\D*)(\\d*)(\\D*)/) || [];\n if (num) {\n minstr = '0'.repeat(placeholder.length) + num;\n maxstr = '9'.repeat(placeholder.length) + num;\n }\n minstr = minstr.padEnd(this.maxLength, '0');\n maxstr = maxstr.padEnd(this.maxLength, '9');\n return [minstr, maxstr];\n }\n doPrepareChar(ch, flags) {\n if (flags === void 0) {\n flags = {};\n }\n let details;\n [ch, details] = super.doPrepareChar(ch.replace(/\\D/g, ''), flags);\n if (!ch) details.skip = !this.isComplete;\n return [ch, details];\n }\n _appendCharRaw(ch, flags) {\n if (flags === void 0) {\n flags = {};\n }\n if (!this.autofix || this.value.length + 1 > this.maxLength) return super._appendCharRaw(ch, flags);\n const fromStr = String(this.from).padStart(this.maxLength, '0');\n const toStr = String(this.to).padStart(this.maxLength, '0');\n const [minstr, maxstr] = this.boundaries(this.value + ch);\n if (Number(maxstr) < this.from) return super._appendCharRaw(fromStr[this.value.length], flags);\n if (Number(minstr) > this.to) {\n if (!flags.tail && this.autofix === 'pad' && this.value.length + 1 < this.maxLength) {\n return super._appendCharRaw(fromStr[this.value.length], flags).aggregate(this._appendCharRaw(ch, flags));\n }\n return super._appendCharRaw(toStr[this.value.length], flags);\n }\n return super._appendCharRaw(ch, flags);\n }\n doValidate(flags) {\n const str = this.value;\n const firstNonZero = str.search(/[^0]/);\n if (firstNonZero === -1 && str.length <= this._matchFrom) return true;\n const [minstr, maxstr] = this.boundaries(str);\n return this.from <= Number(maxstr) && Number(minstr) <= this.to && super.doValidate(flags);\n }\n pad(flags) {\n const details = new ChangeDetails();\n if (this.value.length === this.maxLength) return details;\n const value = this.value;\n const padLength = this.maxLength - this.value.length;\n if (padLength) {\n this.reset();\n for (let i = 0; i < padLength; ++i) {\n details.aggregate(super._appendCharRaw('0', flags));\n }\n\n // append tail\n value.split('').forEach(ch => this._appendCharRaw(ch));\n }\n return details;\n }\n}\nIMask.MaskedRange = MaskedRange;\n\nexport { MaskedRange as default };\n","import MaskedPattern from './pattern.js';\nimport MaskedRange from './range.js';\nimport IMask from '../core/holder.js';\nimport { isString } from '../core/utils.js';\nimport '../core/change-details.js';\nimport './base.js';\nimport '../core/continuous-tail-details.js';\nimport './factory.js';\nimport './pattern/chunk-tail-details.js';\nimport './pattern/cursor.js';\nimport './pattern/fixed-definition.js';\nimport './pattern/input-definition.js';\nimport './regexp.js';\n\nconst DefaultPattern = 'd{.}`m{.}`Y';\n\n// Make format and parse required when pattern is provided\n\n/** Date mask */\nclass MaskedDate extends MaskedPattern {\n static extractPatternOptions(opts) {\n const {\n mask,\n pattern,\n ...patternOpts\n } = opts;\n return {\n ...patternOpts,\n mask: isString(mask) ? mask : pattern\n };\n }\n\n /** Pattern mask for date according to {@link MaskedDate#format} */\n\n /** Start date */\n\n /** End date */\n\n /** Format typed value to string */\n\n /** Parse string to get typed value */\n\n constructor(opts) {\n super(MaskedDate.extractPatternOptions({\n ...MaskedDate.DEFAULTS,\n ...opts\n }));\n }\n updateOptions(opts) {\n super.updateOptions(opts);\n }\n _update(opts) {\n const {\n mask,\n pattern,\n blocks,\n ...patternOpts\n } = {\n ...MaskedDate.DEFAULTS,\n ...opts\n };\n const patternBlocks = Object.assign({}, MaskedDate.GET_DEFAULT_BLOCKS());\n // adjust year block\n if (opts.min) patternBlocks.Y.from = opts.min.getFullYear();\n if (opts.max) patternBlocks.Y.to = opts.max.getFullYear();\n if (opts.min && opts.max && patternBlocks.Y.from === patternBlocks.Y.to) {\n patternBlocks.m.from = opts.min.getMonth() + 1;\n patternBlocks.m.to = opts.max.getMonth() + 1;\n if (patternBlocks.m.from === patternBlocks.m.to) {\n patternBlocks.d.from = opts.min.getDate();\n patternBlocks.d.to = opts.max.getDate();\n }\n }\n Object.assign(patternBlocks, this.blocks, blocks);\n super._update({\n ...patternOpts,\n mask: isString(mask) ? mask : pattern,\n blocks: patternBlocks\n });\n }\n doValidate(flags) {\n const date = this.date;\n return super.doValidate(flags) && (!this.isComplete || this.isDateExist(this.value) && date != null && (this.min == null || this.min <= date) && (this.max == null || date <= this.max));\n }\n\n /** Checks if date is exists */\n isDateExist(str) {\n return this.format(this.parse(str, this), this).indexOf(str) >= 0;\n }\n\n /** Parsed Date */\n get date() {\n return this.typedValue;\n }\n set date(date) {\n this.typedValue = date;\n }\n get typedValue() {\n return this.isComplete ? super.typedValue : null;\n }\n set typedValue(value) {\n super.typedValue = value;\n }\n maskEquals(mask) {\n return mask === Date || super.maskEquals(mask);\n }\n optionsIsChanged(opts) {\n return super.optionsIsChanged(MaskedDate.extractPatternOptions(opts));\n }\n}\nMaskedDate.GET_DEFAULT_BLOCKS = () => ({\n d: {\n mask: MaskedRange,\n from: 1,\n to: 31,\n maxLength: 2\n },\n m: {\n mask: MaskedRange,\n from: 1,\n to: 12,\n maxLength: 2\n },\n Y: {\n mask: MaskedRange,\n from: 1900,\n to: 9999\n }\n});\nMaskedDate.DEFAULTS = {\n ...MaskedPattern.DEFAULTS,\n mask: Date,\n pattern: DefaultPattern,\n format: (date, masked) => {\n if (!date) return '';\n const day = String(date.getDate()).padStart(2, '0');\n const month = String(date.getMonth() + 1).padStart(2, '0');\n const year = date.getFullYear();\n return [day, month, year].join('.');\n },\n parse: (str, masked) => {\n const [day, month, year] = str.split('.').map(Number);\n return new Date(year, month - 1, day);\n }\n};\nIMask.MaskedDate = MaskedDate;\n\nexport { MaskedDate as default };\n","import { DIRECTION, objectIncludes } from '../core/utils.js';\nimport ChangeDetails from '../core/change-details.js';\nimport createMask, { normalizeOpts } from './factory.js';\nimport Masked from './base.js';\nimport IMask from '../core/holder.js';\nimport '../core/continuous-tail-details.js';\n\n/** Dynamic mask for choosing appropriate mask in run-time */\nclass MaskedDynamic extends Masked {\n constructor(opts) {\n super({\n ...MaskedDynamic.DEFAULTS,\n ...opts\n });\n this.currentMask = undefined;\n }\n updateOptions(opts) {\n super.updateOptions(opts);\n }\n _update(opts) {\n super._update(opts);\n if ('mask' in opts) {\n this.exposeMask = undefined;\n // mask could be totally dynamic with only `dispatch` option\n this.compiledMasks = Array.isArray(opts.mask) ? opts.mask.map(m => {\n const {\n expose,\n ...maskOpts\n } = normalizeOpts(m);\n const masked = createMask({\n overwrite: this._overwrite,\n eager: this._eager,\n skipInvalid: this._skipInvalid,\n ...maskOpts\n });\n if (expose) this.exposeMask = masked;\n return masked;\n }) : [];\n\n // this.currentMask = this.doDispatch(''); // probably not needed but lets see\n }\n }\n _appendCharRaw(ch, flags) {\n if (flags === void 0) {\n flags = {};\n }\n const details = this._applyDispatch(ch, flags);\n if (this.currentMask) {\n details.aggregate(this.currentMask._appendChar(ch, this.currentMaskFlags(flags)));\n }\n return details;\n }\n _applyDispatch(appended, flags, tail) {\n if (appended === void 0) {\n appended = '';\n }\n if (flags === void 0) {\n flags = {};\n }\n if (tail === void 0) {\n tail = '';\n }\n const prevValueBeforeTail = flags.tail && flags._beforeTailState != null ? flags._beforeTailState._value : this.value;\n const inputValue = this.rawInputValue;\n const insertValue = flags.tail && flags._beforeTailState != null ? flags._beforeTailState._rawInputValue : inputValue;\n const tailValue = inputValue.slice(insertValue.length);\n const prevMask = this.currentMask;\n const details = new ChangeDetails();\n const prevMaskState = prevMask == null ? void 0 : prevMask.state;\n\n // clone flags to prevent overwriting `_beforeTailState`\n this.currentMask = this.doDispatch(appended, {\n ...flags\n }, tail);\n\n // restore state after dispatch\n if (this.currentMask) {\n if (this.currentMask !== prevMask) {\n // if mask changed reapply input\n this.currentMask.reset();\n if (insertValue) {\n this.currentMask.append(insertValue, {\n raw: true\n });\n details.tailShift = this.currentMask.value.length - prevValueBeforeTail.length;\n }\n if (tailValue) {\n details.tailShift += this.currentMask.append(tailValue, {\n raw: true,\n tail: true\n }).tailShift;\n }\n } else if (prevMaskState) {\n // Dispatch can do something bad with state, so\n // restore prev mask state\n this.currentMask.state = prevMaskState;\n }\n }\n return details;\n }\n _appendPlaceholder() {\n const details = this._applyDispatch();\n if (this.currentMask) {\n details.aggregate(this.currentMask._appendPlaceholder());\n }\n return details;\n }\n _appendEager() {\n const details = this._applyDispatch();\n if (this.currentMask) {\n details.aggregate(this.currentMask._appendEager());\n }\n return details;\n }\n appendTail(tail) {\n const details = new ChangeDetails();\n if (tail) details.aggregate(this._applyDispatch('', {}, tail));\n return details.aggregate(this.currentMask ? this.currentMask.appendTail(tail) : super.appendTail(tail));\n }\n currentMaskFlags(flags) {\n var _flags$_beforeTailSta, _flags$_beforeTailSta2;\n return {\n ...flags,\n _beforeTailState: ((_flags$_beforeTailSta = flags._beforeTailState) == null ? void 0 : _flags$_beforeTailSta.currentMaskRef) === this.currentMask && ((_flags$_beforeTailSta2 = flags._beforeTailState) == null ? void 0 : _flags$_beforeTailSta2.currentMask) || flags._beforeTailState\n };\n }\n doDispatch(appended, flags, tail) {\n if (flags === void 0) {\n flags = {};\n }\n if (tail === void 0) {\n tail = '';\n }\n return this.dispatch(appended, this, flags, tail);\n }\n doValidate(flags) {\n return super.doValidate(flags) && (!this.currentMask || this.currentMask.doValidate(this.currentMaskFlags(flags)));\n }\n doPrepare(str, flags) {\n if (flags === void 0) {\n flags = {};\n }\n let [s, details] = super.doPrepare(str, flags);\n if (this.currentMask) {\n let currentDetails;\n [s, currentDetails] = super.doPrepare(s, this.currentMaskFlags(flags));\n details = details.aggregate(currentDetails);\n }\n return [s, details];\n }\n doPrepareChar(str, flags) {\n if (flags === void 0) {\n flags = {};\n }\n let [s, details] = super.doPrepareChar(str, flags);\n if (this.currentMask) {\n let currentDetails;\n [s, currentDetails] = super.doPrepareChar(s, this.currentMaskFlags(flags));\n details = details.aggregate(currentDetails);\n }\n return [s, details];\n }\n reset() {\n var _this$currentMask;\n (_this$currentMask = this.currentMask) == null || _this$currentMask.reset();\n this.compiledMasks.forEach(m => m.reset());\n }\n get value() {\n return this.exposeMask ? this.exposeMask.value : this.currentMask ? this.currentMask.value : '';\n }\n set value(value) {\n if (this.exposeMask) {\n this.exposeMask.value = value;\n this.currentMask = this.exposeMask;\n this._applyDispatch();\n } else super.value = value;\n }\n get unmaskedValue() {\n return this.exposeMask ? this.exposeMask.unmaskedValue : this.currentMask ? this.currentMask.unmaskedValue : '';\n }\n set unmaskedValue(unmaskedValue) {\n if (this.exposeMask) {\n this.exposeMask.unmaskedValue = unmaskedValue;\n this.currentMask = this.exposeMask;\n this._applyDispatch();\n } else super.unmaskedValue = unmaskedValue;\n }\n get typedValue() {\n return this.exposeMask ? this.exposeMask.typedValue : this.currentMask ? this.currentMask.typedValue : '';\n }\n set typedValue(typedValue) {\n if (this.exposeMask) {\n this.exposeMask.typedValue = typedValue;\n this.currentMask = this.exposeMask;\n this._applyDispatch();\n return;\n }\n let unmaskedValue = String(typedValue);\n\n // double check it\n if (this.currentMask) {\n this.currentMask.typedValue = typedValue;\n unmaskedValue = this.currentMask.unmaskedValue;\n }\n this.unmaskedValue = unmaskedValue;\n }\n get displayValue() {\n return this.currentMask ? this.currentMask.displayValue : '';\n }\n get isComplete() {\n var _this$currentMask2;\n return Boolean((_this$currentMask2 = this.currentMask) == null ? void 0 : _this$currentMask2.isComplete);\n }\n get isFilled() {\n var _this$currentMask3;\n return Boolean((_this$currentMask3 = this.currentMask) == null ? void 0 : _this$currentMask3.isFilled);\n }\n remove(fromPos, toPos) {\n const details = new ChangeDetails();\n if (this.currentMask) {\n details.aggregate(this.currentMask.remove(fromPos, toPos))\n // update with dispatch\n .aggregate(this._applyDispatch());\n }\n return details;\n }\n get state() {\n var _this$currentMask4;\n return {\n ...super.state,\n _rawInputValue: this.rawInputValue,\n compiledMasks: this.compiledMasks.map(m => m.state),\n currentMaskRef: this.currentMask,\n currentMask: (_this$currentMask4 = this.currentMask) == null ? void 0 : _this$currentMask4.state\n };\n }\n set state(state) {\n const {\n compiledMasks,\n currentMaskRef,\n currentMask,\n ...maskedState\n } = state;\n if (compiledMasks) this.compiledMasks.forEach((m, mi) => m.state = compiledMasks[mi]);\n if (currentMaskRef != null) {\n this.currentMask = currentMaskRef;\n this.currentMask.state = currentMask;\n }\n super.state = maskedState;\n }\n extractInput(fromPos, toPos, flags) {\n return this.currentMask ? this.currentMask.extractInput(fromPos, toPos, flags) : '';\n }\n extractTail(fromPos, toPos) {\n return this.currentMask ? this.currentMask.extractTail(fromPos, toPos) : super.extractTail(fromPos, toPos);\n }\n doCommit() {\n if (this.currentMask) this.currentMask.doCommit();\n super.doCommit();\n }\n nearestInputPos(cursorPos, direction) {\n return this.currentMask ? this.currentMask.nearestInputPos(cursorPos, direction) : super.nearestInputPos(cursorPos, direction);\n }\n get overwrite() {\n return this.currentMask ? this.currentMask.overwrite : this._overwrite;\n }\n set overwrite(overwrite) {\n this._overwrite = overwrite;\n }\n get eager() {\n return this.currentMask ? this.currentMask.eager : this._eager;\n }\n set eager(eager) {\n this._eager = eager;\n }\n get skipInvalid() {\n return this.currentMask ? this.currentMask.skipInvalid : this._skipInvalid;\n }\n set skipInvalid(skipInvalid) {\n this._skipInvalid = skipInvalid;\n }\n get autofix() {\n return this.currentMask ? this.currentMask.autofix : this._autofix;\n }\n set autofix(autofix) {\n this._autofix = autofix;\n }\n maskEquals(mask) {\n return Array.isArray(mask) ? this.compiledMasks.every((m, mi) => {\n if (!mask[mi]) return;\n const {\n mask: oldMask,\n ...restOpts\n } = mask[mi];\n return objectIncludes(m, restOpts) && m.maskEquals(oldMask);\n }) : super.maskEquals(mask);\n }\n typedValueEquals(value) {\n var _this$currentMask5;\n return Boolean((_this$currentMask5 = this.currentMask) == null ? void 0 : _this$currentMask5.typedValueEquals(value));\n }\n}\n/** Currently chosen mask */\n/** Currently chosen mask */\n/** Compliled {@link Masked} options */\n/** Chooses {@link Masked} depending on input value */\nMaskedDynamic.DEFAULTS = {\n ...Masked.DEFAULTS,\n dispatch: (appended, masked, flags, tail) => {\n if (!masked.compiledMasks.length) return;\n const inputValue = masked.rawInputValue;\n\n // simulate input\n const inputs = masked.compiledMasks.map((m, index) => {\n const isCurrent = masked.currentMask === m;\n const startInputPos = isCurrent ? m.displayValue.length : m.nearestInputPos(m.displayValue.length, DIRECTION.FORCE_LEFT);\n if (m.rawInputValue !== inputValue) {\n m.reset();\n m.append(inputValue, {\n raw: true\n });\n } else if (!isCurrent) {\n m.remove(startInputPos);\n }\n m.append(appended, masked.currentMaskFlags(flags));\n m.appendTail(tail);\n return {\n index,\n weight: m.rawInputValue.length,\n totalInputPositions: m.totalInputPositions(0, Math.max(startInputPos, m.nearestInputPos(m.displayValue.length, DIRECTION.FORCE_LEFT)))\n };\n });\n\n // pop masks with longer values first\n inputs.sort((i1, i2) => i2.weight - i1.weight || i2.totalInputPositions - i1.totalInputPositions);\n return masked.compiledMasks[inputs[0].index];\n }\n};\nIMask.MaskedDynamic = MaskedDynamic;\n\nexport { MaskedDynamic as default };\n","import MaskedPattern from './pattern.js';\nimport IMask from '../core/holder.js';\nimport ChangeDetails from '../core/change-details.js';\nimport { DIRECTION } from '../core/utils.js';\nimport ContinuousTailDetails from '../core/continuous-tail-details.js';\nimport './base.js';\nimport './factory.js';\nimport './pattern/chunk-tail-details.js';\nimport './pattern/cursor.js';\nimport './pattern/fixed-definition.js';\nimport './pattern/input-definition.js';\nimport './regexp.js';\n\n/** Pattern which validates enum values */\nclass MaskedEnum extends MaskedPattern {\n constructor(opts) {\n super({\n ...MaskedEnum.DEFAULTS,\n ...opts\n }); // mask will be created in _update\n }\n updateOptions(opts) {\n super.updateOptions(opts);\n }\n _update(opts) {\n const {\n enum: enum_,\n ...eopts\n } = opts;\n if (enum_) {\n const lengths = enum_.map(e => e.length);\n const requiredLength = Math.min(...lengths);\n const optionalLength = Math.max(...lengths) - requiredLength;\n eopts.mask = '*'.repeat(requiredLength);\n if (optionalLength) eopts.mask += '[' + '*'.repeat(optionalLength) + ']';\n this.enum = enum_;\n }\n super._update(eopts);\n }\n _appendCharRaw(ch, flags) {\n if (flags === void 0) {\n flags = {};\n }\n const matchFrom = Math.min(this.nearestInputPos(0, DIRECTION.FORCE_RIGHT), this.value.length);\n const matches = this.enum.filter(e => this.matchValue(e, this.unmaskedValue + ch, matchFrom));\n if (matches.length) {\n if (matches.length === 1) {\n this._forEachBlocksInRange(0, this.value.length, (b, bi) => {\n const mch = matches[0][bi];\n if (bi >= this.value.length || mch === b.value) return;\n b.reset();\n b._appendChar(mch, flags);\n });\n }\n const d = super._appendCharRaw(matches[0][this.value.length], flags);\n if (matches.length === 1) {\n matches[0].slice(this.unmaskedValue.length).split('').forEach(mch => d.aggregate(super._appendCharRaw(mch)));\n }\n return d;\n }\n return new ChangeDetails({\n skip: !this.isComplete\n });\n }\n extractTail(fromPos, toPos) {\n if (fromPos === void 0) {\n fromPos = 0;\n }\n if (toPos === void 0) {\n toPos = this.displayValue.length;\n }\n // just drop tail\n return new ContinuousTailDetails('', fromPos);\n }\n remove(fromPos, toPos) {\n if (fromPos === void 0) {\n fromPos = 0;\n }\n if (toPos === void 0) {\n toPos = this.displayValue.length;\n }\n if (fromPos === toPos) return new ChangeDetails();\n const matchFrom = Math.min(super.nearestInputPos(0, DIRECTION.FORCE_RIGHT), this.value.length);\n let pos;\n for (pos = fromPos; pos >= 0; --pos) {\n const matches = this.enum.filter(e => this.matchValue(e, this.value.slice(matchFrom, pos), matchFrom));\n if (matches.length > 1) break;\n }\n const details = super.remove(pos, toPos);\n details.tailShift += pos - fromPos;\n return details;\n }\n get isComplete() {\n return this.enum.indexOf(this.value) >= 0;\n }\n}\n/** Match enum value */\nMaskedEnum.DEFAULTS = {\n ...MaskedPattern.DEFAULTS,\n matchValue: (estr, istr, matchFrom) => estr.indexOf(istr, matchFrom) === matchFrom\n};\nIMask.MaskedEnum = MaskedEnum;\n\nexport { MaskedEnum as default };\n","import Masked from './base.js';\nimport IMask from '../core/holder.js';\nimport '../core/change-details.js';\nimport '../core/continuous-tail-details.js';\nimport '../core/utils.js';\n\n/** Masking by custom Function */\nclass MaskedFunction extends Masked {\n /** */\n\n /** Enable characters overwriting */\n\n /** */\n\n /** */\n\n /** */\n\n updateOptions(opts) {\n super.updateOptions(opts);\n }\n _update(opts) {\n super._update({\n ...opts,\n validate: opts.mask\n });\n }\n}\nIMask.MaskedFunction = MaskedFunction;\n\nexport { MaskedFunction as default };\n","import { escapeRegExp, DIRECTION } from '../core/utils.js';\nimport ChangeDetails from '../core/change-details.js';\nimport Masked from './base.js';\nimport IMask from '../core/holder.js';\nimport '../core/continuous-tail-details.js';\n\nvar _MaskedNumber;\n/** Number mask */\nclass MaskedNumber extends Masked {\n /** Single char */\n\n /** Single char */\n\n /** Array of single chars */\n\n /** */\n\n /** */\n\n /** Digits after point */\n\n /** Flag to remove leading and trailing zeros in the end of editing */\n\n /** Flag to pad trailing zeros after point in the end of editing */\n\n /** Enable characters overwriting */\n\n /** */\n\n /** */\n\n /** */\n\n /** Format typed value to string */\n\n /** Parse string to get typed value */\n\n constructor(opts) {\n super({\n ...MaskedNumber.DEFAULTS,\n ...opts\n });\n }\n updateOptions(opts) {\n super.updateOptions(opts);\n }\n _update(opts) {\n super._update(opts);\n this._updateRegExps();\n }\n _updateRegExps() {\n const start = '^' + (this.allowNegative ? '[+|\\\\-]?' : '');\n const mid = '\\\\d*';\n const end = (this.scale ? \"(\" + escapeRegExp(this.radix) + \"\\\\d{0,\" + this.scale + \"})?\" : '') + '$';\n this._numberRegExp = new RegExp(start + mid + end);\n this._mapToRadixRegExp = new RegExp(\"[\" + this.mapToRadix.map(escapeRegExp).join('') + \"]\", 'g');\n this._thousandsSeparatorRegExp = new RegExp(escapeRegExp(this.thousandsSeparator), 'g');\n }\n _removeThousandsSeparators(value) {\n return value.replace(this._thousandsSeparatorRegExp, '');\n }\n _insertThousandsSeparators(value) {\n // https://stackoverflow.com/questions/2901102/how-to-print-a-number-with-commas-as-thousands-separators-in-javascript\n const parts = value.split(this.radix);\n parts[0] = parts[0].replace(/\\B(?=(\\d{3})+(?!\\d))/g, this.thousandsSeparator);\n return parts.join(this.radix);\n }\n doPrepareChar(ch, flags) {\n if (flags === void 0) {\n flags = {};\n }\n const [prepCh, details] = super.doPrepareChar(this._removeThousandsSeparators(this.scale && this.mapToRadix.length && (\n /*\n radix should be mapped when\n 1) input is done from keyboard = flags.input && flags.raw\n 2) unmasked value is set = !flags.input && !flags.raw\n and should not be mapped when\n 1) value is set = flags.input && !flags.raw\n 2) raw value is set = !flags.input && flags.raw\n */\n flags.input && flags.raw || !flags.input && !flags.raw) ? ch.replace(this._mapToRadixRegExp, this.radix) : ch), flags);\n if (ch && !prepCh) details.skip = true;\n if (prepCh && !this.allowPositive && !this.value && prepCh !== '-') details.aggregate(this._appendChar('-'));\n return [prepCh, details];\n }\n _separatorsCount(to, extendOnSeparators) {\n if (extendOnSeparators === void 0) {\n extendOnSeparators = false;\n }\n let count = 0;\n for (let pos = 0; pos < to; ++pos) {\n if (this._value.indexOf(this.thousandsSeparator, pos) === pos) {\n ++count;\n if (extendOnSeparators) to += this.thousandsSeparator.length;\n }\n }\n return count;\n }\n _separatorsCountFromSlice(slice) {\n if (slice === void 0) {\n slice = this._value;\n }\n return this._separatorsCount(this._removeThousandsSeparators(slice).length, true);\n }\n extractInput(fromPos, toPos, flags) {\n if (fromPos === void 0) {\n fromPos = 0;\n }\n if (toPos === void 0) {\n toPos = this.displayValue.length;\n }\n [fromPos, toPos] = this._adjustRangeWithSeparators(fromPos, toPos);\n return this._removeThousandsSeparators(super.extractInput(fromPos, toPos, flags));\n }\n _appendCharRaw(ch, flags) {\n if (flags === void 0) {\n flags = {};\n }\n const prevBeforeTailValue = flags.tail && flags._beforeTailState ? flags._beforeTailState._value : this._value;\n const prevBeforeTailSeparatorsCount = this._separatorsCountFromSlice(prevBeforeTailValue);\n this._value = this._removeThousandsSeparators(this.value);\n const oldValue = this._value;\n this._value += ch;\n const num = this.number;\n let accepted = !isNaN(num);\n let skip = false;\n if (accepted) {\n let fixedNum;\n if (this.min != null && this.min < 0 && this.number < this.min) fixedNum = this.min;\n if (this.max != null && this.max > 0 && this.number > this.max) fixedNum = this.max;\n if (fixedNum != null) {\n if (this.autofix) {\n this._value = this.format(fixedNum, this).replace(MaskedNumber.UNMASKED_RADIX, this.radix);\n skip || (skip = oldValue === this._value && !flags.tail); // if not changed on tail it's still ok to proceed\n } else {\n accepted = false;\n }\n }\n accepted && (accepted = Boolean(this._value.match(this._numberRegExp)));\n }\n let appendDetails;\n if (!accepted) {\n this._value = oldValue;\n appendDetails = new ChangeDetails();\n } else {\n appendDetails = new ChangeDetails({\n inserted: this._value.slice(oldValue.length),\n rawInserted: skip ? '' : ch,\n skip\n });\n }\n this._value = this._insertThousandsSeparators(this._value);\n const beforeTailValue = flags.tail && flags._beforeTailState ? flags._beforeTailState._value : this._value;\n const beforeTailSeparatorsCount = this._separatorsCountFromSlice(beforeTailValue);\n appendDetails.tailShift += (beforeTailSeparatorsCount - prevBeforeTailSeparatorsCount) * this.thousandsSeparator.length;\n return appendDetails;\n }\n _findSeparatorAround(pos) {\n if (this.thousandsSeparator) {\n const searchFrom = pos - this.thousandsSeparator.length + 1;\n const separatorPos = this.value.indexOf(this.thousandsSeparator, searchFrom);\n if (separatorPos <= pos) return separatorPos;\n }\n return -1;\n }\n _adjustRangeWithSeparators(from, to) {\n const separatorAroundFromPos = this._findSeparatorAround(from);\n if (separatorAroundFromPos >= 0) from = separatorAroundFromPos;\n const separatorAroundToPos = this._findSeparatorAround(to);\n if (separatorAroundToPos >= 0) to = separatorAroundToPos + this.thousandsSeparator.length;\n return [from, to];\n }\n remove(fromPos, toPos) {\n if (fromPos === void 0) {\n fromPos = 0;\n }\n if (toPos === void 0) {\n toPos = this.displayValue.length;\n }\n [fromPos, toPos] = this._adjustRangeWithSeparators(fromPos, toPos);\n const valueBeforePos = this.value.slice(0, fromPos);\n const valueAfterPos = this.value.slice(toPos);\n const prevBeforeTailSeparatorsCount = this._separatorsCount(valueBeforePos.length);\n this._value = this._insertThousandsSeparators(this._removeThousandsSeparators(valueBeforePos + valueAfterPos));\n const beforeTailSeparatorsCount = this._separatorsCountFromSlice(valueBeforePos);\n return new ChangeDetails({\n tailShift: (beforeTailSeparatorsCount - prevBeforeTailSeparatorsCount) * this.thousandsSeparator.length\n });\n }\n nearestInputPos(cursorPos, direction) {\n if (!this.thousandsSeparator) return cursorPos;\n switch (direction) {\n case DIRECTION.NONE:\n case DIRECTION.LEFT:\n case DIRECTION.FORCE_LEFT:\n {\n const separatorAtLeftPos = this._findSeparatorAround(cursorPos - 1);\n if (separatorAtLeftPos >= 0) {\n const separatorAtLeftEndPos = separatorAtLeftPos + this.thousandsSeparator.length;\n if (cursorPos < separatorAtLeftEndPos || this.value.length <= separatorAtLeftEndPos || direction === DIRECTION.FORCE_LEFT) {\n return separatorAtLeftPos;\n }\n }\n break;\n }\n case DIRECTION.RIGHT:\n case DIRECTION.FORCE_RIGHT:\n {\n const separatorAtRightPos = this._findSeparatorAround(cursorPos);\n if (separatorAtRightPos >= 0) {\n return separatorAtRightPos + this.thousandsSeparator.length;\n }\n }\n }\n return cursorPos;\n }\n doCommit() {\n if (this.value) {\n const number = this.number;\n let validnum = number;\n\n // check bounds\n if (this.min != null) validnum = Math.max(validnum, this.min);\n if (this.max != null) validnum = Math.min(validnum, this.max);\n if (validnum !== number) this.unmaskedValue = this.format(validnum, this);\n let formatted = this.value;\n if (this.normalizeZeros) formatted = this._normalizeZeros(formatted);\n if (this.padFractionalZeros && this.scale > 0) formatted = this._padFractionalZeros(formatted);\n this._value = formatted;\n }\n super.doCommit();\n }\n _normalizeZeros(value) {\n const parts = this._removeThousandsSeparators(value).split(this.radix);\n\n // remove leading zeros\n parts[0] = parts[0].replace(/^(\\D*)(0*)(\\d*)/, (match, sign, zeros, num) => sign + num);\n // add leading zero\n if (value.length && !/\\d$/.test(parts[0])) parts[0] = parts[0] + '0';\n if (parts.length > 1) {\n parts[1] = parts[1].replace(/0*$/, ''); // remove trailing zeros\n if (!parts[1].length) parts.length = 1; // remove fractional\n }\n return this._insertThousandsSeparators(parts.join(this.radix));\n }\n _padFractionalZeros(value) {\n if (!value) return value;\n const parts = value.split(this.radix);\n if (parts.length < 2) parts.push('');\n parts[1] = parts[1].padEnd(this.scale, '0');\n return parts.join(this.radix);\n }\n doSkipInvalid(ch, flags, checkTail) {\n if (flags === void 0) {\n flags = {};\n }\n const dropFractional = this.scale === 0 && ch !== this.thousandsSeparator && (ch === this.radix || ch === MaskedNumber.UNMASKED_RADIX || this.mapToRadix.includes(ch));\n return super.doSkipInvalid(ch, flags, checkTail) && !dropFractional;\n }\n get unmaskedValue() {\n return this._removeThousandsSeparators(this._normalizeZeros(this.value)).replace(this.radix, MaskedNumber.UNMASKED_RADIX);\n }\n set unmaskedValue(unmaskedValue) {\n super.unmaskedValue = unmaskedValue;\n }\n get typedValue() {\n return this.parse(this.unmaskedValue, this);\n }\n set typedValue(n) {\n this.rawInputValue = this.format(n, this).replace(MaskedNumber.UNMASKED_RADIX, this.radix);\n }\n\n /** Parsed Number */\n get number() {\n return this.typedValue;\n }\n set number(number) {\n this.typedValue = number;\n }\n get allowNegative() {\n return this.min != null && this.min < 0 || this.max != null && this.max < 0;\n }\n get allowPositive() {\n return this.min != null && this.min > 0 || this.max != null && this.max > 0;\n }\n typedValueEquals(value) {\n // handle 0 -> '' case (typed = 0 even if value = '')\n // for details see https://github.com/uNmAnNeR/imaskjs/issues/134\n return (super.typedValueEquals(value) || MaskedNumber.EMPTY_VALUES.includes(value) && MaskedNumber.EMPTY_VALUES.includes(this.typedValue)) && !(value === 0 && this.value === '');\n }\n}\n_MaskedNumber = MaskedNumber;\nMaskedNumber.UNMASKED_RADIX = '.';\nMaskedNumber.EMPTY_VALUES = [...Masked.EMPTY_VALUES, 0];\nMaskedNumber.DEFAULTS = {\n ...Masked.DEFAULTS,\n mask: Number,\n radix: ',',\n thousandsSeparator: '',\n mapToRadix: [_MaskedNumber.UNMASKED_RADIX],\n min: Number.MIN_SAFE_INTEGER,\n max: Number.MAX_SAFE_INTEGER,\n scale: 2,\n normalizeZeros: true,\n padFractionalZeros: false,\n parse: Number,\n format: n => n.toLocaleString('en-US', {\n useGrouping: false,\n maximumFractionDigits: 20\n })\n};\nIMask.MaskedNumber = MaskedNumber;\n\nexport { MaskedNumber as default };\n","import createMask from './factory.js';\nimport IMask from '../core/holder.js';\nimport '../core/utils.js';\n\n/** Mask pipe source and destination types */\nconst PIPE_TYPE = {\n MASKED: 'value',\n UNMASKED: 'unmaskedValue',\n TYPED: 'typedValue'\n};\n/** Creates new pipe function depending on mask type, source and destination options */\nfunction createPipe(arg, from, to) {\n if (from === void 0) {\n from = PIPE_TYPE.MASKED;\n }\n if (to === void 0) {\n to = PIPE_TYPE.MASKED;\n }\n const masked = createMask(arg);\n return value => masked.runIsolated(m => {\n m[from] = value;\n return m[to];\n });\n}\n\n/** Pipes value through mask depending on mask type, source and destination options */\nfunction pipe(value, mask, from, to) {\n return createPipe(mask, from, to)(value);\n}\nIMask.PIPE_TYPE = PIPE_TYPE;\nIMask.createPipe = createPipe;\nIMask.pipe = pipe;\n\nexport { PIPE_TYPE, createPipe, pipe };\n","import ChangeDetails from '../core/change-details.js';\nimport IMask from '../core/holder.js';\nimport createMask, { normalizeOpts } from './factory.js';\nimport MaskedPattern from './pattern.js';\nimport '../core/utils.js';\nimport './base.js';\nimport '../core/continuous-tail-details.js';\nimport './pattern/chunk-tail-details.js';\nimport './pattern/cursor.js';\nimport './pattern/fixed-definition.js';\nimport './pattern/input-definition.js';\nimport './regexp.js';\n\n/** Pattern mask */\nclass RepeatBlock extends MaskedPattern {\n get repeatFrom() {\n var _ref;\n return (_ref = Array.isArray(this.repeat) ? this.repeat[0] : this.repeat === Infinity ? 0 : this.repeat) != null ? _ref : 0;\n }\n get repeatTo() {\n var _ref2;\n return (_ref2 = Array.isArray(this.repeat) ? this.repeat[1] : this.repeat) != null ? _ref2 : Infinity;\n }\n constructor(opts) {\n super(opts);\n }\n updateOptions(opts) {\n super.updateOptions(opts);\n }\n _update(opts) {\n var _ref3, _ref4, _this$_blocks;\n const {\n repeat,\n ...blockOpts\n } = normalizeOpts(opts); // TODO type\n this._blockOpts = Object.assign({}, this._blockOpts, blockOpts);\n const block = createMask(this._blockOpts);\n this.repeat = (_ref3 = (_ref4 = repeat != null ? repeat : block.repeat) != null ? _ref4 : this.repeat) != null ? _ref3 : Infinity; // TODO type\n\n super._update({\n mask: 'm'.repeat(Math.max(this.repeatTo === Infinity && ((_this$_blocks = this._blocks) == null ? void 0 : _this$_blocks.length) || 0, this.repeatFrom)),\n blocks: {\n m: block\n },\n eager: block.eager,\n overwrite: block.overwrite,\n skipInvalid: block.skipInvalid,\n lazy: block.lazy,\n placeholderChar: block.placeholderChar,\n displayChar: block.displayChar\n });\n }\n _allocateBlock(bi) {\n if (bi < this._blocks.length) return this._blocks[bi];\n if (this.repeatTo === Infinity || this._blocks.length < this.repeatTo) {\n this._blocks.push(createMask(this._blockOpts));\n this.mask += 'm';\n return this._blocks[this._blocks.length - 1];\n }\n }\n _appendCharRaw(ch, flags) {\n if (flags === void 0) {\n flags = {};\n }\n const details = new ChangeDetails();\n for (let bi = (_this$_mapPosToBlock$ = (_this$_mapPosToBlock = this._mapPosToBlock(this.displayValue.length)) == null ? void 0 : _this$_mapPosToBlock.index) != null ? _this$_mapPosToBlock$ : Math.max(this._blocks.length - 1, 0), block, allocated;\n // try to get a block or\n // try to allocate a new block if not allocated already\n block = (_this$_blocks$bi = this._blocks[bi]) != null ? _this$_blocks$bi : allocated = !allocated && this._allocateBlock(bi); ++bi) {\n var _this$_mapPosToBlock$, _this$_mapPosToBlock, _this$_blocks$bi, _flags$_beforeTailSta;\n const blockDetails = block._appendChar(ch, {\n ...flags,\n _beforeTailState: (_flags$_beforeTailSta = flags._beforeTailState) == null || (_flags$_beforeTailSta = _flags$_beforeTailSta._blocks) == null ? void 0 : _flags$_beforeTailSta[bi]\n });\n if (blockDetails.skip && allocated) {\n // remove the last allocated block and break\n this._blocks.pop();\n this.mask = this.mask.slice(1);\n break;\n }\n details.aggregate(blockDetails);\n if (blockDetails.consumed) break; // go next char\n }\n return details;\n }\n _trimEmptyTail(fromPos, toPos) {\n var _this$_mapPosToBlock2, _this$_mapPosToBlock3;\n if (fromPos === void 0) {\n fromPos = 0;\n }\n const firstBlockIndex = Math.max(((_this$_mapPosToBlock2 = this._mapPosToBlock(fromPos)) == null ? void 0 : _this$_mapPosToBlock2.index) || 0, this.repeatFrom, 0);\n let lastBlockIndex;\n if (toPos != null) lastBlockIndex = (_this$_mapPosToBlock3 = this._mapPosToBlock(toPos)) == null ? void 0 : _this$_mapPosToBlock3.index;\n if (lastBlockIndex == null) lastBlockIndex = this._blocks.length - 1;\n let removeCount = 0;\n for (let blockIndex = lastBlockIndex; firstBlockIndex <= blockIndex; --blockIndex, ++removeCount) {\n if (this._blocks[blockIndex].unmaskedValue) break;\n }\n if (removeCount) {\n this._blocks.splice(lastBlockIndex - removeCount + 1, removeCount);\n this.mask = this.mask.slice(removeCount);\n }\n }\n reset() {\n super.reset();\n this._trimEmptyTail();\n }\n remove(fromPos, toPos) {\n if (fromPos === void 0) {\n fromPos = 0;\n }\n if (toPos === void 0) {\n toPos = this.displayValue.length;\n }\n const removeDetails = super.remove(fromPos, toPos);\n this._trimEmptyTail(fromPos, toPos);\n return removeDetails;\n }\n totalInputPositions(fromPos, toPos) {\n if (fromPos === void 0) {\n fromPos = 0;\n }\n if (toPos == null && this.repeatTo === Infinity) return Infinity;\n return super.totalInputPositions(fromPos, toPos);\n }\n get state() {\n return super.state;\n }\n set state(state) {\n this._blocks.length = state._blocks.length;\n this.mask = this.mask.slice(0, this._blocks.length);\n super.state = state;\n }\n}\nIMask.RepeatBlock = RepeatBlock;\n\nexport { RepeatBlock as default };\n","export { default as InputMask } from './controls/input.js';\nimport IMask from './core/holder.js';\nexport { default as HTMLContenteditableMaskElement } from './controls/html-contenteditable-mask-element.js';\nexport { default as HTMLInputMaskElement } from './controls/html-input-mask-element.js';\nexport { default as HTMLMaskElement } from './controls/html-mask-element.js';\nexport { default as MaskElement } from './controls/mask-element.js';\nexport { default as ChangeDetails } from './core/change-details.js';\nexport { DIRECTION, forceDirection } from './core/utils.js';\nexport { default as Masked } from './masked/base.js';\nexport { default as MaskedDate } from './masked/date.js';\nexport { default as MaskedDynamic } from './masked/dynamic.js';\nexport { default as MaskedEnum } from './masked/enum.js';\nexport { default as createMask, normalizeOpts } from './masked/factory.js';\nexport { default as MaskedFunction } from './masked/function.js';\nexport { default as MaskedNumber } from './masked/number.js';\nexport { default as MaskedPattern } from './masked/pattern.js';\nexport { default as ChunksTailDetails } from './masked/pattern/chunk-tail-details.js';\nexport { default as PatternFixedDefinition } from './masked/pattern/fixed-definition.js';\nexport { default as PatternInputDefinition } from './masked/pattern/input-definition.js';\nexport { PIPE_TYPE, createPipe, pipe } from './masked/pipe.js';\nexport { default as MaskedRange } from './masked/range.js';\nexport { default as MaskedRegExp } from './masked/regexp.js';\nexport { default as RepeatBlock } from './masked/repeat.js';\nimport './core/action-details.js';\nimport './controls/input-history.js';\nimport './core/continuous-tail-details.js';\nimport './masked/pattern/cursor.js';\n\ntry {\n globalThis.IMask = IMask;\n} catch {}\n\nexport { IMask as default };\n","import { Controller } from '@hotwired/stimulus';\nimport IMask from \"imask\"\n\n// Turns an input field into a masked input field that accepts amounts, ie\n// monetary values.\nexport default class extends Controller {\n static values = {\n // Character that delimits the decimal places in the input field.\n decimalSeparator: String,\n\n // Character that delimits the thousands in the input field.\n thousandsSeparator: String,\n\n // The number of decimal places to allow in the input field.\n precision: Number,\n }\n\n buildMask(element, options) {\n return IMask(\n element,\n options\n )\n }\n\n configureMaskedInput (element, submittableInput) {\n // Ensure the presentation of the input is not submitted\n element.name = \"\"\n\n // IMask for some reason doesn't support number fields. Force the input to\n // be a text field so IMask works correctly.\n element.type = \"text\"\n\n // Add the submittable, hidden, input after the original input in the DOM\n element.after(submittableInput)\n\n this.mask = this.buildMask(element, this.maskOptions())\n // Initialize the mask on the show input\n // Ensure the mask is initialized with the correct value\n this.mask.unmaskedValue = submittableInput.value\n\n return element\n }\n\n connect() {\n const submittableInput = this.createSubmittableInput(this.element)\n const maskedInput = this.configureMaskedInput(this.element, submittableInput)\n\n this.updateSubmittableInputValueOnMaskAccept(submittableInput)\n }\n\n createSubmittableInput (element) {\n const submittableInput = document.createElement(\"input\")\n submittableInput.type = \"hidden\"\n submittableInput.name = element.name\n submittableInput.value = element.value\n\n return submittableInput\n }\n\n disconnect () {\n this.mask.destroy()\n }\n\n // Returns the options to pass to IMask.\n maskOptions () {\n return {\n mask: Number,\n mapToRadix: ['.'], // symbols to process as radix\n radix: this.decimalSeparatorValue,\n scale: this.precisionValue,\n thousandsSeparator: this.thousandsSeparatorValue,\n }\n }\n\n // Ensure that we assign the correct value to the hidden field\n // when the user inputs any (number) value\n updateSubmittableInputValueOnMaskAccept (submittableInput) {\n this.mask.on('accept', function() {\n // Assign the correct value to the hidden field\n submittableInput.value = this.mask.unmaskedValue\n }.bind(this));\n }\n}\n","function t(){return t=Object.assign?Object.assign.bind():function(t){for(var s=1;s0&&(e.strPos=e.currentElContent.length-1,e.strings.unshift(e.currentElContent)),e.sequence=[],e.strings)e.sequence[u]=u;e.arrayPos=0,e.stopNum=0,e.loop=e.options.loop,e.loopCount=e.options.loopCount,e.curLoop=0,e.shuffle=e.options.shuffle,e.pause={status:!1,typewrite:!0,curString:\"\",curStrPos:0},e.typingComplete=!1,e.autoInsertCss=e.options.autoInsertCss,e.autoInsertCss&&(this.appendCursorAnimationCss(e),this.appendFadeOutAnimationCss(e))},n.getCurrentElContent=function(t){return t.attr?t.el.getAttribute(t.attr):t.isInput?t.el.value:\"html\"===t.contentType?t.el.innerHTML:t.el.textContent},n.appendCursorAnimationCss=function(t){var s=\"data-typed-js-cursor-css\";if(t.showCursor&&!document.querySelector(\"[\"+s+\"]\")){var e=document.createElement(\"style\");e.setAttribute(s,\"true\"),e.innerHTML=\"\\n .typed-cursor{\\n opacity: 1;\\n }\\n .typed-cursor.typed-cursor--blink{\\n animation: typedjsBlink 0.7s infinite;\\n -webkit-animation: typedjsBlink 0.7s infinite;\\n animation: typedjsBlink 0.7s infinite;\\n }\\n @keyframes typedjsBlink{\\n 50% { opacity: 0.0; }\\n }\\n @-webkit-keyframes typedjsBlink{\\n 0% { opacity: 1; }\\n 50% { opacity: 0.0; }\\n 100% { opacity: 1; }\\n }\\n \",document.body.appendChild(e)}},n.appendFadeOutAnimationCss=function(t){var s=\"data-typed-fadeout-js-css\";if(t.fadeOut&&!document.querySelector(\"[\"+s+\"]\")){var e=document.createElement(\"style\");e.setAttribute(s,\"true\"),e.innerHTML=\"\\n .typed-fade-out{\\n opacity: 0;\\n transition: opacity .25s;\\n }\\n .typed-cursor.typed-cursor--blink.typed-fade-out{\\n -webkit-animation: 0;\\n animation: 0;\\n }\\n \",document.body.appendChild(e)}},e}()),n=new(/*#__PURE__*/function(){function t(){}var s=t.prototype;return s.typeHtmlChars=function(t,s,e){if(\"html\"!==e.contentType)return s;var n=t.substring(s).charAt(0);if(\"<\"===n||\"&\"===n){var i;for(i=\"<\"===n?\">\":\";\";t.substring(s+1).charAt(0)!==i&&!(1+ ++s>t.length););s++}return s},s.backSpaceHtmlChars=function(t,s,e){if(\"html\"!==e.contentType)return s;var n=t.substring(s).charAt(0);if(\">\"===n||\";\"===n){var i;for(i=\">\"===n?\"<\":\"&\";t.substring(s-1).charAt(0)!==i&&!(--s<0););s--}return s},t}()),i=/*#__PURE__*/function(){function t(t,s){e.load(this,s,t),this.begin()}var s=t.prototype;return s.toggle=function(){this.pause.status?this.start():this.stop()},s.stop=function(){this.typingComplete||this.pause.status||(this.toggleBlinking(!0),this.pause.status=!0,this.options.onStop(this.arrayPos,this))},s.start=function(){this.typingComplete||this.pause.status&&(this.pause.status=!1,this.pause.typewrite?this.typewrite(this.pause.curString,this.pause.curStrPos):this.backspace(this.pause.curString,this.pause.curStrPos),this.options.onStart(this.arrayPos,this))},s.destroy=function(){this.reset(!1),this.options.onDestroy(this)},s.reset=function(t){void 0===t&&(t=!0),clearInterval(this.timeout),this.replaceText(\"\"),this.cursor&&this.cursor.parentNode&&(this.cursor.parentNode.removeChild(this.cursor),this.cursor=null),this.strPos=0,this.arrayPos=0,this.curLoop=0,t&&(this.insertCursor(),this.options.onReset(this),this.begin())},s.begin=function(){var t=this;this.options.onBegin(this),this.typingComplete=!1,this.shuffleStringsIfNeeded(this),this.insertCursor(),this.bindInputFocusEvents&&this.bindFocusEvents(),this.timeout=setTimeout(function(){0===t.strPos?t.typewrite(t.strings[t.sequence[t.arrayPos]],t.strPos):t.backspace(t.strings[t.sequence[t.arrayPos]],t.strPos)},this.startDelay)},s.typewrite=function(t,s){var e=this;this.fadeOut&&this.el.classList.contains(this.fadeOutClass)&&(this.el.classList.remove(this.fadeOutClass),this.cursor&&this.cursor.classList.remove(this.fadeOutClass));var i=this.humanizer(this.typeSpeed),r=1;!0!==this.pause.status?this.timeout=setTimeout(function(){s=n.typeHtmlChars(t,s,e);var i=0,o=t.substring(s);if(\"^\"===o.charAt(0)&&/^\\^\\d+/.test(o)){var a=1;a+=(o=/\\d+/.exec(o)[0]).length,i=parseInt(o),e.temporaryPause=!0,e.options.onTypingPaused(e.arrayPos,e),t=t.substring(0,s)+t.substring(s+a),e.toggleBlinking(!0)}if(\"`\"===o.charAt(0)){for(;\"`\"!==t.substring(s+r).charAt(0)&&(r++,!(s+r>t.length)););var u=t.substring(0,s),p=t.substring(u.length+1,s+r),c=t.substring(s+r+1);t=u+p+c,r--}e.timeout=setTimeout(function(){e.toggleBlinking(!1),s>=t.length?e.doneTyping(t,s):e.keepTyping(t,s,r),e.temporaryPause&&(e.temporaryPause=!1,e.options.onTypingResumed(e.arrayPos,e))},i)},i):this.setPauseStatus(t,s,!0)},s.keepTyping=function(t,s,e){0===s&&(this.toggleBlinking(!1),this.options.preStringTyped(this.arrayPos,this));var n=t.substring(0,s+=e);this.replaceText(n),this.typewrite(t,s)},s.doneTyping=function(t,s){var e=this;this.options.onStringTyped(this.arrayPos,this),this.toggleBlinking(!0),this.arrayPos===this.strings.length-1&&(this.complete(),!1===this.loop||this.curLoop===this.loopCount)||(this.timeout=setTimeout(function(){e.backspace(t,s)},this.backDelay))},s.backspace=function(t,s){var e=this;if(!0!==this.pause.status){if(this.fadeOut)return this.initFadeOut();this.toggleBlinking(!1);var i=this.humanizer(this.backSpeed);this.timeout=setTimeout(function(){s=n.backSpaceHtmlChars(t,s,e);var i=t.substring(0,s);if(e.replaceText(i),e.smartBackspace){var r=e.strings[e.arrayPos+1];e.stopNum=r&&i===r.substring(0,s)?s:0}s>e.stopNum?(s--,e.backspace(t,s)):s<=e.stopNum&&(e.arrayPos++,e.arrayPos===e.strings.length?(e.arrayPos=0,e.options.onLastStringBackspaced(),e.shuffleStringsIfNeeded(),e.begin()):e.typewrite(e.strings[e.sequence[e.arrayPos]],s))},i)}else this.setPauseStatus(t,s,!1)},s.complete=function(){this.options.onComplete(this),this.loop?this.curLoop++:this.typingComplete=!0},s.setPauseStatus=function(t,s,e){this.pause.typewrite=e,this.pause.curString=t,this.pause.curStrPos=s},s.toggleBlinking=function(t){this.cursor&&(this.pause.status||this.cursorBlinking!==t&&(this.cursorBlinking=t,t?this.cursor.classList.add(\"typed-cursor--blink\"):this.cursor.classList.remove(\"typed-cursor--blink\")))},s.humanizer=function(t){return Math.round(Math.random()*t/2)+t},s.shuffleStringsIfNeeded=function(){this.shuffle&&(this.sequence=this.sequence.sort(function(){return Math.random()-.5}))},s.initFadeOut=function(){var t=this;return this.el.className+=\" \"+this.fadeOutClass,this.cursor&&(this.cursor.className+=\" \"+this.fadeOutClass),setTimeout(function(){t.arrayPos++,t.replaceText(\"\"),t.strings.length>t.arrayPos?t.typewrite(t.strings[t.sequence[t.arrayPos]],0):(t.typewrite(t.strings[0],0),t.arrayPos=0)},this.fadeOutDelay)},s.replaceText=function(t){this.attr?this.el.setAttribute(this.attr,t):this.isInput?this.el.value=t:\"html\"===this.contentType?this.el.innerHTML=t:this.el.textContent=t},s.bindFocusEvents=function(){var t=this;this.isInput&&(this.el.addEventListener(\"focus\",function(s){t.stop()}),this.el.addEventListener(\"blur\",function(s){t.el.value&&0!==t.el.value.length||t.start()}))},s.insertCursor=function(){this.showCursor&&(this.cursor||(this.cursor=document.createElement(\"span\"),this.cursor.className=\"typed-cursor\",this.cursor.setAttribute(\"aria-hidden\",!0),this.cursor.innerHTML=this.cursorChar,this.el.parentNode&&this.el.parentNode.insertBefore(this.cursor,this.el.nextSibling)))},t}();export{i as default};\n//# sourceMappingURL=typed.module.js.map\n","import { Controller } from '@hotwired/stimulus';\nimport Typed from 'typed.js';\n\nexport default class extends Controller {\n static values = {\n items: Array,\n }\n\n connect() {\n this.textElement().innerHTML = \"\"\n const options = this.optionsForTyped()\n this.typed = new Typed(this.textElement(), options)\n }\n\n disconnect() {\n if (this.typed && this.typed.destroy) {\n this.typed.destroy()\n }\n }\n\n // Returns the options for the Typed.js instance.\n optionsForTyped() {\n return {\n backDelay: 2000,\n backSpeed: 10,\n loop: true,\n startDelay: 500,\n strings: this.itemsValue,\n typeSpeed: 50,\n }\n }\n\n // Returns the first strong element. That's the element we want to animate.\n textElement() {\n return this.element.querySelector('strong')\n }\n}\n","import { Controller } from '@hotwired/stimulus';\n\nexport default class extends Controller {\n static targets = [\n 'audio',\n 'pauseButton',\n 'playButton',\n 'progress',\n 'progressBar'\n ]\n\n connect () {\n // Initially hide pause buttons and progress bars\n this.hideAll(this.pauseButtonTargets)\n this.hideAll(this.progressTargets)\n\n this.audioTargets.forEach(function(audioElement) {\n // Ensure the audio element is loaded before playback\n // Shouldn't make a difference, but there are reports of audio not playing on Firefox without it\n audioElement.load()\n\n // Setup progress bar for each audio element\n this.setupProgress(audioElement)\n }.bind(this))\n }\n\n hide (element) {\n element.style.display = 'none'\n }\n\n hideAll (elements) {\n elements.forEach(function(element) {\n element.style.display = 'none'\n })\n }\n\n play (event) {\n const index = event.params.index\n\n // Stop playing all other audio elements\n this.pauseAll()\n\n // Show play button for all audio elements\n this.hideAll(this.pauseButtonTargets)\n this.showAll(this.playButtonTargets)\n\n // Show pause button for this audio element\n this.hide(this.playButtonTargets[index])\n this.show(this.pauseButtonTargets[index])\n\n // Show only current progress bar when playing\n this.hideAll(this.progressTargets)\n this.show(this.progressTargets[index])\n\n this.audioTargets[index].play()\n }\n\n pause (event) {\n const index = event.params.index\n\n // Show play button for this audio element\n this.show(this.playButtonTargets[index])\n this.hide(this.pauseButtonTargets[index])\n\n this.audioTargets[index].pause()\n }\n\n pauseAll () {\n // stop all other audio elements\n this.audioTargets.forEach(function(audioElement) {\n audioElement.pause()\n })\n }\n\n setupProgress (audioElement) {\n const index = audioElement.dataset.index\n const progressBar = this.progressBarTargets[index]\n\n // Display progress\n audioElement.addEventListener('timeupdate', () => {\n progressBar.style.width = `${Math.floor(\n (audioElement.currentTime / audioElement.duration) * 100,\n )}%`;\n });\n }\n\n show (element) {\n element.style.display = 'block'\n }\n\n showAll (elements) {\n elements.forEach(function(element) {\n element.style.display = 'block'\n })\n }\n}\n","/**!\n * Sortable 1.15.6\n * @author\tRubaXa \n * @author\towenm \n * @license MIT\n */\nfunction ownKeys(object, enumerableOnly) {\n var keys = Object.keys(object);\n if (Object.getOwnPropertySymbols) {\n var symbols = Object.getOwnPropertySymbols(object);\n if (enumerableOnly) {\n symbols = symbols.filter(function (sym) {\n return Object.getOwnPropertyDescriptor(object, sym).enumerable;\n });\n }\n keys.push.apply(keys, symbols);\n }\n return keys;\n}\nfunction _objectSpread2(target) {\n for (var i = 1; i < arguments.length; i++) {\n var source = arguments[i] != null ? arguments[i] : {};\n if (i % 2) {\n ownKeys(Object(source), true).forEach(function (key) {\n _defineProperty(target, key, source[key]);\n });\n } else if (Object.getOwnPropertyDescriptors) {\n Object.defineProperties(target, Object.getOwnPropertyDescriptors(source));\n } else {\n ownKeys(Object(source)).forEach(function (key) {\n Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key));\n });\n }\n }\n return target;\n}\nfunction _typeof(obj) {\n \"@babel/helpers - typeof\";\n\n if (typeof Symbol === \"function\" && typeof Symbol.iterator === \"symbol\") {\n _typeof = function (obj) {\n return typeof obj;\n };\n } else {\n _typeof = function (obj) {\n return obj && typeof Symbol === \"function\" && obj.constructor === Symbol && obj !== Symbol.prototype ? \"symbol\" : typeof obj;\n };\n }\n return _typeof(obj);\n}\nfunction _defineProperty(obj, key, value) {\n if (key in obj) {\n Object.defineProperty(obj, key, {\n value: value,\n enumerable: true,\n configurable: true,\n writable: true\n });\n } else {\n obj[key] = value;\n }\n return obj;\n}\nfunction _extends() {\n _extends = Object.assign || function (target) {\n for (var i = 1; i < arguments.length; i++) {\n var source = arguments[i];\n for (var key in source) {\n if (Object.prototype.hasOwnProperty.call(source, key)) {\n target[key] = source[key];\n }\n }\n }\n return target;\n };\n return _extends.apply(this, arguments);\n}\nfunction _objectWithoutPropertiesLoose(source, excluded) {\n if (source == null) return {};\n var target = {};\n var sourceKeys = Object.keys(source);\n var key, i;\n for (i = 0; i < sourceKeys.length; i++) {\n key = sourceKeys[i];\n if (excluded.indexOf(key) >= 0) continue;\n target[key] = source[key];\n }\n return target;\n}\nfunction _objectWithoutProperties(source, excluded) {\n if (source == null) return {};\n var target = _objectWithoutPropertiesLoose(source, excluded);\n var key, i;\n if (Object.getOwnPropertySymbols) {\n var sourceSymbolKeys = Object.getOwnPropertySymbols(source);\n for (i = 0; i < sourceSymbolKeys.length; i++) {\n key = sourceSymbolKeys[i];\n if (excluded.indexOf(key) >= 0) continue;\n if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue;\n target[key] = source[key];\n }\n }\n return target;\n}\nfunction _toConsumableArray(arr) {\n return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread();\n}\nfunction _arrayWithoutHoles(arr) {\n if (Array.isArray(arr)) return _arrayLikeToArray(arr);\n}\nfunction _iterableToArray(iter) {\n if (typeof Symbol !== \"undefined\" && iter[Symbol.iterator] != null || iter[\"@@iterator\"] != null) return Array.from(iter);\n}\nfunction _unsupportedIterableToArray(o, minLen) {\n if (!o) return;\n if (typeof o === \"string\") return _arrayLikeToArray(o, minLen);\n var n = Object.prototype.toString.call(o).slice(8, -1);\n if (n === \"Object\" && o.constructor) n = o.constructor.name;\n if (n === \"Map\" || n === \"Set\") return Array.from(o);\n if (n === \"Arguments\" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen);\n}\nfunction _arrayLikeToArray(arr, len) {\n if (len == null || len > arr.length) len = arr.length;\n for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i];\n return arr2;\n}\nfunction _nonIterableSpread() {\n throw new TypeError(\"Invalid attempt to spread non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.\");\n}\n\nvar version = \"1.15.6\";\n\nfunction userAgent(pattern) {\n if (typeof window !== 'undefined' && window.navigator) {\n return !! /*@__PURE__*/navigator.userAgent.match(pattern);\n }\n}\nvar IE11OrLess = userAgent(/(?:Trident.*rv[ :]?11\\.|msie|iemobile|Windows Phone)/i);\nvar Edge = userAgent(/Edge/i);\nvar FireFox = userAgent(/firefox/i);\nvar Safari = userAgent(/safari/i) && !userAgent(/chrome/i) && !userAgent(/android/i);\nvar IOS = userAgent(/iP(ad|od|hone)/i);\nvar ChromeForAndroid = userAgent(/chrome/i) && userAgent(/android/i);\n\nvar captureMode = {\n capture: false,\n passive: false\n};\nfunction on(el, event, fn) {\n el.addEventListener(event, fn, !IE11OrLess && captureMode);\n}\nfunction off(el, event, fn) {\n el.removeEventListener(event, fn, !IE11OrLess && captureMode);\n}\nfunction matches( /**HTMLElement*/el, /**String*/selector) {\n if (!selector) return;\n selector[0] === '>' && (selector = selector.substring(1));\n if (el) {\n try {\n if (el.matches) {\n return el.matches(selector);\n } else if (el.msMatchesSelector) {\n return el.msMatchesSelector(selector);\n } else if (el.webkitMatchesSelector) {\n return el.webkitMatchesSelector(selector);\n }\n } catch (_) {\n return false;\n }\n }\n return false;\n}\nfunction getParentOrHost(el) {\n return el.host && el !== document && el.host.nodeType ? el.host : el.parentNode;\n}\nfunction closest( /**HTMLElement*/el, /**String*/selector, /**HTMLElement*/ctx, includeCTX) {\n if (el) {\n ctx = ctx || document;\n do {\n if (selector != null && (selector[0] === '>' ? el.parentNode === ctx && matches(el, selector) : matches(el, selector)) || includeCTX && el === ctx) {\n return el;\n }\n if (el === ctx) break;\n /* jshint boss:true */\n } while (el = getParentOrHost(el));\n }\n return null;\n}\nvar R_SPACE = /\\s+/g;\nfunction toggleClass(el, name, state) {\n if (el && name) {\n if (el.classList) {\n el.classList[state ? 'add' : 'remove'](name);\n } else {\n var className = (' ' + el.className + ' ').replace(R_SPACE, ' ').replace(' ' + name + ' ', ' ');\n el.className = (className + (state ? ' ' + name : '')).replace(R_SPACE, ' ');\n }\n }\n}\nfunction css(el, prop, val) {\n var style = el && el.style;\n if (style) {\n if (val === void 0) {\n if (document.defaultView && document.defaultView.getComputedStyle) {\n val = document.defaultView.getComputedStyle(el, '');\n } else if (el.currentStyle) {\n val = el.currentStyle;\n }\n return prop === void 0 ? val : val[prop];\n } else {\n if (!(prop in style) && prop.indexOf('webkit') === -1) {\n prop = '-webkit-' + prop;\n }\n style[prop] = val + (typeof val === 'string' ? '' : 'px');\n }\n }\n}\nfunction matrix(el, selfOnly) {\n var appliedTransforms = '';\n if (typeof el === 'string') {\n appliedTransforms = el;\n } else {\n do {\n var transform = css(el, 'transform');\n if (transform && transform !== 'none') {\n appliedTransforms = transform + ' ' + appliedTransforms;\n }\n /* jshint boss:true */\n } while (!selfOnly && (el = el.parentNode));\n }\n var matrixFn = window.DOMMatrix || window.WebKitCSSMatrix || window.CSSMatrix || window.MSCSSMatrix;\n /*jshint -W056 */\n return matrixFn && new matrixFn(appliedTransforms);\n}\nfunction find(ctx, tagName, iterator) {\n if (ctx) {\n var list = ctx.getElementsByTagName(tagName),\n i = 0,\n n = list.length;\n if (iterator) {\n for (; i < n; i++) {\n iterator(list[i], i);\n }\n }\n return list;\n }\n return [];\n}\nfunction getWindowScrollingElement() {\n var scrollingElement = document.scrollingElement;\n if (scrollingElement) {\n return scrollingElement;\n } else {\n return document.documentElement;\n }\n}\n\n/**\r\n * Returns the \"bounding client rect\" of given element\r\n * @param {HTMLElement} el The element whose boundingClientRect is wanted\r\n * @param {[Boolean]} relativeToContainingBlock Whether the rect should be relative to the containing block of (including) the container\r\n * @param {[Boolean]} relativeToNonStaticParent Whether the rect should be relative to the relative parent of (including) the contaienr\r\n * @param {[Boolean]} undoScale Whether the container's scale() should be undone\r\n * @param {[HTMLElement]} container The parent the element will be placed in\r\n * @return {Object} The boundingClientRect of el, with specified adjustments\r\n */\nfunction getRect(el, relativeToContainingBlock, relativeToNonStaticParent, undoScale, container) {\n if (!el.getBoundingClientRect && el !== window) return;\n var elRect, top, left, bottom, right, height, width;\n if (el !== window && el.parentNode && el !== getWindowScrollingElement()) {\n elRect = el.getBoundingClientRect();\n top = elRect.top;\n left = elRect.left;\n bottom = elRect.bottom;\n right = elRect.right;\n height = elRect.height;\n width = elRect.width;\n } else {\n top = 0;\n left = 0;\n bottom = window.innerHeight;\n right = window.innerWidth;\n height = window.innerHeight;\n width = window.innerWidth;\n }\n if ((relativeToContainingBlock || relativeToNonStaticParent) && el !== window) {\n // Adjust for translate()\n container = container || el.parentNode;\n\n // solves #1123 (see: https://stackoverflow.com/a/37953806/6088312)\n // Not needed on <= IE11\n if (!IE11OrLess) {\n do {\n if (container && container.getBoundingClientRect && (css(container, 'transform') !== 'none' || relativeToNonStaticParent && css(container, 'position') !== 'static')) {\n var containerRect = container.getBoundingClientRect();\n\n // Set relative to edges of padding box of container\n top -= containerRect.top + parseInt(css(container, 'border-top-width'));\n left -= containerRect.left + parseInt(css(container, 'border-left-width'));\n bottom = top + elRect.height;\n right = left + elRect.width;\n break;\n }\n /* jshint boss:true */\n } while (container = container.parentNode);\n }\n }\n if (undoScale && el !== window) {\n // Adjust for scale()\n var elMatrix = matrix(container || el),\n scaleX = elMatrix && elMatrix.a,\n scaleY = elMatrix && elMatrix.d;\n if (elMatrix) {\n top /= scaleY;\n left /= scaleX;\n width /= scaleX;\n height /= scaleY;\n bottom = top + height;\n right = left + width;\n }\n }\n return {\n top: top,\n left: left,\n bottom: bottom,\n right: right,\n width: width,\n height: height\n };\n}\n\n/**\r\n * Checks if a side of an element is scrolled past a side of its parents\r\n * @param {HTMLElement} el The element who's side being scrolled out of view is in question\r\n * @param {String} elSide Side of the element in question ('top', 'left', 'right', 'bottom')\r\n * @param {String} parentSide Side of the parent in question ('top', 'left', 'right', 'bottom')\r\n * @return {HTMLElement} The parent scroll element that the el's side is scrolled past, or null if there is no such element\r\n */\nfunction isScrolledPast(el, elSide, parentSide) {\n var parent = getParentAutoScrollElement(el, true),\n elSideVal = getRect(el)[elSide];\n\n /* jshint boss:true */\n while (parent) {\n var parentSideVal = getRect(parent)[parentSide],\n visible = void 0;\n if (parentSide === 'top' || parentSide === 'left') {\n visible = elSideVal >= parentSideVal;\n } else {\n visible = elSideVal <= parentSideVal;\n }\n if (!visible) return parent;\n if (parent === getWindowScrollingElement()) break;\n parent = getParentAutoScrollElement(parent, false);\n }\n return false;\n}\n\n/**\r\n * Gets nth child of el, ignoring hidden children, sortable's elements (does not ignore clone if it's visible)\r\n * and non-draggable elements\r\n * @param {HTMLElement} el The parent element\r\n * @param {Number} childNum The index of the child\r\n * @param {Object} options Parent Sortable's options\r\n * @return {HTMLElement} The child at index childNum, or null if not found\r\n */\nfunction getChild(el, childNum, options, includeDragEl) {\n var currentChild = 0,\n i = 0,\n children = el.children;\n while (i < children.length) {\n if (children[i].style.display !== 'none' && children[i] !== Sortable.ghost && (includeDragEl || children[i] !== Sortable.dragged) && closest(children[i], options.draggable, el, false)) {\n if (currentChild === childNum) {\n return children[i];\n }\n currentChild++;\n }\n i++;\n }\n return null;\n}\n\n/**\r\n * Gets the last child in the el, ignoring ghostEl or invisible elements (clones)\r\n * @param {HTMLElement} el Parent element\r\n * @param {selector} selector Any other elements that should be ignored\r\n * @return {HTMLElement} The last child, ignoring ghostEl\r\n */\nfunction lastChild(el, selector) {\n var last = el.lastElementChild;\n while (last && (last === Sortable.ghost || css(last, 'display') === 'none' || selector && !matches(last, selector))) {\n last = last.previousElementSibling;\n }\n return last || null;\n}\n\n/**\r\n * Returns the index of an element within its parent for a selected set of\r\n * elements\r\n * @param {HTMLElement} el\r\n * @param {selector} selector\r\n * @return {number}\r\n */\nfunction index(el, selector) {\n var index = 0;\n if (!el || !el.parentNode) {\n return -1;\n }\n\n /* jshint boss:true */\n while (el = el.previousElementSibling) {\n if (el.nodeName.toUpperCase() !== 'TEMPLATE' && el !== Sortable.clone && (!selector || matches(el, selector))) {\n index++;\n }\n }\n return index;\n}\n\n/**\r\n * Returns the scroll offset of the given element, added with all the scroll offsets of parent elements.\r\n * The value is returned in real pixels.\r\n * @param {HTMLElement} el\r\n * @return {Array} Offsets in the format of [left, top]\r\n */\nfunction getRelativeScrollOffset(el) {\n var offsetLeft = 0,\n offsetTop = 0,\n winScroller = getWindowScrollingElement();\n if (el) {\n do {\n var elMatrix = matrix(el),\n scaleX = elMatrix.a,\n scaleY = elMatrix.d;\n offsetLeft += el.scrollLeft * scaleX;\n offsetTop += el.scrollTop * scaleY;\n } while (el !== winScroller && (el = el.parentNode));\n }\n return [offsetLeft, offsetTop];\n}\n\n/**\r\n * Returns the index of the object within the given array\r\n * @param {Array} arr Array that may or may not hold the object\r\n * @param {Object} obj An object that has a key-value pair unique to and identical to a key-value pair in the object you want to find\r\n * @return {Number} The index of the object in the array, or -1\r\n */\nfunction indexOfObject(arr, obj) {\n for (var i in arr) {\n if (!arr.hasOwnProperty(i)) continue;\n for (var key in obj) {\n if (obj.hasOwnProperty(key) && obj[key] === arr[i][key]) return Number(i);\n }\n }\n return -1;\n}\nfunction getParentAutoScrollElement(el, includeSelf) {\n // skip to window\n if (!el || !el.getBoundingClientRect) return getWindowScrollingElement();\n var elem = el;\n var gotSelf = false;\n do {\n // we don't need to get elem css if it isn't even overflowing in the first place (performance)\n if (elem.clientWidth < elem.scrollWidth || elem.clientHeight < elem.scrollHeight) {\n var elemCSS = css(elem);\n if (elem.clientWidth < elem.scrollWidth && (elemCSS.overflowX == 'auto' || elemCSS.overflowX == 'scroll') || elem.clientHeight < elem.scrollHeight && (elemCSS.overflowY == 'auto' || elemCSS.overflowY == 'scroll')) {\n if (!elem.getBoundingClientRect || elem === document.body) return getWindowScrollingElement();\n if (gotSelf || includeSelf) return elem;\n gotSelf = true;\n }\n }\n /* jshint boss:true */\n } while (elem = elem.parentNode);\n return getWindowScrollingElement();\n}\nfunction extend(dst, src) {\n if (dst && src) {\n for (var key in src) {\n if (src.hasOwnProperty(key)) {\n dst[key] = src[key];\n }\n }\n }\n return dst;\n}\nfunction isRectEqual(rect1, rect2) {\n return Math.round(rect1.top) === Math.round(rect2.top) && Math.round(rect1.left) === Math.round(rect2.left) && Math.round(rect1.height) === Math.round(rect2.height) && Math.round(rect1.width) === Math.round(rect2.width);\n}\nvar _throttleTimeout;\nfunction throttle(callback, ms) {\n return function () {\n if (!_throttleTimeout) {\n var args = arguments,\n _this = this;\n if (args.length === 1) {\n callback.call(_this, args[0]);\n } else {\n callback.apply(_this, args);\n }\n _throttleTimeout = setTimeout(function () {\n _throttleTimeout = void 0;\n }, ms);\n }\n };\n}\nfunction cancelThrottle() {\n clearTimeout(_throttleTimeout);\n _throttleTimeout = void 0;\n}\nfunction scrollBy(el, x, y) {\n el.scrollLeft += x;\n el.scrollTop += y;\n}\nfunction clone(el) {\n var Polymer = window.Polymer;\n var $ = window.jQuery || window.Zepto;\n if (Polymer && Polymer.dom) {\n return Polymer.dom(el).cloneNode(true);\n } else if ($) {\n return $(el).clone(true)[0];\n } else {\n return el.cloneNode(true);\n }\n}\nfunction setRect(el, rect) {\n css(el, 'position', 'absolute');\n css(el, 'top', rect.top);\n css(el, 'left', rect.left);\n css(el, 'width', rect.width);\n css(el, 'height', rect.height);\n}\nfunction unsetRect(el) {\n css(el, 'position', '');\n css(el, 'top', '');\n css(el, 'left', '');\n css(el, 'width', '');\n css(el, 'height', '');\n}\nfunction getChildContainingRectFromElement(container, options, ghostEl) {\n var rect = {};\n Array.from(container.children).forEach(function (child) {\n var _rect$left, _rect$top, _rect$right, _rect$bottom;\n if (!closest(child, options.draggable, container, false) || child.animated || child === ghostEl) return;\n var childRect = getRect(child);\n rect.left = Math.min((_rect$left = rect.left) !== null && _rect$left !== void 0 ? _rect$left : Infinity, childRect.left);\n rect.top = Math.min((_rect$top = rect.top) !== null && _rect$top !== void 0 ? _rect$top : Infinity, childRect.top);\n rect.right = Math.max((_rect$right = rect.right) !== null && _rect$right !== void 0 ? _rect$right : -Infinity, childRect.right);\n rect.bottom = Math.max((_rect$bottom = rect.bottom) !== null && _rect$bottom !== void 0 ? _rect$bottom : -Infinity, childRect.bottom);\n });\n rect.width = rect.right - rect.left;\n rect.height = rect.bottom - rect.top;\n rect.x = rect.left;\n rect.y = rect.top;\n return rect;\n}\nvar expando = 'Sortable' + new Date().getTime();\n\nfunction AnimationStateManager() {\n var animationStates = [],\n animationCallbackId;\n return {\n captureAnimationState: function captureAnimationState() {\n animationStates = [];\n if (!this.options.animation) return;\n var children = [].slice.call(this.el.children);\n children.forEach(function (child) {\n if (css(child, 'display') === 'none' || child === Sortable.ghost) return;\n animationStates.push({\n target: child,\n rect: getRect(child)\n });\n var fromRect = _objectSpread2({}, animationStates[animationStates.length - 1].rect);\n\n // If animating: compensate for current animation\n if (child.thisAnimationDuration) {\n var childMatrix = matrix(child, true);\n if (childMatrix) {\n fromRect.top -= childMatrix.f;\n fromRect.left -= childMatrix.e;\n }\n }\n child.fromRect = fromRect;\n });\n },\n addAnimationState: function addAnimationState(state) {\n animationStates.push(state);\n },\n removeAnimationState: function removeAnimationState(target) {\n animationStates.splice(indexOfObject(animationStates, {\n target: target\n }), 1);\n },\n animateAll: function animateAll(callback) {\n var _this = this;\n if (!this.options.animation) {\n clearTimeout(animationCallbackId);\n if (typeof callback === 'function') callback();\n return;\n }\n var animating = false,\n animationTime = 0;\n animationStates.forEach(function (state) {\n var time = 0,\n target = state.target,\n fromRect = target.fromRect,\n toRect = getRect(target),\n prevFromRect = target.prevFromRect,\n prevToRect = target.prevToRect,\n animatingRect = state.rect,\n targetMatrix = matrix(target, true);\n if (targetMatrix) {\n // Compensate for current animation\n toRect.top -= targetMatrix.f;\n toRect.left -= targetMatrix.e;\n }\n target.toRect = toRect;\n if (target.thisAnimationDuration) {\n // Could also check if animatingRect is between fromRect and toRect\n if (isRectEqual(prevFromRect, toRect) && !isRectEqual(fromRect, toRect) &&\n // Make sure animatingRect is on line between toRect & fromRect\n (animatingRect.top - toRect.top) / (animatingRect.left - toRect.left) === (fromRect.top - toRect.top) / (fromRect.left - toRect.left)) {\n // If returning to same place as started from animation and on same axis\n time = calculateRealTime(animatingRect, prevFromRect, prevToRect, _this.options);\n }\n }\n\n // if fromRect != toRect: animate\n if (!isRectEqual(toRect, fromRect)) {\n target.prevFromRect = fromRect;\n target.prevToRect = toRect;\n if (!time) {\n time = _this.options.animation;\n }\n _this.animate(target, animatingRect, toRect, time);\n }\n if (time) {\n animating = true;\n animationTime = Math.max(animationTime, time);\n clearTimeout(target.animationResetTimer);\n target.animationResetTimer = setTimeout(function () {\n target.animationTime = 0;\n target.prevFromRect = null;\n target.fromRect = null;\n target.prevToRect = null;\n target.thisAnimationDuration = null;\n }, time);\n target.thisAnimationDuration = time;\n }\n });\n clearTimeout(animationCallbackId);\n if (!animating) {\n if (typeof callback === 'function') callback();\n } else {\n animationCallbackId = setTimeout(function () {\n if (typeof callback === 'function') callback();\n }, animationTime);\n }\n animationStates = [];\n },\n animate: function animate(target, currentRect, toRect, duration) {\n if (duration) {\n css(target, 'transition', '');\n css(target, 'transform', '');\n var elMatrix = matrix(this.el),\n scaleX = elMatrix && elMatrix.a,\n scaleY = elMatrix && elMatrix.d,\n translateX = (currentRect.left - toRect.left) / (scaleX || 1),\n translateY = (currentRect.top - toRect.top) / (scaleY || 1);\n target.animatingX = !!translateX;\n target.animatingY = !!translateY;\n css(target, 'transform', 'translate3d(' + translateX + 'px,' + translateY + 'px,0)');\n this.forRepaintDummy = repaint(target); // repaint\n\n css(target, 'transition', 'transform ' + duration + 'ms' + (this.options.easing ? ' ' + this.options.easing : ''));\n css(target, 'transform', 'translate3d(0,0,0)');\n typeof target.animated === 'number' && clearTimeout(target.animated);\n target.animated = setTimeout(function () {\n css(target, 'transition', '');\n css(target, 'transform', '');\n target.animated = false;\n target.animatingX = false;\n target.animatingY = false;\n }, duration);\n }\n }\n };\n}\nfunction repaint(target) {\n return target.offsetWidth;\n}\nfunction calculateRealTime(animatingRect, fromRect, toRect, options) {\n return Math.sqrt(Math.pow(fromRect.top - animatingRect.top, 2) + Math.pow(fromRect.left - animatingRect.left, 2)) / Math.sqrt(Math.pow(fromRect.top - toRect.top, 2) + Math.pow(fromRect.left - toRect.left, 2)) * options.animation;\n}\n\nvar plugins = [];\nvar defaults = {\n initializeByDefault: true\n};\nvar PluginManager = {\n mount: function mount(plugin) {\n // Set default static properties\n for (var option in defaults) {\n if (defaults.hasOwnProperty(option) && !(option in plugin)) {\n plugin[option] = defaults[option];\n }\n }\n plugins.forEach(function (p) {\n if (p.pluginName === plugin.pluginName) {\n throw \"Sortable: Cannot mount plugin \".concat(plugin.pluginName, \" more than once\");\n }\n });\n plugins.push(plugin);\n },\n pluginEvent: function pluginEvent(eventName, sortable, evt) {\n var _this = this;\n this.eventCanceled = false;\n evt.cancel = function () {\n _this.eventCanceled = true;\n };\n var eventNameGlobal = eventName + 'Global';\n plugins.forEach(function (plugin) {\n if (!sortable[plugin.pluginName]) return;\n // Fire global events if it exists in this sortable\n if (sortable[plugin.pluginName][eventNameGlobal]) {\n sortable[plugin.pluginName][eventNameGlobal](_objectSpread2({\n sortable: sortable\n }, evt));\n }\n\n // Only fire plugin event if plugin is enabled in this sortable,\n // and plugin has event defined\n if (sortable.options[plugin.pluginName] && sortable[plugin.pluginName][eventName]) {\n sortable[plugin.pluginName][eventName](_objectSpread2({\n sortable: sortable\n }, evt));\n }\n });\n },\n initializePlugins: function initializePlugins(sortable, el, defaults, options) {\n plugins.forEach(function (plugin) {\n var pluginName = plugin.pluginName;\n if (!sortable.options[pluginName] && !plugin.initializeByDefault) return;\n var initialized = new plugin(sortable, el, sortable.options);\n initialized.sortable = sortable;\n initialized.options = sortable.options;\n sortable[pluginName] = initialized;\n\n // Add default options from plugin\n _extends(defaults, initialized.defaults);\n });\n for (var option in sortable.options) {\n if (!sortable.options.hasOwnProperty(option)) continue;\n var modified = this.modifyOption(sortable, option, sortable.options[option]);\n if (typeof modified !== 'undefined') {\n sortable.options[option] = modified;\n }\n }\n },\n getEventProperties: function getEventProperties(name, sortable) {\n var eventProperties = {};\n plugins.forEach(function (plugin) {\n if (typeof plugin.eventProperties !== 'function') return;\n _extends(eventProperties, plugin.eventProperties.call(sortable[plugin.pluginName], name));\n });\n return eventProperties;\n },\n modifyOption: function modifyOption(sortable, name, value) {\n var modifiedValue;\n plugins.forEach(function (plugin) {\n // Plugin must exist on the Sortable\n if (!sortable[plugin.pluginName]) return;\n\n // If static option listener exists for this option, call in the context of the Sortable's instance of this plugin\n if (plugin.optionListeners && typeof plugin.optionListeners[name] === 'function') {\n modifiedValue = plugin.optionListeners[name].call(sortable[plugin.pluginName], value);\n }\n });\n return modifiedValue;\n }\n};\n\nfunction dispatchEvent(_ref) {\n var sortable = _ref.sortable,\n rootEl = _ref.rootEl,\n name = _ref.name,\n targetEl = _ref.targetEl,\n cloneEl = _ref.cloneEl,\n toEl = _ref.toEl,\n fromEl = _ref.fromEl,\n oldIndex = _ref.oldIndex,\n newIndex = _ref.newIndex,\n oldDraggableIndex = _ref.oldDraggableIndex,\n newDraggableIndex = _ref.newDraggableIndex,\n originalEvent = _ref.originalEvent,\n putSortable = _ref.putSortable,\n extraEventProperties = _ref.extraEventProperties;\n sortable = sortable || rootEl && rootEl[expando];\n if (!sortable) return;\n var evt,\n options = sortable.options,\n onName = 'on' + name.charAt(0).toUpperCase() + name.substr(1);\n // Support for new CustomEvent feature\n if (window.CustomEvent && !IE11OrLess && !Edge) {\n evt = new CustomEvent(name, {\n bubbles: true,\n cancelable: true\n });\n } else {\n evt = document.createEvent('Event');\n evt.initEvent(name, true, true);\n }\n evt.to = toEl || rootEl;\n evt.from = fromEl || rootEl;\n evt.item = targetEl || rootEl;\n evt.clone = cloneEl;\n evt.oldIndex = oldIndex;\n evt.newIndex = newIndex;\n evt.oldDraggableIndex = oldDraggableIndex;\n evt.newDraggableIndex = newDraggableIndex;\n evt.originalEvent = originalEvent;\n evt.pullMode = putSortable ? putSortable.lastPutMode : undefined;\n var allEventProperties = _objectSpread2(_objectSpread2({}, extraEventProperties), PluginManager.getEventProperties(name, sortable));\n for (var option in allEventProperties) {\n evt[option] = allEventProperties[option];\n }\n if (rootEl) {\n rootEl.dispatchEvent(evt);\n }\n if (options[onName]) {\n options[onName].call(sortable, evt);\n }\n}\n\nvar _excluded = [\"evt\"];\nvar pluginEvent = function pluginEvent(eventName, sortable) {\n var _ref = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {},\n originalEvent = _ref.evt,\n data = _objectWithoutProperties(_ref, _excluded);\n PluginManager.pluginEvent.bind(Sortable)(eventName, sortable, _objectSpread2({\n dragEl: dragEl,\n parentEl: parentEl,\n ghostEl: ghostEl,\n rootEl: rootEl,\n nextEl: nextEl,\n lastDownEl: lastDownEl,\n cloneEl: cloneEl,\n cloneHidden: cloneHidden,\n dragStarted: moved,\n putSortable: putSortable,\n activeSortable: Sortable.active,\n originalEvent: originalEvent,\n oldIndex: oldIndex,\n oldDraggableIndex: oldDraggableIndex,\n newIndex: newIndex,\n newDraggableIndex: newDraggableIndex,\n hideGhostForTarget: _hideGhostForTarget,\n unhideGhostForTarget: _unhideGhostForTarget,\n cloneNowHidden: function cloneNowHidden() {\n cloneHidden = true;\n },\n cloneNowShown: function cloneNowShown() {\n cloneHidden = false;\n },\n dispatchSortableEvent: function dispatchSortableEvent(name) {\n _dispatchEvent({\n sortable: sortable,\n name: name,\n originalEvent: originalEvent\n });\n }\n }, data));\n};\nfunction _dispatchEvent(info) {\n dispatchEvent(_objectSpread2({\n putSortable: putSortable,\n cloneEl: cloneEl,\n targetEl: dragEl,\n rootEl: rootEl,\n oldIndex: oldIndex,\n oldDraggableIndex: oldDraggableIndex,\n newIndex: newIndex,\n newDraggableIndex: newDraggableIndex\n }, info));\n}\nvar dragEl,\n parentEl,\n ghostEl,\n rootEl,\n nextEl,\n lastDownEl,\n cloneEl,\n cloneHidden,\n oldIndex,\n newIndex,\n oldDraggableIndex,\n newDraggableIndex,\n activeGroup,\n putSortable,\n awaitingDragStarted = false,\n ignoreNextClick = false,\n sortables = [],\n tapEvt,\n touchEvt,\n lastDx,\n lastDy,\n tapDistanceLeft,\n tapDistanceTop,\n moved,\n lastTarget,\n lastDirection,\n pastFirstInvertThresh = false,\n isCircumstantialInvert = false,\n targetMoveDistance,\n // For positioning ghost absolutely\n ghostRelativeParent,\n ghostRelativeParentInitialScroll = [],\n // (left, top)\n\n _silent = false,\n savedInputChecked = [];\n\n/** @const */\nvar documentExists = typeof document !== 'undefined',\n PositionGhostAbsolutely = IOS,\n CSSFloatProperty = Edge || IE11OrLess ? 'cssFloat' : 'float',\n // This will not pass for IE9, because IE9 DnD only works on anchors\n supportDraggable = documentExists && !ChromeForAndroid && !IOS && 'draggable' in document.createElement('div'),\n supportCssPointerEvents = function () {\n if (!documentExists) return;\n // false when <= IE11\n if (IE11OrLess) {\n return false;\n }\n var el = document.createElement('x');\n el.style.cssText = 'pointer-events:auto';\n return el.style.pointerEvents === 'auto';\n }(),\n _detectDirection = function _detectDirection(el, options) {\n var elCSS = css(el),\n elWidth = parseInt(elCSS.width) - parseInt(elCSS.paddingLeft) - parseInt(elCSS.paddingRight) - parseInt(elCSS.borderLeftWidth) - parseInt(elCSS.borderRightWidth),\n child1 = getChild(el, 0, options),\n child2 = getChild(el, 1, options),\n firstChildCSS = child1 && css(child1),\n secondChildCSS = child2 && css(child2),\n firstChildWidth = firstChildCSS && parseInt(firstChildCSS.marginLeft) + parseInt(firstChildCSS.marginRight) + getRect(child1).width,\n secondChildWidth = secondChildCSS && parseInt(secondChildCSS.marginLeft) + parseInt(secondChildCSS.marginRight) + getRect(child2).width;\n if (elCSS.display === 'flex') {\n return elCSS.flexDirection === 'column' || elCSS.flexDirection === 'column-reverse' ? 'vertical' : 'horizontal';\n }\n if (elCSS.display === 'grid') {\n return elCSS.gridTemplateColumns.split(' ').length <= 1 ? 'vertical' : 'horizontal';\n }\n if (child1 && firstChildCSS[\"float\"] && firstChildCSS[\"float\"] !== 'none') {\n var touchingSideChild2 = firstChildCSS[\"float\"] === 'left' ? 'left' : 'right';\n return child2 && (secondChildCSS.clear === 'both' || secondChildCSS.clear === touchingSideChild2) ? 'vertical' : 'horizontal';\n }\n return child1 && (firstChildCSS.display === 'block' || firstChildCSS.display === 'flex' || firstChildCSS.display === 'table' || firstChildCSS.display === 'grid' || firstChildWidth >= elWidth && elCSS[CSSFloatProperty] === 'none' || child2 && elCSS[CSSFloatProperty] === 'none' && firstChildWidth + secondChildWidth > elWidth) ? 'vertical' : 'horizontal';\n },\n _dragElInRowColumn = function _dragElInRowColumn(dragRect, targetRect, vertical) {\n var dragElS1Opp = vertical ? dragRect.left : dragRect.top,\n dragElS2Opp = vertical ? dragRect.right : dragRect.bottom,\n dragElOppLength = vertical ? dragRect.width : dragRect.height,\n targetS1Opp = vertical ? targetRect.left : targetRect.top,\n targetS2Opp = vertical ? targetRect.right : targetRect.bottom,\n targetOppLength = vertical ? targetRect.width : targetRect.height;\n return dragElS1Opp === targetS1Opp || dragElS2Opp === targetS2Opp || dragElS1Opp + dragElOppLength / 2 === targetS1Opp + targetOppLength / 2;\n },\n /**\r\n * Detects first nearest empty sortable to X and Y position using emptyInsertThreshold.\r\n * @param {Number} x X position\r\n * @param {Number} y Y position\r\n * @return {HTMLElement} Element of the first found nearest Sortable\r\n */\n _detectNearestEmptySortable = function _detectNearestEmptySortable(x, y) {\n var ret;\n sortables.some(function (sortable) {\n var threshold = sortable[expando].options.emptyInsertThreshold;\n if (!threshold || lastChild(sortable)) return;\n var rect = getRect(sortable),\n insideHorizontally = x >= rect.left - threshold && x <= rect.right + threshold,\n insideVertically = y >= rect.top - threshold && y <= rect.bottom + threshold;\n if (insideHorizontally && insideVertically) {\n return ret = sortable;\n }\n });\n return ret;\n },\n _prepareGroup = function _prepareGroup(options) {\n function toFn(value, pull) {\n return function (to, from, dragEl, evt) {\n var sameGroup = to.options.group.name && from.options.group.name && to.options.group.name === from.options.group.name;\n if (value == null && (pull || sameGroup)) {\n // Default pull value\n // Default pull and put value if same group\n return true;\n } else if (value == null || value === false) {\n return false;\n } else if (pull && value === 'clone') {\n return value;\n } else if (typeof value === 'function') {\n return toFn(value(to, from, dragEl, evt), pull)(to, from, dragEl, evt);\n } else {\n var otherGroup = (pull ? to : from).options.group.name;\n return value === true || typeof value === 'string' && value === otherGroup || value.join && value.indexOf(otherGroup) > -1;\n }\n };\n }\n var group = {};\n var originalGroup = options.group;\n if (!originalGroup || _typeof(originalGroup) != 'object') {\n originalGroup = {\n name: originalGroup\n };\n }\n group.name = originalGroup.name;\n group.checkPull = toFn(originalGroup.pull, true);\n group.checkPut = toFn(originalGroup.put);\n group.revertClone = originalGroup.revertClone;\n options.group = group;\n },\n _hideGhostForTarget = function _hideGhostForTarget() {\n if (!supportCssPointerEvents && ghostEl) {\n css(ghostEl, 'display', 'none');\n }\n },\n _unhideGhostForTarget = function _unhideGhostForTarget() {\n if (!supportCssPointerEvents && ghostEl) {\n css(ghostEl, 'display', '');\n }\n };\n\n// #1184 fix - Prevent click event on fallback if dragged but item not changed position\nif (documentExists && !ChromeForAndroid) {\n document.addEventListener('click', function (evt) {\n if (ignoreNextClick) {\n evt.preventDefault();\n evt.stopPropagation && evt.stopPropagation();\n evt.stopImmediatePropagation && evt.stopImmediatePropagation();\n ignoreNextClick = false;\n return false;\n }\n }, true);\n}\nvar nearestEmptyInsertDetectEvent = function nearestEmptyInsertDetectEvent(evt) {\n if (dragEl) {\n evt = evt.touches ? evt.touches[0] : evt;\n var nearest = _detectNearestEmptySortable(evt.clientX, evt.clientY);\n if (nearest) {\n // Create imitation event\n var event = {};\n for (var i in evt) {\n if (evt.hasOwnProperty(i)) {\n event[i] = evt[i];\n }\n }\n event.target = event.rootEl = nearest;\n event.preventDefault = void 0;\n event.stopPropagation = void 0;\n nearest[expando]._onDragOver(event);\n }\n }\n};\nvar _checkOutsideTargetEl = function _checkOutsideTargetEl(evt) {\n if (dragEl) {\n dragEl.parentNode[expando]._isOutsideThisEl(evt.target);\n }\n};\n\n/**\r\n * @class Sortable\r\n * @param {HTMLElement} el\r\n * @param {Object} [options]\r\n */\nfunction Sortable(el, options) {\n if (!(el && el.nodeType && el.nodeType === 1)) {\n throw \"Sortable: `el` must be an HTMLElement, not \".concat({}.toString.call(el));\n }\n this.el = el; // root element\n this.options = options = _extends({}, options);\n\n // Export instance\n el[expando] = this;\n var defaults = {\n group: null,\n sort: true,\n disabled: false,\n store: null,\n handle: null,\n draggable: /^[uo]l$/i.test(el.nodeName) ? '>li' : '>*',\n swapThreshold: 1,\n // percentage; 0 <= x <= 1\n invertSwap: false,\n // invert always\n invertedSwapThreshold: null,\n // will be set to same as swapThreshold if default\n removeCloneOnHide: true,\n direction: function direction() {\n return _detectDirection(el, this.options);\n },\n ghostClass: 'sortable-ghost',\n chosenClass: 'sortable-chosen',\n dragClass: 'sortable-drag',\n ignore: 'a, img',\n filter: null,\n preventOnFilter: true,\n animation: 0,\n easing: null,\n setData: function setData(dataTransfer, dragEl) {\n dataTransfer.setData('Text', dragEl.textContent);\n },\n dropBubble: false,\n dragoverBubble: false,\n dataIdAttr: 'data-id',\n delay: 0,\n delayOnTouchOnly: false,\n touchStartThreshold: (Number.parseInt ? Number : window).parseInt(window.devicePixelRatio, 10) || 1,\n forceFallback: false,\n fallbackClass: 'sortable-fallback',\n fallbackOnBody: false,\n fallbackTolerance: 0,\n fallbackOffset: {\n x: 0,\n y: 0\n },\n // Disabled on Safari: #1571; Enabled on Safari IOS: #2244\n supportPointer: Sortable.supportPointer !== false && 'PointerEvent' in window && (!Safari || IOS),\n emptyInsertThreshold: 5\n };\n PluginManager.initializePlugins(this, el, defaults);\n\n // Set default options\n for (var name in defaults) {\n !(name in options) && (options[name] = defaults[name]);\n }\n _prepareGroup(options);\n\n // Bind all private methods\n for (var fn in this) {\n if (fn.charAt(0) === '_' && typeof this[fn] === 'function') {\n this[fn] = this[fn].bind(this);\n }\n }\n\n // Setup drag mode\n this.nativeDraggable = options.forceFallback ? false : supportDraggable;\n if (this.nativeDraggable) {\n // Touch start threshold cannot be greater than the native dragstart threshold\n this.options.touchStartThreshold = 1;\n }\n\n // Bind events\n if (options.supportPointer) {\n on(el, 'pointerdown', this._onTapStart);\n } else {\n on(el, 'mousedown', this._onTapStart);\n on(el, 'touchstart', this._onTapStart);\n }\n if (this.nativeDraggable) {\n on(el, 'dragover', this);\n on(el, 'dragenter', this);\n }\n sortables.push(this.el);\n\n // Restore sorting\n options.store && options.store.get && this.sort(options.store.get(this) || []);\n\n // Add animation state manager\n _extends(this, AnimationStateManager());\n}\nSortable.prototype = /** @lends Sortable.prototype */{\n constructor: Sortable,\n _isOutsideThisEl: function _isOutsideThisEl(target) {\n if (!this.el.contains(target) && target !== this.el) {\n lastTarget = null;\n }\n },\n _getDirection: function _getDirection(evt, target) {\n return typeof this.options.direction === 'function' ? this.options.direction.call(this, evt, target, dragEl) : this.options.direction;\n },\n _onTapStart: function _onTapStart( /** Event|TouchEvent */evt) {\n if (!evt.cancelable) return;\n var _this = this,\n el = this.el,\n options = this.options,\n preventOnFilter = options.preventOnFilter,\n type = evt.type,\n touch = evt.touches && evt.touches[0] || evt.pointerType && evt.pointerType === 'touch' && evt,\n target = (touch || evt).target,\n originalTarget = evt.target.shadowRoot && (evt.path && evt.path[0] || evt.composedPath && evt.composedPath()[0]) || target,\n filter = options.filter;\n _saveInputCheckedState(el);\n\n // Don't trigger start event when an element is been dragged, otherwise the evt.oldindex always wrong when set option.group.\n if (dragEl) {\n return;\n }\n if (/mousedown|pointerdown/.test(type) && evt.button !== 0 || options.disabled) {\n return; // only left button and enabled\n }\n\n // cancel dnd if original target is content editable\n if (originalTarget.isContentEditable) {\n return;\n }\n\n // Safari ignores further event handling after mousedown\n if (!this.nativeDraggable && Safari && target && target.tagName.toUpperCase() === 'SELECT') {\n return;\n }\n target = closest(target, options.draggable, el, false);\n if (target && target.animated) {\n return;\n }\n if (lastDownEl === target) {\n // Ignoring duplicate `down`\n return;\n }\n\n // Get the index of the dragged element within its parent\n oldIndex = index(target);\n oldDraggableIndex = index(target, options.draggable);\n\n // Check filter\n if (typeof filter === 'function') {\n if (filter.call(this, evt, target, this)) {\n _dispatchEvent({\n sortable: _this,\n rootEl: originalTarget,\n name: 'filter',\n targetEl: target,\n toEl: el,\n fromEl: el\n });\n pluginEvent('filter', _this, {\n evt: evt\n });\n preventOnFilter && evt.preventDefault();\n return; // cancel dnd\n }\n } else if (filter) {\n filter = filter.split(',').some(function (criteria) {\n criteria = closest(originalTarget, criteria.trim(), el, false);\n if (criteria) {\n _dispatchEvent({\n sortable: _this,\n rootEl: criteria,\n name: 'filter',\n targetEl: target,\n fromEl: el,\n toEl: el\n });\n pluginEvent('filter', _this, {\n evt: evt\n });\n return true;\n }\n });\n if (filter) {\n preventOnFilter && evt.preventDefault();\n return; // cancel dnd\n }\n }\n if (options.handle && !closest(originalTarget, options.handle, el, false)) {\n return;\n }\n\n // Prepare `dragstart`\n this._prepareDragStart(evt, touch, target);\n },\n _prepareDragStart: function _prepareDragStart( /** Event */evt, /** Touch */touch, /** HTMLElement */target) {\n var _this = this,\n el = _this.el,\n options = _this.options,\n ownerDocument = el.ownerDocument,\n dragStartFn;\n if (target && !dragEl && target.parentNode === el) {\n var dragRect = getRect(target);\n rootEl = el;\n dragEl = target;\n parentEl = dragEl.parentNode;\n nextEl = dragEl.nextSibling;\n lastDownEl = target;\n activeGroup = options.group;\n Sortable.dragged = dragEl;\n tapEvt = {\n target: dragEl,\n clientX: (touch || evt).clientX,\n clientY: (touch || evt).clientY\n };\n tapDistanceLeft = tapEvt.clientX - dragRect.left;\n tapDistanceTop = tapEvt.clientY - dragRect.top;\n this._lastX = (touch || evt).clientX;\n this._lastY = (touch || evt).clientY;\n dragEl.style['will-change'] = 'all';\n dragStartFn = function dragStartFn() {\n pluginEvent('delayEnded', _this, {\n evt: evt\n });\n if (Sortable.eventCanceled) {\n _this._onDrop();\n return;\n }\n // Delayed drag has been triggered\n // we can re-enable the events: touchmove/mousemove\n _this._disableDelayedDragEvents();\n if (!FireFox && _this.nativeDraggable) {\n dragEl.draggable = true;\n }\n\n // Bind the events: dragstart/dragend\n _this._triggerDragStart(evt, touch);\n\n // Drag start event\n _dispatchEvent({\n sortable: _this,\n name: 'choose',\n originalEvent: evt\n });\n\n // Chosen item\n toggleClass(dragEl, options.chosenClass, true);\n };\n\n // Disable \"draggable\"\n options.ignore.split(',').forEach(function (criteria) {\n find(dragEl, criteria.trim(), _disableDraggable);\n });\n on(ownerDocument, 'dragover', nearestEmptyInsertDetectEvent);\n on(ownerDocument, 'mousemove', nearestEmptyInsertDetectEvent);\n on(ownerDocument, 'touchmove', nearestEmptyInsertDetectEvent);\n if (options.supportPointer) {\n on(ownerDocument, 'pointerup', _this._onDrop);\n // Native D&D triggers pointercancel\n !this.nativeDraggable && on(ownerDocument, 'pointercancel', _this._onDrop);\n } else {\n on(ownerDocument, 'mouseup', _this._onDrop);\n on(ownerDocument, 'touchend', _this._onDrop);\n on(ownerDocument, 'touchcancel', _this._onDrop);\n }\n\n // Make dragEl draggable (must be before delay for FireFox)\n if (FireFox && this.nativeDraggable) {\n this.options.touchStartThreshold = 4;\n dragEl.draggable = true;\n }\n pluginEvent('delayStart', this, {\n evt: evt\n });\n\n // Delay is impossible for native DnD in Edge or IE\n if (options.delay && (!options.delayOnTouchOnly || touch) && (!this.nativeDraggable || !(Edge || IE11OrLess))) {\n if (Sortable.eventCanceled) {\n this._onDrop();\n return;\n }\n // If the user moves the pointer or let go the click or touch\n // before the delay has been reached:\n // disable the delayed drag\n if (options.supportPointer) {\n on(ownerDocument, 'pointerup', _this._disableDelayedDrag);\n on(ownerDocument, 'pointercancel', _this._disableDelayedDrag);\n } else {\n on(ownerDocument, 'mouseup', _this._disableDelayedDrag);\n on(ownerDocument, 'touchend', _this._disableDelayedDrag);\n on(ownerDocument, 'touchcancel', _this._disableDelayedDrag);\n }\n on(ownerDocument, 'mousemove', _this._delayedDragTouchMoveHandler);\n on(ownerDocument, 'touchmove', _this._delayedDragTouchMoveHandler);\n options.supportPointer && on(ownerDocument, 'pointermove', _this._delayedDragTouchMoveHandler);\n _this._dragStartTimer = setTimeout(dragStartFn, options.delay);\n } else {\n dragStartFn();\n }\n }\n },\n _delayedDragTouchMoveHandler: function _delayedDragTouchMoveHandler( /** TouchEvent|PointerEvent **/e) {\n var touch = e.touches ? e.touches[0] : e;\n if (Math.max(Math.abs(touch.clientX - this._lastX), Math.abs(touch.clientY - this._lastY)) >= Math.floor(this.options.touchStartThreshold / (this.nativeDraggable && window.devicePixelRatio || 1))) {\n this._disableDelayedDrag();\n }\n },\n _disableDelayedDrag: function _disableDelayedDrag() {\n dragEl && _disableDraggable(dragEl);\n clearTimeout(this._dragStartTimer);\n this._disableDelayedDragEvents();\n },\n _disableDelayedDragEvents: function _disableDelayedDragEvents() {\n var ownerDocument = this.el.ownerDocument;\n off(ownerDocument, 'mouseup', this._disableDelayedDrag);\n off(ownerDocument, 'touchend', this._disableDelayedDrag);\n off(ownerDocument, 'touchcancel', this._disableDelayedDrag);\n off(ownerDocument, 'pointerup', this._disableDelayedDrag);\n off(ownerDocument, 'pointercancel', this._disableDelayedDrag);\n off(ownerDocument, 'mousemove', this._delayedDragTouchMoveHandler);\n off(ownerDocument, 'touchmove', this._delayedDragTouchMoveHandler);\n off(ownerDocument, 'pointermove', this._delayedDragTouchMoveHandler);\n },\n _triggerDragStart: function _triggerDragStart( /** Event */evt, /** Touch */touch) {\n touch = touch || evt.pointerType == 'touch' && evt;\n if (!this.nativeDraggable || touch) {\n if (this.options.supportPointer) {\n on(document, 'pointermove', this._onTouchMove);\n } else if (touch) {\n on(document, 'touchmove', this._onTouchMove);\n } else {\n on(document, 'mousemove', this._onTouchMove);\n }\n } else {\n on(dragEl, 'dragend', this);\n on(rootEl, 'dragstart', this._onDragStart);\n }\n try {\n if (document.selection) {\n _nextTick(function () {\n document.selection.empty();\n });\n } else {\n window.getSelection().removeAllRanges();\n }\n } catch (err) {}\n },\n _dragStarted: function _dragStarted(fallback, evt) {\n awaitingDragStarted = false;\n if (rootEl && dragEl) {\n pluginEvent('dragStarted', this, {\n evt: evt\n });\n if (this.nativeDraggable) {\n on(document, 'dragover', _checkOutsideTargetEl);\n }\n var options = this.options;\n\n // Apply effect\n !fallback && toggleClass(dragEl, options.dragClass, false);\n toggleClass(dragEl, options.ghostClass, true);\n Sortable.active = this;\n fallback && this._appendGhost();\n\n // Drag start event\n _dispatchEvent({\n sortable: this,\n name: 'start',\n originalEvent: evt\n });\n } else {\n this._nulling();\n }\n },\n _emulateDragOver: function _emulateDragOver() {\n if (touchEvt) {\n this._lastX = touchEvt.clientX;\n this._lastY = touchEvt.clientY;\n _hideGhostForTarget();\n var target = document.elementFromPoint(touchEvt.clientX, touchEvt.clientY);\n var parent = target;\n while (target && target.shadowRoot) {\n target = target.shadowRoot.elementFromPoint(touchEvt.clientX, touchEvt.clientY);\n if (target === parent) break;\n parent = target;\n }\n dragEl.parentNode[expando]._isOutsideThisEl(target);\n if (parent) {\n do {\n if (parent[expando]) {\n var inserted = void 0;\n inserted = parent[expando]._onDragOver({\n clientX: touchEvt.clientX,\n clientY: touchEvt.clientY,\n target: target,\n rootEl: parent\n });\n if (inserted && !this.options.dragoverBubble) {\n break;\n }\n }\n target = parent; // store last element\n }\n /* jshint boss:true */ while (parent = getParentOrHost(parent));\n }\n _unhideGhostForTarget();\n }\n },\n _onTouchMove: function _onTouchMove( /**TouchEvent*/evt) {\n if (tapEvt) {\n var options = this.options,\n fallbackTolerance = options.fallbackTolerance,\n fallbackOffset = options.fallbackOffset,\n touch = evt.touches ? evt.touches[0] : evt,\n ghostMatrix = ghostEl && matrix(ghostEl, true),\n scaleX = ghostEl && ghostMatrix && ghostMatrix.a,\n scaleY = ghostEl && ghostMatrix && ghostMatrix.d,\n relativeScrollOffset = PositionGhostAbsolutely && ghostRelativeParent && getRelativeScrollOffset(ghostRelativeParent),\n dx = (touch.clientX - tapEvt.clientX + fallbackOffset.x) / (scaleX || 1) + (relativeScrollOffset ? relativeScrollOffset[0] - ghostRelativeParentInitialScroll[0] : 0) / (scaleX || 1),\n dy = (touch.clientY - tapEvt.clientY + fallbackOffset.y) / (scaleY || 1) + (relativeScrollOffset ? relativeScrollOffset[1] - ghostRelativeParentInitialScroll[1] : 0) / (scaleY || 1);\n\n // only set the status to dragging, when we are actually dragging\n if (!Sortable.active && !awaitingDragStarted) {\n if (fallbackTolerance && Math.max(Math.abs(touch.clientX - this._lastX), Math.abs(touch.clientY - this._lastY)) < fallbackTolerance) {\n return;\n }\n this._onDragStart(evt, true);\n }\n if (ghostEl) {\n if (ghostMatrix) {\n ghostMatrix.e += dx - (lastDx || 0);\n ghostMatrix.f += dy - (lastDy || 0);\n } else {\n ghostMatrix = {\n a: 1,\n b: 0,\n c: 0,\n d: 1,\n e: dx,\n f: dy\n };\n }\n var cssMatrix = \"matrix(\".concat(ghostMatrix.a, \",\").concat(ghostMatrix.b, \",\").concat(ghostMatrix.c, \",\").concat(ghostMatrix.d, \",\").concat(ghostMatrix.e, \",\").concat(ghostMatrix.f, \")\");\n css(ghostEl, 'webkitTransform', cssMatrix);\n css(ghostEl, 'mozTransform', cssMatrix);\n css(ghostEl, 'msTransform', cssMatrix);\n css(ghostEl, 'transform', cssMatrix);\n lastDx = dx;\n lastDy = dy;\n touchEvt = touch;\n }\n evt.cancelable && evt.preventDefault();\n }\n },\n _appendGhost: function _appendGhost() {\n // Bug if using scale(): https://stackoverflow.com/questions/2637058\n // Not being adjusted for\n if (!ghostEl) {\n var container = this.options.fallbackOnBody ? document.body : rootEl,\n rect = getRect(dragEl, true, PositionGhostAbsolutely, true, container),\n options = this.options;\n\n // Position absolutely\n if (PositionGhostAbsolutely) {\n // Get relatively positioned parent\n ghostRelativeParent = container;\n while (css(ghostRelativeParent, 'position') === 'static' && css(ghostRelativeParent, 'transform') === 'none' && ghostRelativeParent !== document) {\n ghostRelativeParent = ghostRelativeParent.parentNode;\n }\n if (ghostRelativeParent !== document.body && ghostRelativeParent !== document.documentElement) {\n if (ghostRelativeParent === document) ghostRelativeParent = getWindowScrollingElement();\n rect.top += ghostRelativeParent.scrollTop;\n rect.left += ghostRelativeParent.scrollLeft;\n } else {\n ghostRelativeParent = getWindowScrollingElement();\n }\n ghostRelativeParentInitialScroll = getRelativeScrollOffset(ghostRelativeParent);\n }\n ghostEl = dragEl.cloneNode(true);\n toggleClass(ghostEl, options.ghostClass, false);\n toggleClass(ghostEl, options.fallbackClass, true);\n toggleClass(ghostEl, options.dragClass, true);\n css(ghostEl, 'transition', '');\n css(ghostEl, 'transform', '');\n css(ghostEl, 'box-sizing', 'border-box');\n css(ghostEl, 'margin', 0);\n css(ghostEl, 'top', rect.top);\n css(ghostEl, 'left', rect.left);\n css(ghostEl, 'width', rect.width);\n css(ghostEl, 'height', rect.height);\n css(ghostEl, 'opacity', '0.8');\n css(ghostEl, 'position', PositionGhostAbsolutely ? 'absolute' : 'fixed');\n css(ghostEl, 'zIndex', '100000');\n css(ghostEl, 'pointerEvents', 'none');\n Sortable.ghost = ghostEl;\n container.appendChild(ghostEl);\n\n // Set transform-origin\n css(ghostEl, 'transform-origin', tapDistanceLeft / parseInt(ghostEl.style.width) * 100 + '% ' + tapDistanceTop / parseInt(ghostEl.style.height) * 100 + '%');\n }\n },\n _onDragStart: function _onDragStart( /**Event*/evt, /**boolean*/fallback) {\n var _this = this;\n var dataTransfer = evt.dataTransfer;\n var options = _this.options;\n pluginEvent('dragStart', this, {\n evt: evt\n });\n if (Sortable.eventCanceled) {\n this._onDrop();\n return;\n }\n pluginEvent('setupClone', this);\n if (!Sortable.eventCanceled) {\n cloneEl = clone(dragEl);\n cloneEl.removeAttribute(\"id\");\n cloneEl.draggable = false;\n cloneEl.style['will-change'] = '';\n this._hideClone();\n toggleClass(cloneEl, this.options.chosenClass, false);\n Sortable.clone = cloneEl;\n }\n\n // #1143: IFrame support workaround\n _this.cloneId = _nextTick(function () {\n pluginEvent('clone', _this);\n if (Sortable.eventCanceled) return;\n if (!_this.options.removeCloneOnHide) {\n rootEl.insertBefore(cloneEl, dragEl);\n }\n _this._hideClone();\n _dispatchEvent({\n sortable: _this,\n name: 'clone'\n });\n });\n !fallback && toggleClass(dragEl, options.dragClass, true);\n\n // Set proper drop events\n if (fallback) {\n ignoreNextClick = true;\n _this._loopId = setInterval(_this._emulateDragOver, 50);\n } else {\n // Undo what was set in _prepareDragStart before drag started\n off(document, 'mouseup', _this._onDrop);\n off(document, 'touchend', _this._onDrop);\n off(document, 'touchcancel', _this._onDrop);\n if (dataTransfer) {\n dataTransfer.effectAllowed = 'move';\n options.setData && options.setData.call(_this, dataTransfer, dragEl);\n }\n on(document, 'drop', _this);\n\n // #1276 fix:\n css(dragEl, 'transform', 'translateZ(0)');\n }\n awaitingDragStarted = true;\n _this._dragStartId = _nextTick(_this._dragStarted.bind(_this, fallback, evt));\n on(document, 'selectstart', _this);\n moved = true;\n window.getSelection().removeAllRanges();\n if (Safari) {\n css(document.body, 'user-select', 'none');\n }\n },\n // Returns true - if no further action is needed (either inserted or another condition)\n _onDragOver: function _onDragOver( /**Event*/evt) {\n var el = this.el,\n target = evt.target,\n dragRect,\n targetRect,\n revert,\n options = this.options,\n group = options.group,\n activeSortable = Sortable.active,\n isOwner = activeGroup === group,\n canSort = options.sort,\n fromSortable = putSortable || activeSortable,\n vertical,\n _this = this,\n completedFired = false;\n if (_silent) return;\n function dragOverEvent(name, extra) {\n pluginEvent(name, _this, _objectSpread2({\n evt: evt,\n isOwner: isOwner,\n axis: vertical ? 'vertical' : 'horizontal',\n revert: revert,\n dragRect: dragRect,\n targetRect: targetRect,\n canSort: canSort,\n fromSortable: fromSortable,\n target: target,\n completed: completed,\n onMove: function onMove(target, after) {\n return _onMove(rootEl, el, dragEl, dragRect, target, getRect(target), evt, after);\n },\n changed: changed\n }, extra));\n }\n\n // Capture animation state\n function capture() {\n dragOverEvent('dragOverAnimationCapture');\n _this.captureAnimationState();\n if (_this !== fromSortable) {\n fromSortable.captureAnimationState();\n }\n }\n\n // Return invocation when dragEl is inserted (or completed)\n function completed(insertion) {\n dragOverEvent('dragOverCompleted', {\n insertion: insertion\n });\n if (insertion) {\n // Clones must be hidden before folding animation to capture dragRectAbsolute properly\n if (isOwner) {\n activeSortable._hideClone();\n } else {\n activeSortable._showClone(_this);\n }\n if (_this !== fromSortable) {\n // Set ghost class to new sortable's ghost class\n toggleClass(dragEl, putSortable ? putSortable.options.ghostClass : activeSortable.options.ghostClass, false);\n toggleClass(dragEl, options.ghostClass, true);\n }\n if (putSortable !== _this && _this !== Sortable.active) {\n putSortable = _this;\n } else if (_this === Sortable.active && putSortable) {\n putSortable = null;\n }\n\n // Animation\n if (fromSortable === _this) {\n _this._ignoreWhileAnimating = target;\n }\n _this.animateAll(function () {\n dragOverEvent('dragOverAnimationComplete');\n _this._ignoreWhileAnimating = null;\n });\n if (_this !== fromSortable) {\n fromSortable.animateAll();\n fromSortable._ignoreWhileAnimating = null;\n }\n }\n\n // Null lastTarget if it is not inside a previously swapped element\n if (target === dragEl && !dragEl.animated || target === el && !target.animated) {\n lastTarget = null;\n }\n\n // no bubbling and not fallback\n if (!options.dragoverBubble && !evt.rootEl && target !== document) {\n dragEl.parentNode[expando]._isOutsideThisEl(evt.target);\n\n // Do not detect for empty insert if already inserted\n !insertion && nearestEmptyInsertDetectEvent(evt);\n }\n !options.dragoverBubble && evt.stopPropagation && evt.stopPropagation();\n return completedFired = true;\n }\n\n // Call when dragEl has been inserted\n function changed() {\n newIndex = index(dragEl);\n newDraggableIndex = index(dragEl, options.draggable);\n _dispatchEvent({\n sortable: _this,\n name: 'change',\n toEl: el,\n newIndex: newIndex,\n newDraggableIndex: newDraggableIndex,\n originalEvent: evt\n });\n }\n if (evt.preventDefault !== void 0) {\n evt.cancelable && evt.preventDefault();\n }\n target = closest(target, options.draggable, el, true);\n dragOverEvent('dragOver');\n if (Sortable.eventCanceled) return completedFired;\n if (dragEl.contains(evt.target) || target.animated && target.animatingX && target.animatingY || _this._ignoreWhileAnimating === target) {\n return completed(false);\n }\n ignoreNextClick = false;\n if (activeSortable && !options.disabled && (isOwner ? canSort || (revert = parentEl !== rootEl) // Reverting item into the original list\n : putSortable === this || (this.lastPutMode = activeGroup.checkPull(this, activeSortable, dragEl, evt)) && group.checkPut(this, activeSortable, dragEl, evt))) {\n vertical = this._getDirection(evt, target) === 'vertical';\n dragRect = getRect(dragEl);\n dragOverEvent('dragOverValid');\n if (Sortable.eventCanceled) return completedFired;\n if (revert) {\n parentEl = rootEl; // actualization\n capture();\n this._hideClone();\n dragOverEvent('revert');\n if (!Sortable.eventCanceled) {\n if (nextEl) {\n rootEl.insertBefore(dragEl, nextEl);\n } else {\n rootEl.appendChild(dragEl);\n }\n }\n return completed(true);\n }\n var elLastChild = lastChild(el, options.draggable);\n if (!elLastChild || _ghostIsLast(evt, vertical, this) && !elLastChild.animated) {\n // Insert to end of list\n\n // If already at end of list: Do not insert\n if (elLastChild === dragEl) {\n return completed(false);\n }\n\n // if there is a last element, it is the target\n if (elLastChild && el === evt.target) {\n target = elLastChild;\n }\n if (target) {\n targetRect = getRect(target);\n }\n if (_onMove(rootEl, el, dragEl, dragRect, target, targetRect, evt, !!target) !== false) {\n capture();\n if (elLastChild && elLastChild.nextSibling) {\n // the last draggable element is not the last node\n el.insertBefore(dragEl, elLastChild.nextSibling);\n } else {\n el.appendChild(dragEl);\n }\n parentEl = el; // actualization\n\n changed();\n return completed(true);\n }\n } else if (elLastChild && _ghostIsFirst(evt, vertical, this)) {\n // Insert to start of list\n var firstChild = getChild(el, 0, options, true);\n if (firstChild === dragEl) {\n return completed(false);\n }\n target = firstChild;\n targetRect = getRect(target);\n if (_onMove(rootEl, el, dragEl, dragRect, target, targetRect, evt, false) !== false) {\n capture();\n el.insertBefore(dragEl, firstChild);\n parentEl = el; // actualization\n\n changed();\n return completed(true);\n }\n } else if (target.parentNode === el) {\n targetRect = getRect(target);\n var direction = 0,\n targetBeforeFirstSwap,\n differentLevel = dragEl.parentNode !== el,\n differentRowCol = !_dragElInRowColumn(dragEl.animated && dragEl.toRect || dragRect, target.animated && target.toRect || targetRect, vertical),\n side1 = vertical ? 'top' : 'left',\n scrolledPastTop = isScrolledPast(target, 'top', 'top') || isScrolledPast(dragEl, 'top', 'top'),\n scrollBefore = scrolledPastTop ? scrolledPastTop.scrollTop : void 0;\n if (lastTarget !== target) {\n targetBeforeFirstSwap = targetRect[side1];\n pastFirstInvertThresh = false;\n isCircumstantialInvert = !differentRowCol && options.invertSwap || differentLevel;\n }\n direction = _getSwapDirection(evt, target, targetRect, vertical, differentRowCol ? 1 : options.swapThreshold, options.invertedSwapThreshold == null ? options.swapThreshold : options.invertedSwapThreshold, isCircumstantialInvert, lastTarget === target);\n var sibling;\n if (direction !== 0) {\n // Check if target is beside dragEl in respective direction (ignoring hidden elements)\n var dragIndex = index(dragEl);\n do {\n dragIndex -= direction;\n sibling = parentEl.children[dragIndex];\n } while (sibling && (css(sibling, 'display') === 'none' || sibling === ghostEl));\n }\n // If dragEl is already beside target: Do not insert\n if (direction === 0 || sibling === target) {\n return completed(false);\n }\n lastTarget = target;\n lastDirection = direction;\n var nextSibling = target.nextElementSibling,\n after = false;\n after = direction === 1;\n var moveVector = _onMove(rootEl, el, dragEl, dragRect, target, targetRect, evt, after);\n if (moveVector !== false) {\n if (moveVector === 1 || moveVector === -1) {\n after = moveVector === 1;\n }\n _silent = true;\n setTimeout(_unsilent, 30);\n capture();\n if (after && !nextSibling) {\n el.appendChild(dragEl);\n } else {\n target.parentNode.insertBefore(dragEl, after ? nextSibling : target);\n }\n\n // Undo chrome's scroll adjustment (has no effect on other browsers)\n if (scrolledPastTop) {\n scrollBy(scrolledPastTop, 0, scrollBefore - scrolledPastTop.scrollTop);\n }\n parentEl = dragEl.parentNode; // actualization\n\n // must be done before animation\n if (targetBeforeFirstSwap !== undefined && !isCircumstantialInvert) {\n targetMoveDistance = Math.abs(targetBeforeFirstSwap - getRect(target)[side1]);\n }\n changed();\n return completed(true);\n }\n }\n if (el.contains(dragEl)) {\n return completed(false);\n }\n }\n return false;\n },\n _ignoreWhileAnimating: null,\n _offMoveEvents: function _offMoveEvents() {\n off(document, 'mousemove', this._onTouchMove);\n off(document, 'touchmove', this._onTouchMove);\n off(document, 'pointermove', this._onTouchMove);\n off(document, 'dragover', nearestEmptyInsertDetectEvent);\n off(document, 'mousemove', nearestEmptyInsertDetectEvent);\n off(document, 'touchmove', nearestEmptyInsertDetectEvent);\n },\n _offUpEvents: function _offUpEvents() {\n var ownerDocument = this.el.ownerDocument;\n off(ownerDocument, 'mouseup', this._onDrop);\n off(ownerDocument, 'touchend', this._onDrop);\n off(ownerDocument, 'pointerup', this._onDrop);\n off(ownerDocument, 'pointercancel', this._onDrop);\n off(ownerDocument, 'touchcancel', this._onDrop);\n off(document, 'selectstart', this);\n },\n _onDrop: function _onDrop( /**Event*/evt) {\n var el = this.el,\n options = this.options;\n\n // Get the index of the dragged element within its parent\n newIndex = index(dragEl);\n newDraggableIndex = index(dragEl, options.draggable);\n pluginEvent('drop', this, {\n evt: evt\n });\n parentEl = dragEl && dragEl.parentNode;\n\n // Get again after plugin event\n newIndex = index(dragEl);\n newDraggableIndex = index(dragEl, options.draggable);\n if (Sortable.eventCanceled) {\n this._nulling();\n return;\n }\n awaitingDragStarted = false;\n isCircumstantialInvert = false;\n pastFirstInvertThresh = false;\n clearInterval(this._loopId);\n clearTimeout(this._dragStartTimer);\n _cancelNextTick(this.cloneId);\n _cancelNextTick(this._dragStartId);\n\n // Unbind events\n if (this.nativeDraggable) {\n off(document, 'drop', this);\n off(el, 'dragstart', this._onDragStart);\n }\n this._offMoveEvents();\n this._offUpEvents();\n if (Safari) {\n css(document.body, 'user-select', '');\n }\n css(dragEl, 'transform', '');\n if (evt) {\n if (moved) {\n evt.cancelable && evt.preventDefault();\n !options.dropBubble && evt.stopPropagation();\n }\n ghostEl && ghostEl.parentNode && ghostEl.parentNode.removeChild(ghostEl);\n if (rootEl === parentEl || putSortable && putSortable.lastPutMode !== 'clone') {\n // Remove clone(s)\n cloneEl && cloneEl.parentNode && cloneEl.parentNode.removeChild(cloneEl);\n }\n if (dragEl) {\n if (this.nativeDraggable) {\n off(dragEl, 'dragend', this);\n }\n _disableDraggable(dragEl);\n dragEl.style['will-change'] = '';\n\n // Remove classes\n // ghostClass is added in dragStarted\n if (moved && !awaitingDragStarted) {\n toggleClass(dragEl, putSortable ? putSortable.options.ghostClass : this.options.ghostClass, false);\n }\n toggleClass(dragEl, this.options.chosenClass, false);\n\n // Drag stop event\n _dispatchEvent({\n sortable: this,\n name: 'unchoose',\n toEl: parentEl,\n newIndex: null,\n newDraggableIndex: null,\n originalEvent: evt\n });\n if (rootEl !== parentEl) {\n if (newIndex >= 0) {\n // Add event\n _dispatchEvent({\n rootEl: parentEl,\n name: 'add',\n toEl: parentEl,\n fromEl: rootEl,\n originalEvent: evt\n });\n\n // Remove event\n _dispatchEvent({\n sortable: this,\n name: 'remove',\n toEl: parentEl,\n originalEvent: evt\n });\n\n // drag from one list and drop into another\n _dispatchEvent({\n rootEl: parentEl,\n name: 'sort',\n toEl: parentEl,\n fromEl: rootEl,\n originalEvent: evt\n });\n _dispatchEvent({\n sortable: this,\n name: 'sort',\n toEl: parentEl,\n originalEvent: evt\n });\n }\n putSortable && putSortable.save();\n } else {\n if (newIndex !== oldIndex) {\n if (newIndex >= 0) {\n // drag & drop within the same list\n _dispatchEvent({\n sortable: this,\n name: 'update',\n toEl: parentEl,\n originalEvent: evt\n });\n _dispatchEvent({\n sortable: this,\n name: 'sort',\n toEl: parentEl,\n originalEvent: evt\n });\n }\n }\n }\n if (Sortable.active) {\n /* jshint eqnull:true */\n if (newIndex == null || newIndex === -1) {\n newIndex = oldIndex;\n newDraggableIndex = oldDraggableIndex;\n }\n _dispatchEvent({\n sortable: this,\n name: 'end',\n toEl: parentEl,\n originalEvent: evt\n });\n\n // Save sorting\n this.save();\n }\n }\n }\n this._nulling();\n },\n _nulling: function _nulling() {\n pluginEvent('nulling', this);\n rootEl = dragEl = parentEl = ghostEl = nextEl = cloneEl = lastDownEl = cloneHidden = tapEvt = touchEvt = moved = newIndex = newDraggableIndex = oldIndex = oldDraggableIndex = lastTarget = lastDirection = putSortable = activeGroup = Sortable.dragged = Sortable.ghost = Sortable.clone = Sortable.active = null;\n savedInputChecked.forEach(function (el) {\n el.checked = true;\n });\n savedInputChecked.length = lastDx = lastDy = 0;\n },\n handleEvent: function handleEvent( /**Event*/evt) {\n switch (evt.type) {\n case 'drop':\n case 'dragend':\n this._onDrop(evt);\n break;\n case 'dragenter':\n case 'dragover':\n if (dragEl) {\n this._onDragOver(evt);\n _globalDragOver(evt);\n }\n break;\n case 'selectstart':\n evt.preventDefault();\n break;\n }\n },\n /**\r\n * Serializes the item into an array of string.\r\n * @returns {String[]}\r\n */\n toArray: function toArray() {\n var order = [],\n el,\n children = this.el.children,\n i = 0,\n n = children.length,\n options = this.options;\n for (; i < n; i++) {\n el = children[i];\n if (closest(el, options.draggable, this.el, false)) {\n order.push(el.getAttribute(options.dataIdAttr) || _generateId(el));\n }\n }\n return order;\n },\n /**\r\n * Sorts the elements according to the array.\r\n * @param {String[]} order order of the items\r\n */\n sort: function sort(order, useAnimation) {\n var items = {},\n rootEl = this.el;\n this.toArray().forEach(function (id, i) {\n var el = rootEl.children[i];\n if (closest(el, this.options.draggable, rootEl, false)) {\n items[id] = el;\n }\n }, this);\n useAnimation && this.captureAnimationState();\n order.forEach(function (id) {\n if (items[id]) {\n rootEl.removeChild(items[id]);\n rootEl.appendChild(items[id]);\n }\n });\n useAnimation && this.animateAll();\n },\n /**\r\n * Save the current sorting\r\n */\n save: function save() {\n var store = this.options.store;\n store && store.set && store.set(this);\n },\n /**\r\n * For each element in the set, get the first element that matches the selector by testing the element itself and traversing up through its ancestors in the DOM tree.\r\n * @param {HTMLElement} el\r\n * @param {String} [selector] default: `options.draggable`\r\n * @returns {HTMLElement|null}\r\n */\n closest: function closest$1(el, selector) {\n return closest(el, selector || this.options.draggable, this.el, false);\n },\n /**\r\n * Set/get option\r\n * @param {string} name\r\n * @param {*} [value]\r\n * @returns {*}\r\n */\n option: function option(name, value) {\n var options = this.options;\n if (value === void 0) {\n return options[name];\n } else {\n var modifiedValue = PluginManager.modifyOption(this, name, value);\n if (typeof modifiedValue !== 'undefined') {\n options[name] = modifiedValue;\n } else {\n options[name] = value;\n }\n if (name === 'group') {\n _prepareGroup(options);\n }\n }\n },\n /**\r\n * Destroy\r\n */\n destroy: function destroy() {\n pluginEvent('destroy', this);\n var el = this.el;\n el[expando] = null;\n off(el, 'mousedown', this._onTapStart);\n off(el, 'touchstart', this._onTapStart);\n off(el, 'pointerdown', this._onTapStart);\n if (this.nativeDraggable) {\n off(el, 'dragover', this);\n off(el, 'dragenter', this);\n }\n // Remove draggable attributes\n Array.prototype.forEach.call(el.querySelectorAll('[draggable]'), function (el) {\n el.removeAttribute('draggable');\n });\n this._onDrop();\n this._disableDelayedDragEvents();\n sortables.splice(sortables.indexOf(this.el), 1);\n this.el = el = null;\n },\n _hideClone: function _hideClone() {\n if (!cloneHidden) {\n pluginEvent('hideClone', this);\n if (Sortable.eventCanceled) return;\n css(cloneEl, 'display', 'none');\n if (this.options.removeCloneOnHide && cloneEl.parentNode) {\n cloneEl.parentNode.removeChild(cloneEl);\n }\n cloneHidden = true;\n }\n },\n _showClone: function _showClone(putSortable) {\n if (putSortable.lastPutMode !== 'clone') {\n this._hideClone();\n return;\n }\n if (cloneHidden) {\n pluginEvent('showClone', this);\n if (Sortable.eventCanceled) return;\n\n // show clone at dragEl or original position\n if (dragEl.parentNode == rootEl && !this.options.group.revertClone) {\n rootEl.insertBefore(cloneEl, dragEl);\n } else if (nextEl) {\n rootEl.insertBefore(cloneEl, nextEl);\n } else {\n rootEl.appendChild(cloneEl);\n }\n if (this.options.group.revertClone) {\n this.animate(dragEl, cloneEl);\n }\n css(cloneEl, 'display', '');\n cloneHidden = false;\n }\n }\n};\nfunction _globalDragOver( /**Event*/evt) {\n if (evt.dataTransfer) {\n evt.dataTransfer.dropEffect = 'move';\n }\n evt.cancelable && evt.preventDefault();\n}\nfunction _onMove(fromEl, toEl, dragEl, dragRect, targetEl, targetRect, originalEvent, willInsertAfter) {\n var evt,\n sortable = fromEl[expando],\n onMoveFn = sortable.options.onMove,\n retVal;\n // Support for new CustomEvent feature\n if (window.CustomEvent && !IE11OrLess && !Edge) {\n evt = new CustomEvent('move', {\n bubbles: true,\n cancelable: true\n });\n } else {\n evt = document.createEvent('Event');\n evt.initEvent('move', true, true);\n }\n evt.to = toEl;\n evt.from = fromEl;\n evt.dragged = dragEl;\n evt.draggedRect = dragRect;\n evt.related = targetEl || toEl;\n evt.relatedRect = targetRect || getRect(toEl);\n evt.willInsertAfter = willInsertAfter;\n evt.originalEvent = originalEvent;\n fromEl.dispatchEvent(evt);\n if (onMoveFn) {\n retVal = onMoveFn.call(sortable, evt, originalEvent);\n }\n return retVal;\n}\nfunction _disableDraggable(el) {\n el.draggable = false;\n}\nfunction _unsilent() {\n _silent = false;\n}\nfunction _ghostIsFirst(evt, vertical, sortable) {\n var firstElRect = getRect(getChild(sortable.el, 0, sortable.options, true));\n var childContainingRect = getChildContainingRectFromElement(sortable.el, sortable.options, ghostEl);\n var spacer = 10;\n return vertical ? evt.clientX < childContainingRect.left - spacer || evt.clientY < firstElRect.top && evt.clientX < firstElRect.right : evt.clientY < childContainingRect.top - spacer || evt.clientY < firstElRect.bottom && evt.clientX < firstElRect.left;\n}\nfunction _ghostIsLast(evt, vertical, sortable) {\n var lastElRect = getRect(lastChild(sortable.el, sortable.options.draggable));\n var childContainingRect = getChildContainingRectFromElement(sortable.el, sortable.options, ghostEl);\n var spacer = 10;\n return vertical ? evt.clientX > childContainingRect.right + spacer || evt.clientY > lastElRect.bottom && evt.clientX > lastElRect.left : evt.clientY > childContainingRect.bottom + spacer || evt.clientX > lastElRect.right && evt.clientY > lastElRect.top;\n}\nfunction _getSwapDirection(evt, target, targetRect, vertical, swapThreshold, invertedSwapThreshold, invertSwap, isLastTarget) {\n var mouseOnAxis = vertical ? evt.clientY : evt.clientX,\n targetLength = vertical ? targetRect.height : targetRect.width,\n targetS1 = vertical ? targetRect.top : targetRect.left,\n targetS2 = vertical ? targetRect.bottom : targetRect.right,\n invert = false;\n if (!invertSwap) {\n // Never invert or create dragEl shadow when target movemenet causes mouse to move past the end of regular swapThreshold\n if (isLastTarget && targetMoveDistance < targetLength * swapThreshold) {\n // multiplied only by swapThreshold because mouse will already be inside target by (1 - threshold) * targetLength / 2\n // check if past first invert threshold on side opposite of lastDirection\n if (!pastFirstInvertThresh && (lastDirection === 1 ? mouseOnAxis > targetS1 + targetLength * invertedSwapThreshold / 2 : mouseOnAxis < targetS2 - targetLength * invertedSwapThreshold / 2)) {\n // past first invert threshold, do not restrict inverted threshold to dragEl shadow\n pastFirstInvertThresh = true;\n }\n if (!pastFirstInvertThresh) {\n // dragEl shadow (target move distance shadow)\n if (lastDirection === 1 ? mouseOnAxis < targetS1 + targetMoveDistance // over dragEl shadow\n : mouseOnAxis > targetS2 - targetMoveDistance) {\n return -lastDirection;\n }\n } else {\n invert = true;\n }\n } else {\n // Regular\n if (mouseOnAxis > targetS1 + targetLength * (1 - swapThreshold) / 2 && mouseOnAxis < targetS2 - targetLength * (1 - swapThreshold) / 2) {\n return _getInsertDirection(target);\n }\n }\n }\n invert = invert || invertSwap;\n if (invert) {\n // Invert of regular\n if (mouseOnAxis < targetS1 + targetLength * invertedSwapThreshold / 2 || mouseOnAxis > targetS2 - targetLength * invertedSwapThreshold / 2) {\n return mouseOnAxis > targetS1 + targetLength / 2 ? 1 : -1;\n }\n }\n return 0;\n}\n\n/**\r\n * Gets the direction dragEl must be swapped relative to target in order to make it\r\n * seem that dragEl has been \"inserted\" into that element's position\r\n * @param {HTMLElement} target The target whose position dragEl is being inserted at\r\n * @return {Number} Direction dragEl must be swapped\r\n */\nfunction _getInsertDirection(target) {\n if (index(dragEl) < index(target)) {\n return 1;\n } else {\n return -1;\n }\n}\n\n/**\r\n * Generate id\r\n * @param {HTMLElement} el\r\n * @returns {String}\r\n * @private\r\n */\nfunction _generateId(el) {\n var str = el.tagName + el.className + el.src + el.href + el.textContent,\n i = str.length,\n sum = 0;\n while (i--) {\n sum += str.charCodeAt(i);\n }\n return sum.toString(36);\n}\nfunction _saveInputCheckedState(root) {\n savedInputChecked.length = 0;\n var inputs = root.getElementsByTagName('input');\n var idx = inputs.length;\n while (idx--) {\n var el = inputs[idx];\n el.checked && savedInputChecked.push(el);\n }\n}\nfunction _nextTick(fn) {\n return setTimeout(fn, 0);\n}\nfunction _cancelNextTick(id) {\n return clearTimeout(id);\n}\n\n// Fixed #973:\nif (documentExists) {\n on(document, 'touchmove', function (evt) {\n if ((Sortable.active || awaitingDragStarted) && evt.cancelable) {\n evt.preventDefault();\n }\n });\n}\n\n// Export utils\nSortable.utils = {\n on: on,\n off: off,\n css: css,\n find: find,\n is: function is(el, selector) {\n return !!closest(el, selector, el, false);\n },\n extend: extend,\n throttle: throttle,\n closest: closest,\n toggleClass: toggleClass,\n clone: clone,\n index: index,\n nextTick: _nextTick,\n cancelNextTick: _cancelNextTick,\n detectDirection: _detectDirection,\n getChild: getChild,\n expando: expando\n};\n\n/**\r\n * Get the Sortable instance of an element\r\n * @param {HTMLElement} element The element\r\n * @return {Sortable|undefined} The instance of Sortable\r\n */\nSortable.get = function (element) {\n return element[expando];\n};\n\n/**\r\n * Mount a plugin to Sortable\r\n * @param {...SortablePlugin|SortablePlugin[]} plugins Plugins being mounted\r\n */\nSortable.mount = function () {\n for (var _len = arguments.length, plugins = new Array(_len), _key = 0; _key < _len; _key++) {\n plugins[_key] = arguments[_key];\n }\n if (plugins[0].constructor === Array) plugins = plugins[0];\n plugins.forEach(function (plugin) {\n if (!plugin.prototype || !plugin.prototype.constructor) {\n throw \"Sortable: Mounted plugin must be a constructor function, not \".concat({}.toString.call(plugin));\n }\n if (plugin.utils) Sortable.utils = _objectSpread2(_objectSpread2({}, Sortable.utils), plugin.utils);\n PluginManager.mount(plugin);\n });\n};\n\n/**\r\n * Create sortable instance\r\n * @param {HTMLElement} el\r\n * @param {Object} [options]\r\n */\nSortable.create = function (el, options) {\n return new Sortable(el, options);\n};\n\n// Export\nSortable.version = version;\n\nvar autoScrolls = [],\n scrollEl,\n scrollRootEl,\n scrolling = false,\n lastAutoScrollX,\n lastAutoScrollY,\n touchEvt$1,\n pointerElemChangedInterval;\nfunction AutoScrollPlugin() {\n function AutoScroll() {\n this.defaults = {\n scroll: true,\n forceAutoScrollFallback: false,\n scrollSensitivity: 30,\n scrollSpeed: 10,\n bubbleScroll: true\n };\n\n // Bind all private methods\n for (var fn in this) {\n if (fn.charAt(0) === '_' && typeof this[fn] === 'function') {\n this[fn] = this[fn].bind(this);\n }\n }\n }\n AutoScroll.prototype = {\n dragStarted: function dragStarted(_ref) {\n var originalEvent = _ref.originalEvent;\n if (this.sortable.nativeDraggable) {\n on(document, 'dragover', this._handleAutoScroll);\n } else {\n if (this.options.supportPointer) {\n on(document, 'pointermove', this._handleFallbackAutoScroll);\n } else if (originalEvent.touches) {\n on(document, 'touchmove', this._handleFallbackAutoScroll);\n } else {\n on(document, 'mousemove', this._handleFallbackAutoScroll);\n }\n }\n },\n dragOverCompleted: function dragOverCompleted(_ref2) {\n var originalEvent = _ref2.originalEvent;\n // For when bubbling is canceled and using fallback (fallback 'touchmove' always reached)\n if (!this.options.dragOverBubble && !originalEvent.rootEl) {\n this._handleAutoScroll(originalEvent);\n }\n },\n drop: function drop() {\n if (this.sortable.nativeDraggable) {\n off(document, 'dragover', this._handleAutoScroll);\n } else {\n off(document, 'pointermove', this._handleFallbackAutoScroll);\n off(document, 'touchmove', this._handleFallbackAutoScroll);\n off(document, 'mousemove', this._handleFallbackAutoScroll);\n }\n clearPointerElemChangedInterval();\n clearAutoScrolls();\n cancelThrottle();\n },\n nulling: function nulling() {\n touchEvt$1 = scrollRootEl = scrollEl = scrolling = pointerElemChangedInterval = lastAutoScrollX = lastAutoScrollY = null;\n autoScrolls.length = 0;\n },\n _handleFallbackAutoScroll: function _handleFallbackAutoScroll(evt) {\n this._handleAutoScroll(evt, true);\n },\n _handleAutoScroll: function _handleAutoScroll(evt, fallback) {\n var _this = this;\n var x = (evt.touches ? evt.touches[0] : evt).clientX,\n y = (evt.touches ? evt.touches[0] : evt).clientY,\n elem = document.elementFromPoint(x, y);\n touchEvt$1 = evt;\n\n // IE does not seem to have native autoscroll,\n // Edge's autoscroll seems too conditional,\n // MACOS Safari does not have autoscroll,\n // Firefox and Chrome are good\n if (fallback || this.options.forceAutoScrollFallback || Edge || IE11OrLess || Safari) {\n autoScroll(evt, this.options, elem, fallback);\n\n // Listener for pointer element change\n var ogElemScroller = getParentAutoScrollElement(elem, true);\n if (scrolling && (!pointerElemChangedInterval || x !== lastAutoScrollX || y !== lastAutoScrollY)) {\n pointerElemChangedInterval && clearPointerElemChangedInterval();\n // Detect for pointer elem change, emulating native DnD behaviour\n pointerElemChangedInterval = setInterval(function () {\n var newElem = getParentAutoScrollElement(document.elementFromPoint(x, y), true);\n if (newElem !== ogElemScroller) {\n ogElemScroller = newElem;\n clearAutoScrolls();\n }\n autoScroll(evt, _this.options, newElem, fallback);\n }, 10);\n lastAutoScrollX = x;\n lastAutoScrollY = y;\n }\n } else {\n // if DnD is enabled (and browser has good autoscrolling), first autoscroll will already scroll, so get parent autoscroll of first autoscroll\n if (!this.options.bubbleScroll || getParentAutoScrollElement(elem, true) === getWindowScrollingElement()) {\n clearAutoScrolls();\n return;\n }\n autoScroll(evt, this.options, getParentAutoScrollElement(elem, false), false);\n }\n }\n };\n return _extends(AutoScroll, {\n pluginName: 'scroll',\n initializeByDefault: true\n });\n}\nfunction clearAutoScrolls() {\n autoScrolls.forEach(function (autoScroll) {\n clearInterval(autoScroll.pid);\n });\n autoScrolls = [];\n}\nfunction clearPointerElemChangedInterval() {\n clearInterval(pointerElemChangedInterval);\n}\nvar autoScroll = throttle(function (evt, options, rootEl, isFallback) {\n // Bug: https://bugzilla.mozilla.org/show_bug.cgi?id=505521\n if (!options.scroll) return;\n var x = (evt.touches ? evt.touches[0] : evt).clientX,\n y = (evt.touches ? evt.touches[0] : evt).clientY,\n sens = options.scrollSensitivity,\n speed = options.scrollSpeed,\n winScroller = getWindowScrollingElement();\n var scrollThisInstance = false,\n scrollCustomFn;\n\n // New scroll root, set scrollEl\n if (scrollRootEl !== rootEl) {\n scrollRootEl = rootEl;\n clearAutoScrolls();\n scrollEl = options.scroll;\n scrollCustomFn = options.scrollFn;\n if (scrollEl === true) {\n scrollEl = getParentAutoScrollElement(rootEl, true);\n }\n }\n var layersOut = 0;\n var currentParent = scrollEl;\n do {\n var el = currentParent,\n rect = getRect(el),\n top = rect.top,\n bottom = rect.bottom,\n left = rect.left,\n right = rect.right,\n width = rect.width,\n height = rect.height,\n canScrollX = void 0,\n canScrollY = void 0,\n scrollWidth = el.scrollWidth,\n scrollHeight = el.scrollHeight,\n elCSS = css(el),\n scrollPosX = el.scrollLeft,\n scrollPosY = el.scrollTop;\n if (el === winScroller) {\n canScrollX = width < scrollWidth && (elCSS.overflowX === 'auto' || elCSS.overflowX === 'scroll' || elCSS.overflowX === 'visible');\n canScrollY = height < scrollHeight && (elCSS.overflowY === 'auto' || elCSS.overflowY === 'scroll' || elCSS.overflowY === 'visible');\n } else {\n canScrollX = width < scrollWidth && (elCSS.overflowX === 'auto' || elCSS.overflowX === 'scroll');\n canScrollY = height < scrollHeight && (elCSS.overflowY === 'auto' || elCSS.overflowY === 'scroll');\n }\n var vx = canScrollX && (Math.abs(right - x) <= sens && scrollPosX + width < scrollWidth) - (Math.abs(left - x) <= sens && !!scrollPosX);\n var vy = canScrollY && (Math.abs(bottom - y) <= sens && scrollPosY + height < scrollHeight) - (Math.abs(top - y) <= sens && !!scrollPosY);\n if (!autoScrolls[layersOut]) {\n for (var i = 0; i <= layersOut; i++) {\n if (!autoScrolls[i]) {\n autoScrolls[i] = {};\n }\n }\n }\n if (autoScrolls[layersOut].vx != vx || autoScrolls[layersOut].vy != vy || autoScrolls[layersOut].el !== el) {\n autoScrolls[layersOut].el = el;\n autoScrolls[layersOut].vx = vx;\n autoScrolls[layersOut].vy = vy;\n clearInterval(autoScrolls[layersOut].pid);\n if (vx != 0 || vy != 0) {\n scrollThisInstance = true;\n /* jshint loopfunc:true */\n autoScrolls[layersOut].pid = setInterval(function () {\n // emulate drag over during autoscroll (fallback), emulating native DnD behaviour\n if (isFallback && this.layer === 0) {\n Sortable.active._onTouchMove(touchEvt$1); // To move ghost if it is positioned absolutely\n }\n var scrollOffsetY = autoScrolls[this.layer].vy ? autoScrolls[this.layer].vy * speed : 0;\n var scrollOffsetX = autoScrolls[this.layer].vx ? autoScrolls[this.layer].vx * speed : 0;\n if (typeof scrollCustomFn === 'function') {\n if (scrollCustomFn.call(Sortable.dragged.parentNode[expando], scrollOffsetX, scrollOffsetY, evt, touchEvt$1, autoScrolls[this.layer].el) !== 'continue') {\n return;\n }\n }\n scrollBy(autoScrolls[this.layer].el, scrollOffsetX, scrollOffsetY);\n }.bind({\n layer: layersOut\n }), 24);\n }\n }\n layersOut++;\n } while (options.bubbleScroll && currentParent !== winScroller && (currentParent = getParentAutoScrollElement(currentParent, false)));\n scrolling = scrollThisInstance; // in case another function catches scrolling as false in between when it is not\n}, 30);\n\nvar drop = function drop(_ref) {\n var originalEvent = _ref.originalEvent,\n putSortable = _ref.putSortable,\n dragEl = _ref.dragEl,\n activeSortable = _ref.activeSortable,\n dispatchSortableEvent = _ref.dispatchSortableEvent,\n hideGhostForTarget = _ref.hideGhostForTarget,\n unhideGhostForTarget = _ref.unhideGhostForTarget;\n if (!originalEvent) return;\n var toSortable = putSortable || activeSortable;\n hideGhostForTarget();\n var touch = originalEvent.changedTouches && originalEvent.changedTouches.length ? originalEvent.changedTouches[0] : originalEvent;\n var target = document.elementFromPoint(touch.clientX, touch.clientY);\n unhideGhostForTarget();\n if (toSortable && !toSortable.el.contains(target)) {\n dispatchSortableEvent('spill');\n this.onSpill({\n dragEl: dragEl,\n putSortable: putSortable\n });\n }\n};\nfunction Revert() {}\nRevert.prototype = {\n startIndex: null,\n dragStart: function dragStart(_ref2) {\n var oldDraggableIndex = _ref2.oldDraggableIndex;\n this.startIndex = oldDraggableIndex;\n },\n onSpill: function onSpill(_ref3) {\n var dragEl = _ref3.dragEl,\n putSortable = _ref3.putSortable;\n this.sortable.captureAnimationState();\n if (putSortable) {\n putSortable.captureAnimationState();\n }\n var nextSibling = getChild(this.sortable.el, this.startIndex, this.options);\n if (nextSibling) {\n this.sortable.el.insertBefore(dragEl, nextSibling);\n } else {\n this.sortable.el.appendChild(dragEl);\n }\n this.sortable.animateAll();\n if (putSortable) {\n putSortable.animateAll();\n }\n },\n drop: drop\n};\n_extends(Revert, {\n pluginName: 'revertOnSpill'\n});\nfunction Remove() {}\nRemove.prototype = {\n onSpill: function onSpill(_ref4) {\n var dragEl = _ref4.dragEl,\n putSortable = _ref4.putSortable;\n var parentSortable = putSortable || this.sortable;\n parentSortable.captureAnimationState();\n dragEl.parentNode && dragEl.parentNode.removeChild(dragEl);\n parentSortable.animateAll();\n },\n drop: drop\n};\n_extends(Remove, {\n pluginName: 'removeOnSpill'\n});\n\nvar lastSwapEl;\nfunction SwapPlugin() {\n function Swap() {\n this.defaults = {\n swapClass: 'sortable-swap-highlight'\n };\n }\n Swap.prototype = {\n dragStart: function dragStart(_ref) {\n var dragEl = _ref.dragEl;\n lastSwapEl = dragEl;\n },\n dragOverValid: function dragOverValid(_ref2) {\n var completed = _ref2.completed,\n target = _ref2.target,\n onMove = _ref2.onMove,\n activeSortable = _ref2.activeSortable,\n changed = _ref2.changed,\n cancel = _ref2.cancel;\n if (!activeSortable.options.swap) return;\n var el = this.sortable.el,\n options = this.options;\n if (target && target !== el) {\n var prevSwapEl = lastSwapEl;\n if (onMove(target) !== false) {\n toggleClass(target, options.swapClass, true);\n lastSwapEl = target;\n } else {\n lastSwapEl = null;\n }\n if (prevSwapEl && prevSwapEl !== lastSwapEl) {\n toggleClass(prevSwapEl, options.swapClass, false);\n }\n }\n changed();\n completed(true);\n cancel();\n },\n drop: function drop(_ref3) {\n var activeSortable = _ref3.activeSortable,\n putSortable = _ref3.putSortable,\n dragEl = _ref3.dragEl;\n var toSortable = putSortable || this.sortable;\n var options = this.options;\n lastSwapEl && toggleClass(lastSwapEl, options.swapClass, false);\n if (lastSwapEl && (options.swap || putSortable && putSortable.options.swap)) {\n if (dragEl !== lastSwapEl) {\n toSortable.captureAnimationState();\n if (toSortable !== activeSortable) activeSortable.captureAnimationState();\n swapNodes(dragEl, lastSwapEl);\n toSortable.animateAll();\n if (toSortable !== activeSortable) activeSortable.animateAll();\n }\n }\n },\n nulling: function nulling() {\n lastSwapEl = null;\n }\n };\n return _extends(Swap, {\n pluginName: 'swap',\n eventProperties: function eventProperties() {\n return {\n swapItem: lastSwapEl\n };\n }\n });\n}\nfunction swapNodes(n1, n2) {\n var p1 = n1.parentNode,\n p2 = n2.parentNode,\n i1,\n i2;\n if (!p1 || !p2 || p1.isEqualNode(n2) || p2.isEqualNode(n1)) return;\n i1 = index(n1);\n i2 = index(n2);\n if (p1.isEqualNode(p2) && i1 < i2) {\n i2++;\n }\n p1.insertBefore(n2, p1.children[i1]);\n p2.insertBefore(n1, p2.children[i2]);\n}\n\nvar multiDragElements = [],\n multiDragClones = [],\n lastMultiDragSelect,\n // for selection with modifier key down (SHIFT)\n multiDragSortable,\n initialFolding = false,\n // Initial multi-drag fold when drag started\n folding = false,\n // Folding any other time\n dragStarted = false,\n dragEl$1,\n clonesFromRect,\n clonesHidden;\nfunction MultiDragPlugin() {\n function MultiDrag(sortable) {\n // Bind all private methods\n for (var fn in this) {\n if (fn.charAt(0) === '_' && typeof this[fn] === 'function') {\n this[fn] = this[fn].bind(this);\n }\n }\n if (!sortable.options.avoidImplicitDeselect) {\n if (sortable.options.supportPointer) {\n on(document, 'pointerup', this._deselectMultiDrag);\n } else {\n on(document, 'mouseup', this._deselectMultiDrag);\n on(document, 'touchend', this._deselectMultiDrag);\n }\n }\n on(document, 'keydown', this._checkKeyDown);\n on(document, 'keyup', this._checkKeyUp);\n this.defaults = {\n selectedClass: 'sortable-selected',\n multiDragKey: null,\n avoidImplicitDeselect: false,\n setData: function setData(dataTransfer, dragEl) {\n var data = '';\n if (multiDragElements.length && multiDragSortable === sortable) {\n multiDragElements.forEach(function (multiDragElement, i) {\n data += (!i ? '' : ', ') + multiDragElement.textContent;\n });\n } else {\n data = dragEl.textContent;\n }\n dataTransfer.setData('Text', data);\n }\n };\n }\n MultiDrag.prototype = {\n multiDragKeyDown: false,\n isMultiDrag: false,\n delayStartGlobal: function delayStartGlobal(_ref) {\n var dragged = _ref.dragEl;\n dragEl$1 = dragged;\n },\n delayEnded: function delayEnded() {\n this.isMultiDrag = ~multiDragElements.indexOf(dragEl$1);\n },\n setupClone: function setupClone(_ref2) {\n var sortable = _ref2.sortable,\n cancel = _ref2.cancel;\n if (!this.isMultiDrag) return;\n for (var i = 0; i < multiDragElements.length; i++) {\n multiDragClones.push(clone(multiDragElements[i]));\n multiDragClones[i].sortableIndex = multiDragElements[i].sortableIndex;\n multiDragClones[i].draggable = false;\n multiDragClones[i].style['will-change'] = '';\n toggleClass(multiDragClones[i], this.options.selectedClass, false);\n multiDragElements[i] === dragEl$1 && toggleClass(multiDragClones[i], this.options.chosenClass, false);\n }\n sortable._hideClone();\n cancel();\n },\n clone: function clone(_ref3) {\n var sortable = _ref3.sortable,\n rootEl = _ref3.rootEl,\n dispatchSortableEvent = _ref3.dispatchSortableEvent,\n cancel = _ref3.cancel;\n if (!this.isMultiDrag) return;\n if (!this.options.removeCloneOnHide) {\n if (multiDragElements.length && multiDragSortable === sortable) {\n insertMultiDragClones(true, rootEl);\n dispatchSortableEvent('clone');\n cancel();\n }\n }\n },\n showClone: function showClone(_ref4) {\n var cloneNowShown = _ref4.cloneNowShown,\n rootEl = _ref4.rootEl,\n cancel = _ref4.cancel;\n if (!this.isMultiDrag) return;\n insertMultiDragClones(false, rootEl);\n multiDragClones.forEach(function (clone) {\n css(clone, 'display', '');\n });\n cloneNowShown();\n clonesHidden = false;\n cancel();\n },\n hideClone: function hideClone(_ref5) {\n var _this = this;\n var sortable = _ref5.sortable,\n cloneNowHidden = _ref5.cloneNowHidden,\n cancel = _ref5.cancel;\n if (!this.isMultiDrag) return;\n multiDragClones.forEach(function (clone) {\n css(clone, 'display', 'none');\n if (_this.options.removeCloneOnHide && clone.parentNode) {\n clone.parentNode.removeChild(clone);\n }\n });\n cloneNowHidden();\n clonesHidden = true;\n cancel();\n },\n dragStartGlobal: function dragStartGlobal(_ref6) {\n var sortable = _ref6.sortable;\n if (!this.isMultiDrag && multiDragSortable) {\n multiDragSortable.multiDrag._deselectMultiDrag();\n }\n multiDragElements.forEach(function (multiDragElement) {\n multiDragElement.sortableIndex = index(multiDragElement);\n });\n\n // Sort multi-drag elements\n multiDragElements = multiDragElements.sort(function (a, b) {\n return a.sortableIndex - b.sortableIndex;\n });\n dragStarted = true;\n },\n dragStarted: function dragStarted(_ref7) {\n var _this2 = this;\n var sortable = _ref7.sortable;\n if (!this.isMultiDrag) return;\n if (this.options.sort) {\n // Capture rects,\n // hide multi drag elements (by positioning them absolute),\n // set multi drag elements rects to dragRect,\n // show multi drag elements,\n // animate to rects,\n // unset rects & remove from DOM\n\n sortable.captureAnimationState();\n if (this.options.animation) {\n multiDragElements.forEach(function (multiDragElement) {\n if (multiDragElement === dragEl$1) return;\n css(multiDragElement, 'position', 'absolute');\n });\n var dragRect = getRect(dragEl$1, false, true, true);\n multiDragElements.forEach(function (multiDragElement) {\n if (multiDragElement === dragEl$1) return;\n setRect(multiDragElement, dragRect);\n });\n folding = true;\n initialFolding = true;\n }\n }\n sortable.animateAll(function () {\n folding = false;\n initialFolding = false;\n if (_this2.options.animation) {\n multiDragElements.forEach(function (multiDragElement) {\n unsetRect(multiDragElement);\n });\n }\n\n // Remove all auxiliary multidrag items from el, if sorting enabled\n if (_this2.options.sort) {\n removeMultiDragElements();\n }\n });\n },\n dragOver: function dragOver(_ref8) {\n var target = _ref8.target,\n completed = _ref8.completed,\n cancel = _ref8.cancel;\n if (folding && ~multiDragElements.indexOf(target)) {\n completed(false);\n cancel();\n }\n },\n revert: function revert(_ref9) {\n var fromSortable = _ref9.fromSortable,\n rootEl = _ref9.rootEl,\n sortable = _ref9.sortable,\n dragRect = _ref9.dragRect;\n if (multiDragElements.length > 1) {\n // Setup unfold animation\n multiDragElements.forEach(function (multiDragElement) {\n sortable.addAnimationState({\n target: multiDragElement,\n rect: folding ? getRect(multiDragElement) : dragRect\n });\n unsetRect(multiDragElement);\n multiDragElement.fromRect = dragRect;\n fromSortable.removeAnimationState(multiDragElement);\n });\n folding = false;\n insertMultiDragElements(!this.options.removeCloneOnHide, rootEl);\n }\n },\n dragOverCompleted: function dragOverCompleted(_ref10) {\n var sortable = _ref10.sortable,\n isOwner = _ref10.isOwner,\n insertion = _ref10.insertion,\n activeSortable = _ref10.activeSortable,\n parentEl = _ref10.parentEl,\n putSortable = _ref10.putSortable;\n var options = this.options;\n if (insertion) {\n // Clones must be hidden before folding animation to capture dragRectAbsolute properly\n if (isOwner) {\n activeSortable._hideClone();\n }\n initialFolding = false;\n // If leaving sort:false root, or already folding - Fold to new location\n if (options.animation && multiDragElements.length > 1 && (folding || !isOwner && !activeSortable.options.sort && !putSortable)) {\n // Fold: Set all multi drag elements's rects to dragEl's rect when multi-drag elements are invisible\n var dragRectAbsolute = getRect(dragEl$1, false, true, true);\n multiDragElements.forEach(function (multiDragElement) {\n if (multiDragElement === dragEl$1) return;\n setRect(multiDragElement, dragRectAbsolute);\n\n // Move element(s) to end of parentEl so that it does not interfere with multi-drag clones insertion if they are inserted\n // while folding, and so that we can capture them again because old sortable will no longer be fromSortable\n parentEl.appendChild(multiDragElement);\n });\n folding = true;\n }\n\n // Clones must be shown (and check to remove multi drags) after folding when interfering multiDragElements are moved out\n if (!isOwner) {\n // Only remove if not folding (folding will remove them anyways)\n if (!folding) {\n removeMultiDragElements();\n }\n if (multiDragElements.length > 1) {\n var clonesHiddenBefore = clonesHidden;\n activeSortable._showClone(sortable);\n\n // Unfold animation for clones if showing from hidden\n if (activeSortable.options.animation && !clonesHidden && clonesHiddenBefore) {\n multiDragClones.forEach(function (clone) {\n activeSortable.addAnimationState({\n target: clone,\n rect: clonesFromRect\n });\n clone.fromRect = clonesFromRect;\n clone.thisAnimationDuration = null;\n });\n }\n } else {\n activeSortable._showClone(sortable);\n }\n }\n }\n },\n dragOverAnimationCapture: function dragOverAnimationCapture(_ref11) {\n var dragRect = _ref11.dragRect,\n isOwner = _ref11.isOwner,\n activeSortable = _ref11.activeSortable;\n multiDragElements.forEach(function (multiDragElement) {\n multiDragElement.thisAnimationDuration = null;\n });\n if (activeSortable.options.animation && !isOwner && activeSortable.multiDrag.isMultiDrag) {\n clonesFromRect = _extends({}, dragRect);\n var dragMatrix = matrix(dragEl$1, true);\n clonesFromRect.top -= dragMatrix.f;\n clonesFromRect.left -= dragMatrix.e;\n }\n },\n dragOverAnimationComplete: function dragOverAnimationComplete() {\n if (folding) {\n folding = false;\n removeMultiDragElements();\n }\n },\n drop: function drop(_ref12) {\n var evt = _ref12.originalEvent,\n rootEl = _ref12.rootEl,\n parentEl = _ref12.parentEl,\n sortable = _ref12.sortable,\n dispatchSortableEvent = _ref12.dispatchSortableEvent,\n oldIndex = _ref12.oldIndex,\n putSortable = _ref12.putSortable;\n var toSortable = putSortable || this.sortable;\n if (!evt) return;\n var options = this.options,\n children = parentEl.children;\n\n // Multi-drag selection\n if (!dragStarted) {\n if (options.multiDragKey && !this.multiDragKeyDown) {\n this._deselectMultiDrag();\n }\n toggleClass(dragEl$1, options.selectedClass, !~multiDragElements.indexOf(dragEl$1));\n if (!~multiDragElements.indexOf(dragEl$1)) {\n multiDragElements.push(dragEl$1);\n dispatchEvent({\n sortable: sortable,\n rootEl: rootEl,\n name: 'select',\n targetEl: dragEl$1,\n originalEvent: evt\n });\n\n // Modifier activated, select from last to dragEl\n if (evt.shiftKey && lastMultiDragSelect && sortable.el.contains(lastMultiDragSelect)) {\n var lastIndex = index(lastMultiDragSelect),\n currentIndex = index(dragEl$1);\n if (~lastIndex && ~currentIndex && lastIndex !== currentIndex) {\n (function () {\n // Must include lastMultiDragSelect (select it), in case modified selection from no selection\n // (but previous selection existed)\n var n, i;\n if (currentIndex > lastIndex) {\n i = lastIndex;\n n = currentIndex;\n } else {\n i = currentIndex;\n n = lastIndex + 1;\n }\n var filter = options.filter;\n for (; i < n; i++) {\n if (~multiDragElements.indexOf(children[i])) continue;\n // Check if element is draggable\n if (!closest(children[i], options.draggable, parentEl, false)) continue;\n // Check if element is filtered\n var filtered = filter && (typeof filter === 'function' ? filter.call(sortable, evt, children[i], sortable) : filter.split(',').some(function (criteria) {\n return closest(children[i], criteria.trim(), parentEl, false);\n }));\n if (filtered) continue;\n toggleClass(children[i], options.selectedClass, true);\n multiDragElements.push(children[i]);\n dispatchEvent({\n sortable: sortable,\n rootEl: rootEl,\n name: 'select',\n targetEl: children[i],\n originalEvent: evt\n });\n }\n })();\n }\n } else {\n lastMultiDragSelect = dragEl$1;\n }\n multiDragSortable = toSortable;\n } else {\n multiDragElements.splice(multiDragElements.indexOf(dragEl$1), 1);\n lastMultiDragSelect = null;\n dispatchEvent({\n sortable: sortable,\n rootEl: rootEl,\n name: 'deselect',\n targetEl: dragEl$1,\n originalEvent: evt\n });\n }\n }\n\n // Multi-drag drop\n if (dragStarted && this.isMultiDrag) {\n folding = false;\n // Do not \"unfold\" after around dragEl if reverted\n if ((parentEl[expando].options.sort || parentEl !== rootEl) && multiDragElements.length > 1) {\n var dragRect = getRect(dragEl$1),\n multiDragIndex = index(dragEl$1, ':not(.' + this.options.selectedClass + ')');\n if (!initialFolding && options.animation) dragEl$1.thisAnimationDuration = null;\n toSortable.captureAnimationState();\n if (!initialFolding) {\n if (options.animation) {\n dragEl$1.fromRect = dragRect;\n multiDragElements.forEach(function (multiDragElement) {\n multiDragElement.thisAnimationDuration = null;\n if (multiDragElement !== dragEl$1) {\n var rect = folding ? getRect(multiDragElement) : dragRect;\n multiDragElement.fromRect = rect;\n\n // Prepare unfold animation\n toSortable.addAnimationState({\n target: multiDragElement,\n rect: rect\n });\n }\n });\n }\n\n // Multi drag elements are not necessarily removed from the DOM on drop, so to reinsert\n // properly they must all be removed\n removeMultiDragElements();\n multiDragElements.forEach(function (multiDragElement) {\n if (children[multiDragIndex]) {\n parentEl.insertBefore(multiDragElement, children[multiDragIndex]);\n } else {\n parentEl.appendChild(multiDragElement);\n }\n multiDragIndex++;\n });\n\n // If initial folding is done, the elements may have changed position because they are now\n // unfolding around dragEl, even though dragEl may not have his index changed, so update event\n // must be fired here as Sortable will not.\n if (oldIndex === index(dragEl$1)) {\n var update = false;\n multiDragElements.forEach(function (multiDragElement) {\n if (multiDragElement.sortableIndex !== index(multiDragElement)) {\n update = true;\n return;\n }\n });\n if (update) {\n dispatchSortableEvent('update');\n dispatchSortableEvent('sort');\n }\n }\n }\n\n // Must be done after capturing individual rects (scroll bar)\n multiDragElements.forEach(function (multiDragElement) {\n unsetRect(multiDragElement);\n });\n toSortable.animateAll();\n }\n multiDragSortable = toSortable;\n }\n\n // Remove clones if necessary\n if (rootEl === parentEl || putSortable && putSortable.lastPutMode !== 'clone') {\n multiDragClones.forEach(function (clone) {\n clone.parentNode && clone.parentNode.removeChild(clone);\n });\n }\n },\n nullingGlobal: function nullingGlobal() {\n this.isMultiDrag = dragStarted = false;\n multiDragClones.length = 0;\n },\n destroyGlobal: function destroyGlobal() {\n this._deselectMultiDrag();\n off(document, 'pointerup', this._deselectMultiDrag);\n off(document, 'mouseup', this._deselectMultiDrag);\n off(document, 'touchend', this._deselectMultiDrag);\n off(document, 'keydown', this._checkKeyDown);\n off(document, 'keyup', this._checkKeyUp);\n },\n _deselectMultiDrag: function _deselectMultiDrag(evt) {\n if (typeof dragStarted !== \"undefined\" && dragStarted) return;\n\n // Only deselect if selection is in this sortable\n if (multiDragSortable !== this.sortable) return;\n\n // Only deselect if target is not item in this sortable\n if (evt && closest(evt.target, this.options.draggable, this.sortable.el, false)) return;\n\n // Only deselect if left click\n if (evt && evt.button !== 0) return;\n while (multiDragElements.length) {\n var el = multiDragElements[0];\n toggleClass(el, this.options.selectedClass, false);\n multiDragElements.shift();\n dispatchEvent({\n sortable: this.sortable,\n rootEl: this.sortable.el,\n name: 'deselect',\n targetEl: el,\n originalEvent: evt\n });\n }\n },\n _checkKeyDown: function _checkKeyDown(evt) {\n if (evt.key === this.options.multiDragKey) {\n this.multiDragKeyDown = true;\n }\n },\n _checkKeyUp: function _checkKeyUp(evt) {\n if (evt.key === this.options.multiDragKey) {\n this.multiDragKeyDown = false;\n }\n }\n };\n return _extends(MultiDrag, {\n // Static methods & properties\n pluginName: 'multiDrag',\n utils: {\n /**\r\n * Selects the provided multi-drag item\r\n * @param {HTMLElement} el The element to be selected\r\n */\n select: function select(el) {\n var sortable = el.parentNode[expando];\n if (!sortable || !sortable.options.multiDrag || ~multiDragElements.indexOf(el)) return;\n if (multiDragSortable && multiDragSortable !== sortable) {\n multiDragSortable.multiDrag._deselectMultiDrag();\n multiDragSortable = sortable;\n }\n toggleClass(el, sortable.options.selectedClass, true);\n multiDragElements.push(el);\n },\n /**\r\n * Deselects the provided multi-drag item\r\n * @param {HTMLElement} el The element to be deselected\r\n */\n deselect: function deselect(el) {\n var sortable = el.parentNode[expando],\n index = multiDragElements.indexOf(el);\n if (!sortable || !sortable.options.multiDrag || !~index) return;\n toggleClass(el, sortable.options.selectedClass, false);\n multiDragElements.splice(index, 1);\n }\n },\n eventProperties: function eventProperties() {\n var _this3 = this;\n var oldIndicies = [],\n newIndicies = [];\n multiDragElements.forEach(function (multiDragElement) {\n oldIndicies.push({\n multiDragElement: multiDragElement,\n index: multiDragElement.sortableIndex\n });\n\n // multiDragElements will already be sorted if folding\n var newIndex;\n if (folding && multiDragElement !== dragEl$1) {\n newIndex = -1;\n } else if (folding) {\n newIndex = index(multiDragElement, ':not(.' + _this3.options.selectedClass + ')');\n } else {\n newIndex = index(multiDragElement);\n }\n newIndicies.push({\n multiDragElement: multiDragElement,\n index: newIndex\n });\n });\n return {\n items: _toConsumableArray(multiDragElements),\n clones: [].concat(multiDragClones),\n oldIndicies: oldIndicies,\n newIndicies: newIndicies\n };\n },\n optionListeners: {\n multiDragKey: function multiDragKey(key) {\n key = key.toLowerCase();\n if (key === 'ctrl') {\n key = 'Control';\n } else if (key.length > 1) {\n key = key.charAt(0).toUpperCase() + key.substr(1);\n }\n return key;\n }\n }\n });\n}\nfunction insertMultiDragElements(clonesInserted, rootEl) {\n multiDragElements.forEach(function (multiDragElement, i) {\n var target = rootEl.children[multiDragElement.sortableIndex + (clonesInserted ? Number(i) : 0)];\n if (target) {\n rootEl.insertBefore(multiDragElement, target);\n } else {\n rootEl.appendChild(multiDragElement);\n }\n });\n}\n\n/**\r\n * Insert multi-drag clones\r\n * @param {[Boolean]} elementsInserted Whether the multi-drag elements are inserted\r\n * @param {HTMLElement} rootEl\r\n */\nfunction insertMultiDragClones(elementsInserted, rootEl) {\n multiDragClones.forEach(function (clone, i) {\n var target = rootEl.children[clone.sortableIndex + (elementsInserted ? Number(i) : 0)];\n if (target) {\n rootEl.insertBefore(clone, target);\n } else {\n rootEl.appendChild(clone);\n }\n });\n}\nfunction removeMultiDragElements() {\n multiDragElements.forEach(function (multiDragElement) {\n if (multiDragElement === dragEl$1) return;\n multiDragElement.parentNode && multiDragElement.parentNode.removeChild(multiDragElement);\n });\n}\n\nSortable.mount(new AutoScrollPlugin());\nSortable.mount(Remove, Revert);\n\nexport default Sortable;\nexport { MultiDragPlugin as MultiDrag, Sortable, SwapPlugin as Swap };\n","export class FetchResponse {\n constructor (response) {\n this.response = response\n }\n\n get statusCode () {\n return this.response.status\n }\n\n get redirected () {\n return this.response.redirected\n }\n\n get ok () {\n return this.response.ok\n }\n\n get unauthenticated () {\n return this.statusCode === 401\n }\n\n get unprocessableEntity () {\n return this.statusCode === 422\n }\n\n get authenticationURL () {\n return this.response.headers.get('WWW-Authenticate')\n }\n\n get contentType () {\n const contentType = this.response.headers.get('Content-Type') || ''\n\n return contentType.replace(/;.*$/, '')\n }\n\n get headers () {\n return this.response.headers\n }\n\n get html () {\n if (this.contentType.match(/^(application|text)\\/(html|xhtml\\+xml)$/)) {\n return this.text\n }\n\n return Promise.reject(new Error(`Expected an HTML response but got \"${this.contentType}\" instead`))\n }\n\n get json () {\n if (this.contentType.match(/^application\\/.*json$/)) {\n return this.responseJson || (this.responseJson = this.response.json())\n }\n\n return Promise.reject(new Error(`Expected a JSON response but got \"${this.contentType}\" instead`))\n }\n\n get text () {\n return this.responseText || (this.responseText = this.response.text())\n }\n\n get isTurboStream () {\n return this.contentType.match(/^text\\/vnd\\.turbo-stream\\.html/)\n }\n\n async renderTurboStream () {\n if (this.isTurboStream) {\n if (window.Turbo) {\n await window.Turbo.renderStreamMessage(await this.text)\n } else {\n console.warn('You must set `window.Turbo = Turbo` to automatically process Turbo Stream events with request.js')\n }\n } else {\n return Promise.reject(new Error(`Expected a Turbo Stream response but got \"${this.contentType}\" instead`))\n }\n }\n}\n","export class RequestInterceptor {\n static register (interceptor) {\n this.interceptor = interceptor\n }\n\n static get () {\n return this.interceptor\n }\n\n static reset () {\n this.interceptor = undefined\n }\n}\n","export function getCookie (name) {\n const cookies = document.cookie ? document.cookie.split('; ') : []\n const prefix = `${encodeURIComponent(name)}=`\n const cookie = cookies.find(cookie => cookie.startsWith(prefix))\n\n if (cookie) {\n const value = cookie.split('=').slice(1).join('=')\n\n if (value) {\n return decodeURIComponent(value)\n }\n }\n}\n\nexport function compact (object) {\n const result = {}\n\n for (const key in object) {\n const value = object[key]\n if (value !== undefined) {\n result[key] = value\n }\n }\n\n return result\n}\n\nexport function metaContent (name) {\n const element = document.head.querySelector(`meta[name=\"${name}\"]`)\n return element && element.content\n}\n\nexport function stringEntriesFromFormData (formData) {\n return [...formData].reduce((entries, [name, value]) => {\n return entries.concat(typeof value === 'string' ? [[name, value]] : [])\n }, [])\n}\n\nexport function mergeEntries (searchParams, entries) {\n for (const [name, value] of entries) {\n if (value instanceof window.File) continue\n\n if (searchParams.has(name) && !name.includes('[]')) {\n searchParams.delete(name)\n searchParams.set(name, value)\n } else {\n searchParams.append(name, value)\n }\n }\n}\n","import { FetchResponse } from './fetch_response'\nimport { RequestInterceptor } from './request_interceptor'\nimport { getCookie, compact, metaContent, stringEntriesFromFormData, mergeEntries } from './lib/utils'\n\nexport class FetchRequest {\n constructor (method, url, options = {}) {\n this.method = method\n this.options = options\n this.originalUrl = url.toString()\n }\n\n async perform () {\n try {\n const requestInterceptor = RequestInterceptor.get()\n if (requestInterceptor) {\n await requestInterceptor(this)\n }\n } catch (error) {\n console.error(error)\n }\n\n const response = new FetchResponse(await window.fetch(this.url, this.fetchOptions))\n\n if (response.unauthenticated && response.authenticationURL) {\n return Promise.reject(window.location.href = response.authenticationURL)\n }\n\n if (response.ok && response.isTurboStream) {\n await response.renderTurboStream()\n }\n\n return response\n }\n\n addHeader (key, value) {\n const headers = this.additionalHeaders\n headers[key] = value\n this.options.headers = headers\n }\n\n sameHostname () {\n if (!this.originalUrl.startsWith('http:')) {\n return true\n }\n\n try {\n return new URL(this.originalUrl).hostname === window.location.hostname\n } catch (_) {\n return true\n }\n }\n\n get fetchOptions () {\n return {\n method: this.method.toUpperCase(),\n headers: this.headers,\n body: this.formattedBody,\n signal: this.signal,\n credentials: 'same-origin',\n redirect: this.redirect\n }\n }\n\n get headers () {\n const baseHeaders = {\n 'X-Requested-With': 'XMLHttpRequest',\n 'Content-Type': this.contentType,\n Accept: this.accept\n }\n\n if (this.sameHostname()) {\n baseHeaders['X-CSRF-Token'] = this.csrfToken\n }\n\n return compact(\n Object.assign(baseHeaders, this.additionalHeaders)\n )\n }\n\n get csrfToken () {\n return getCookie(metaContent('csrf-param')) || metaContent('csrf-token')\n }\n\n get contentType () {\n if (this.options.contentType) {\n return this.options.contentType\n } else if (this.body == null || this.body instanceof window.FormData) {\n return undefined\n } else if (this.body instanceof window.File) {\n return this.body.type\n }\n\n return 'application/json'\n }\n\n get accept () {\n switch (this.responseKind) {\n case 'html':\n return 'text/html, application/xhtml+xml'\n case 'turbo-stream':\n return 'text/vnd.turbo-stream.html, text/html, application/xhtml+xml'\n case 'json':\n return 'application/json, application/vnd.api+json'\n default:\n return '*/*'\n }\n }\n\n get body () {\n return this.options.body\n }\n\n get query () {\n const originalQuery = (this.originalUrl.split('?')[1] || '').split('#')[0]\n const params = new URLSearchParams(originalQuery)\n\n let requestQuery = this.options.query\n if (requestQuery instanceof window.FormData) {\n requestQuery = stringEntriesFromFormData(requestQuery)\n } else if (requestQuery instanceof window.URLSearchParams) {\n requestQuery = requestQuery.entries()\n } else {\n requestQuery = Object.entries(requestQuery || {})\n }\n\n mergeEntries(params, requestQuery)\n\n const query = params.toString()\n return (query.length > 0 ? `?${query}` : '')\n }\n\n get url () {\n return (this.originalUrl.split('?')[0]).split('#')[0] + this.query\n }\n\n get responseKind () {\n return this.options.responseKind || 'html'\n }\n\n get signal () {\n return this.options.signal\n }\n\n get redirect () {\n return this.options.redirect || 'follow'\n }\n\n get additionalHeaders () {\n return this.options.headers || {}\n }\n\n get formattedBody () {\n const bodyIsAString = Object.prototype.toString.call(this.body) === '[object String]'\n const contentTypeIsJson = this.headers['Content-Type'] === 'application/json'\n\n if (contentTypeIsJson && !bodyIsAString) {\n return JSON.stringify(this.body)\n }\n\n return this.body\n }\n}\n","import { FetchRequest } from './fetch_request'\n\nasync function get (url, options) {\n const request = new FetchRequest('get', url, options)\n return request.perform()\n}\n\nasync function post (url, options) {\n const request = new FetchRequest('post', url, options)\n return request.perform()\n}\n\nasync function put (url, options) {\n const request = new FetchRequest('put', url, options)\n return request.perform()\n}\n\nasync function patch (url, options) {\n const request = new FetchRequest('patch', url, options)\n return request.perform()\n}\n\nasync function destroy (url, options) {\n const request = new FetchRequest('delete', url, options)\n return request.perform()\n}\n\nexport { get, post, put, patch, destroy }\n","var __defProp = Object.defineProperty;\nvar __getOwnPropSymbols = Object.getOwnPropertySymbols;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __propIsEnum = Object.prototype.propertyIsEnumerable;\nvar __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;\nvar __spreadValues = (a, b) => {\n for (var prop in b || (b = {}))\n if (__hasOwnProp.call(b, prop))\n __defNormalProp(a, prop, b[prop]);\n if (__getOwnPropSymbols)\n for (var prop of __getOwnPropSymbols(b)) {\n if (__propIsEnum.call(b, prop))\n __defNormalProp(a, prop, b[prop]);\n }\n return a;\n};\nimport { Controller } from \"@hotwired/stimulus\";\nimport Sortable from \"sortablejs\";\nimport { patch } from \"@rails/request.js\";\nclass src_default extends Controller {\n initialize() {\n this.end = this.end.bind(this);\n }\n connect() {\n this.sortable = new Sortable(this.element, __spreadValues(__spreadValues({}, this.defaultOptions), this.options));\n }\n disconnect() {\n this.sortable.destroy();\n this.sortable = void 0;\n }\n async end({ item, newIndex }) {\n if (!item.dataset.sortableUpdateUrl)\n return;\n const param = this.resourceNameValue ? `${this.resourceNameValue}[${this.paramNameValue}]` : this.paramNameValue;\n const data = new FormData();\n data.append(param, newIndex + 1);\n await patch(item.dataset.sortableUpdateUrl, { body: data, responseKind: this.responseKindValue });\n }\n get options() {\n return {\n animation: this.animationValue || this.defaultOptions.animation || 150,\n handle: this.handleValue || this.defaultOptions.handle || void 0,\n onEnd: this.end\n };\n }\n get defaultOptions() {\n return {};\n }\n}\nsrc_default.values = {\n resourceName: String,\n paramName: {\n type: String,\n default: \"position\"\n },\n responseKind: {\n type: String,\n default: \"html\"\n },\n animation: Number,\n handle: String\n};\nexport { src_default as default };\n","/*\nUnobtrusive JavaScript\nhttps://github.com/rails/rails/blob/master/actionview/app/assets/javascripts\nReleased under the MIT license\n */;\n\n(function() {\n var context = this;\n\n (function() {\n (function() {\n this.Rails = {\n linkClickSelector: 'a[data-confirm], a[data-method], a[data-remote]:not([disabled]), a[data-disable-with], a[data-disable]',\n buttonClickSelector: {\n selector: 'button[data-remote]:not([form]), button[data-confirm]:not([form])',\n exclude: 'form button'\n },\n inputChangeSelector: 'select[data-remote], input[data-remote], textarea[data-remote]',\n formSubmitSelector: 'form',\n formInputClickSelector: 'form input[type=submit], form input[type=image], form button[type=submit], form button:not([type]), input[type=submit][form], input[type=image][form], button[type=submit][form], button[form]:not([type])',\n formDisableSelector: 'input[data-disable-with]:enabled, button[data-disable-with]:enabled, textarea[data-disable-with]:enabled, input[data-disable]:enabled, button[data-disable]:enabled, textarea[data-disable]:enabled',\n formEnableSelector: 'input[data-disable-with]:disabled, button[data-disable-with]:disabled, textarea[data-disable-with]:disabled, input[data-disable]:disabled, button[data-disable]:disabled, textarea[data-disable]:disabled',\n fileInputSelector: 'input[name][type=file]:not([disabled])',\n linkDisableSelector: 'a[data-disable-with], a[data-disable]',\n buttonDisableSelector: 'button[data-remote][data-disable-with], button[data-remote][data-disable]'\n };\n\n }).call(this);\n }).call(context);\n\n var Rails = context.Rails;\n\n (function() {\n (function() {\n var nonce;\n\n nonce = null;\n\n Rails.loadCSPNonce = function() {\n var ref;\n return nonce = (ref = document.querySelector(\"meta[name=csp-nonce]\")) != null ? ref.content : void 0;\n };\n\n Rails.cspNonce = function() {\n return nonce != null ? nonce : Rails.loadCSPNonce();\n };\n\n }).call(this);\n (function() {\n var expando, m;\n\n m = Element.prototype.matches || Element.prototype.matchesSelector || Element.prototype.mozMatchesSelector || Element.prototype.msMatchesSelector || Element.prototype.oMatchesSelector || Element.prototype.webkitMatchesSelector;\n\n Rails.matches = function(element, selector) {\n if (selector.exclude != null) {\n return m.call(element, selector.selector) && !m.call(element, selector.exclude);\n } else {\n return m.call(element, selector);\n }\n };\n\n expando = '_ujsData';\n\n Rails.getData = function(element, key) {\n var ref;\n return (ref = element[expando]) != null ? ref[key] : void 0;\n };\n\n Rails.setData = function(element, key, value) {\n if (element[expando] == null) {\n element[expando] = {};\n }\n return element[expando][key] = value;\n };\n\n Rails.$ = function(selector) {\n return Array.prototype.slice.call(document.querySelectorAll(selector));\n };\n\n }).call(this);\n (function() {\n var $, csrfParam, csrfToken;\n\n $ = Rails.$;\n\n csrfToken = Rails.csrfToken = function() {\n var meta;\n meta = document.querySelector('meta[name=csrf-token]');\n return meta && meta.content;\n };\n\n csrfParam = Rails.csrfParam = function() {\n var meta;\n meta = document.querySelector('meta[name=csrf-param]');\n return meta && meta.content;\n };\n\n Rails.CSRFProtection = function(xhr) {\n var token;\n token = csrfToken();\n if (token != null) {\n return xhr.setRequestHeader('X-CSRF-Token', token);\n }\n };\n\n Rails.refreshCSRFTokens = function() {\n var param, token;\n token = csrfToken();\n param = csrfParam();\n if ((token != null) && (param != null)) {\n return $('form input[name=\"' + param + '\"]').forEach(function(input) {\n return input.value = token;\n });\n }\n };\n\n }).call(this);\n (function() {\n var CustomEvent, fire, matches, preventDefault;\n\n matches = Rails.matches;\n\n CustomEvent = window.CustomEvent;\n\n if (typeof CustomEvent !== 'function') {\n CustomEvent = function(event, params) {\n var evt;\n evt = document.createEvent('CustomEvent');\n evt.initCustomEvent(event, params.bubbles, params.cancelable, params.detail);\n return evt;\n };\n CustomEvent.prototype = window.Event.prototype;\n preventDefault = CustomEvent.prototype.preventDefault;\n CustomEvent.prototype.preventDefault = function() {\n var result;\n result = preventDefault.call(this);\n if (this.cancelable && !this.defaultPrevented) {\n Object.defineProperty(this, 'defaultPrevented', {\n get: function() {\n return true;\n }\n });\n }\n return result;\n };\n }\n\n fire = Rails.fire = function(obj, name, data) {\n var event;\n event = new CustomEvent(name, {\n bubbles: true,\n cancelable: true,\n detail: data\n });\n obj.dispatchEvent(event);\n return !event.defaultPrevented;\n };\n\n Rails.stopEverything = function(e) {\n fire(e.target, 'ujs:everythingStopped');\n e.preventDefault();\n e.stopPropagation();\n return e.stopImmediatePropagation();\n };\n\n Rails.delegate = function(element, selector, eventType, handler) {\n return element.addEventListener(eventType, function(e) {\n var target;\n target = e.target;\n while (!(!(target instanceof Element) || matches(target, selector))) {\n target = target.parentNode;\n }\n if (target instanceof Element && handler.call(target, e) === false) {\n e.preventDefault();\n return e.stopPropagation();\n }\n });\n };\n\n }).call(this);\n (function() {\n var AcceptHeaders, CSRFProtection, createXHR, cspNonce, fire, prepareOptions, processResponse;\n\n cspNonce = Rails.cspNonce, CSRFProtection = Rails.CSRFProtection, fire = Rails.fire;\n\n AcceptHeaders = {\n '*': '*/*',\n text: 'text/plain',\n html: 'text/html',\n xml: 'application/xml, text/xml',\n json: 'application/json, text/javascript',\n script: 'text/javascript, application/javascript, application/ecmascript, application/x-ecmascript'\n };\n\n Rails.ajax = function(options) {\n var xhr;\n options = prepareOptions(options);\n xhr = createXHR(options, function() {\n var ref, response;\n response = processResponse((ref = xhr.response) != null ? ref : xhr.responseText, xhr.getResponseHeader('Content-Type'));\n if (Math.floor(xhr.status / 100) === 2) {\n if (typeof options.success === \"function\") {\n options.success(response, xhr.statusText, xhr);\n }\n } else {\n if (typeof options.error === \"function\") {\n options.error(response, xhr.statusText, xhr);\n }\n }\n return typeof options.complete === \"function\" ? options.complete(xhr, xhr.statusText) : void 0;\n });\n if ((options.beforeSend != null) && !options.beforeSend(xhr, options)) {\n return false;\n }\n if (xhr.readyState === XMLHttpRequest.OPENED) {\n return xhr.send(options.data);\n }\n };\n\n prepareOptions = function(options) {\n options.url = options.url || location.href;\n options.type = options.type.toUpperCase();\n if (options.type === 'GET' && options.data) {\n if (options.url.indexOf('?') < 0) {\n options.url += '?' + options.data;\n } else {\n options.url += '&' + options.data;\n }\n }\n if (AcceptHeaders[options.dataType] == null) {\n options.dataType = '*';\n }\n options.accept = AcceptHeaders[options.dataType];\n if (options.dataType !== '*') {\n options.accept += ', */*; q=0.01';\n }\n return options;\n };\n\n createXHR = function(options, done) {\n var xhr;\n xhr = new XMLHttpRequest();\n xhr.open(options.type, options.url, true);\n xhr.setRequestHeader('Accept', options.accept);\n if (typeof options.data === 'string') {\n xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');\n }\n if (!options.crossDomain) {\n xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');\n CSRFProtection(xhr);\n }\n xhr.withCredentials = !!options.withCredentials;\n xhr.onreadystatechange = function() {\n if (xhr.readyState === XMLHttpRequest.DONE) {\n return done(xhr);\n }\n };\n return xhr;\n };\n\n processResponse = function(response, type) {\n var parser, script;\n if (typeof response === 'string' && typeof type === 'string') {\n if (type.match(/\\bjson\\b/)) {\n try {\n response = JSON.parse(response);\n } catch (error) {}\n } else if (type.match(/\\b(?:java|ecma)script\\b/)) {\n script = document.createElement('script');\n script.setAttribute('nonce', cspNonce());\n script.text = response;\n document.head.appendChild(script).parentNode.removeChild(script);\n } else if (type.match(/\\b(xml|html|svg)\\b/)) {\n parser = new DOMParser();\n type = type.replace(/;.+/, '');\n try {\n response = parser.parseFromString(response, type);\n } catch (error) {}\n }\n }\n return response;\n };\n\n Rails.href = function(element) {\n return element.href;\n };\n\n Rails.isCrossDomain = function(url) {\n var e, originAnchor, urlAnchor;\n originAnchor = document.createElement('a');\n originAnchor.href = location.href;\n urlAnchor = document.createElement('a');\n try {\n urlAnchor.href = url;\n return !(((!urlAnchor.protocol || urlAnchor.protocol === ':') && !urlAnchor.host) || (originAnchor.protocol + '//' + originAnchor.host === urlAnchor.protocol + '//' + urlAnchor.host));\n } catch (error) {\n e = error;\n return true;\n }\n };\n\n }).call(this);\n (function() {\n var matches, toArray;\n\n matches = Rails.matches;\n\n toArray = function(e) {\n return Array.prototype.slice.call(e);\n };\n\n Rails.serializeElement = function(element, additionalParam) {\n var inputs, params;\n inputs = [element];\n if (matches(element, 'form')) {\n inputs = toArray(element.elements);\n }\n params = [];\n inputs.forEach(function(input) {\n if (!input.name || input.disabled) {\n return;\n }\n if (matches(input, 'select')) {\n return toArray(input.options).forEach(function(option) {\n if (option.selected) {\n return params.push({\n name: input.name,\n value: option.value\n });\n }\n });\n } else if (input.checked || ['radio', 'checkbox', 'submit'].indexOf(input.type) === -1) {\n return params.push({\n name: input.name,\n value: input.value\n });\n }\n });\n if (additionalParam) {\n params.push(additionalParam);\n }\n return params.map(function(param) {\n if (param.name != null) {\n return (encodeURIComponent(param.name)) + \"=\" + (encodeURIComponent(param.value));\n } else {\n return param;\n }\n }).join('&');\n };\n\n Rails.formElements = function(form, selector) {\n if (matches(form, 'form')) {\n return toArray(form.elements).filter(function(el) {\n return matches(el, selector);\n });\n } else {\n return toArray(form.querySelectorAll(selector));\n }\n };\n\n }).call(this);\n (function() {\n var allowAction, fire, stopEverything;\n\n fire = Rails.fire, stopEverything = Rails.stopEverything;\n\n Rails.handleConfirm = function(e) {\n if (!allowAction(this)) {\n return stopEverything(e);\n }\n };\n\n allowAction = function(element) {\n var answer, callback, message;\n message = element.getAttribute('data-confirm');\n if (!message) {\n return true;\n }\n answer = false;\n if (fire(element, 'confirm')) {\n try {\n answer = confirm(message);\n } catch (error) {}\n callback = fire(element, 'confirm:complete', [answer]);\n }\n return answer && callback;\n };\n\n }).call(this);\n (function() {\n var disableFormElement, disableFormElements, disableLinkElement, enableFormElement, enableFormElements, enableLinkElement, formElements, getData, matches, setData, stopEverything;\n\n matches = Rails.matches, getData = Rails.getData, setData = Rails.setData, stopEverything = Rails.stopEverything, formElements = Rails.formElements;\n\n Rails.handleDisabledElement = function(e) {\n var element;\n element = this;\n if (element.disabled) {\n return stopEverything(e);\n }\n };\n\n Rails.enableElement = function(e) {\n var element;\n element = e instanceof Event ? e.target : e;\n if (matches(element, Rails.linkDisableSelector)) {\n return enableLinkElement(element);\n } else if (matches(element, Rails.buttonDisableSelector) || matches(element, Rails.formEnableSelector)) {\n return enableFormElement(element);\n } else if (matches(element, Rails.formSubmitSelector)) {\n return enableFormElements(element);\n }\n };\n\n Rails.disableElement = function(e) {\n var element;\n element = e instanceof Event ? e.target : e;\n if (matches(element, Rails.linkDisableSelector)) {\n return disableLinkElement(element);\n } else if (matches(element, Rails.buttonDisableSelector) || matches(element, Rails.formDisableSelector)) {\n return disableFormElement(element);\n } else if (matches(element, Rails.formSubmitSelector)) {\n return disableFormElements(element);\n }\n };\n\n disableLinkElement = function(element) {\n var replacement;\n replacement = element.getAttribute('data-disable-with');\n if (replacement != null) {\n setData(element, 'ujs:enable-with', element.innerHTML);\n element.innerHTML = replacement;\n }\n element.addEventListener('click', stopEverything);\n return setData(element, 'ujs:disabled', true);\n };\n\n enableLinkElement = function(element) {\n var originalText;\n originalText = getData(element, 'ujs:enable-with');\n if (originalText != null) {\n element.innerHTML = originalText;\n setData(element, 'ujs:enable-with', null);\n }\n element.removeEventListener('click', stopEverything);\n return setData(element, 'ujs:disabled', null);\n };\n\n disableFormElements = function(form) {\n return formElements(form, Rails.formDisableSelector).forEach(disableFormElement);\n };\n\n disableFormElement = function(element) {\n var replacement;\n replacement = element.getAttribute('data-disable-with');\n if (replacement != null) {\n if (matches(element, 'button')) {\n setData(element, 'ujs:enable-with', element.innerHTML);\n element.innerHTML = replacement;\n } else {\n setData(element, 'ujs:enable-with', element.value);\n element.value = replacement;\n }\n }\n element.disabled = true;\n return setData(element, 'ujs:disabled', true);\n };\n\n enableFormElements = function(form) {\n return formElements(form, Rails.formEnableSelector).forEach(enableFormElement);\n };\n\n enableFormElement = function(element) {\n var originalText;\n originalText = getData(element, 'ujs:enable-with');\n if (originalText != null) {\n if (matches(element, 'button')) {\n element.innerHTML = originalText;\n } else {\n element.value = originalText;\n }\n setData(element, 'ujs:enable-with', null);\n }\n element.disabled = false;\n return setData(element, 'ujs:disabled', null);\n };\n\n }).call(this);\n (function() {\n var stopEverything;\n\n stopEverything = Rails.stopEverything;\n\n Rails.handleMethod = function(e) {\n var csrfParam, csrfToken, form, formContent, href, link, method;\n link = this;\n method = link.getAttribute('data-method');\n if (!method) {\n return;\n }\n href = Rails.href(link);\n csrfToken = Rails.csrfToken();\n csrfParam = Rails.csrfParam();\n form = document.createElement('form');\n formContent = \"\";\n if ((csrfParam != null) && (csrfToken != null) && !Rails.isCrossDomain(href)) {\n formContent += \"\";\n }\n formContent += '';\n form.method = 'post';\n form.action = href;\n form.target = link.target;\n form.innerHTML = formContent;\n form.style.display = 'none';\n document.body.appendChild(form);\n form.querySelector('[type=\"submit\"]').click();\n return stopEverything(e);\n };\n\n }).call(this);\n (function() {\n var ajax, fire, getData, isCrossDomain, isRemote, matches, serializeElement, setData, stopEverything,\n slice = [].slice;\n\n matches = Rails.matches, getData = Rails.getData, setData = Rails.setData, fire = Rails.fire, stopEverything = Rails.stopEverything, ajax = Rails.ajax, isCrossDomain = Rails.isCrossDomain, serializeElement = Rails.serializeElement;\n\n isRemote = function(element) {\n var value;\n value = element.getAttribute('data-remote');\n return (value != null) && value !== 'false';\n };\n\n Rails.handleRemote = function(e) {\n var button, data, dataType, element, method, url, withCredentials;\n element = this;\n if (!isRemote(element)) {\n return true;\n }\n if (!fire(element, 'ajax:before')) {\n fire(element, 'ajax:stopped');\n return false;\n }\n withCredentials = element.getAttribute('data-with-credentials');\n dataType = element.getAttribute('data-type') || 'script';\n if (matches(element, Rails.formSubmitSelector)) {\n button = getData(element, 'ujs:submit-button');\n method = getData(element, 'ujs:submit-button-formmethod') || element.method;\n url = getData(element, 'ujs:submit-button-formaction') || element.getAttribute('action') || location.href;\n if (method.toUpperCase() === 'GET') {\n url = url.replace(/\\?.*$/, '');\n }\n if (element.enctype === 'multipart/form-data') {\n data = new FormData(element);\n if (button != null) {\n data.append(button.name, button.value);\n }\n } else {\n data = serializeElement(element, button);\n }\n setData(element, 'ujs:submit-button', null);\n setData(element, 'ujs:submit-button-formmethod', null);\n setData(element, 'ujs:submit-button-formaction', null);\n } else if (matches(element, Rails.buttonClickSelector) || matches(element, Rails.inputChangeSelector)) {\n method = element.getAttribute('data-method');\n url = element.getAttribute('data-url');\n data = serializeElement(element, element.getAttribute('data-params'));\n } else {\n method = element.getAttribute('data-method');\n url = Rails.href(element);\n data = element.getAttribute('data-params');\n }\n ajax({\n type: method || 'GET',\n url: url,\n data: data,\n dataType: dataType,\n beforeSend: function(xhr, options) {\n if (fire(element, 'ajax:beforeSend', [xhr, options])) {\n return fire(element, 'ajax:send', [xhr]);\n } else {\n fire(element, 'ajax:stopped');\n return false;\n }\n },\n success: function() {\n var args;\n args = 1 <= arguments.length ? slice.call(arguments, 0) : [];\n return fire(element, 'ajax:success', args);\n },\n error: function() {\n var args;\n args = 1 <= arguments.length ? slice.call(arguments, 0) : [];\n return fire(element, 'ajax:error', args);\n },\n complete: function() {\n var args;\n args = 1 <= arguments.length ? slice.call(arguments, 0) : [];\n return fire(element, 'ajax:complete', args);\n },\n crossDomain: isCrossDomain(url),\n withCredentials: (withCredentials != null) && withCredentials !== 'false'\n });\n return stopEverything(e);\n };\n\n Rails.formSubmitButtonClick = function(e) {\n var button, form;\n button = this;\n form = button.form;\n if (!form) {\n return;\n }\n if (button.name) {\n setData(form, 'ujs:submit-button', {\n name: button.name,\n value: button.value\n });\n }\n setData(form, 'ujs:formnovalidate-button', button.formNoValidate);\n setData(form, 'ujs:submit-button-formaction', button.getAttribute('formaction'));\n return setData(form, 'ujs:submit-button-formmethod', button.getAttribute('formmethod'));\n };\n\n Rails.preventInsignificantClick = function(e) {\n var data, insignificantMetaClick, link, metaClick, method, nonPrimaryMouseClick;\n link = this;\n method = (link.getAttribute('data-method') || 'GET').toUpperCase();\n data = link.getAttribute('data-params');\n metaClick = e.metaKey || e.ctrlKey;\n insignificantMetaClick = metaClick && method === 'GET' && !data;\n nonPrimaryMouseClick = (e.button != null) && e.button !== 0;\n if (nonPrimaryMouseClick || insignificantMetaClick) {\n return e.stopImmediatePropagation();\n }\n };\n\n }).call(this);\n (function() {\n var $, CSRFProtection, delegate, disableElement, enableElement, fire, formSubmitButtonClick, getData, handleConfirm, handleDisabledElement, handleMethod, handleRemote, loadCSPNonce, preventInsignificantClick, refreshCSRFTokens;\n\n fire = Rails.fire, delegate = Rails.delegate, getData = Rails.getData, $ = Rails.$, refreshCSRFTokens = Rails.refreshCSRFTokens, CSRFProtection = Rails.CSRFProtection, loadCSPNonce = Rails.loadCSPNonce, enableElement = Rails.enableElement, disableElement = Rails.disableElement, handleDisabledElement = Rails.handleDisabledElement, handleConfirm = Rails.handleConfirm, preventInsignificantClick = Rails.preventInsignificantClick, handleRemote = Rails.handleRemote, formSubmitButtonClick = Rails.formSubmitButtonClick, handleMethod = Rails.handleMethod;\n\n if ((typeof jQuery !== \"undefined\" && jQuery !== null) && (jQuery.ajax != null)) {\n if (jQuery.rails) {\n throw new Error('If you load both jquery_ujs and rails-ujs, use rails-ujs only.');\n }\n jQuery.rails = Rails;\n jQuery.ajaxPrefilter(function(options, originalOptions, xhr) {\n if (!options.crossDomain) {\n return CSRFProtection(xhr);\n }\n });\n }\n\n Rails.start = function() {\n if (window._rails_loaded) {\n throw new Error('rails-ujs has already been loaded!');\n }\n window.addEventListener('pageshow', function() {\n $(Rails.formEnableSelector).forEach(function(el) {\n if (getData(el, 'ujs:disabled')) {\n return enableElement(el);\n }\n });\n return $(Rails.linkDisableSelector).forEach(function(el) {\n if (getData(el, 'ujs:disabled')) {\n return enableElement(el);\n }\n });\n });\n delegate(document, Rails.linkDisableSelector, 'ajax:complete', enableElement);\n delegate(document, Rails.linkDisableSelector, 'ajax:stopped', enableElement);\n delegate(document, Rails.buttonDisableSelector, 'ajax:complete', enableElement);\n delegate(document, Rails.buttonDisableSelector, 'ajax:stopped', enableElement);\n delegate(document, Rails.linkClickSelector, 'click', preventInsignificantClick);\n delegate(document, Rails.linkClickSelector, 'click', handleDisabledElement);\n delegate(document, Rails.linkClickSelector, 'click', handleConfirm);\n delegate(document, Rails.linkClickSelector, 'click', disableElement);\n delegate(document, Rails.linkClickSelector, 'click', handleRemote);\n delegate(document, Rails.linkClickSelector, 'click', handleMethod);\n delegate(document, Rails.buttonClickSelector, 'click', preventInsignificantClick);\n delegate(document, Rails.buttonClickSelector, 'click', handleDisabledElement);\n delegate(document, Rails.buttonClickSelector, 'click', handleConfirm);\n delegate(document, Rails.buttonClickSelector, 'click', disableElement);\n delegate(document, Rails.buttonClickSelector, 'click', handleRemote);\n delegate(document, Rails.inputChangeSelector, 'change', handleDisabledElement);\n delegate(document, Rails.inputChangeSelector, 'change', handleConfirm);\n delegate(document, Rails.inputChangeSelector, 'change', handleRemote);\n delegate(document, Rails.formSubmitSelector, 'submit', handleDisabledElement);\n delegate(document, Rails.formSubmitSelector, 'submit', handleConfirm);\n delegate(document, Rails.formSubmitSelector, 'submit', handleRemote);\n delegate(document, Rails.formSubmitSelector, 'submit', function(e) {\n return setTimeout((function() {\n return disableElement(e);\n }), 13);\n });\n delegate(document, Rails.formSubmitSelector, 'ajax:send', disableElement);\n delegate(document, Rails.formSubmitSelector, 'ajax:complete', enableElement);\n delegate(document, Rails.formInputClickSelector, 'click', preventInsignificantClick);\n delegate(document, Rails.formInputClickSelector, 'click', handleDisabledElement);\n delegate(document, Rails.formInputClickSelector, 'click', handleConfirm);\n delegate(document, Rails.formInputClickSelector, 'click', formSubmitButtonClick);\n document.addEventListener('DOMContentLoaded', refreshCSRFTokens);\n document.addEventListener('DOMContentLoaded', loadCSPNonce);\n return window._rails_loaded = true;\n };\n\n if (window.Rails === Rails && fire(document, 'rails:attachBindings')) {\n Rails.start();\n }\n\n }).call(this);\n }).call(this);\n\n if (typeof module === \"object\" && module.exports) {\n module.exports = Rails;\n } else if (typeof define === \"function\" && define.amd) {\n define(Rails);\n }\n}).call(this);\n","import Sortable from 'stimulus-sortable'\nimport Rails from 'rails-ujs'\n\nexport default class extends Sortable {\n static targets = ['audioCard']\n\n static values = {\n updateUrl: String\n }\n\n connect() {\n console.log(\"AudioController connected\")\n super.connect()\n }\n\n end() {\n const audioPositions = this.audioCardTargets.map((audioCard, index) => {\n let id = audioCard.dataset.audioId\n let position = index\n\n return {id: id, position: position}\n })\n\n this.persistPositions(audioPositions)\n }\n\n get defaultOptions() {\n return {\n animation: 500,\n handle: '.move-handle'\n }\n }\n\n persistPositions(positions) {\n const formData = new FormData()\n\n positions.forEach(function ({id, position}) {\n formData.append(`clips[${position}][position]`, position)\n formData.append(`clips[${position}][id]`, id)\n })\n\n Rails.ajax({\n data: formData,\n type: 'PATCH',\n url: this.updateUrlValue\n })\n }\n}\n","class t extends Date{static parseDateTime(e,s=\"YYYY-MM-DD\",n=\"en-US\"){if(!e)return new Date((new Date).setHours(0,0,0,0));if(e instanceof t)return e.toJSDate();if(e instanceof Date)return e;if(/^-?\\d{10,}$/.test(String(e)))return new Date(Number(e));if(\"string\"==typeof e){const r=[];let a=null;for(;null!=(a=t.regex.exec(s));)\"\\\\\"!==a[1]&&r.push(a);if(r.length){const s={year:null,month:null,shortMonth:null,longMonth:null,day:null,hour:0,minute:0,second:0,ampm:null,value:\"\"};r[0].index>0&&(s.value+=\".*?\");for(const[e,a]of Object.entries(r)){const r=Number(e),{group:i,pattern:h}=t.formatPatterns(a[0],n);s[i]=r+1,s.value+=h,s.value+=\".*?\"}const a=new RegExp(`^${s.value}$`);if(a.test(e)){const r=a.exec(e),i=Number(r[s.year]);let h=null;s.month?h=Number(r[s.month])-1:s.shortMonth?h=t.shortMonths(n).indexOf(r[s.shortMonth]):s.longMonth&&(h=t.longMonths(n).indexOf(r[s.longMonth]));const g=Number(r[s.day])||1,o=Number(r[s.hour]);let u=Number.isNaN(o)?0:o;const c=Number(r[s.minute]),l=Number.isNaN(c)?0:c,m=Number(r[s.second]),d=Number.isNaN(m)?0:m,M=r[s.ampm];return M&&\"PM\"===M&&(u+=12,24===u&&(u=0)),new Date(i,h,g,u,l,d,0)}}}return new Date((new Date).setHours(0,0,0,0))}static regex=/(\\\\)?(Y{2,4}|M{1,4}|D{1,2}|H{1,2}|h{1,2}|m{1,2}|s{1,2}|A|a)/g;static MONTH_JS=[0,1,2,3,4,5,6,7,8,9,10,11];static shortMonths(e){return t.MONTH_JS.map((t=>new Date(2019,t).toLocaleString(e,{month:\"short\"})))}static longMonths(e){return t.MONTH_JS.map((t=>new Date(2019,t).toLocaleString(e,{month:\"long\"})))}static formatPatterns(e,s){switch(e){case\"YY\":case\"YYYY\":return{group:\"year\",pattern:`(\\\\d{${e.length}})`};case\"M\":return{group:\"month\",pattern:\"(\\\\d{1,2})\"};case\"MM\":return{group:\"month\",pattern:\"(\\\\d{2})\"};case\"MMM\":return{group:\"shortMonth\",pattern:`(${t.shortMonths(s).join(\"|\")})`};case\"MMMM\":return{group:\"longMonth\",pattern:`(${t.longMonths(s).join(\"|\")})`};case\"D\":return{group:\"day\",pattern:\"(\\\\d{1,2})\"};case\"DD\":return{group:\"day\",pattern:\"(\\\\d{2})\"};case\"h\":case\"H\":return{group:\"hour\",pattern:\"(\\\\d{1,2})\"};case\"hh\":case\"HH\":return{group:\"hour\",pattern:\"(\\\\d{2})\"};case\"m\":return{group:\"minute\",pattern:\"(\\\\d{1,2})\"};case\"mm\":return{group:\"minute\",pattern:\"(\\\\d{2})\"};case\"s\":return{group:\"second\",pattern:\"(\\\\d{1,2})\"};case\"ss\":return{group:\"second\",pattern:\"(\\\\d{2})\"};case\"a\":case\"A\":return{group:\"ampm\",pattern:\"(AM|PM|am|pm)\"}}}lang;constructor(e=null,s=\"YYYY-MM-DD\",n=\"en-US\"){super(t.parseDateTime(e,s,n)),this.lang=n}getWeek(t){const e=new Date(this.midnight_ts(this)),s=(this.getDay()+(7-t))%7;e.setDate(e.getDate()-s);const n=e.getTime();return e.setMonth(0,1),e.getDay()!==t&&e.setMonth(0,1+(4-e.getDay()+7)%7),1+Math.ceil((n-e.getTime())/6048e5)}clone(){return new t(this)}toJSDate(){return new Date(this)}inArray(t,e=\"[]\"){return t.some((t=>t instanceof Array?this.isBetween(t[0],t[1],e):this.isSame(t,\"day\")))}isBetween(t,e,s=\"()\"){switch(s){default:case\"()\":return this.midnight_ts(this)>this.midnight_ts(t)&&this.midnight_ts(this)=this.midnight_ts(t)&&this.midnight_ts(this)this.midnight_ts(t)&&this.midnight_ts(this)<=this.midnight_ts(e);case\"[]\":return this.midnight_ts()>=this.midnight_ts(t)&&this.midnight_ts()<=this.midnight_ts(e)}}isBefore(t,e=\"days\"){switch(e){case\"day\":case\"days\":return new Date(t.getFullYear(),t.getMonth(),t.getDate()).getTime()>new Date(this.getFullYear(),this.getMonth(),this.getDate()).getTime();case\"month\":case\"months\":return new Date(t.getFullYear(),t.getMonth(),1).getTime()>new Date(this.getFullYear(),this.getMonth(),1).getTime();case\"year\":case\"years\":return t.getFullYear()>this.getFullYear()}throw new Error(\"isBefore: Invalid unit!\")}isSameOrBefore(t,e=\"days\"){switch(e){case\"day\":case\"days\":return new Date(t.getFullYear(),t.getMonth(),t.getDate()).getTime()>=new Date(this.getFullYear(),this.getMonth(),this.getDate()).getTime();case\"month\":case\"months\":return new Date(t.getFullYear(),t.getMonth(),1).getTime()>=new Date(this.getFullYear(),this.getMonth(),1).getTime()}throw new Error(\"isSameOrBefore: Invalid unit!\")}isAfter(t,e=\"days\"){switch(e){case\"day\":case\"days\":return new Date(this.getFullYear(),this.getMonth(),this.getDate()).getTime()>new Date(t.getFullYear(),t.getMonth(),t.getDate()).getTime();case\"month\":case\"months\":return new Date(this.getFullYear(),this.getMonth(),1).getTime()>new Date(t.getFullYear(),t.getMonth(),1).getTime();case\"year\":case\"years\":return this.getFullYear()>t.getFullYear()}throw new Error(\"isAfter: Invalid unit!\")}isSameOrAfter(t,e=\"days\"){switch(e){case\"day\":case\"days\":return new Date(this.getFullYear(),this.getMonth(),this.getDate()).getTime()>=new Date(t.getFullYear(),t.getMonth(),t.getDate()).getTime();case\"month\":case\"months\":return new Date(this.getFullYear(),this.getMonth(),1).getTime()>=new Date(t.getFullYear(),t.getMonth(),1).getTime()}throw new Error(\"isSameOrAfter: Invalid unit!\")}isSame(t,e=\"days\"){switch(e){case\"day\":case\"days\":return new Date(this.getFullYear(),this.getMonth(),this.getDate()).getTime()===new Date(t.getFullYear(),t.getMonth(),t.getDate()).getTime();case\"month\":case\"months\":return new Date(this.getFullYear(),this.getMonth(),1).getTime()===new Date(t.getFullYear(),t.getMonth(),1).getTime()}throw new Error(\"isSame: Invalid unit!\")}add(t,e=\"days\"){switch(e){case\"day\":case\"days\":this.setDate(this.getDate()+t);break;case\"month\":case\"months\":this.setMonth(this.getMonth()+t)}return this}subtract(t,e=\"days\"){switch(e){case\"day\":case\"days\":this.setDate(this.getDate()-t);break;case\"month\":case\"months\":this.setMonth(this.getMonth()-t)}return this}diff(t,e=\"days\"){switch(e){default:case\"day\":case\"days\":return Math.round((this.midnight_ts()-this.midnight_ts(t))/864e5);case\"month\":case\"months\":let e=12*(t.getFullYear()-this.getFullYear());return e-=t.getMonth(),e+=this.getMonth(),e}}format(e,s=\"en-US\"){let n=\"\";const r=[];let a=null;for(;null!=(a=t.regex.exec(e));)\"\\\\\"!==a[1]&&r.push(a);if(r.length){r[0].index>0&&(n+=e.substring(0,r[0].index));for(const[t,a]of Object.entries(r)){const i=Number(t);n+=this.formatTokens(a[0],s),r[i+1]&&(n+=e.substring(a.index+a[0].length,r[i+1].index)),i===r.length-1&&(n+=e.substring(a.index+a[0].length))}}return n.replace(/\\\\/g,\"\")}midnight_ts(t){return t?new Date(t.getFullYear(),t.getMonth(),t.getDate(),0,0,0,0).getTime():new Date(this.getFullYear(),this.getMonth(),this.getDate(),0,0,0,0).getTime()}formatTokens(e,s){switch(e){case\"YY\":return String(this.getFullYear()).slice(-2);case\"YYYY\":return String(this.getFullYear());case\"M\":return String(this.getMonth()+1);case\"MM\":return`0${this.getMonth()+1}`.slice(-2);case\"MMM\":return t.shortMonths(s)[this.getMonth()];case\"MMMM\":return t.longMonths(s)[this.getMonth()];case\"D\":return String(this.getDate());case\"DD\":return`0${this.getDate()}`.slice(-2);case\"H\":return String(this.getHours());case\"HH\":return`0${this.getHours()}`.slice(-2);case\"h\":return String(this.getHours()%12||12);case\"hh\":return`0${this.getHours()%12||12}`.slice(-2);case\"m\":return String(this.getMinutes());case\"mm\":return`0${this.getMinutes()}`.slice(-2);case\"s\":return String(this.getSeconds());case\"ss\":return`0${this.getSeconds()}`.slice(-2);case\"a\":return this.getHours()<12||24===this.getHours()?\"am\":\"pm\";case\"A\":return this.getHours()<12||24===this.getHours()?\"AM\":\"PM\";default:return\"\"}}}export{t as DateTime};\n","/* global window */\n/* global ga */\n/* global dataLayer */\n\nimport { Controller } from '@hotwired/stimulus';\nimport { DateTime } from '@easepick/datetime';\n\nexport default class extends Controller {\n static targets = [\"clientId\", \"form\"]\n\n static values = {\n \"artist-name\": String,\n \"email-regex\": String,\n \"categories\": String,\n translations: Object\n }\n\n connect () {\n this.setupGoogleAnalytics();\n this.setupForm();\n }\n\n setupGoogleAnalytics () {\n var self = this;\n\n this.GoogleAnalytics = {\n // Returns true if Google Analytics is loaded\n isEnabled: function() {\n return (typeof(window.ga) != \"undefined\")\n },\n\n setClientId: function() {\n // assign value to the hidden client id field to track successful booking\n // events serverside\n if(self.GoogleAnalytics.isEnabled()) {\n window.ga(self.GoogleAnalytics.updateClientIdField);\n }\n },\n\n updateClientIdField: function() {\n var trackerClients = window.ga.getAll()\n if (trackerClients) {\n var field = self.clientIdTarget\n for (var i = 0; i < trackerClients.length; i++) {\n var clientId = trackerClients[i].get('clientId')\n if (clientId && !field.val()) {\n field.val(clientId)\n clearInterval(self.GoogleAnalytics.timer)\n }\n }\n }\n },\n\n updateClientIdFieldWhenPossible: function() {\n self.GoogleAnalytics.timer = setInterval(self.GoogleAnalytics.setClientId, 250)\n }\n }\n }\n\n setupClientIdFetcher() {\n this.GoogleAnalytics.updateClientIdFieldWhenPossible()\n }\n\n setupEventlisteners () {\n var self = this;\n\n this.formTarget.addEventListener(\"ajax:beforeSend\", function(_event) {\n this.setupClientIdFetcher()\n this.formTarget.classList.add('is-submitted');\n }.bind(this))\n\n this.formTarget.addEventListener(\"ajax:success\", function(event) {\n const xhr = event.detail[2];\n\n self.element.innerHTML = xhr.responseText;\n\n if (typeof dataLayer !== 'undefined') {\n dataLayer.push({\n 'event': 'eventCreated',\n 'eventCategory': self.categoriesValue,\n 'eventArtistName': self.artistNameValue\n });\n }\n })\n\n this.formTarget.addEventListener(\"ajax:error\", function(event) {\n const xhr = event.detail[2];\n self.element.innerHTML = xhr.responseText;\n self.setupForm();\n })\n }\n\n setupValidations () {\n var self = this;\n const emailRegex = self.emailRegexValue;\n const translations = self.translationsValue;\n\n this.Validations = {\n // ValidDate not currently run - should probably be added with our datepicker controller\n validDate: function(element) {\n var chosenDate = new DateTime(element.value, \"DD-MM-YYYY\");\n\n if (!chosenDate) {\n return self.Validations.reset(element);\n }\n\n var today = new DateTime();\n\n if (chosenDate >= today) {\n self.Validations.validInput(element)\n } else {\n self.Validations.invalidInput(element, translations.invalid_date)\n }\n },\n\n validateAlwaysValid: function(element) {\n if (element.value == \"\") {\n self.Validations.reset(element);\n } else {\n self.Validations.validInput(element);\n }\n },\n\n validateContactName: function(element) {\n if (element.value != \"\") {\n self.Validations.validInput(element);\n } else {\n self.Validations.invalidInput(element, translations.invalid_contact_name)\n }\n },\n\n validateContactEmail: function(element) {\n let contactEmail = element.value.trim();\n if (self.Validations.validateEmail(contactEmail)) {\n self.Validations.validInput(element);\n } else {\n self.Validations.invalidInput(element, translations.invalid_contact_email)\n }\n },\n\n validateContactPhone: function(element) {\n if (element.intlTelInput) {\n // Use intlTelInput validations\n if (element.intlTelInput.isValidNumber()) {\n self.Validations.validInput(element);\n } else {\n self.Validations.invalidInput(element, translations.invalid_contact_phone)\n }\n } else {\n // Use the old, naive validations\n contactPhone = element.value;\n if (Validations.validatePhone(contactPhone)) {\n self.Validations.validInput(element);\n } else {\n self.Validations.invalidInput(element, translations.invalid_contact_phone)\n }\n }\n },\n\n validInput: function(element) {\n self.Validations.reset(element);\n\n const parentFormGroup = self.Validations.parents(element, '.form-group-wrapper')[0]\n parentFormGroup.classList.add('valid-input');\n },\n\n reset: function(element) {\n const parentFormGroup = self.Validations.parents(element, '.form-group-wrapper')[0]\n parentFormGroup.classList.remove(\"has-error\");\n parentFormGroup.classList.remove(\"valid-input\");\n },\n\n invalidInput: function(element, msg) {\n self.Validations.reset(element);\n\n const parentFormGroup = self.Validations.parents(element, '.form-group-wrapper')[0]\n parentFormGroup.classList.add('has-error');\n let helpBlock = parentFormGroup.querySelectorAll(':scope .help-block')[0]\n\n if (helpBlock) {\n helpBlock.remove();\n }\n\n let invalidFeedBackElement = document.createElement('span');\n invalidFeedBackElement.classList.add('help-block');\n invalidFeedBackElement.classList.add('invalid-feedback');\n invalidFeedBackElement.textContent = msg;\n\n parentFormGroup.append(invalidFeedBackElement);\n },\n\n parents (element, selector) {\n const parents = [];\n while ((element = element.parentNode) && element !== document) {\n if (!selector || element.matches(selector)) parents.push(element);\n }\n return parents;\n },\n\n validatePhone: function(number) {\n stripped_number = self.Validations.stripNumber(number);\n\n if (stripped_number.length > 0) {\n return true;\n }\n return false;\n },\n\n validateEmail: function(email) {\n var re = new RegExp(emailRegex);\n\n return re.test(email);\n },\n\n stripNumber: function(number) {\n // remove beginning and trailing whitespace\n stripped_number = number.trim();\n\n // remove whitespace from within the resulting number\n stripped_number = stripped_number.replace(/\\s+/g, '');\n\n return stripped_number;\n }\n }\n }\n\n setupForm () {\n const self = this;\n\n this.setupEventlisteners()\n this.setupClientIdFetcher()\n this.setupValidations();\n\n var validations = [\n ['[name=\"booking_event[event_date]\"]', [this.Validations.validDate], \"select\"],\n ['[name=\"booking_event[event_time]\"]', [this.Validations.validateAlwaysValid]],\n ['[name=\"booking_event[event_kind]\"]', [this.Validations.validateAlwaysValid]],\n ['[name=\"booking_event[event_location]\"]', [this.Validations.validateAlwaysValid]],\n ['[name=\"booking_event[event_size]\"]', [this.Validations.validateAlwaysValid]],\n ['[name=\"booking_event[contact_name]\"]', [this.Validations.validateContactName]],\n ['[name=\"booking_event[contact_email]\"]', [this.Validations.validateContactEmail]],\n ['[name=\"booking_event[contact_phone_number]\"]', [this.Validations.validateContactPhone]]\n ];\n\n validations.forEach(function(validationConfig) {\n var elements = self.element.querySelectorAll(validationConfig[0]);\n var validationsToAdd = validationConfig[1];\n var bindEvent = validationConfig[2] || \"change\";\n\n validationsToAdd.forEach(function(validationFunction, _index) {\n elements.forEach(function(element) {\n if (element.value) {\n validationFunction(element)\n }\n\n element.addEventListener(bindEvent, function(event) {\n validationFunction(event.target)\n })\n })\n })\n })\n }\n}\n","import { Controller } from '@hotwired/stimulus';\n\n// Toggles the checked state of elements on and off\nexport default class extends Controller {\n static targets = [\"checkbox\"]\n\n // Check all checkboxes\n check(event) {\n this.setChecked(true, event.params.tag)\n\n event.preventDefault();\n }\n\n setChecked(checked, onlyWithTag) {\n this.checkboxTargets.forEach((checkbox) => {\n const rawTaggedValue = checkbox.dataset.bulkCheckerTaggedValue\n let taggedValues = []\n if (rawTaggedValue) {\n taggedValues = JSON.parse(rawTaggedValue)\n }\n if (!onlyWithTag || taggedValues.includes(onlyWithTag)) {\n checkbox.checked = checked\n }\n })\n }\n\n toggle(event) {\n const allChecked = this.checkboxTargets.every((checkbox) => checkbox.checked)\n this.setChecked(!allChecked, event.params.tag)\n\n event.preventDefault();\n }\n\n // Uncheck all checkboxes\n uncheck(event) {\n this.setChecked(false, event.params.tag)\n\n event.preventDefault();\n }\n}\n","// @fancyapps/ui/Fancybox v4.0.31\nconst t=t=>\"object\"==typeof t&&null!==t&&t.constructor===Object&&\"[object Object]\"===Object.prototype.toString.call(t),e=(...i)=>{let s=!1;\"boolean\"==typeof i[0]&&(s=i.shift());let o=i[0];if(!o||\"object\"!=typeof o)throw new Error(\"extendee must be an object\");const n=i.slice(1),a=n.length;for(let i=0;i(t=parseFloat(t)||0,Math.round((t+Number.EPSILON)*e)/e),s=function(t){return!!(t&&\"object\"==typeof t&&t instanceof Element&&t!==document.body)&&(!t.__Panzoom&&(function(t){const e=getComputedStyle(t)[\"overflow-y\"],i=getComputedStyle(t)[\"overflow-x\"],s=(\"scroll\"===e||\"auto\"===e)&&Math.abs(t.scrollHeight-t.clientHeight)>1,o=(\"scroll\"===i||\"auto\"===i)&&Math.abs(t.scrollWidth-t.clientWidth)>1;return s||o}(t)?t:s(t.parentNode)))},o=\"undefined\"!=typeof window&&window.ResizeObserver||class{constructor(t){this.observables=[],this.boundCheck=this.check.bind(this),this.boundCheck(),this.callback=t}observe(t){if(this.observables.some((e=>e.el===t)))return;const e={el:t,size:{height:t.clientHeight,width:t.clientWidth}};this.observables.push(e)}unobserve(t){this.observables=this.observables.filter((e=>e.el!==t))}disconnect(){this.observables=[]}check(){const t=this.observables.filter((t=>{const e=t.el.clientHeight,i=t.el.clientWidth;if(t.size.height!==e||t.size.width!==i)return t.size.height=e,t.size.width=i,!0})).map((t=>t.el));t.length>0&&this.callback(t),window.requestAnimationFrame(this.boundCheck)}};class n{constructor(t){this.id=self.Touch&&t instanceof Touch?t.identifier:-1,this.pageX=t.pageX,this.pageY=t.pageY,this.clientX=t.clientX,this.clientY=t.clientY}}const a=(t,e)=>e?Math.sqrt((e.clientX-t.clientX)**2+(e.clientY-t.clientY)**2):0,r=(t,e)=>e?{clientX:(t.clientX+e.clientX)/2,clientY:(t.clientY+e.clientY)/2}:t;class h{constructor(t,{start:e=(()=>!0),move:i=(()=>{}),end:s=(()=>{})}={}){this._element=t,this.startPointers=[],this.currentPointers=[],this._pointerStart=t=>{if(t.buttons>0&&0!==t.button)return;const e=new n(t);this.currentPointers.some((t=>t.id===e.id))||this._triggerPointerStart(e,t)&&(window.addEventListener(\"mousemove\",this._move),window.addEventListener(\"mouseup\",this._pointerEnd))},this._touchStart=t=>{for(const e of Array.from(t.changedTouches||[]))this._triggerPointerStart(new n(e),t)},this._move=t=>{const e=this.currentPointers.slice(),i=(t=>\"changedTouches\"in t)(t)?Array.from(t.changedTouches).map((t=>new n(t))):[new n(t)];for(const t of i){const e=this.currentPointers.findIndex((e=>e.id===t.id));e<0||(this.currentPointers[e]=t)}this._moveCallback(e,this.currentPointers.slice(),t)},this._triggerPointerEnd=(t,e)=>{const i=this.currentPointers.findIndex((e=>e.id===t.id));return!(i<0)&&(this.currentPointers.splice(i,1),this.startPointers.splice(i,1),this._endCallback(t,e),!0)},this._pointerEnd=t=>{t.buttons>0&&0!==t.button||this._triggerPointerEnd(new n(t),t)&&(window.removeEventListener(\"mousemove\",this._move,{passive:!1}),window.removeEventListener(\"mouseup\",this._pointerEnd,{passive:!1}))},this._touchEnd=t=>{for(const e of Array.from(t.changedTouches||[]))this._triggerPointerEnd(new n(e),t)},this._startCallback=e,this._moveCallback=i,this._endCallback=s,this._element.addEventListener(\"mousedown\",this._pointerStart,{passive:!1}),this._element.addEventListener(\"touchstart\",this._touchStart,{passive:!1}),this._element.addEventListener(\"touchmove\",this._move,{passive:!1}),this._element.addEventListener(\"touchend\",this._touchEnd),this._element.addEventListener(\"touchcancel\",this._touchEnd)}stop(){this._element.removeEventListener(\"mousedown\",this._pointerStart,{passive:!1}),this._element.removeEventListener(\"touchstart\",this._touchStart,{passive:!1}),this._element.removeEventListener(\"touchmove\",this._move,{passive:!1}),this._element.removeEventListener(\"touchend\",this._touchEnd),this._element.removeEventListener(\"touchcancel\",this._touchEnd),window.removeEventListener(\"mousemove\",this._move),window.removeEventListener(\"mouseup\",this._pointerEnd)}_triggerPointerStart(t,e){return!!this._startCallback(t,e)&&(this.currentPointers.push(t),this.startPointers.push(t),!0)}}class l{constructor(t={}){this.options=e(!0,{},t),this.plugins=[],this.events={};for(const t of[\"on\",\"once\"])for(const e of Object.entries(this.options[t]||{}))this[t](...e)}option(t,e,...i){t=String(t);let s=(o=t,n=this.options,o.split(\".\").reduce((function(t,e){return t&&t[e]}),n));var o,n;return\"function\"==typeof s&&(s=s.call(this,this,...i)),void 0===s?e:s}localize(t,e=[]){return t=(t=String(t).replace(/\\{\\{(\\w+).?(\\w+)?\\}\\}/g,((t,i,s)=>{let o=\"\";s?o=this.option(`${i[0]+i.toLowerCase().substring(1)}.l10n.${s}`):i&&(o=this.option(`l10n.${i}`)),o||(o=t);for(let t=0;te))}on(e,i){if(t(e)){for(const t of Object.entries(e))this.on(...t);return this}return String(e).split(\" \").forEach((t=>{const e=this.events[t]=this.events[t]||[];-1==e.indexOf(i)&&e.push(i)})),this}once(e,i){if(t(e)){for(const t of Object.entries(e))this.once(...t);return this}return String(e).split(\" \").forEach((t=>{const e=(...s)=>{this.off(t,e),i.call(this,this,...s)};e._=i,this.on(t,e)})),this}off(e,i){if(!t(e))return e.split(\" \").forEach((t=>{const e=this.events[t];if(!e||!e.length)return this;let s=-1;for(let t=0,o=e.length;t1||Math.abs(e.left-this.dragStart.rect.left)>1))return t.preventDefault(),void t.stopPropagation();!1!==this.trigger(\"click\",t)&&this.option(\"zoom\")&&\"toggleZoom\"===this.option(\"click\")&&(t.preventDefault(),t.stopPropagation(),this.zoomWithClick(t))}onWheel(t){!1!==this.trigger(\"wheel\",t)&&this.option(\"zoom\")&&this.option(\"wheel\")&&this.zoomWithWheel(t)}zoomWithWheel(t){void 0===this.changedDelta&&(this.changedDelta=0);const e=Math.max(-1,Math.min(1,-t.deltaY||-t.deltaX||t.wheelDelta||-t.detail)),i=this.content.scale;let s=i*(100+e*this.option(\"wheelFactor\"))/100;if(e<0&&Math.abs(i-this.option(\"minScale\"))<.01||e>0&&Math.abs(i-this.option(\"maxScale\"))<.01?(this.changedDelta+=Math.abs(e),s=i):(this.changedDelta=0,s=Math.max(Math.min(s,this.option(\"maxScale\")),this.option(\"minScale\"))),this.changedDelta>this.option(\"wheelLimit\"))return;if(t.preventDefault(),s===i)return;const o=this.$content.getBoundingClientRect(),n=t.clientX-o.left,a=t.clientY-o.top;this.zoomTo(s,{x:n,y:a})}zoomWithClick(t){const e=this.$content.getClientRects()[0],i=t.clientX-e.left,s=t.clientY-e.top;this.toggleZoom({x:i,y:s})}attachEvents(){this.$content.addEventListener(\"load\",this.onLoad),this.$container.addEventListener(\"wheel\",this.onWheel,{passive:!1}),this.$container.addEventListener(\"click\",this.onClick,{passive:!1}),this.initObserver();const t=new h(this.$container,{start:(e,i)=>{if(!this.option(\"touch\"))return!1;if(this.velocity.scale<0)return!1;const o=i.composedPath()[0];if(!t.currentPointers.length){if(-1!==[\"BUTTON\",\"TEXTAREA\",\"OPTION\",\"INPUT\",\"SELECT\",\"VIDEO\"].indexOf(o.nodeName))return!1;if(this.option(\"textSelection\")&&((t,e,i)=>{const s=t.childNodes,o=document.createRange();for(let t=0;t=a.left&&i>=a.top&&e<=a.right&&i<=a.bottom)return n}return!1})(o,e.clientX,e.clientY))return!1}return!s(o)&&(!1!==this.trigger(\"touchStart\",i)&&(\"mousedown\"===i.type&&i.preventDefault(),this.state=\"pointerdown\",this.resetDragPosition(),this.dragPosition.midPoint=null,this.dragPosition.time=Date.now(),!0))},move:(e,i,s)=>{if(\"pointerdown\"!==this.state)return;if(!1===this.trigger(\"touchMove\",s))return void s.preventDefault();if(i.length<2&&!0===this.option(\"panOnlyZoomed\")&&this.content.width<=this.viewport.width&&this.content.height<=this.viewport.height&&this.transform.scale<=this.option(\"baseScale\"))return;if(i.length>1&&(!this.option(\"zoom\")||!1===this.option(\"pinchToZoom\")))return;const o=r(e[0],e[1]),n=r(i[0],i[1]),h=n.clientX-o.clientX,l=n.clientY-o.clientY,c=a(e[0],e[1]),d=a(i[0],i[1]),u=c&&d?d/c:1;this.dragOffset.x+=h,this.dragOffset.y+=l,this.dragOffset.scale*=u,this.dragOffset.time=Date.now()-this.dragPosition.time;const f=1===this.dragStart.scale&&this.option(\"lockAxis\");if(f&&!this.lockAxis){if(Math.abs(this.dragOffset.x)<6&&Math.abs(this.dragOffset.y)<6)return void s.preventDefault();const t=Math.abs(180*Math.atan2(this.dragOffset.y,this.dragOffset.x)/Math.PI);this.lockAxis=t>45&&t<135?\"y\":\"x\"}if(\"xy\"===f||\"y\"!==this.lockAxis){if(s.preventDefault(),s.stopPropagation(),s.stopImmediatePropagation(),this.lockAxis&&(this.dragOffset[\"x\"===this.lockAxis?\"y\":\"x\"]=0),this.$container.classList.add(this.option(\"draggingClass\")),this.transform.scale===this.option(\"baseScale\")&&\"y\"===this.lockAxis||(this.dragPosition.x=this.dragStart.x+this.dragOffset.x),this.transform.scale===this.option(\"baseScale\")&&\"x\"===this.lockAxis||(this.dragPosition.y=this.dragStart.y+this.dragOffset.y),this.dragPosition.scale=this.dragStart.scale*this.dragOffset.scale,i.length>1){const e=r(t.startPointers[0],t.startPointers[1]),i=e.clientX-this.dragStart.rect.x,s=e.clientY-this.dragStart.rect.y,{deltaX:o,deltaY:a}=this.getZoomDelta(this.content.scale*this.dragOffset.scale,i,s);this.dragPosition.x-=o,this.dragPosition.y-=a,this.dragPosition.midPoint=n}else this.setDragResistance();this.transform={x:this.dragPosition.x,y:this.dragPosition.y,scale:this.dragPosition.scale},this.startAnimation()}},end:(e,i)=>{if(\"pointerdown\"!==this.state)return;if(this._dragOffset={...this.dragOffset},t.currentPointers.length)return void this.resetDragPosition();if(this.state=\"decel\",this.friction=this.option(\"decelFriction\"),this.recalculateTransform(),this.$container.classList.remove(this.option(\"draggingClass\")),!1===this.trigger(\"touchEnd\",i))return;if(\"decel\"!==this.state)return;const s=this.option(\"minScale\");if(this.transform.scale.01){const t=this.dragPosition.midPoint||e,i=this.$content.getClientRects()[0];this.zoomTo(o,{friction:.64,x:t.clientX-i.left,y:t.clientY-i.top})}else;}});this.pointerTracker=t}initObserver(){this.resizeObserver||(this.resizeObserver=new o((()=>{this.updateTimer||(this.updateTimer=setTimeout((()=>{const t=this.$container.getBoundingClientRect();t.width&&t.height?((Math.abs(t.width-this.container.width)>1||Math.abs(t.height-this.container.height)>1)&&(this.isAnimating()&&this.endAnimation(!0),this.updateMetrics(),this.panTo({x:this.content.x,y:this.content.y,scale:this.option(\"baseScale\"),friction:0})),this.updateTimer=null):this.updateTimer=null}),this.updateRate))})),this.resizeObserver.observe(this.$container))}resetDragPosition(){this.lockAxis=null,this.friction=this.option(\"friction\"),this.velocity={x:0,y:0,scale:0};const{x:t,y:e,scale:i}=this.content;this.dragStart={rect:this.$content.getBoundingClientRect(),x:t,y:e,scale:i},this.dragPosition={...this.dragPosition,x:t,y:e,scale:i},this.dragOffset={x:0,y:0,scale:1,time:0}}updateMetrics(t){!0!==t&&this.trigger(\"beforeUpdate\");const e=this.$container,s=this.$content,o=this.$viewport,n=s instanceof HTMLImageElement,a=this.option(\"zoom\"),r=this.option(\"resizeParent\",a);let h=this.option(\"width\"),l=this.option(\"height\"),c=h||(d=s,Math.max(parseFloat(d.naturalWidth||0),parseFloat(d.width&&d.width.baseVal&&d.width.baseVal.value||0),parseFloat(d.offsetWidth||0),parseFloat(d.scrollWidth||0)));var d;let u=l||(t=>Math.max(parseFloat(t.naturalHeight||0),parseFloat(t.height&&t.height.baseVal&&t.height.baseVal.value||0),parseFloat(t.offsetHeight||0),parseFloat(t.scrollHeight||0)))(s);Object.assign(s.style,{width:h?`${h}px`:\"\",height:l?`${l}px`:\"\",maxWidth:\"\",maxHeight:\"\"}),r&&Object.assign(o.style,{width:\"\",height:\"\"});const f=this.option(\"ratio\");c=i(c*f),u=i(u*f),h=c,l=u;const g=s.getBoundingClientRect(),p=o.getBoundingClientRect(),m=o==e?p:e.getBoundingClientRect();let y=Math.max(o.offsetWidth,i(p.width)),v=Math.max(o.offsetHeight,i(p.height)),b=window.getComputedStyle(o);if(y-=parseFloat(b.paddingLeft)+parseFloat(b.paddingRight),v-=parseFloat(b.paddingTop)+parseFloat(b.paddingBottom),this.viewport.width=y,this.viewport.height=v,a){if(Math.abs(c-g.width)>.1||Math.abs(u-g.height)>.1){const t=((t,e,i,s)=>{const o=Math.min(i/t||0,s/e);return{width:t*o||0,height:e*o||0}})(c,u,Math.min(c,g.width),Math.min(u,g.height));h=i(t.width),l=i(t.height)}Object.assign(s.style,{width:`${h}px`,height:`${l}px`,transform:\"\"})}if(r&&(Object.assign(o.style,{width:`${h}px`,height:`${l}px`}),this.viewport={...this.viewport,width:h,height:l}),n&&a&&\"function\"!=typeof this.options.maxScale){const t=this.option(\"maxScale\");this.options.maxScale=function(){return this.content.origWidth>0&&this.content.fitWidth>0?this.content.origWidth/this.content.fitWidth:t}}this.content={...this.content,origWidth:c,origHeight:u,fitWidth:h,fitHeight:l,width:h,height:l,scale:1,isZoomable:a},this.container={width:m.width,height:m.height},!0!==t&&this.trigger(\"afterUpdate\")}zoomIn(t){this.zoomTo(this.content.scale+(t||this.option(\"step\")))}zoomOut(t){this.zoomTo(this.content.scale-(t||this.option(\"step\")))}toggleZoom(t={}){const e=this.option(\"maxScale\"),i=this.option(\"baseScale\"),s=this.content.scale>i+.5*(e-i)?i:e;this.zoomTo(s,t)}zoomTo(t=this.option(\"baseScale\"),{x:e=null,y:s=null}={}){t=Math.max(Math.min(t,this.option(\"maxScale\")),this.option(\"minScale\"));const o=i(this.content.scale/(this.content.width/this.content.fitWidth),1e7);null===e&&(e=this.content.width*o*.5),null===s&&(s=this.content.height*o*.5);const{deltaX:n,deltaY:a}=this.getZoomDelta(t,e,s);e=this.content.x-n,s=this.content.y-a,this.panTo({x:e,y:s,scale:t,friction:this.option(\"zoomFriction\")})}getZoomDelta(t,e=0,i=0){const s=this.content.fitWidth*this.content.scale,o=this.content.fitHeight*this.content.scale,n=e>0&&s?e/s:0,a=i>0&&o?i/o:0;return{deltaX:(this.content.fitWidth*t-s)*n,deltaY:(this.content.fitHeight*t-o)*a}}panTo({x:t=this.content.x,y:e=this.content.y,scale:i,friction:s=this.option(\"friction\"),ignoreBounds:o=!1}={}){if(i=i||this.content.scale||1,!o){const{boundX:s,boundY:o}=this.getBounds(i);s&&(t=Math.max(Math.min(t,s.to),s.from)),o&&(e=Math.max(Math.min(e,o.to),o.from))}this.friction=s,this.transform={...this.transform,x:t,y:e,scale:i},s?(this.state=\"panning\",this.velocity={x:(1/this.friction-1)*(t-this.content.x),y:(1/this.friction-1)*(e-this.content.y),scale:(1/this.friction-1)*(i-this.content.scale)},this.startAnimation()):this.endAnimation()}startAnimation(){this.rAF?cancelAnimationFrame(this.rAF):this.trigger(\"startAnimation\"),this.rAF=requestAnimationFrame((()=>this.animate()))}animate(){if(this.setEdgeForce(),this.setDragForce(),this.velocity.x*=this.friction,this.velocity.y*=this.friction,this.velocity.scale*=this.friction,this.content.x+=this.velocity.x,this.content.y+=this.velocity.y,this.content.scale+=this.velocity.scale,this.isAnimating())this.setTransform();else if(\"pointerdown\"!==this.state)return void this.endAnimation();this.rAF=requestAnimationFrame((()=>this.animate()))}getBounds(t){let e=this.boundX,s=this.boundY;if(void 0!==e&&void 0!==s)return{boundX:e,boundY:s};e={from:0,to:0},s={from:0,to:0},t=t||this.transform.scale;const o=this.content.fitWidth*t,n=this.content.fitHeight*t,a=this.viewport.width,r=this.viewport.height;if(oe.to),i&&(n=this.content.yi.to),s||o){let i=((s?e.from:e.to)-this.content.x)*t;const o=this.content.x+(this.velocity.x+i)/this.friction;o>=e.from&&o<=e.to&&(i+=this.velocity.x),this.velocity.x=i,this.recalculateTransform()}if(n||a){let e=((n?i.from:i.to)-this.content.y)*t;const s=this.content.y+(e+this.velocity.y)/this.friction;s>=i.from&&s<=i.to&&(e+=this.velocity.y),this.velocity.y=e,this.recalculateTransform()}}setDragResistance(){if(\"pointerdown\"!==this.state)return;const{boundX:t,boundY:e}=this.getBounds(this.dragPosition.scale);let i,s,o,n;if(t&&(i=this.dragPosition.xt.to),e&&(o=this.dragPosition.ye.to),(i||s)&&(!i||!s)){const e=i?t.from:t.to,s=e-this.dragPosition.x;this.dragPosition.x=e-.3*s}if((o||n)&&(!o||!n)){const t=o?e.from:e.to,i=t-this.dragPosition.y;this.dragPosition.y=t-.3*i}}setDragForce(){\"pointerdown\"===this.state&&(this.velocity.x=this.dragPosition.x-this.content.x,this.velocity.y=this.dragPosition.y-this.content.y,this.velocity.scale=this.dragPosition.scale-this.content.scale)}recalculateTransform(){this.transform.x=this.content.x+this.velocity.x/(1/this.friction-1),this.transform.y=this.content.y+this.velocity.y/(1/this.friction-1),this.transform.scale=this.content.scale+this.velocity.scale/(1/this.friction-1)}isAnimating(){return!(!this.friction||!(Math.abs(this.velocity.x)>.05||Math.abs(this.velocity.y)>.05||Math.abs(this.velocity.scale)>.05))}setTransform(t){let e,s,o;if(t?(e=i(this.transform.x),s=i(this.transform.y),o=this.transform.scale,this.content={...this.content,x:e,y:s,scale:o}):(e=i(this.content.x),s=i(this.content.y),o=this.content.scale/(this.content.width/this.content.fitWidth),this.content={...this.content,x:e,y:s}),this.trigger(\"beforeTransform\"),e=i(this.content.x),s=i(this.content.y),t&&this.option(\"zoom\")){let t,n;t=i(this.content.fitWidth*o),n=i(this.content.fitHeight*o),this.content.width=t,this.content.height=n,this.transform={...this.transform,width:t,height:n,scale:o},Object.assign(this.$content.style,{width:`${t}px`,height:`${n}px`,maxWidth:\"none\",maxHeight:\"none\",transform:`translate3d(${e}px, ${s}px, 0) scale(1)`})}else this.$content.style.transform=`translate3d(${e}px, ${s}px, 0) scale(${o})`;this.trigger(\"afterTransform\")}endAnimation(t){cancelAnimationFrame(this.rAF),this.rAF=null,this.velocity={x:0,y:0,scale:0},this.setTransform(!0),this.state=\"ready\",this.handleCursor(),!0!==t&&this.trigger(\"endAnimation\")}handleCursor(){const t=this.option(\"draggableClass\");t&&this.option(\"touch\")&&(1==this.option(\"panOnlyZoomed\")&&this.content.width<=this.viewport.width&&this.content.height<=this.viewport.height&&this.transform.scale<=this.option(\"baseScale\")?this.$container.classList.remove(t):this.$container.classList.add(t))}detachEvents(){this.$content.removeEventListener(\"load\",this.onLoad),this.$container.removeEventListener(\"wheel\",this.onWheel,{passive:!1}),this.$container.removeEventListener(\"click\",this.onClick,{passive:!1}),this.pointerTracker&&(this.pointerTracker.stop(),this.pointerTracker=null),this.resizeObserver&&(this.resizeObserver.disconnect(),this.resizeObserver=null)}destroy(){\"destroy\"!==this.state&&(this.state=\"destroy\",clearTimeout(this.updateTimer),this.updateTimer=null,cancelAnimationFrame(this.rAF),this.rAF=null,this.detachEvents(),this.detachPlugins(),this.resetDragPosition())}}d.version=\"4.0.31\",d.Plugins={};const u=(t,e)=>{let i=0;return function(...s){const o=(new Date).getTime();if(!(o-i{e.preventDefault(),e.stopPropagation(),this.carousel[\"slide\"+(\"next\"===t?\"Next\":\"Prev\")]()})),e}build(){this.$container||(this.$container=document.createElement(\"div\"),this.$container.classList.add(...this.option(\"classNames.main\").split(\" \")),this.carousel.$container.appendChild(this.$container)),this.$next||(this.$next=this.createButton(\"next\"),this.$container.appendChild(this.$next)),this.$prev||(this.$prev=this.createButton(\"prev\"),this.$container.appendChild(this.$prev))}onRefresh(){const t=this.carousel.pages.length;t<=1||t>1&&this.carousel.elemDimWidth=t-1&&this.$next.setAttribute(\"disabled\",\"\")))}cleanup(){this.$prev&&this.$prev.remove(),this.$prev=null,this.$next&&this.$next.remove(),this.$next=null,this.$container&&this.$container.remove(),this.$container=null}attach(){this.carousel.on(\"refresh change\",this.onRefresh)}detach(){this.carousel.off(\"refresh change\",this.onRefresh),this.cleanup()}}f.defaults={prevTpl:'',nextTpl:'',classNames:{main:\"carousel__nav\",button:\"carousel__button\",next:\"is-next\",prev:\"is-prev\"}};class g{constructor(t){this.carousel=t,this.selectedIndex=null,this.friction=0,this.onNavReady=this.onNavReady.bind(this),this.onNavClick=this.onNavClick.bind(this),this.onNavCreateSlide=this.onNavCreateSlide.bind(this),this.onTargetChange=this.onTargetChange.bind(this)}addAsTargetFor(t){this.target=this.carousel,this.nav=t,this.attachEvents()}addAsNavFor(t){this.target=t,this.nav=this.carousel,this.attachEvents()}attachEvents(){this.nav.options.initialSlide=this.target.options.initialPage,this.nav.on(\"ready\",this.onNavReady),this.nav.on(\"createSlide\",this.onNavCreateSlide),this.nav.on(\"Panzoom.click\",this.onNavClick),this.target.on(\"change\",this.onTargetChange),this.target.on(\"Panzoom.afterUpdate\",this.onTargetChange)}onNavReady(){this.onTargetChange(!0)}onNavClick(t,e,i){const s=i.target.closest(\".carousel__slide\");if(!s)return;i.stopPropagation();const o=parseInt(s.dataset.index,10),n=this.target.findPageForSlide(o);this.target.page!==n&&this.target.slideTo(n,{friction:this.friction}),this.markSelectedSlide(o)}onNavCreateSlide(t,e){e.index===this.selectedIndex&&this.markSelectedSlide(e.index)}onTargetChange(){const t=this.target.pages[this.target.page].indexes[0],e=this.nav.findPageForSlide(t);this.nav.slideTo(e),this.markSelectedSlide(t)}markSelectedSlide(t){this.selectedIndex=t,[...this.nav.slides].filter((t=>t.$el&&t.$el.classList.remove(\"is-nav-selected\")));const e=this.nav.slides[t];e&&e.$el&&e.$el.classList.add(\"is-nav-selected\")}attach(t){const e=t.options.Sync;(e.target||e.nav)&&(e.target?this.addAsNavFor(e.target):e.nav&&this.addAsTargetFor(e.nav),this.friction=e.friction)}detach(){this.nav&&(this.nav.off(\"ready\",this.onNavReady),this.nav.off(\"Panzoom.click\",this.onNavClick),this.nav.off(\"createSlide\",this.onNavCreateSlide)),this.target&&(this.target.off(\"Panzoom.afterUpdate\",this.onTargetChange),this.target.off(\"change\",this.onTargetChange))}}g.defaults={friction:.92};const p={Navigation:f,Dots:class{constructor(t){this.carousel=t,this.$list=null,this.events={change:this.onChange.bind(this),refresh:this.onRefresh.bind(this)}}buildList(){if(this.carousel.pages.length{if(!(\"page\"in t.target.dataset))return;t.preventDefault(),t.stopPropagation();const e=parseInt(t.target.dataset.page,10),i=this.carousel;e!==i.page&&(i.pages.length<3&&i.option(\"infinite\")?i[0==e?\"slidePrev\":\"slideNext\"]():i.slideTo(e))})),this.$list=t,this.carousel.$container.appendChild(t),this.carousel.$container.classList.add(\"has-dots\"),t}removeList(){this.$list&&(this.$list.parentNode.removeChild(this.$list),this.$list=null),this.carousel.$container.classList.remove(\"has-dots\")}rebuildDots(){let t=this.$list;const e=!!t,i=this.carousel.pages.length;if(i<2)return void(e&&this.removeList());e||(t=this.buildList());const s=this.$list.children.length;if(s>i)for(let t=i;t{const i=t.code;let s;\"Enter\"===i||\"NumpadEnter\"===i?s=e:\"ArrowRight\"===i?s=e.nextSibling:\"ArrowLeft\"===i&&(s=e.previousSibling),s&&s.click()})),this.$list.appendChild(e)}this.setActiveDot()}}setActiveDot(){if(!this.$list)return;this.$list.childNodes.forEach((t=>{t.classList.remove(\"is-selected\")}));const t=this.$list.childNodes[this.carousel.page];t&&t.classList.add(\"is-selected\")}onChange(){this.setActiveDot()}onRefresh(){this.rebuildDots()}attach(){this.carousel.on(this.events)}detach(){this.removeList(),this.carousel.off(this.events),this.carousel=null}},Sync:g};const m={slides:[],preload:0,slidesPerPage:\"auto\",initialPage:null,initialSlide:null,friction:.92,center:!0,infinite:!0,fill:!0,dragFree:!1,prefix:\"\",classNames:{viewport:\"carousel__viewport\",track:\"carousel__track\",slide:\"carousel__slide\",slideSelected:\"is-selected\"},l10n:{NEXT:\"Next slide\",PREV:\"Previous slide\",GOTO:\"Go to slide #%d\"}};class y extends l{constructor(t,i={}){if(super(i=e(!0,{},m,i)),this.state=\"init\",this.$container=t,!(this.$container instanceof HTMLElement))throw new Error(\"No root element provided\");this.slideNext=u(this.slideNext.bind(this),250),this.slidePrev=u(this.slidePrev.bind(this),250),this.init(),t.__Carousel=this}init(){this.pages=[],this.page=this.pageIndex=null,this.prevPage=this.prevPageIndex=null,this.attachPlugins(y.Plugins),this.trigger(\"init\"),this.initLayout(),this.initSlides(),this.updateMetrics(),this.$track&&this.pages.length&&(this.$track.style.transform=`translate3d(${-1*this.pages[this.page].left}px, 0px, 0) scale(1)`),this.manageSlideVisiblity(),this.initPanzoom(),this.state=\"ready\",this.trigger(\"ready\")}initLayout(){const t=this.option(\"prefix\"),e=this.option(\"classNames\");this.$viewport=this.option(\"viewport\")||this.$container.querySelector(`.${t}${e.viewport}`),this.$viewport||(this.$viewport=document.createElement(\"div\"),this.$viewport.classList.add(...(t+e.viewport).split(\" \")),this.$viewport.append(...this.$container.childNodes),this.$container.appendChild(this.$viewport)),this.$track=this.option(\"track\")||this.$container.querySelector(`.${t}${e.track}`),this.$track||(this.$track=document.createElement(\"div\"),this.$track.classList.add(...(t+e.track).split(\" \")),this.$track.append(...this.$viewport.childNodes),this.$viewport.appendChild(this.$track))}initSlides(){this.slides=[];this.$viewport.querySelectorAll(`.${this.option(\"prefix\")}${this.option(\"classNames.slide\")}`).forEach((t=>{const e={$el:t,isDom:!0};this.slides.push(e),this.trigger(\"createSlide\",e,this.slides.length)})),Array.isArray(this.options.slides)&&(this.slides=e(!0,[...this.slides],this.options.slides))}updateMetrics(){let t,e=0,s=[];this.slides.forEach(((i,o)=>{const n=i.$el,a=i.isDom||!t?this.getSlideMetrics(n):t;i.index=o,i.width=a,i.left=e,t=a,e+=a,s.push(o)}));let o=Math.max(this.$track.offsetWidth,i(this.$track.getBoundingClientRect().width)),n=getComputedStyle(this.$track);o-=parseFloat(n.paddingLeft)+parseFloat(n.paddingRight),this.contentWidth=e,this.viewportWidth=o;const a=[],r=this.option(\"slidesPerPage\");if(Number.isInteger(r)&&e>o)for(let t=0;to)&&(a.push({indexes:[],slides:[]}),t=a.length-1,e=0),e+=s.width,a[t].indexes.push(i),a[t].slides.push(s)}}const h=this.option(\"center\"),l=this.option(\"fill\");a.forEach(((t,i)=>{t.index=i,t.width=t.slides.reduce(((t,e)=>t+e.width),0),t.left=t.slides[0].left,h&&(t.left+=.5*(o-t.width)*-1),l&&!this.option(\"infiniteX\",this.option(\"infinite\"))&&e>o&&(t.left=Math.max(t.left,0),t.left=Math.min(t.left,e-o))}));const c=[];let d;a.forEach((t=>{const e={...t};d&&e.left===d.left?(d.width+=e.width,d.slides=[...d.slides,...e.slides],d.indexes=[...d.indexes,...e.indexes]):(e.index=c.length,d=e,c.push(e))})),this.pages=c;let u=this.page;if(null===u){const t=this.option(\"initialSlide\");u=null!==t?this.findPageForSlide(t):parseInt(this.option(\"initialPage\",0),10)||0,c[u]||(u=c.length&&u>c.length?c[c.length-1].index:0),this.page=u,this.pageIndex=u}this.updatePanzoom(),this.trigger(\"refresh\")}getSlideMetrics(t){if(!t){const e=this.slides[0];(t=document.createElement(\"div\")).dataset.isTestEl=1,t.style.visibility=\"hidden\",t.classList.add(...(this.option(\"prefix\")+this.option(\"classNames.slide\")).split(\" \")),e.customClass&&t.classList.add(...e.customClass.split(\" \")),this.$track.prepend(t)}let e=Math.max(t.offsetWidth,i(t.getBoundingClientRect().width));const s=t.currentStyle||window.getComputedStyle(t);return e=e+(parseFloat(s.marginLeft)||0)+(parseFloat(s.marginRight)||0),t.dataset.isTestEl&&t.remove(),e}findPageForSlide(t){t=parseInt(t,10)||0;const e=this.pages.find((e=>e.indexes.indexOf(t)>-1));return e?e.index:null}slideNext(){this.slideTo(this.pageIndex+1)}slidePrev(){this.slideTo(this.pageIndex-1)}slideTo(t,e={}){const{x:i=-1*this.setPage(t,!0),y:s=0,friction:o=this.option(\"friction\")}=e;this.Panzoom.content.x===i&&!this.Panzoom.velocity.x&&o||(this.Panzoom.panTo({x:i,y:s,friction:o,ignoreBounds:!0}),\"ready\"===this.state&&\"ready\"===this.Panzoom.state&&this.trigger(\"settle\"))}initPanzoom(){this.Panzoom&&this.Panzoom.destroy();const t=e(!0,{},{content:this.$track,wrapInner:!1,resizeParent:!1,zoom:!1,click:!1,lockAxis:\"x\",x:this.pages.length?-1*this.pages[this.page].left:0,centerOnStart:!1,textSelection:()=>this.option(\"textSelection\",!1),panOnlyZoomed:function(){return this.content.width<=this.viewport.width}},this.option(\"Panzoom\"));this.Panzoom=new d(this.$container,t),this.Panzoom.on({\"*\":(t,...e)=>this.trigger(`Panzoom.${t}`,...e),afterUpdate:()=>{this.updatePage()},beforeTransform:this.onBeforeTransform.bind(this),touchEnd:this.onTouchEnd.bind(this),endAnimation:()=>{this.trigger(\"settle\")}}),this.updateMetrics(),this.manageSlideVisiblity()}updatePanzoom(){this.Panzoom&&(this.Panzoom.content={...this.Panzoom.content,fitWidth:this.contentWidth,origWidth:this.contentWidth,width:this.contentWidth},this.pages.length>1&&this.option(\"infiniteX\",this.option(\"infinite\"))?this.Panzoom.boundX=null:this.pages.length&&(this.Panzoom.boundX={from:-1*this.pages[this.pages.length-1].left,to:-1*this.pages[0].left}),this.option(\"infiniteY\",this.option(\"infinite\"))?this.Panzoom.boundY=null:this.Panzoom.boundY={from:0,to:0},this.Panzoom.handleCursor())}manageSlideVisiblity(){const t=this.contentWidth,e=this.viewportWidth;let i=this.Panzoom?-1*this.Panzoom.content.x:this.pages.length?this.pages[this.page].left:0;const s=this.option(\"preload\"),o=this.option(\"infiniteX\",this.option(\"infinite\")),n=parseFloat(getComputedStyle(this.$viewport,null).getPropertyValue(\"padding-left\")),a=parseFloat(getComputedStyle(this.$viewport,null).getPropertyValue(\"padding-right\"));this.slides.forEach((r=>{let h,l,c=0;h=i-n,l=i+e+a,h-=s*(e+n+a),l+=s*(e+n+a);const d=r.left+r.width>h&&r.lefth&&r.lefth&&r.lefti&&r.left<=i+e+a&&(c=0)):this.removeSlideEl(r),r.hasDiff=c}));let r=0,h=0;this.slides.forEach(((e,i)=>{let s=0;e.$el?(i!==r||e.hasDiff?s=h+e.hasDiff*t:h=0,e.$el.style.left=Math.abs(s)>.1?`${h+e.hasDiff*t}px`:\"\",r++):h+=e.width})),this.markSelectedSlides()}createSlideEl(t){if(!t)return;if(t.$el){let e=t.$el.dataset.index;if(!e||parseInt(e,10)!==t.index){let e;t.$el.dataset.index=t.index,t.$el.querySelectorAll(\"[data-lazy-srcset]\").forEach((t=>{t.srcset=t.dataset.lazySrcset})),t.$el.querySelectorAll(\"[data-lazy-src]\").forEach((t=>{let e=t.dataset.lazySrc;t instanceof HTMLImageElement?t.src=e:t.style.backgroundImage=`url('${e}')`})),(e=t.$el.dataset.lazySrc)&&(t.$el.style.backgroundImage=`url('${e}')`),t.state=\"ready\"}return}const e=document.createElement(\"div\");e.dataset.index=t.index,e.classList.add(...(this.option(\"prefix\")+this.option(\"classNames.slide\")).split(\" \")),t.customClass&&e.classList.add(...t.customClass.split(\" \")),t.html&&(e.innerHTML=t.html);const i=[];this.slides.forEach(((t,e)=>{t.$el&&i.push(e)}));const s=t.index;let o=null;if(i.length){let t=i.reduce(((t,e)=>Math.abs(e-s){const o=i.$el;if(!o)return;const n=this.pages[this.page];n&&n.indexes&&n.indexes.indexOf(s)>-1?(t&&!o.classList.contains(t)&&(o.classList.add(t),this.trigger(\"selectSlide\",i)),o.removeAttribute(e)):(t&&o.classList.contains(t)&&(o.classList.remove(t),this.trigger(\"unselectSlide\",i)),o.setAttribute(e,!0))}))}updatePage(){this.updateMetrics(),this.slideTo(this.page,{friction:0})}onBeforeTransform(){this.option(\"infiniteX\",this.option(\"infinite\"))&&this.manageInfiniteTrack(),this.manageSlideVisiblity()}manageInfiniteTrack(){const t=this.contentWidth,e=this.viewportWidth;if(!this.option(\"infiniteX\",this.option(\"infinite\"))||this.pages.length<2||te&&(i.content.x-=t,this.pageIndex=this.pageIndex+this.pages.length,s=!0),s&&\"pointerdown\"===i.state&&i.resetDragPosition(),s}onTouchEnd(t,e){const i=this.option(\"dragFree\");if(!i&&this.pages.length>1&&t.dragOffset.time<350&&Math.abs(t.dragOffset.y)<1&&Math.abs(t.dragOffset.x)>5)this[t.dragOffset.x<0?\"slideNext\":\"slidePrev\"]();else if(i){const[,e]=this.getPageFromPosition(-1*t.transform.x);this.setPage(e)}else this.slideToClosest()}slideToClosest(t={}){let[,e]=this.getPageFromPosition(-1*this.Panzoom.content.x);this.slideTo(e,t)}getPageFromPosition(t){const e=this.pages.length;this.option(\"center\")&&(t+=.5*this.viewportWidth);const i=Math.floor(t/this.contentWidth);t-=i*this.contentWidth;let s=this.slides.find((e=>e.left<=t&&e.left+e.width>t));if(s){let t=this.findPageForSlide(s.index);return[t,t+i*e]}return[0,0]}setPage(t,e){let i=0,s=parseInt(t,10)||0;const o=this.page,n=this.pageIndex,a=this.pages.length,r=this.contentWidth,h=this.viewportWidth;if(t=(s%a+a)%a,this.option(\"infiniteX\",this.option(\"infinite\"))&&r>h){const o=Math.floor(s/a)||0,n=r;if(i=this.pages[t].left+o*n,!0===e&&a>2){let t=-1*this.Panzoom.content.x;const e=i-n,o=i+n,r=Math.abs(t-i),h=Math.abs(t-e),l=Math.abs(t-o);l{this.removeSlideEl(t)})),this.slides=[],this.Panzoom.destroy(),this.detachPlugins()}}y.version=\"4.0.31\",y.Plugins=p;const v=!(\"undefined\"==typeof window||!window.document||!window.document.createElement);let b=null;const x=[\"a[href]\",\"area[href]\",'input:not([disabled]):not([type=\"hidden\"]):not([aria-hidden])',\"select:not([disabled]):not([aria-hidden])\",\"textarea:not([disabled]):not([aria-hidden])\",\"button:not([disabled]):not([aria-hidden])\",\"iframe\",\"object\",\"embed\",\"video\",\"audio\",\"[contenteditable]\",'[tabindex]:not([tabindex^=\"-\"]):not([disabled]):not([aria-hidden])'],w=t=>{if(t&&v){null===b&&document.createElement(\"div\").focus({get preventScroll(){return b=!0,!1}});try{if(t.setActive)t.setActive();else if(b)t.focus({preventScroll:!0});else{const e=window.pageXOffset||document.body.scrollTop,i=window.pageYOffset||document.body.scrollLeft;t.focus(),document.body.scrollTo({top:e,left:i,behavior:\"auto\"})}}catch(t){}}};const $={minSlideCount:2,minScreenHeight:500,autoStart:!0,key:\"t\",Carousel:{},tpl:'
'};class C{constructor(t){this.fancybox=t,this.$container=null,this.state=\"init\";for(const t of[\"onPrepare\",\"onClosing\",\"onKeydown\"])this[t]=this[t].bind(this);this.events={prepare:this.onPrepare,closing:this.onClosing,keydown:this.onKeydown}}onPrepare(){this.getSlides().length=this.fancybox.option(\"Thumbs.minScreenHeight\")&&this.build()}onClosing(){this.Carousel&&this.Carousel.Panzoom.detachEvents()}onKeydown(t,e){e===t.option(\"Thumbs.key\")&&this.toggle()}build(){if(this.$container)return;const t=document.createElement(\"div\");t.classList.add(\"fancybox__thumbs\"),this.fancybox.$carousel.parentNode.insertBefore(t,this.fancybox.$carousel.nextSibling),this.Carousel=new y(t,e(!0,{Dots:!1,Navigation:!1,Sync:{friction:0},infinite:!1,center:!0,fill:!0,dragFree:!0,slidesPerPage:1,preload:1},this.fancybox.option(\"Thumbs.Carousel\"),{Sync:{target:this.fancybox.Carousel},slides:this.getSlides()})),this.Carousel.Panzoom.on(\"wheel\",((t,e)=>{e.preventDefault(),this.fancybox[e.deltaY<0?\"prev\":\"next\"]()})),this.$container=t,this.state=\"visible\"}getSlides(){const t=[];for(const e of this.fancybox.items){const i=e.thumb;i&&t.push({html:this.fancybox.option(\"Thumbs.tpl\").replace(/\\{\\{src\\}\\}/gi,i),customClass:`has-thumb has-${e.type||\"image\"}`})}return t}toggle(){\"visible\"===this.state?this.hide():\"hidden\"===this.state?this.show():this.build()}show(){\"hidden\"===this.state&&(this.$container.style.display=\"\",this.Carousel.Panzoom.attachEvents(),this.state=\"visible\")}hide(){\"visible\"===this.state&&(this.Carousel.Panzoom.detachEvents(),this.$container.style.display=\"none\",this.state=\"hidden\")}cleanup(){this.Carousel&&(this.Carousel.destroy(),this.Carousel=null),this.$container&&(this.$container.remove(),this.$container=null),this.state=\"init\"}attach(){this.fancybox.on(this.events)}detach(){this.fancybox.off(this.events),this.cleanup()}}C.defaults=$;const S=(t,e)=>{const i=new URL(t),s=new URLSearchParams(i.search);let o=new URLSearchParams;for(const[t,i]of[...s,...Object.entries(e)])\"t\"===t?o.set(\"start\",parseInt(i)):o.set(t,i);o=o.toString();let n=t.match(/#t=((.*)?\\d+s)/);return n&&(o+=`#t=${n[1]}`),o},E={video:{autoplay:!0,ratio:16/9},youtube:{autohide:1,fs:1,rel:0,hd:1,wmode:\"transparent\",enablejsapi:1,html5:1},vimeo:{hd:1,show_title:1,show_byline:1,show_portrait:0,fullscreen:1},html5video:{tpl:'',format:\"\"}};class P{constructor(t){this.fancybox=t;for(const t of[\"onInit\",\"onReady\",\"onCreateSlide\",\"onRemoveSlide\",\"onSelectSlide\",\"onUnselectSlide\",\"onRefresh\",\"onMessage\"])this[t]=this[t].bind(this);this.events={init:this.onInit,ready:this.onReady,\"Carousel.createSlide\":this.onCreateSlide,\"Carousel.removeSlide\":this.onRemoveSlide,\"Carousel.selectSlide\":this.onSelectSlide,\"Carousel.unselectSlide\":this.onUnselectSlide,\"Carousel.refresh\":this.onRefresh}}onInit(){for(const t of this.fancybox.items)this.processType(t)}processType(t){if(t.html)return t.src=t.html,t.type=\"html\",void delete t.html;const i=t.src||\"\";let s=t.type||this.fancybox.options.type,o=null;if(!i||\"string\"==typeof i){if(o=i.match(/(?:youtube\\.com|youtu\\.be|youtube\\-nocookie\\.com)\\/(?:watch\\?(?:.*&)?v=|v\\/|u\\/|embed\\/?)?(videoseries\\?list=(?:.*)|[\\w-]{11}|\\?listType=(?:.*)&list=(?:.*))(?:.*)/i)){const e=S(i,this.fancybox.option(\"Html.youtube\")),n=encodeURIComponent(o[1]);t.videoId=n,t.src=`https://www.youtube-nocookie.com/embed/${n}?${e}`,t.thumb=t.thumb||`https://i.ytimg.com/vi/${n}/mqdefault.jpg`,t.vendor=\"youtube\",s=\"video\"}else if(o=i.match(/^.+vimeo.com\\/(?:\\/)?([\\d]+)(.*)?/)){const e=S(i,this.fancybox.option(\"Html.vimeo\")),n=encodeURIComponent(o[1]);t.videoId=n,t.src=`https://player.vimeo.com/video/${n}?${e}`,t.vendor=\"vimeo\",s=\"video\"}else(o=i.match(/(?:maps\\.)?google\\.([a-z]{2,3}(?:\\.[a-z]{2})?)\\/(?:(?:(?:maps\\/(?:place\\/(?:.*)\\/)?\\@(.*),(\\d+.?\\d+?)z))|(?:\\?ll=))(.*)?/i))?(t.src=`//maps.google.${o[1]}/?ll=${(o[2]?o[2]+\"&z=\"+Math.floor(o[3])+(o[4]?o[4].replace(/^\\//,\"&\"):\"\"):o[4]+\"\").replace(/\\?/,\"&\")}&output=${o[4]&&o[4].indexOf(\"layer=c\")>0?\"svembed\":\"embed\"}`,s=\"map\"):(o=i.match(/(?:maps\\.)?google\\.([a-z]{2,3}(?:\\.[a-z]{2})?)\\/(?:maps\\/search\\/)(.*)/i))&&(t.src=`//maps.google.${o[1]}/maps?q=${o[2].replace(\"query=\",\"q=\").replace(\"api=1\",\"\")}&output=embed`,s=\"map\");s||(\"#\"===i.charAt(0)?s=\"inline\":(o=i.match(/\\.(mp4|mov|ogv|webm)((\\?|#).*)?$/i))?(s=\"html5video\",t.format=t.format||\"video/\"+(\"ogv\"===o[1]?\"ogg\":o[1])):i.match(/(^data:image\\/[a-z0-9+\\/=]*,)|(\\.(jp(e|g|eg)|gif|png|bmp|webp|svg|ico)((\\?|#).*)?$)/i)?s=\"image\":i.match(/\\.(pdf)((\\?|#).*)?$/i)&&(s=\"pdf\")),t.type=s||this.fancybox.option(\"defaultType\",\"image\"),\"html5video\"!==s&&\"video\"!==s||(t.video=e({},this.fancybox.option(\"Html.video\"),t.video),t._width&&t._height?t.ratio=parseFloat(t._width)/parseFloat(t._height):t.ratio=t.ratio||t.video.ratio||E.video.ratio)}}onReady(){this.fancybox.Carousel.slides.forEach((t=>{t.$el&&(this.setContent(t),t.index===this.fancybox.getSlide().index&&this.playVideo(t))}))}onCreateSlide(t,e,i){\"ready\"===this.fancybox.state&&this.setContent(i)}loadInlineContent(t){let e;if(t.src instanceof HTMLElement)e=t.src;else if(\"string\"==typeof t.src){const i=t.src.split(\"#\",2),s=2===i.length&&\"\"===i[0]?i[1]:i[0];e=document.getElementById(s)}if(e){if(\"clone\"===t.type||e.$placeHolder){e=e.cloneNode(!0);let i=e.getAttribute(\"id\");i=i?`${i}--clone`:`clone-${this.fancybox.id}-${t.index}`,e.setAttribute(\"id\",i)}else{const t=document.createElement(\"div\");t.classList.add(\"fancybox-placeholder\"),e.parentNode.insertBefore(t,e),e.$placeHolder=t}this.fancybox.setContent(t,e)}else this.fancybox.setError(t,\"{{ELEMENT_NOT_FOUND}}\")}loadAjaxContent(t){const e=this.fancybox,i=new XMLHttpRequest;e.showLoading(t),i.onreadystatechange=function(){i.readyState===XMLHttpRequest.DONE&&\"ready\"===e.state&&(e.hideLoading(t),200===i.status?e.setContent(t,i.responseText):e.setError(t,404===i.status?\"{{AJAX_NOT_FOUND}}\":\"{{AJAX_FORBIDDEN}}\"))};const s=t.ajax||null;i.open(s?\"POST\":\"GET\",t.src),i.setRequestHeader(\"Content-Type\",\"application/x-www-form-urlencoded\"),i.setRequestHeader(\"X-Requested-With\",\"XMLHttpRequest\"),i.send(s),t.xhr=i}loadIframeContent(t){const e=this.fancybox,i=document.createElement(\"iframe\");if(i.className=\"fancybox__iframe\",i.setAttribute(\"id\",`fancybox__iframe_${e.id}_${t.index}`),i.setAttribute(\"allow\",\"autoplay; fullscreen\"),i.setAttribute(\"scrolling\",\"auto\"),t.$iframe=i,\"iframe\"!==t.type||!1===t.preload)return i.setAttribute(\"src\",t.src),this.fancybox.setContent(t,i),void this.resizeIframe(t);e.showLoading(t);const s=document.createElement(\"div\");s.style.visibility=\"hidden\",this.fancybox.setContent(t,s),s.appendChild(i),i.onerror=()=>{e.setError(t,\"{{IFRAME_ERROR}}\")},i.onload=()=>{e.hideLoading(t);let s=!1;i.isReady||(i.isReady=!0,s=!0),i.src.length&&(i.parentNode.style.visibility=\"\",this.resizeIframe(t),s&&e.revealContent(t))},i.setAttribute(\"src\",t.src)}setAspectRatio(t){const e=t.$content,i=t.ratio;if(!e)return;let s=t._width,o=t._height;if(i||s&&o){Object.assign(e.style,{width:s&&o?\"100%\":\"\",height:s&&o?\"100%\":\"\",maxWidth:\"\",maxHeight:\"\"});let t=e.offsetWidth,n=e.offsetHeight;if(s=s||t,o=o||n,s>t||o>n){let e=Math.min(t/s,n/o);s*=e,o*=e}Math.abs(s/o-i)>.01&&(i{t.$el&&(t.$iframe&&this.resizeIframe(t),t.ratio&&this.setAspectRatio(t))}))}setContent(t){if(t&&!t.isDom){switch(t.type){case\"html\":this.fancybox.setContent(t,t.src);break;case\"html5video\":this.fancybox.setContent(t,this.fancybox.option(\"Html.html5video.tpl\").replace(/\\{\\{src\\}\\}/gi,t.src).replace(\"{{format}}\",t.format||t.html5video&&t.html5video.format||\"\").replace(\"{{poster}}\",t.poster||t.thumb||\"\"));break;case\"inline\":case\"clone\":this.loadInlineContent(t);break;case\"ajax\":this.loadAjaxContent(t);break;case\"pdf\":case\"video\":case\"map\":t.preload=!1;case\"iframe\":this.loadIframeContent(t)}t.ratio&&this.setAspectRatio(t)}}onSelectSlide(t,e,i){\"ready\"===t.state&&this.playVideo(i)}playVideo(t){if(\"html5video\"===t.type&&t.video.autoplay)try{const e=t.$el.querySelector(\"video\");if(e){const t=e.play();void 0!==t&&t.then((()=>{})).catch((t=>{e.muted=!0,e.play()}))}}catch(t){}if(\"video\"!==t.type||!t.$iframe||!t.$iframe.contentWindow)return;const e=()=>{if(\"done\"===t.state&&t.$iframe&&t.$iframe.contentWindow){let e;if(t.$iframe.isReady)return t.video&&t.video.autoplay&&(e=\"youtube\"==t.vendor?{event:\"command\",func:\"playVideo\"}:{method:\"play\",value:\"true\"}),void(e&&t.$iframe.contentWindow.postMessage(JSON.stringify(e),\"*\"));\"youtube\"===t.vendor&&(e={event:\"listening\",id:t.$iframe.getAttribute(\"id\")},t.$iframe.contentWindow.postMessage(JSON.stringify(e),\"*\"))}t.poller=setTimeout(e,250)};e()}onUnselectSlide(t,e,i){if(\"html5video\"===i.type){try{i.$el.querySelector(\"video\").pause()}catch(t){}return}let s=!1;\"vimeo\"==i.vendor?s={method:\"pause\",value:\"true\"}:\"youtube\"===i.vendor&&(s={event:\"command\",func:\"pauseVideo\"}),s&&i.$iframe&&i.$iframe.contentWindow&&i.$iframe.contentWindow.postMessage(JSON.stringify(s),\"*\"),clearTimeout(i.poller)}onRemoveSlide(t,e,i){i.xhr&&(i.xhr.abort(),i.xhr=null),i.$iframe&&(i.$iframe.onload=i.$iframe.onerror=null,i.$iframe.src=\"//about:blank\",i.$iframe=null);const s=i.$content;\"inline\"===i.type&&s&&(s.classList.remove(\"fancybox__content\"),\"none\"!==s.style.display&&(s.style.display=\"none\")),i.$closeButton&&(i.$closeButton.remove(),i.$closeButton=null);const o=s&&s.$placeHolder;o&&(o.parentNode.insertBefore(s,o),o.remove(),s.$placeHolder=null)}onMessage(t){try{let e=JSON.parse(t.data);if(\"https://player.vimeo.com\"===t.origin){if(\"ready\"===e.event)for(let e of document.getElementsByClassName(\"fancybox__iframe\"))e.contentWindow===t.source&&(e.isReady=1)}else\"https://www.youtube-nocookie.com\"===t.origin&&\"onReady\"===e.event&&(document.getElementById(e.id).isReady=1)}catch(t){}}attach(){this.fancybox.on(this.events),window.addEventListener(\"message\",this.onMessage,!1)}detach(){this.fancybox.off(this.events),window.removeEventListener(\"message\",this.onMessage,!1)}}P.defaults=E;class T{constructor(t){this.fancybox=t;for(const t of[\"onReady\",\"onClosing\",\"onDone\",\"onPageChange\",\"onCreateSlide\",\"onRemoveSlide\",\"onImageStatusChange\"])this[t]=this[t].bind(this);this.events={ready:this.onReady,closing:this.onClosing,done:this.onDone,\"Carousel.change\":this.onPageChange,\"Carousel.createSlide\":this.onCreateSlide,\"Carousel.removeSlide\":this.onRemoveSlide}}onReady(){this.fancybox.Carousel.slides.forEach((t=>{t.$el&&this.setContent(t)}))}onDone(t,e){this.handleCursor(e)}onClosing(t){clearTimeout(this.clickTimer),this.clickTimer=null,t.Carousel.slides.forEach((t=>{t.$image&&(t.state=\"destroy\"),t.Panzoom&&t.Panzoom.detachEvents()})),\"closing\"===this.fancybox.state&&this.canZoom(t.getSlide())&&this.zoomOut()}onCreateSlide(t,e,i){\"ready\"===this.fancybox.state&&this.setContent(i)}onRemoveSlide(t,e,i){i.$image&&(i.$el.classList.remove(t.option(\"Image.canZoomInClass\")),i.$image.remove(),i.$image=null),i.Panzoom&&(i.Panzoom.destroy(),i.Panzoom=null),i.$el&&i.$el.dataset&&delete i.$el.dataset.imageFit}setContent(t){if(t.isDom||t.html||t.type&&\"image\"!==t.type)return;if(t.$image)return;t.type=\"image\",t.state=\"loading\";const e=document.createElement(\"div\");e.style.visibility=\"hidden\";const i=document.createElement(\"img\");i.addEventListener(\"load\",(e=>{e.stopImmediatePropagation(),this.onImageStatusChange(t)})),i.addEventListener(\"error\",(()=>{this.onImageStatusChange(t)})),i.src=t.src,i.alt=\"\",i.draggable=!1,i.classList.add(\"fancybox__image\"),t.srcset&&i.setAttribute(\"srcset\",t.srcset),t.sizes&&i.setAttribute(\"sizes\",t.sizes),t.$image=i;const s=this.fancybox.option(\"Image.wrap\");if(s){const o=document.createElement(\"div\");o.classList.add(\"string\"==typeof s?s:\"fancybox__image-wrap\"),o.appendChild(i),e.appendChild(o),t.$wrap=o}else e.appendChild(i);t.$el.dataset.imageFit=this.fancybox.option(\"Image.fit\"),this.fancybox.setContent(t,e),i.complete||i.error?this.onImageStatusChange(t):this.fancybox.showLoading(t)}onImageStatusChange(t){const e=t.$image;e&&\"loading\"===t.state&&(e.complete&&e.naturalWidth&&e.naturalHeight?(this.fancybox.hideLoading(t),\"contain\"===this.fancybox.option(\"Image.fit\")&&this.initSlidePanzoom(t),t.$el.addEventListener(\"wheel\",(e=>this.onWheel(t,e)),{passive:!1}),t.$content.addEventListener(\"click\",(e=>this.onClick(t,e)),{passive:!1}),this.revealContent(t)):this.fancybox.setError(t,\"{{IMAGE_ERROR}}\"))}initSlidePanzoom(t){t.Panzoom||(t.Panzoom=new d(t.$el,e(!0,this.fancybox.option(\"Image.Panzoom\",{}),{viewport:t.$wrap,content:t.$image,width:t._width,height:t._height,wrapInner:!1,textSelection:!0,touch:this.fancybox.option(\"Image.touch\"),panOnlyZoomed:!0,click:!1,wheel:!1})),t.Panzoom.on(\"startAnimation\",(()=>{this.fancybox.trigger(\"Image.startAnimation\",t)})),t.Panzoom.on(\"endAnimation\",(()=>{\"zoomIn\"===t.state&&this.fancybox.done(t),this.handleCursor(t),this.fancybox.trigger(\"Image.endAnimation\",t)})),t.Panzoom.on(\"afterUpdate\",(()=>{this.handleCursor(t),this.fancybox.trigger(\"Image.afterUpdate\",t)})))}revealContent(t){null===this.fancybox.Carousel.prevPage&&t.index===this.fancybox.options.startIndex&&this.canZoom(t)?this.zoomIn():this.fancybox.revealContent(t)}getZoomInfo(t){const e=t.$thumb.getBoundingClientRect(),i=e.width,s=e.height,o=t.$content.getBoundingClientRect(),n=o.width,a=o.height,r=o.top-e.top,h=o.left-e.left;let l=this.fancybox.option(\"Image.zoomOpacity\");return\"auto\"===l&&(l=Math.abs(i/s-n/a)>.1),{top:r,left:h,scale:n&&i?i/n:1,opacity:l}}canZoom(t){const e=this.fancybox,i=e.$container;if(window.visualViewport&&1!==window.visualViewport.scale)return!1;if(t.Panzoom&&!t.Panzoom.content.width)return!1;if(!e.option(\"Image.zoom\")||\"contain\"!==e.option(\"Image.fit\"))return!1;const s=t.$thumb;if(!s||\"loading\"===t.state)return!1;i.classList.add(\"fancybox__no-click\");const o=s.getBoundingClientRect();let n;if(this.fancybox.option(\"Image.ignoreCoveredThumbnail\")){const t=document.elementFromPoint(o.left+1,o.top+1)===s,e=document.elementFromPoint(o.right-1,o.bottom-1)===s;n=t&&e}else n=document.elementFromPoint(o.left+.5*o.width,o.top+.5*o.height)===s;return i.classList.remove(\"fancybox__no-click\"),n}zoomIn(){const t=this.fancybox,e=t.getSlide(),i=e.Panzoom,{top:s,left:o,scale:n,opacity:a}=this.getZoomInfo(e);t.trigger(\"reveal\",e),i.panTo({x:-1*o,y:-1*s,scale:n,friction:0,ignoreBounds:!0}),e.$content.style.visibility=\"\",e.state=\"zoomIn\",!0===a&&i.on(\"afterTransform\",(t=>{\"zoomIn\"!==e.state&&\"zoomOut\"!==e.state||(t.$content.style.opacity=Math.min(1,1-(1-t.content.scale)/(1-n)))})),i.panTo({x:0,y:0,scale:1,friction:this.fancybox.option(\"Image.zoomFriction\")})}zoomOut(){const t=this.fancybox,e=t.getSlide(),i=e.Panzoom;if(!i)return;e.state=\"zoomOut\",t.state=\"customClosing\",e.$caption&&(e.$caption.style.visibility=\"hidden\");let s=this.fancybox.option(\"Image.zoomFriction\");const o=t=>{const{top:o,left:n,scale:a,opacity:r}=this.getZoomInfo(e);t||r||(s*=.82),i.panTo({x:-1*n,y:-1*o,scale:a,friction:s,ignoreBounds:!0}),s*=.98};window.addEventListener(\"scroll\",o),i.once(\"endAnimation\",(()=>{window.removeEventListener(\"scroll\",o),t.destroy()})),o()}handleCursor(t){if(\"image\"!==t.type||!t.$el)return;const e=t.Panzoom,i=this.fancybox.option(\"Image.click\",!1,t),s=this.fancybox.option(\"Image.touch\"),o=t.$el.classList,n=this.fancybox.option(\"Image.canZoomInClass\"),a=this.fancybox.option(\"Image.canZoomOutClass\");if(o.remove(a),o.remove(n),e&&\"toggleZoom\"===i){e&&1===e.content.scale&&e.option(\"maxScale\")-e.content.scale>.01?o.add(n):e.content.scale>1&&!s&&o.add(a)}else\"close\"===i&&o.add(a)}onWheel(t,e){if(\"ready\"===this.fancybox.state&&!1!==this.fancybox.trigger(\"Image.wheel\",e))switch(this.fancybox.option(\"Image.wheel\")){case\"zoom\":\"done\"===t.state&&t.Panzoom&&t.Panzoom.zoomWithWheel(e);break;case\"close\":this.fancybox.close();break;case\"slide\":this.fancybox[e.deltaY<0?\"prev\":\"next\"]()}}onClick(t,e){if(\"ready\"!==this.fancybox.state)return;const i=t.Panzoom;if(i&&(i.dragPosition.midPoint||0!==i.dragOffset.x||0!==i.dragOffset.y||1!==i.dragOffset.scale))return;if(this.fancybox.Carousel.Panzoom.lockAxis)return!1;const s=i=>{switch(i){case\"toggleZoom\":e.stopPropagation(),t.Panzoom&&t.Panzoom.zoomWithClick(e);break;case\"close\":this.fancybox.close();break;case\"next\":e.stopPropagation(),this.fancybox.next()}},o=this.fancybox.option(\"Image.click\"),n=this.fancybox.option(\"Image.doubleClick\");n?this.clickTimer?(clearTimeout(this.clickTimer),this.clickTimer=null,s(n)):this.clickTimer=setTimeout((()=>{this.clickTimer=null,s(o)}),300):s(o)}onPageChange(t,e){const i=t.getSlide();e.slides.forEach((t=>{t.Panzoom&&\"done\"===t.state&&t.index!==i.index&&t.Panzoom.panTo({x:0,y:0,scale:1,friction:.8})}))}attach(){this.fancybox.on(this.events)}detach(){this.fancybox.off(this.events)}}T.defaults={canZoomInClass:\"can-zoom_in\",canZoomOutClass:\"can-zoom_out\",zoom:!0,zoomOpacity:\"auto\",zoomFriction:.82,ignoreCoveredThumbnail:!1,touch:!0,click:\"toggleZoom\",doubleClick:null,wheel:\"zoom\",fit:\"contain\",wrap:!1,Panzoom:{ratio:1}};class L{constructor(t){this.fancybox=t;for(const t of[\"onChange\",\"onClosing\"])this[t]=this[t].bind(this);this.events={initCarousel:this.onChange,\"Carousel.change\":this.onChange,closing:this.onClosing},this.hasCreatedHistory=!1,this.origHash=\"\",this.timer=null}onChange(t){const e=t.Carousel;this.timer&&clearTimeout(this.timer);const i=null===e.prevPage,s=t.getSlide(),o=new URL(document.URL).hash;let n=!1;if(s.slug)n=\"#\"+s.slug;else{const i=s.$trigger&&s.$trigger.dataset,o=t.option(\"slug\")||i&&i.fancybox;o&&o.length&&\"true\"!==o&&(n=\"#\"+o+(e.slides.length>1?\"-\"+(s.index+1):\"\"))}i&&(this.origHash=o!==n?o:\"\"),n&&o!==n&&(this.timer=setTimeout((()=>{try{window.history[i?\"pushState\":\"replaceState\"]({},document.title,window.location.pathname+window.location.search+n),i&&(this.hasCreatedHistory=!0)}catch(t){}}),300))}onClosing(){if(this.timer&&clearTimeout(this.timer),!0!==this.hasSilentClose)try{return void window.history.replaceState({},document.title,window.location.pathname+window.location.search+(this.origHash||\"\"))}catch(t){}}attach(t){t.on(this.events)}detach(t){t.off(this.events)}static startFromUrl(){const t=L.Fancybox;if(!t||t.getInstance()||!1===t.defaults.Hash)return;const{hash:e,slug:i,index:s}=L.getParsedURL();if(!i)return;let o=document.querySelector(`[data-slug=\"${e}\"]`);if(o&&o.dispatchEvent(new CustomEvent(\"click\",{bubbles:!0,cancelable:!0})),t.getInstance())return;const n=document.querySelectorAll(`[data-fancybox=\"${i}\"]`);n.length&&(null===s&&1===n.length?o=n[0]:s&&(o=n[s-1]),o&&o.dispatchEvent(new CustomEvent(\"click\",{bubbles:!0,cancelable:!0})))}static onHashChange(){const{slug:t,index:e}=L.getParsedURL(),i=L.Fancybox,s=i&&i.getInstance();if(s&&s.plugins.Hash){if(t){const i=s.Carousel;if(t===s.option(\"slug\"))return i.slideTo(e-1);for(let e of i.slides)if(e.slug&&e.slug===t)return i.slideTo(e.index);const o=s.getSlide(),n=o.$trigger&&o.$trigger.dataset;if(n&&n.fancybox===t)return i.slideTo(e-1)}s.plugins.Hash.hasSilentClose=!0,s.close()}L.startFromUrl()}static create(t){function e(){window.addEventListener(\"hashchange\",L.onHashChange,!1),L.startFromUrl()}L.Fancybox=t,v&&window.requestAnimationFrame((()=>{/complete|interactive|loaded/.test(document.readyState)?e():document.addEventListener(\"DOMContentLoaded\",e)}))}static destroy(){window.removeEventListener(\"hashchange\",L.onHashChange,!1)}static getParsedURL(){const t=window.location.hash.substr(1),e=t.split(\"-\"),i=e.length>1&&/^\\+?\\d+$/.test(e[e.length-1])&&parseInt(e.pop(-1),10)||null;return{hash:t,slug:e.join(\"-\"),index:i}}}const _={pageXOffset:0,pageYOffset:0,element:()=>document.fullscreenElement||document.mozFullScreenElement||document.webkitFullscreenElement,activate(t){_.pageXOffset=window.pageXOffset,_.pageYOffset=window.pageYOffset,t.requestFullscreen?t.requestFullscreen():t.mozRequestFullScreen?t.mozRequestFullScreen():t.webkitRequestFullscreen?t.webkitRequestFullscreen():t.msRequestFullscreen&&t.msRequestFullscreen()},deactivate(){document.exitFullscreen?document.exitFullscreen():document.mozCancelFullScreen?document.mozCancelFullScreen():document.webkitExitFullscreen&&document.webkitExitFullscreen()}};class A{constructor(t){this.fancybox=t,this.active=!1,this.handleVisibilityChange=this.handleVisibilityChange.bind(this)}isActive(){return this.active}setTimer(){if(!this.active||this.timer)return;const t=this.fancybox.option(\"slideshow.delay\",3e3);this.timer=setTimeout((()=>{this.timer=null,this.fancybox.option(\"infinite\")||this.fancybox.getSlide().index!==this.fancybox.Carousel.slides.length-1?this.fancybox.next():this.fancybox.jumpTo(0,{friction:0})}),t);let e=this.$progress;e||(e=document.createElement(\"div\"),e.classList.add(\"fancybox__progress\"),this.fancybox.$carousel.parentNode.insertBefore(e,this.fancybox.$carousel),this.$progress=e,e.offsetHeight),e.style.transitionDuration=`${t}ms`,e.style.transform=\"scaleX(1)\"}clearTimer(){clearTimeout(this.timer),this.timer=null,this.$progress&&(this.$progress.style.transitionDuration=\"\",this.$progress.style.transform=\"\",this.$progress.offsetHeight)}activate(){this.active||(this.active=!0,this.fancybox.$container.classList.add(\"has-slideshow\"),\"done\"===this.fancybox.getSlide().state&&this.setTimer(),document.addEventListener(\"visibilitychange\",this.handleVisibilityChange,!1))}handleVisibilityChange(){this.deactivate()}deactivate(){this.active=!1,this.clearTimer(),this.fancybox.$container.classList.remove(\"has-slideshow\"),document.removeEventListener(\"visibilitychange\",this.handleVisibilityChange,!1)}toggle(){this.active?this.deactivate():this.fancybox.Carousel.slides.length>1&&this.activate()}}const z={display:[\"counter\",\"zoom\",\"slideshow\",\"fullscreen\",\"thumbs\",\"close\"],autoEnable:!0,items:{counter:{position:\"left\",type:\"div\",class:\"fancybox__counter\",html:' / ',attr:{tabindex:-1}},prev:{type:\"button\",class:\"fancybox__button--prev\",label:\"PREV\",html:'',attr:{\"data-fancybox-prev\":\"\"}},next:{type:\"button\",class:\"fancybox__button--next\",label:\"NEXT\",html:'',attr:{\"data-fancybox-next\":\"\"}},fullscreen:{type:\"button\",class:\"fancybox__button--fullscreen\",label:\"TOGGLE_FULLSCREEN\",html:'\\n \\n \\n ',click:function(t){t.preventDefault(),_.element()?_.deactivate():_.activate(this.fancybox.$container)}},slideshow:{type:\"button\",class:\"fancybox__button--slideshow\",label:\"TOGGLE_SLIDESHOW\",html:'\\n \\n \\n ',click:function(t){t.preventDefault(),this.Slideshow.toggle()}},zoom:{type:\"button\",class:\"fancybox__button--zoom\",label:\"TOGGLE_ZOOM\",html:'',click:function(t){t.preventDefault();const e=this.fancybox.getSlide().Panzoom;e&&e.toggleZoom()}},download:{type:\"link\",label:\"DOWNLOAD\",class:\"fancybox__button--download\",html:'',click:function(t){t.stopPropagation()}},thumbs:{type:\"button\",label:\"TOGGLE_THUMBS\",class:\"fancybox__button--thumbs\",html:'',click:function(t){t.stopPropagation();const e=this.fancybox.plugins.Thumbs;e&&e.toggle()}},close:{type:\"button\",label:\"CLOSE\",class:\"fancybox__button--close\",html:'',attr:{\"data-fancybox-close\":\"\",tabindex:0}}}};class k{constructor(t){this.fancybox=t,this.$container=null,this.state=\"init\";for(const t of[\"onInit\",\"onPrepare\",\"onDone\",\"onKeydown\",\"onClosing\",\"onChange\",\"onSettle\",\"onRefresh\"])this[t]=this[t].bind(this);this.events={init:this.onInit,prepare:this.onPrepare,done:this.onDone,keydown:this.onKeydown,closing:this.onClosing,\"Carousel.change\":this.onChange,\"Carousel.settle\":this.onSettle,\"Carousel.Panzoom.touchStart\":()=>this.onRefresh(),\"Image.startAnimation\":(t,e)=>this.onRefresh(e),\"Image.afterUpdate\":(t,e)=>this.onRefresh(e)}}onInit(){if(this.fancybox.option(\"Toolbar.autoEnable\")){let t=!1;for(const e of this.fancybox.items)if(\"image\"===e.type){t=!0;break}if(!t)return void(this.state=\"disabled\")}for(const e of this.fancybox.option(\"Toolbar.display\")){if(\"close\"===(t(e)?e.id:e)){this.fancybox.options.closeButton=!1;break}}}onPrepare(){const t=this.fancybox;if(\"init\"===this.state&&(this.build(),this.update(),this.Slideshow=new A(t),!t.Carousel.prevPage&&(t.option(\"slideshow.autoStart\")&&this.Slideshow.activate(),t.option(\"fullscreen.autoStart\")&&!_.element())))try{_.activate(t.$container)}catch(t){}}onFsChange(){window.scrollTo(_.pageXOffset,_.pageYOffset)}onSettle(){const t=this.fancybox,e=this.Slideshow;e&&e.isActive()&&(t.getSlide().index!==t.Carousel.slides.length-1||t.option(\"infinite\")?\"done\"===t.getSlide().state&&e.setTimer():e.deactivate())}onChange(){this.update(),this.Slideshow&&this.Slideshow.isActive()&&this.Slideshow.clearTimer()}onDone(t,e){const i=this.Slideshow;e.index===t.getSlide().index&&(this.update(),i&&i.isActive()&&(t.option(\"infinite\")||e.index!==t.Carousel.slides.length-1?i.setTimer():i.deactivate()))}onRefresh(t){t&&t.index!==this.fancybox.getSlide().index||(this.update(),!this.Slideshow||!this.Slideshow.isActive()||t&&\"done\"!==t.state||this.Slideshow.deactivate())}onKeydown(t,e,i){\" \"===e&&this.Slideshow&&(this.Slideshow.toggle(),i.preventDefault())}onClosing(){this.Slideshow&&this.Slideshow.deactivate(),document.removeEventListener(\"fullscreenchange\",this.onFsChange)}createElement(t){let e;\"div\"===t.type?e=document.createElement(\"div\"):(e=document.createElement(\"link\"===t.type?\"a\":\"button\"),e.classList.add(\"carousel__button\")),e.innerHTML=t.html,e.setAttribute(\"tabindex\",t.tabindex||0),t.class&&e.classList.add(...t.class.split(\" \"));for(const i in t.attr)e.setAttribute(i,t.attr[i]);t.label&&e.setAttribute(\"title\",this.fancybox.localize(`{{${t.label}}}`)),t.click&&e.addEventListener(\"click\",t.click.bind(this)),\"prev\"===t.id&&e.setAttribute(\"data-fancybox-prev\",\"\"),\"next\"===t.id&&e.setAttribute(\"data-fancybox-next\",\"\");const i=e.querySelector(\"svg\");return i&&(i.setAttribute(\"role\",\"img\"),i.setAttribute(\"tabindex\",\"-1\"),i.setAttribute(\"xmlns\",\"http://www.w3.org/2000/svg\")),e}build(){this.cleanup();const i=this.fancybox.option(\"Toolbar.items\"),s=[{position:\"left\",items:[]},{position:\"center\",items:[]},{position:\"right\",items:[]}],o=this.fancybox.plugins.Thumbs;for(const n of this.fancybox.option(\"Toolbar.display\")){let a,r;if(t(n)?(a=n.id,r=e({},i[a],n)):(a=n,r=i[a]),[\"counter\",\"next\",\"prev\",\"slideshow\"].includes(a)&&this.fancybox.items.length<2)continue;if(\"fullscreen\"===a){if(!document.fullscreenEnabled||window.fullScreen)continue;document.addEventListener(\"fullscreenchange\",this.onFsChange)}if(\"thumbs\"===a&&(!o||\"disabled\"===o.state))continue;if(!r)continue;let h=r.position||\"right\",l=s.find((t=>t.position===h));l&&l.items.push(r)}const n=document.createElement(\"div\");n.classList.add(\"fancybox__toolbar\");for(const t of s)if(t.items.length){const e=document.createElement(\"div\");e.classList.add(\"fancybox__toolbar__items\"),e.classList.add(`fancybox__toolbar__items--${t.position}`);for(const i of t.items)e.appendChild(this.createElement(i));n.appendChild(e)}this.fancybox.$carousel.parentNode.insertBefore(n,this.fancybox.$carousel),this.$container=n}update(){const t=this.fancybox.getSlide(),e=t.index,i=this.fancybox.items.length,s=t.downloadSrc||(\"image\"!==t.type||t.error?null:t.src);for(const t of this.fancybox.$container.querySelectorAll(\"a.fancybox__button--download\"))s?(t.removeAttribute(\"disabled\"),t.removeAttribute(\"tabindex\"),t.setAttribute(\"href\",s),t.setAttribute(\"download\",s),t.setAttribute(\"target\",\"_blank\")):(t.setAttribute(\"disabled\",\"\"),t.setAttribute(\"tabindex\",-1),t.removeAttribute(\"href\"),t.removeAttribute(\"download\"));const o=t.Panzoom,n=o&&o.option(\"maxScale\")>o.option(\"baseScale\");for(const t of this.fancybox.$container.querySelectorAll(\".fancybox__button--zoom\"))n?t.removeAttribute(\"disabled\"):t.setAttribute(\"disabled\",\"\");for(const e of this.fancybox.$container.querySelectorAll(\"[data-fancybox-index]\"))e.innerHTML=t.index+1;for(const t of this.fancybox.$container.querySelectorAll(\"[data-fancybox-count]\"))t.innerHTML=i;if(!this.fancybox.option(\"infinite\")){for(const t of this.fancybox.$container.querySelectorAll(\"[data-fancybox-prev]\"))0===e?t.setAttribute(\"disabled\",\"\"):t.removeAttribute(\"disabled\");for(const t of this.fancybox.$container.querySelectorAll(\"[data-fancybox-next]\"))e===i-1?t.setAttribute(\"disabled\",\"\"):t.removeAttribute(\"disabled\")}}cleanup(){this.Slideshow&&this.Slideshow.isActive()&&this.Slideshow.clearTimer(),this.$container&&this.$container.remove(),this.$container=null}attach(){this.fancybox.on(this.events)}detach(){this.fancybox.off(this.events),this.cleanup()}}k.defaults=z;const O={ScrollLock:class{constructor(t){this.fancybox=t,this.viewport=null,this.pendingUpdate=null;for(const t of[\"onReady\",\"onResize\",\"onTouchstart\",\"onTouchmove\"])this[t]=this[t].bind(this)}onReady(){const t=window.visualViewport;t&&(this.viewport=t,this.startY=0,t.addEventListener(\"resize\",this.onResize),this.updateViewport()),window.addEventListener(\"touchstart\",this.onTouchstart,{passive:!1}),window.addEventListener(\"touchmove\",this.onTouchmove,{passive:!1}),window.addEventListener(\"wheel\",this.onWheel,{passive:!1})}onResize(){this.updateViewport()}updateViewport(){const t=this.fancybox,e=this.viewport,i=e.scale||1,s=t.$container;if(!s)return;let o=\"\",n=\"\",a=\"\";i-1>.1&&(o=e.width*i+\"px\",n=e.height*i+\"px\",a=`translate3d(${e.offsetLeft}px, ${e.offsetTop}px, 0) scale(${1/i})`),s.style.width=o,s.style.height=n,s.style.transform=a}onTouchstart(t){this.startY=t.touches?t.touches[0].screenY:t.screenY}onTouchmove(t){const e=this.startY,i=window.innerWidth/window.document.documentElement.clientWidth;if(!t.cancelable)return;if(t.touches.length>1||1!==i)return;const o=s(t.composedPath()[0]);if(!o)return void t.preventDefault();const n=window.getComputedStyle(o),a=parseInt(n.getPropertyValue(\"height\"),10),r=t.touches?t.touches[0].screenY:t.screenY,h=e<=r&&0===o.scrollTop,l=e>=r&&o.scrollHeight-o.scrollTop===a;(h||l)&&t.preventDefault()}onWheel(t){s(t.composedPath()[0])||t.preventDefault()}cleanup(){this.pendingUpdate&&(cancelAnimationFrame(this.pendingUpdate),this.pendingUpdate=null);const t=this.viewport;t&&(t.removeEventListener(\"resize\",this.onResize),this.viewport=null),window.removeEventListener(\"touchstart\",this.onTouchstart,!1),window.removeEventListener(\"touchmove\",this.onTouchmove,!1),window.removeEventListener(\"wheel\",this.onWheel,{passive:!1})}attach(){this.fancybox.on(\"initLayout\",this.onReady)}detach(){this.fancybox.off(\"initLayout\",this.onReady),this.cleanup()}},Thumbs:C,Html:P,Toolbar:k,Image:T,Hash:L};const M={startIndex:0,preload:1,infinite:!0,showClass:\"fancybox-zoomInUp\",hideClass:\"fancybox-fadeOut\",animated:!0,hideScrollbar:!0,parentEl:null,mainClass:null,autoFocus:!0,trapFocus:!0,placeFocusBack:!0,click:\"close\",closeButton:\"inside\",dragToClose:!0,keyboard:{Escape:\"close\",Delete:\"close\",Backspace:\"close\",PageUp:\"next\",PageDown:\"prev\",ArrowUp:\"next\",ArrowDown:\"prev\",ArrowRight:\"next\",ArrowLeft:\"prev\"},template:{closeButton:'',spinner:'',main:null},l10n:{CLOSE:\"Close\",NEXT:\"Next\",PREV:\"Previous\",MODAL:\"You can close this modal content with the ESC key\",ERROR:\"Something Went Wrong, Please Try Again Later\",IMAGE_ERROR:\"Image Not Found\",ELEMENT_NOT_FOUND:\"HTML Element Not Found\",AJAX_NOT_FOUND:\"Error Loading AJAX : Not Found\",AJAX_FORBIDDEN:\"Error Loading AJAX : Forbidden\",IFRAME_ERROR:\"Error Loading Page\",TOGGLE_ZOOM:\"Toggle zoom level\",TOGGLE_THUMBS:\"Toggle thumbnails\",TOGGLE_SLIDESHOW:\"Toggle slideshow\",TOGGLE_FULLSCREEN:\"Toggle full-screen mode\",DOWNLOAD:\"Download\"}},I=new Map;let F=0;class R extends l{constructor(t,i={}){t=t.map((t=>(t.width&&(t._width=t.width),t.height&&(t._height=t.height),t))),super(e(!0,{},M,i)),this.bindHandlers(),this.state=\"init\",this.setItems(t),this.attachPlugins(R.Plugins),this.trigger(\"init\"),!0===this.option(\"hideScrollbar\")&&this.hideScrollbar(),this.initLayout(),this.initCarousel(),this.attachEvents(),I.set(this.id,this),this.trigger(\"prepare\"),this.state=\"ready\",this.trigger(\"ready\"),this.$container.setAttribute(\"aria-hidden\",\"false\"),this.option(\"trapFocus\")&&this.focus()}option(t,...e){const i=this.getSlide();let s=i?i[t]:void 0;return void 0!==s?(\"function\"==typeof s&&(s=s.call(this,this,...e)),s):super.option(t,...e)}bindHandlers(){for(const t of[\"onMousedown\",\"onKeydown\",\"onClick\",\"onFocus\",\"onCreateSlide\",\"onSettle\",\"onTouchMove\",\"onTouchEnd\",\"onTransform\"])this[t]=this[t].bind(this)}attachEvents(){document.addEventListener(\"mousedown\",this.onMousedown),document.addEventListener(\"keydown\",this.onKeydown,!0),this.option(\"trapFocus\")&&document.addEventListener(\"focus\",this.onFocus,!0),this.$container.addEventListener(\"click\",this.onClick)}detachEvents(){document.removeEventListener(\"mousedown\",this.onMousedown),document.removeEventListener(\"keydown\",this.onKeydown,!0),document.removeEventListener(\"focus\",this.onFocus,!0),this.$container.removeEventListener(\"click\",this.onClick)}initLayout(){this.$root=this.option(\"parentEl\")||document.body;let t=this.option(\"template.main\");t&&(this.$root.insertAdjacentHTML(\"beforeend\",this.localize(t)),this.$container=this.$root.querySelector(\".fancybox__container\")),this.$container||(this.$container=document.createElement(\"div\"),this.$root.appendChild(this.$container)),this.$container.onscroll=()=>(this.$container.scrollLeft=0,!1),Object.entries({class:\"fancybox__container\",role:\"dialog\",tabIndex:\"-1\",\"aria-modal\":\"true\",\"aria-hidden\":\"true\",\"aria-label\":this.localize(\"{{MODAL}}\")}).forEach((t=>this.$container.setAttribute(...t))),this.option(\"animated\")&&this.$container.classList.add(\"is-animated\"),this.$backdrop=this.$container.querySelector(\".fancybox__backdrop\"),this.$backdrop||(this.$backdrop=document.createElement(\"div\"),this.$backdrop.classList.add(\"fancybox__backdrop\"),this.$container.appendChild(this.$backdrop)),this.$carousel=this.$container.querySelector(\".fancybox__carousel\"),this.$carousel||(this.$carousel=document.createElement(\"div\"),this.$carousel.classList.add(\"fancybox__carousel\"),this.$container.appendChild(this.$carousel)),this.$container.Fancybox=this,this.id=this.$container.getAttribute(\"id\"),this.id||(this.id=this.options.id||++F,this.$container.setAttribute(\"id\",\"fancybox-\"+this.id));const e=this.option(\"mainClass\");return e&&this.$container.classList.add(...e.split(\" \")),document.documentElement.classList.add(\"with-fancybox\"),this.trigger(\"initLayout\"),this}setItems(t){const e=[];for(const i of t){const t=i.$trigger;if(t){const e=t.dataset||{};i.src=e.src||t.getAttribute(\"href\")||i.src,i.type=e.type||i.type,!i.src&&t instanceof HTMLImageElement&&(i.src=t.currentSrc||i.$trigger.src)}let s=i.$thumb;if(!s){let t=i.$trigger&&i.$trigger.origTarget;t&&(s=t instanceof HTMLImageElement?t:t.querySelector(\"img:not([aria-hidden])\")),!s&&i.$trigger&&(s=i.$trigger instanceof HTMLImageElement?i.$trigger:i.$trigger.querySelector(\"img:not([aria-hidden])\"))}i.$thumb=s||null;let o=i.thumb;!o&&s&&(o=s.currentSrc||s.src,!o&&s.dataset&&(o=s.dataset.lazySrc||s.dataset.src)),o||\"image\"!==i.type||(o=i.src),i.thumb=o||null,i.caption=i.caption||\"\",e.push(i)}this.items=e}initCarousel(){return this.Carousel=new y(this.$carousel,e(!0,{},{prefix:\"\",classNames:{viewport:\"fancybox__viewport\",track:\"fancybox__track\",slide:\"fancybox__slide\"},textSelection:!0,preload:this.option(\"preload\"),friction:.88,slides:this.items,initialPage:this.options.startIndex,slidesPerPage:1,infiniteX:this.option(\"infinite\"),infiniteY:!0,l10n:this.option(\"l10n\"),Dots:!1,Navigation:{classNames:{main:\"fancybox__nav\",button:\"carousel__button\",next:\"is-next\",prev:\"is-prev\"}},Panzoom:{textSelection:!0,panOnlyZoomed:()=>this.Carousel&&this.Carousel.pages&&this.Carousel.pages.length<2&&!this.option(\"dragToClose\"),lockAxis:()=>{if(this.Carousel){let t=\"x\";return this.option(\"dragToClose\")&&(t+=\"y\"),t}}},on:{\"*\":(t,...e)=>this.trigger(`Carousel.${t}`,...e),init:t=>this.Carousel=t,createSlide:this.onCreateSlide,settle:this.onSettle}},this.option(\"Carousel\"))),this.option(\"dragToClose\")&&this.Carousel.Panzoom.on({touchMove:this.onTouchMove,afterTransform:this.onTransform,touchEnd:this.onTouchEnd}),this.trigger(\"initCarousel\"),this}onCreateSlide(t,e){let i=e.caption||\"\";if(\"function\"==typeof this.options.caption&&(i=this.options.caption.call(this,this,this.Carousel,e)),\"string\"==typeof i&&i.length){const t=document.createElement(\"div\"),s=`fancybox__caption_${this.id}_${e.index}`;t.className=\"fancybox__caption\",t.innerHTML=i,t.setAttribute(\"id\",s),e.$caption=e.$el.appendChild(t),e.$el.classList.add(\"has-caption\"),e.$el.setAttribute(\"aria-labelledby\",s)}}onSettle(){this.option(\"autoFocus\")&&this.focus()}onFocus(t){this.isTopmost()&&this.focus(t)}onClick(t){if(t.defaultPrevented)return;let e=t.composedPath()[0];if(e.matches(\"[data-fancybox-close]\"))return t.preventDefault(),void R.close(!1,t);if(e.matches(\"[data-fancybox-next]\"))return t.preventDefault(),void R.next();if(e.matches(\"[data-fancybox-prev]\"))return t.preventDefault(),void R.prev();const i=document.activeElement;if(i){if(i.closest(\"[contenteditable]\"))return;e.matches(x)||i.blur()}if(e.closest(\".fancybox__content\"))return;if(getSelection().toString().length)return;if(!1===this.trigger(\"click\",t))return;switch(this.option(\"click\")){case\"close\":this.close();break;case\"next\":this.next()}}onTouchMove(){const t=this.getSlide().Panzoom;return!t||1===t.content.scale}onTouchEnd(t){const e=t.dragOffset.y;Math.abs(e)>=150||Math.abs(e)>=35&&t.dragOffset.time<350?(this.option(\"hideClass\")&&(this.getSlide().hideClass=\"fancybox-throwOut\"+(t.content.y<0?\"Up\":\"Down\")),this.close()):\"y\"===t.lockAxis&&t.panTo({y:0})}onTransform(t){if(this.$backdrop){const e=Math.abs(t.content.y),i=e<1?\"\":Math.max(.33,Math.min(1,1-e/t.content.fitHeight*1.5));this.$container.style.setProperty(\"--fancybox-ts\",i?\"0s\":\"\"),this.$container.style.setProperty(\"--fancybox-opacity\",i)}}onMousedown(){\"ready\"===this.state&&document.body.classList.add(\"is-using-mouse\")}onKeydown(t){if(!this.isTopmost())return;document.body.classList.remove(\"is-using-mouse\");const e=t.key,i=this.option(\"keyboard\");if(!i||t.ctrlKey||t.altKey||t.shiftKey)return;const s=t.composedPath()[0],o=document.activeElement&&document.activeElement.classList,n=o&&o.contains(\"carousel__button\");if(\"Escape\"!==e&&!n){if(t.target.isContentEditable||-1!==[\"BUTTON\",\"TEXTAREA\",\"OPTION\",\"INPUT\",\"SELECT\",\"VIDEO\"].indexOf(s.nodeName))return}if(!1===this.trigger(\"keydown\",e,t))return;const a=i[e];\"function\"==typeof this[a]&&this[a]()}getSlide(){const t=this.Carousel;if(!t)return null;const e=null===t.page?t.option(\"initialPage\"):t.page,i=t.pages||[];return i.length&&i[e]?i[e].slides[0]:null}focus(t){if(R.ignoreFocusChange)return;if([\"init\",\"closing\",\"customClosing\",\"destroy\"].indexOf(this.state)>-1)return;const e=this.$container,i=this.getSlide(),s=\"done\"===i.state?i.$el:null;if(s&&s.contains(document.activeElement))return;t&&t.preventDefault(),R.ignoreFocusChange=!0;const o=Array.from(e.querySelectorAll(x));let n,a=[];for(let t of o){const e=t.offsetParent,i=s&&s.contains(t),o=!this.Carousel.$viewport.contains(t);e&&(i||o)?(a.push(t),void 0!==t.dataset.origTabindex&&(t.tabIndex=t.dataset.origTabindex,t.removeAttribute(\"data-orig-tabindex\")),(t.hasAttribute(\"autoFocus\")||!n&&i&&!t.classList.contains(\"carousel__button\"))&&(n=t)):(t.dataset.origTabindex=void 0===t.dataset.origTabindex?t.getAttribute(\"tabindex\"):t.dataset.origTabindex,t.tabIndex=-1)}t?a.indexOf(t.target)>-1?this.lastFocus=t.target:this.lastFocus===e?w(a[a.length-1]):w(e):this.option(\"autoFocus\")&&n?w(n):a.indexOf(document.activeElement)<0&&w(e),this.lastFocus=document.activeElement,R.ignoreFocusChange=!1}hideScrollbar(){if(!v)return;const t=window.innerWidth-document.documentElement.getBoundingClientRect().width,e=\"fancybox-style-noscroll\";let i=document.getElementById(e);i||t>0&&(i=document.createElement(\"style\"),i.id=e,i.type=\"text/css\",i.innerHTML=`.compensate-for-scrollbar {padding-right: ${t}px;}`,document.getElementsByTagName(\"head\")[0].appendChild(i),document.body.classList.add(\"compensate-for-scrollbar\"))}revealScrollbar(){document.body.classList.remove(\"compensate-for-scrollbar\");const t=document.getElementById(\"fancybox-style-noscroll\");t&&t.remove()}clearContent(t){this.Carousel.trigger(\"removeSlide\",t),t.$content&&(t.$content.remove(),t.$content=null),t.$closeButton&&(t.$closeButton.remove(),t.$closeButton=null),t._className&&t.$el.classList.remove(t._className)}setContent(t,e,i={}){let s;const o=t.$el;if(e instanceof HTMLElement)[\"img\",\"iframe\",\"video\",\"audio\"].indexOf(e.nodeName.toLowerCase())>-1?(s=document.createElement(\"div\"),s.appendChild(e)):s=e;else{const t=document.createRange().createContextualFragment(e);s=document.createElement(\"div\"),s.appendChild(t)}if(t.filter&&!t.error&&(s=s.querySelector(t.filter)),s instanceof Element)return t._className=`has-${i.suffix||t.type||\"unknown\"}`,o.classList.add(t._className),s.classList.add(\"fancybox__content\"),\"none\"!==s.style.display&&\"none\"!==getComputedStyle(s).getPropertyValue(\"display\")||(s.style.display=t.display||this.option(\"defaultDisplay\")||\"flex\"),t.id&&s.setAttribute(\"id\",t.id),t.$content=s,o.prepend(s),this.manageCloseButton(t),\"loading\"!==t.state&&this.revealContent(t),s;this.setError(t,\"{{ELEMENT_NOT_FOUND}}\")}manageCloseButton(t){const e=void 0===t.closeButton?this.option(\"closeButton\"):t.closeButton;if(!e||\"top\"===e&&this.$closeButton)return;const i=document.createElement(\"button\");i.classList.add(\"carousel__button\",\"is-close\"),i.setAttribute(\"title\",this.options.l10n.CLOSE),i.innerHTML=this.option(\"template.closeButton\"),i.addEventListener(\"click\",(t=>this.close(t))),\"inside\"===e?(t.$closeButton&&t.$closeButton.remove(),t.$closeButton=t.$content.appendChild(i)):this.$closeButton=this.$container.insertBefore(i,this.$container.firstChild)}revealContent(t){this.trigger(\"reveal\",t),t.$content.style.visibility=\"\";let e=!1;t.error||\"loading\"===t.state||null!==this.Carousel.prevPage||t.index!==this.options.startIndex||(e=void 0===t.showClass?this.option(\"showClass\"):t.showClass),e?(t.state=\"animating\",this.animateCSS(t.$content,e,(()=>{this.done(t)}))):this.done(t)}animateCSS(t,e,i){if(t&&t.dispatchEvent(new CustomEvent(\"animationend\",{bubbles:!0,cancelable:!0})),!t||!e)return void(\"function\"==typeof i&&i());const s=function(o){o.currentTarget===this&&(t.removeEventListener(\"animationend\",s),i&&i(),t.classList.remove(e))};t.addEventListener(\"animationend\",s),t.classList.add(e)}done(t){t.state=\"done\",this.trigger(\"done\",t);const e=this.getSlide();e&&t.index===e.index&&this.option(\"autoFocus\")&&this.focus()}setError(t,e){t.error=e,this.hideLoading(t),this.clearContent(t);const i=document.createElement(\"div\");i.classList.add(\"fancybox-error\"),i.innerHTML=this.localize(e||\"

{{ERROR}}

\"),this.setContent(t,i,{suffix:\"error\"})}showLoading(t){t.state=\"loading\",t.$el.classList.add(\"is-loading\");let e=t.$el.querySelector(\".fancybox__spinner\");e||(e=document.createElement(\"div\"),e.classList.add(\"fancybox__spinner\"),e.innerHTML=this.option(\"template.spinner\"),e.addEventListener(\"click\",(()=>{this.Carousel.Panzoom.velocity||this.close()})),t.$el.prepend(e))}hideLoading(t){const e=t.$el&&t.$el.querySelector(\".fancybox__spinner\");e&&(e.remove(),t.$el.classList.remove(\"is-loading\")),\"loading\"===t.state&&(this.trigger(\"load\",t),t.state=\"ready\")}next(){const t=this.Carousel;t&&t.pages.length>1&&t.slideNext()}prev(){const t=this.Carousel;t&&t.pages.length>1&&t.slidePrev()}jumpTo(...t){this.Carousel&&this.Carousel.slideTo(...t)}isClosing(){return[\"closing\",\"customClosing\",\"destroy\"].includes(this.state)}isTopmost(){return R.getInstance().id==this.id}close(t){if(t&&t.preventDefault(),this.isClosing())return;if(!1===this.trigger(\"shouldClose\",t))return;if(this.state=\"closing\",this.Carousel.Panzoom.destroy(),this.detachEvents(),this.trigger(\"closing\",t),\"destroy\"===this.state)return;this.$container.setAttribute(\"aria-hidden\",\"true\"),this.$container.classList.add(\"is-closing\");const e=this.getSlide();if(this.Carousel.slides.forEach((t=>{t.$content&&t.index!==e.index&&this.Carousel.trigger(\"removeSlide\",t)})),\"closing\"===this.state){const t=void 0===e.hideClass?this.option(\"hideClass\"):e.hideClass;this.animateCSS(e.$content,t,(()=>{this.destroy()}),!0)}}destroy(){if(\"destroy\"===this.state)return;this.state=\"destroy\",this.trigger(\"destroy\");const t=this.option(\"placeFocusBack\")?this.option(\"triggerTarget\",this.getSlide().$trigger):null;this.Carousel.destroy(),this.detachPlugins(),this.Carousel=null,this.options={},this.events={},this.$container.remove(),this.$container=this.$backdrop=this.$carousel=null,t&&w(t),I.delete(this.id);const e=R.getInstance();e?e.focus():(document.documentElement.classList.remove(\"with-fancybox\"),document.body.classList.remove(\"is-using-mouse\"),this.revealScrollbar())}static show(t,e={}){return new R(t,e)}static fromEvent(t,e={}){if(t.defaultPrevented)return;if(t.button&&0!==t.button)return;if(t.ctrlKey||t.metaKey||t.shiftKey)return;const i=t.composedPath()[0];let s,o,n,a=i;if((a.matches(\"[data-fancybox-trigger]\")||(a=a.closest(\"[data-fancybox-trigger]\")))&&(e.triggerTarget=a,s=a&&a.dataset&&a.dataset.fancyboxTrigger),s){const t=document.querySelectorAll(`[data-fancybox=\"${s}\"]`),e=parseInt(a.dataset.fancyboxIndex,10)||0;a=t.length?t[e]:a}Array.from(R.openers.keys()).reverse().some((e=>{n=a||i;let s=!1;try{n instanceof Element&&(\"string\"==typeof e||e instanceof String)&&(s=n.matches(e)||(n=n.closest(e)))}catch(t){}return!!s&&(t.preventDefault(),o=e,!0)}));let r=!1;if(o){e.event=t,e.target=n,n.origTarget=i,r=R.fromOpener(o,e);const s=R.getInstance();s&&\"ready\"===s.state&&t.detail&&document.body.classList.add(\"is-using-mouse\")}return r}static fromOpener(t,i={}){let s=[],o=i.startIndex||0,n=i.target||null;const a=void 0!==(i=e({},i,R.openers.get(t))).groupAll&&i.groupAll,r=void 0===i.groupAttr?\"data-fancybox\":i.groupAttr,h=r&&n?n.getAttribute(`${r}`):\"\";if(!n||h||a){const e=i.root||(n?n.getRootNode():document.body);s=[].slice.call(e.querySelectorAll(t))}if(n&&!a&&(s=h?s.filter((t=>t.getAttribute(`${r}`)===h)):[n]),!s.length)return!1;const l=R.getInstance();return!(l&&s.indexOf(l.options.$trigger)>-1)&&(o=n?s.indexOf(n):o,s=s.map((function(t){const e=[\"false\",\"0\",\"no\",\"null\",\"undefined\"],i=[\"true\",\"1\",\"yes\"],s=Object.assign({},t.dataset),o={};for(let[t,n]of Object.entries(s))if(\"fancybox\"!==t)if(\"width\"===t||\"height\"===t)o[`_${t}`]=n;else if(\"string\"==typeof n||n instanceof String)if(e.indexOf(n)>-1)o[t]=!1;else if(i.indexOf(o[t])>-1)o[t]=!0;else try{o[t]=JSON.parse(n)}catch(e){o[t]=n}else o[t]=n;return t instanceof Element&&(o.$trigger=t),o})),new R(s,e({},i,{startIndex:o,$trigger:n})))}static bind(t,e={}){function i(){document.body.addEventListener(\"click\",R.fromEvent,!1)}v&&(R.openers.size||(/complete|interactive|loaded/.test(document.readyState)?i():document.addEventListener(\"DOMContentLoaded\",i)),R.openers.set(t,e))}static unbind(t){R.openers.delete(t),R.openers.size||R.destroy()}static destroy(){let t;for(;t=R.getInstance();)t.destroy();R.openers=new Map,document.body.removeEventListener(\"click\",R.fromEvent,!1)}static getInstance(t){if(t)return I.get(t);return Array.from(I.values()).reverse().find((t=>!t.isClosing()&&t))||null}static close(t=!0,e){if(t)for(const t of I.values())t.close(e);else{const t=R.getInstance();t&&t.close(e)}}static next(){const t=R.getInstance();t&&t.next()}static prev(){const t=R.getInstance();t&&t.prev()}}R.version=\"4.0.31\",R.defaults=M,R.openers=new Map,R.Plugins=O,R.bind(\"[data-fancybox]\");for(const[t,e]of Object.entries(R.Plugins||{}))\"function\"==typeof e.create&&e.create(R);export{y as Carousel,R as Fancybox,d as Panzoom};\n","import { Controller } from '@hotwired/stimulus';\nimport { Carousel } from '@fancyapps/ui';\n\nexport default class extends Controller {\n connect() {\n const container = this.element\n const options = {\n slidesPerPage: 1,\n }\n\n new Carousel(container, options)\n }\n}\n","import { Controller } from '@hotwired/stimulus';\n\nexport default class extends Controller {\n static targets = [\n 'categoryInput',\n 'link',\n 'selectLabel',\n ]\n\n connect () {\n if (this.categoryInputTarget.dataset.categoryName != undefined) {\n this.updateSelectLabelFromElement(this.categoryInputTarget)\n }\n }\n\n updateCategory (event) {\n this.updateCategoryFromElement(event.target)\n this.updateSelectLabelFromElement(event.target)\n }\n\n updateCategoryValueFromData () {\n if (this.categoryInputTarget.value) {\n return\n }\n\n this.categoryInputTarget.value = this.categoryInputTarget.dataset.categoryId\n }\n\n updateCategoryFromElement (element) {\n this.categoryInputTarget.value = element.dataset.categoryId\n this.categoryInputTarget.dataset.categoryName = element.dataset.categoryName\n this.categoryInputTarget.dataset.categoryId = element.dataset.categoryId\n }\n\n updateSelectLabelFromElement (element) {\n this.selectLabelTarget.textContent = element.dataset.categoryName\n }\n}\n","import { Controller } from '@hotwired/stimulus';\n\nexport default class extends Controller {\n static targets = ['childCategory', 'emptyChildCategory', 'rootCategory']\n\n connect () {\n this.updateChildCategories();\n }\n\n updateChildCategories () {\n const childCategories = this.childCategoryTargets\n const venueCategorySelect = this.rootCategoryTarget\n const selectedOption = venueCategorySelect.options[venueCategorySelect.selectedIndex].value\n\n childCategories.forEach((childCategory) => {\n const parentCategoryId = childCategory.dataset.parentCategoryId\n\n if (parentCategoryId === selectedOption) {\n this.emptyChildCategoryTarget.style.display = 'none'\n this.showCategory(childCategory)\n } else if (selectedOption === '') {\n this.emptyChildCategoryTarget.style.display = 'block'\n this.hideCategory(childCategory)\n } else {\n this.hideCategory(childCategory)\n }\n })\n }\n\n hideCategory (childCategory) {\n childCategory.style.display = 'none'\n childCategory.disabled = true\n }\n\n showCategory (childCategory) {\n childCategory.classList.remove('d-none')\n childCategory.style.display = 'block'\n childCategory.disabled = false\n }\n}\n","import { Controller } from '@hotwired/stimulus';\n\nexport default class extends Controller {\n static targets = ['source', 'form']\n\n connect () {\n this.sourceTargets.forEach((source) => {\n source.addEventListener('change', this.handleChange.bind(this))\n })\n }\n\n handleChange (event) {\n const syncKey = event.target.dataset.checkboxSyncKey\n const isChecked = event.target.checked\n\n this.syncCheckboxes(syncKey, isChecked)\n }\n\n syncCheckboxes (syncKey, isChecked) {\n if (!syncKey) { return; }\n\n this.sourceTargets.forEach((source) => {\n if (source.dataset.checkboxSyncKey === syncKey) {\n source.checked = isChecked\n }\n })\n }\n}\n","// JavaScript autoComplete v1.0.4\n// https://github.com/Pixabay/JavaScript-autoComplete\nvar autoComplete = function(){function e(e){function t(e,t){return e.classList?e.classList.contains(t):new RegExp(\"\\\\b\"+t+\"\\\\b\").test(e.className)}function o(e,t,o){e.attachEvent?e.attachEvent(\"on\"+t,o):e.addEventListener(t,o)}function s(e,t,o){e.detachEvent?e.detachEvent(\"on\"+t,o):e.removeEventListener(t,o)}function n(e,s,n,l){o(l||document,s,function(o){for(var s,l=o.target||o.srcElement;l&&!(s=t(l,e));)l=l.parentElement;s&&n.call(l,o)})}if(document.querySelector){var l={selector:0,source:0,minChars:3,delay:150,offsetLeft:0,offsetTop:1,cache:1,menuClass:\"\",renderItem:function(e,t){t=t.replace(/[-\\/\\\\^$*+?.()|[\\]{}]/g,\"\\\\$&\");var o=new RegExp(\"(\"+t.split(\" \").join(\"|\")+\")\",\"gi\");return'
'+e.replace(o,\"$1\")+\"
\"},onSelect:function(){}};for(var c in e)e.hasOwnProperty(c)&&(l[c]=e[c]);for(var a=\"object\"==typeof l.selector?[l.selector]:document.querySelectorAll(l.selector),u=0;u0?i.sc.scrollTop=n+i.sc.suggestionHeight+s-i.sc.maxHeight:0>n&&(i.sc.scrollTop=n+s)}else i.sc.scrollTop=0},o(window,\"resize\",i.updateSC),document.body.appendChild(i.sc),n(\"autocomplete-suggestion\",\"mouseleave\",function(){var e=i.sc.querySelector(\".autocomplete-suggestion.selected\");e&&setTimeout(function(){e.className=e.className.replace(\"selected\",\"\")},20)},i.sc),n(\"autocomplete-suggestion\",\"mouseover\",function(){var e=i.sc.querySelector(\".autocomplete-suggestion.selected\");e&&(e.className=e.className.replace(\"selected\",\"\")),this.className+=\" selected\"},i.sc),n(\"autocomplete-suggestion\",\"mousedown\",function(e){if(t(this,\"autocomplete-suggestion\")){var o=this.getAttribute(\"data-val\");i.value=o,l.onSelect(e,o,this),i.sc.style.display=\"none\"}},i.sc),i.blurHandler=function(){try{var e=document.querySelector(\".autocomplete-suggestions:hover\")}catch(t){var e=0}e?i!==document.activeElement&&setTimeout(function(){i.focus()},20):(i.last_val=i.value,i.sc.style.display=\"none\",setTimeout(function(){i.sc.style.display=\"none\"},350))},o(i,\"blur\",i.blurHandler);var r=function(e){var t=i.value;if(i.cache[t]=e,e.length&&t.length>=l.minChars){for(var o=\"\",s=0;st||t>40)&&13!=t&&27!=t){var o=i.value;if(o.length>=l.minChars){if(o!=i.last_val){if(i.last_val=o,clearTimeout(i.timer),l.cache){if(o in i.cache)return void r(i.cache[o]);for(var s=1;s' + display_name + ''\n return html\n }\n },\n\n selector: inputSelector,\n\n minChars: 2,\n\n source: function (term, response) {\n fetch('/cities/search.json?query=' + term)\n .then(res => res.json())\n .then(function(res) {\n response(res)\n\n // Store first suggestion\n if (res.length > 0) {\n var firstSuggestion = res[0]\n\n outputSelector.value = firstSuggestion.city.id\n onFirstSuggestion(firstSuggestion)\n }\n\n })\n }\n });\n\n this.buildRandomString = function() {\n var result = Math.random().toString(36).replace(/[^a-z]+/g, '').substr(0, 5);\n return result;\n }\n}\n","import cityPicker from '../backend/_city_picker';\nimport { Controller } from \"@hotwired/stimulus\";\n\nexport default class extends Controller {\n static targets = [\"input\", \"output\", \"submit\"]\n\n connect () {\n const input = this.inputTarget\n const output = this.outputTarget\n\n new cityPicker({\n input: input,\n output: output,\n onFirstSuggestion: (suggestion) => {\n this.firstSuggestion = suggestion\n }\n })\n\n this.disableEnterKey(input)\n }\n\n submit (event) {\n if (this.firstSuggestion && !this.outputTarget.value) {\n // Fill in the hidden field with the first suggestion\n this.outputTarget.value = this.firstSuggestion.city.id\n }\n }\n\n disableEnterKey (input) {\n input.addEventListener(\"keypress\", function(event) {\n if (event.keyCode === 13) {\n event.preventDefault();\n }\n });\n }\n}\n","import { Controller } from '@hotwired/stimulus';\n\n// Controller that forwards clicks on table cell elements to the first link\n// inside that table cell.\n//\n// This makes it possible to click anywhere in a table row to follow the link in\n// each cell regardless of padding and margin - even if the link is empty.\nexport default class extends Controller {\n connect() {\n this.element.addEventListener('click', (event) => {\n const target = event.target;\n const nodeName = target.nodeName;\n if (nodeName == 'TD') {\n const element = event.currentTarget.querySelector('a');\n if (element !== undefined) {\n element.click();\n }\n }\n });\n }\n}\n","/* global window */\n/* global IntersectionObserver */\nimport { Controller } from '@hotwired/stimulus';\n\nfunction easeInOutSine(x) {\n return -(Math.cos(Math.PI * x) - 1) / 2;\n}\n\nfunction supportsIntersectionObserver() {\n if (typeof (IntersectionObserver) === 'undefined') {\n return false;\n }\n return true;\n}\n\nexport default class extends Controller {\n animate() {\n window.requestAnimationFrame(this.step.bind(this));\n }\n\n connect() {\n if (!supportsIntersectionObserver()) { return; }\n\n this.initializeCallback();\n }\n\n step(timestamp) {\n if (!this.start) {\n this.start = timestamp;\n }\n const progress = (timestamp - this.start) / this.duration;\n const actualNumber = easeInOutSine(progress) * this.final;\n\n this.setText(Math.floor(actualNumber));\n\n if (progress < 1) {\n this.animate();\n } else {\n this.setText(this.final);\n }\n }\n\n initializeCallback() {\n this.startObserving();\n this.duration = 4000; // duration in ms\n this.final = parseInt(this.element.textContent, 10); // parse out the final number\n }\n\n animateAndStopObserving(entries) {\n entries.forEach((entry) => {\n if (entry.isIntersecting) {\n this.animate();\n this.stopObserving();\n }\n });\n }\n\n setText(text) {\n this.element.textContent = text;\n }\n\n startObserving() {\n this.observer = new IntersectionObserver(this.animateAndStopObserving.bind(this));\n this.observer.observe(this.element);\n }\n\n stopObserving() {\n this.observer.unobserve(this.element);\n }\n}\n","class t extends Date{static parseDateTime(e,i=\"YYYY-MM-DD\",n=\"en-US\"){if(!e)return new Date((new Date).setHours(0,0,0,0));if(e instanceof t)return e.toJSDate();if(e instanceof Date)return e;if(/^-?\\d{10,}$/.test(String(e)))return new Date(Number(e));if(\"string\"==typeof e){const s=[];let o=null;for(;null!=(o=t.regex.exec(i));)\"\\\\\"!==o[1]&&s.push(o);if(s.length){const i={year:null,month:null,shortMonth:null,longMonth:null,day:null,hour:0,minute:0,second:0,ampm:null,value:\"\"};s[0].index>0&&(i.value+=\".*?\");for(const[e,o]of Object.entries(s)){const s=Number(e),{group:a,pattern:r}=t.formatPatterns(o[0],n);i[a]=s+1,i.value+=r,i.value+=\".*?\"}const o=new RegExp(`^${i.value}$`);if(o.test(e)){const s=o.exec(e),a=Number(s[i.year]);let r=null;i.month?r=Number(s[i.month])-1:i.shortMonth?r=t.shortMonths(n).indexOf(s[i.shortMonth]):i.longMonth&&(r=t.longMonths(n).indexOf(s[i.longMonth]));const c=Number(s[i.day])||1,l=Number(s[i.hour]);let h=Number.isNaN(l)?0:l;const d=Number(s[i.minute]),p=Number.isNaN(d)?0:d,u=Number(s[i.second]),g=Number.isNaN(u)?0:u,m=s[i.ampm];return m&&\"PM\"===m&&(h+=12,24===h&&(h=0)),new Date(a,r,c,h,p,g,0)}}}return new Date((new Date).setHours(0,0,0,0))}static regex=/(\\\\)?(Y{2,4}|M{1,4}|D{1,2}|H{1,2}|h{1,2}|m{1,2}|s{1,2}|A|a)/g;static MONTH_JS=[0,1,2,3,4,5,6,7,8,9,10,11];static shortMonths(e){return t.MONTH_JS.map((t=>new Date(2019,t).toLocaleString(e,{month:\"short\"})))}static longMonths(e){return t.MONTH_JS.map((t=>new Date(2019,t).toLocaleString(e,{month:\"long\"})))}static formatPatterns(e,i){switch(e){case\"YY\":case\"YYYY\":return{group:\"year\",pattern:`(\\\\d{${e.length}})`};case\"M\":return{group:\"month\",pattern:\"(\\\\d{1,2})\"};case\"MM\":return{group:\"month\",pattern:\"(\\\\d{2})\"};case\"MMM\":return{group:\"shortMonth\",pattern:`(${t.shortMonths(i).join(\"|\")})`};case\"MMMM\":return{group:\"longMonth\",pattern:`(${t.longMonths(i).join(\"|\")})`};case\"D\":return{group:\"day\",pattern:\"(\\\\d{1,2})\"};case\"DD\":return{group:\"day\",pattern:\"(\\\\d{2})\"};case\"h\":case\"H\":return{group:\"hour\",pattern:\"(\\\\d{1,2})\"};case\"hh\":case\"HH\":return{group:\"hour\",pattern:\"(\\\\d{2})\"};case\"m\":return{group:\"minute\",pattern:\"(\\\\d{1,2})\"};case\"mm\":return{group:\"minute\",pattern:\"(\\\\d{2})\"};case\"s\":return{group:\"second\",pattern:\"(\\\\d{1,2})\"};case\"ss\":return{group:\"second\",pattern:\"(\\\\d{2})\"};case\"a\":case\"A\":return{group:\"ampm\",pattern:\"(AM|PM|am|pm)\"}}}lang;constructor(e=null,i=\"YYYY-MM-DD\",n=\"en-US\"){super(t.parseDateTime(e,i,n)),this.lang=n}getWeek(t){const e=new Date(this.midnight_ts(this)),i=(this.getDay()+(7-t))%7;e.setDate(e.getDate()-i);const n=e.getTime();return e.setMonth(0,1),e.getDay()!==t&&e.setMonth(0,1+(4-e.getDay()+7)%7),1+Math.ceil((n-e.getTime())/6048e5)}clone(){return new t(this)}toJSDate(){return new Date(this)}inArray(t,e=\"[]\"){return t.some((t=>t instanceof Array?this.isBetween(t[0],t[1],e):this.isSame(t,\"day\")))}isBetween(t,e,i=\"()\"){switch(i){default:case\"()\":return this.midnight_ts(this)>this.midnight_ts(t)&&this.midnight_ts(this)=this.midnight_ts(t)&&this.midnight_ts(this)this.midnight_ts(t)&&this.midnight_ts(this)<=this.midnight_ts(e);case\"[]\":return this.midnight_ts()>=this.midnight_ts(t)&&this.midnight_ts()<=this.midnight_ts(e)}}isBefore(t,e=\"days\"){switch(e){case\"day\":case\"days\":return new Date(t.getFullYear(),t.getMonth(),t.getDate()).getTime()>new Date(this.getFullYear(),this.getMonth(),this.getDate()).getTime();case\"month\":case\"months\":return new Date(t.getFullYear(),t.getMonth(),1).getTime()>new Date(this.getFullYear(),this.getMonth(),1).getTime();case\"year\":case\"years\":return t.getFullYear()>this.getFullYear()}throw new Error(\"isBefore: Invalid unit!\")}isSameOrBefore(t,e=\"days\"){switch(e){case\"day\":case\"days\":return new Date(t.getFullYear(),t.getMonth(),t.getDate()).getTime()>=new Date(this.getFullYear(),this.getMonth(),this.getDate()).getTime();case\"month\":case\"months\":return new Date(t.getFullYear(),t.getMonth(),1).getTime()>=new Date(this.getFullYear(),this.getMonth(),1).getTime()}throw new Error(\"isSameOrBefore: Invalid unit!\")}isAfter(t,e=\"days\"){switch(e){case\"day\":case\"days\":return new Date(this.getFullYear(),this.getMonth(),this.getDate()).getTime()>new Date(t.getFullYear(),t.getMonth(),t.getDate()).getTime();case\"month\":case\"months\":return new Date(this.getFullYear(),this.getMonth(),1).getTime()>new Date(t.getFullYear(),t.getMonth(),1).getTime();case\"year\":case\"years\":return this.getFullYear()>t.getFullYear()}throw new Error(\"isAfter: Invalid unit!\")}isSameOrAfter(t,e=\"days\"){switch(e){case\"day\":case\"days\":return new Date(this.getFullYear(),this.getMonth(),this.getDate()).getTime()>=new Date(t.getFullYear(),t.getMonth(),t.getDate()).getTime();case\"month\":case\"months\":return new Date(this.getFullYear(),this.getMonth(),1).getTime()>=new Date(t.getFullYear(),t.getMonth(),1).getTime()}throw new Error(\"isSameOrAfter: Invalid unit!\")}isSame(t,e=\"days\"){switch(e){case\"day\":case\"days\":return new Date(this.getFullYear(),this.getMonth(),this.getDate()).getTime()===new Date(t.getFullYear(),t.getMonth(),t.getDate()).getTime();case\"month\":case\"months\":return new Date(this.getFullYear(),this.getMonth(),1).getTime()===new Date(t.getFullYear(),t.getMonth(),1).getTime()}throw new Error(\"isSame: Invalid unit!\")}add(t,e=\"days\"){switch(e){case\"day\":case\"days\":this.setDate(this.getDate()+t);break;case\"month\":case\"months\":this.setMonth(this.getMonth()+t)}return this}subtract(t,e=\"days\"){switch(e){case\"day\":case\"days\":this.setDate(this.getDate()-t);break;case\"month\":case\"months\":this.setMonth(this.getMonth()-t)}return this}diff(t,e=\"days\"){switch(e){default:case\"day\":case\"days\":return Math.round((this.midnight_ts()-this.midnight_ts(t))/864e5);case\"month\":case\"months\":let e=12*(t.getFullYear()-this.getFullYear());return e-=t.getMonth(),e+=this.getMonth(),e}}format(e,i=\"en-US\"){let n=\"\";const s=[];let o=null;for(;null!=(o=t.regex.exec(e));)\"\\\\\"!==o[1]&&s.push(o);if(s.length){s[0].index>0&&(n+=e.substring(0,s[0].index));for(const[t,o]of Object.entries(s)){const a=Number(t);n+=this.formatTokens(o[0],i),s[a+1]&&(n+=e.substring(o.index+o[0].length,s[a+1].index)),a===s.length-1&&(n+=e.substring(o.index+o[0].length))}}return n.replace(/\\\\/g,\"\")}midnight_ts(t){return t?new Date(t.getFullYear(),t.getMonth(),t.getDate(),0,0,0,0).getTime():new Date(this.getFullYear(),this.getMonth(),this.getDate(),0,0,0,0).getTime()}formatTokens(e,i){switch(e){case\"YY\":return String(this.getFullYear()).slice(-2);case\"YYYY\":return String(this.getFullYear());case\"M\":return String(this.getMonth()+1);case\"MM\":return`0${this.getMonth()+1}`.slice(-2);case\"MMM\":return t.shortMonths(i)[this.getMonth()];case\"MMMM\":return t.longMonths(i)[this.getMonth()];case\"D\":return String(this.getDate());case\"DD\":return`0${this.getDate()}`.slice(-2);case\"H\":return String(this.getHours());case\"HH\":return`0${this.getHours()}`.slice(-2);case\"h\":return String(this.getHours()%12||12);case\"hh\":return`0${this.getHours()%12||12}`.slice(-2);case\"m\":return String(this.getMinutes());case\"mm\":return`0${this.getMinutes()}`.slice(-2);case\"s\":return String(this.getSeconds());case\"ss\":return`0${this.getSeconds()}`.slice(-2);case\"a\":return this.getHours()<12||24===this.getHours()?\"am\":\"pm\";case\"A\":return this.getHours()<12||24===this.getHours()?\"AM\":\"PM\";default:return\"\"}}}class e{picker;constructor(t){this.picker=t}render(e,i){e||(e=new t),e.setDate(1),e.setHours(0,0,0,0),\"function\"==typeof this[`get${i}View`]&&this[`get${i}View`](e)}getContainerView(t){this.picker.ui.container.innerHTML=\"\",this.picker.options.header&&this.picker.trigger(\"render\",{date:t.clone(),view:\"Header\"}),this.picker.trigger(\"render\",{date:t.clone(),view:\"Main\"}),this.picker.options.autoApply||this.picker.trigger(\"render\",{date:t.clone(),view:\"Footer\"})}getHeaderView(t){const e=document.createElement(\"header\");this.picker.options.header instanceof HTMLElement&&e.appendChild(this.picker.options.header),\"string\"==typeof this.picker.options.header&&(e.innerHTML=this.picker.options.header),this.picker.ui.container.appendChild(e),this.picker.trigger(\"view\",{target:e,date:t.clone(),view:\"Header\"})}getMainView(t){const e=document.createElement(\"main\");this.picker.ui.container.appendChild(e);const i=document.createElement(\"div\");i.className=`calendars grid-${this.picker.options.grid}`;for(let e=0;e${t.toLocaleString(this.picker.options.lang,{month:\"long\"})} ${t.format(\"YYYY\")}`,e.appendChild(i);const n=document.createElement(\"button\");n.className=\"previous-button unit\",n.innerHTML=this.picker.options.locale.previousMonth,e.appendChild(n);const s=document.createElement(\"button\");return s.className=\"next-button unit\",s.innerHTML=this.picker.options.locale.nextMonth,e.appendChild(s),e}getCalendarDayNamesView(){const t=document.createElement(\"div\");t.className=\"daynames-row\";for(let e=1;e<=7;e++){const i=3+this.picker.options.firstDay+e,n=document.createElement(\"div\");n.className=\"dayname\",n.innerHTML=new Date(1970,0,i,12,0,0,0).toLocaleString(this.picker.options.lang,{weekday:\"short\"}),n.title=new Date(1970,0,i,12,0,0,0).toLocaleString(this.picker.options.lang,{weekday:\"long\"}),t.appendChild(n),this.picker.trigger(\"view\",{dayIdx:i,view:\"CalendarDayName\",target:n})}return t}getCalendarDaysView(t){const e=document.createElement(\"div\");e.className=\"days-grid\";const i=this.calcOffsetDays(t,this.picker.options.firstDay),n=32-new Date(t.getFullYear(),t.getMonth(),32).getDate();for(let t=0;t{\"function\"==typeof e?t.push(new e):\"string\"==typeof e&&\"undefined\"!=typeof easepick&&Object.prototype.hasOwnProperty.call(easepick,e)?t.push(new easepick[e]):console.warn(`easepick: ${e} not found.`)})),t.sort(((t,e)=>t.priority>e.priority?-1:t.prioritye.dependencies.length?1:t.dependencies.length{t.attach(this.picker),this.instances[t.getName()]=t}))}getInstance(t){return this.instances[t]}addInstance(t){if(Object.prototype.hasOwnProperty.call(this.instances,t))console.warn(`easepick: ${t} already added.`);else{if(\"undefined\"!=typeof easepick&&Object.prototype.hasOwnProperty.call(easepick,t)){const e=new easepick[t];return e.attach(this.picker),this.instances[e.getName()]=e,e}if(\"undefined\"!==this.getPluginFn(t)){const e=new(this.getPluginFn(t));return e.attach(this.picker),this.instances[e.getName()]=e,e}console.warn(`easepick: ${t} not found.`)}return null}removeInstance(t){return t in this.instances&&this.instances[t].detach(),delete this.instances[t]}reloadInstance(t){return this.removeInstance(t),this.addInstance(t)}getPluginFn(t){return[...this.picker.options.plugins].filter((e=>\"function\"==typeof e&&(new e).getName()===t)).shift()}}class n{Calendar=new e(this);PluginManager=new i(this);calendars=[];datePicked=[];cssLoaded=0;binds={hidePicker:this.hidePicker.bind(this),show:this.show.bind(this)};options={doc:document,css:[],element:null,firstDay:1,grid:1,calendars:1,lang:\"en-US\",date:null,format:\"YYYY-MM-DD\",readonly:!0,autoApply:!0,header:!1,inline:!1,scrollToDate:!0,locale:{nextMonth:'',previousMonth:'',cancel:\"Cancel\",apply:\"Apply\"},documentClick:this.binds.hidePicker,plugins:[]};ui={container:null,shadowRoot:null,wrapper:null};version=\"1.2.1\";constructor(t){const e={...this.options.locale,...t.locale};this.options={...this.options,...t},this.options.locale=e,this.handleOptions(),this.ui.wrapper=document.createElement(\"span\"),this.ui.wrapper.style.display=\"none\",this.ui.wrapper.style.position=\"absolute\",this.ui.wrapper.style.pointerEvents=\"none\",this.ui.wrapper.className=\"easepick-wrapper\",this.ui.wrapper.attachShadow({mode:\"open\"}),this.ui.shadowRoot=this.ui.wrapper.shadowRoot,this.ui.container=document.createElement(\"div\"),this.ui.container.className=\"container\",this.options.zIndex&&(this.ui.container.style.zIndex=String(this.options.zIndex)),this.options.inline&&(this.ui.wrapper.style.position=\"relative\",this.ui.container.classList.add(\"inline\")),this.ui.shadowRoot.appendChild(this.ui.container),this.options.element.after(this.ui.wrapper),this.handleCSS(),this.options.element.addEventListener(\"click\",this.binds.show),this.on(\"view\",this.onView.bind(this)),this.on(\"render\",this.onRender.bind(this)),this.PluginManager.initialize(),this.parseValues(),\"function\"==typeof this.options.setup&&this.options.setup(this),this.on(\"click\",this.onClick.bind(this));const i=this.options.scrollToDate?this.getDate():null;this.renderAll(i)}on(t,e,i={}){this.ui.container.addEventListener(t,e,i)}off(t,e,i={}){this.ui.container.removeEventListener(t,e,i)}trigger(t,e={}){return this.ui.container.dispatchEvent(new CustomEvent(t,{detail:e}))}destroy(){this.options.element.removeEventListener(\"click\",this.binds.show),\"function\"==typeof this.options.documentClick&&document.removeEventListener(\"click\",this.options.documentClick,!0),Object.keys(this.PluginManager.instances).forEach((t=>{this.PluginManager.removeInstance(t)})),this.ui.wrapper.remove()}onRender(t){const{view:e,date:i}=t.detail;this.Calendar.render(i,e)}onView(t){const{view:e,target:i}=t.detail;\"Footer\"===e&&this.datePicked.length&&(i.querySelector(\".apply-button\").disabled=!1)}onClickHeaderButton(t){this.isCalendarHeaderButton(t)&&(t.classList.contains(\"next-button\")?this.calendars[0].add(1,\"month\"):this.calendars[0].subtract(1,\"month\"),this.renderAll(this.calendars[0]))}onClickCalendarDay(e){if(this.isCalendarDay(e)){const i=new t(e.dataset.time);this.options.autoApply?(this.setDate(i),this.trigger(\"select\",{date:this.getDate()}),this.hide()):(this.datePicked[0]=i,this.trigger(\"preselect\",{date:this.getDate()}),this.renderAll())}}onClickApplyButton(t){if(this.isApplyButton(t)){if(this.datePicked[0]instanceof Date){const t=this.datePicked[0].clone();this.setDate(t)}this.hide(),this.trigger(\"select\",{date:this.getDate()})}}onClickCancelButton(t){this.isCancelButton(t)&&this.hide()}onClick(t){const e=t.target;if(e instanceof HTMLElement){const t=e.closest(\".unit\");if(!(t instanceof HTMLElement))return;this.onClickHeaderButton(t),this.onClickCalendarDay(t),this.onClickApplyButton(t),this.onClickCancelButton(t)}}isShown(){return this.ui.container.classList.contains(\"inline\")||this.ui.container.classList.contains(\"show\")}show(t){if(this.isShown())return;const e=t&&\"target\"in t?t.target:this.options.element,{top:i,left:n}=this.adjustPosition(e);this.ui.container.style.top=`${i}px`,this.ui.container.style.left=`${n}px`,this.ui.container.classList.add(\"show\"),this.trigger(\"show\",{target:e})}hide(){this.ui.container.classList.remove(\"show\"),this.datePicked.length=0,this.renderAll(),this.trigger(\"hide\")}setDate(e){const i=new t(e,this.options.format);this.options.date=i.clone(),this.updateValues(),this.calendars.length&&this.renderAll()}getDate(){return this.options.date instanceof t?this.options.date.clone():null}parseValues(){this.options.date?this.setDate(this.options.date):this.options.element instanceof HTMLInputElement&&this.options.element.value.length&&this.setDate(this.options.element.value),this.options.date instanceof Date||(this.options.date=null)}updateValues(){const t=this.getDate(),e=t instanceof Date?t.format(this.options.format,this.options.lang):\"\",i=this.options.element;i instanceof HTMLInputElement?i.value=e:i instanceof HTMLElement&&(i.innerText=e)}hidePicker(t){let e=t.target,i=null;e.shadowRoot&&(e=t.composedPath()[0],i=e.getRootNode().host),this.isShown()&&i!==this.ui.wrapper&&e!==this.options.element&&this.hide()}renderAll(t){this.trigger(\"render\",{view:\"Container\",date:(t||this.calendars[0]).clone()})}isCalendarHeaderButton(t){return[\"previous-button\",\"next-button\"].some((e=>t.classList.contains(e)))}isCalendarDay(t){return t.classList.contains(\"day\")}isApplyButton(t){return t.classList.contains(\"apply-button\")}isCancelButton(t){return t.classList.contains(\"cancel-button\")}gotoDate(e){const i=new t(e,this.options.format);i.setDate(1),this.calendars[0]=i.clone(),this.renderAll()}clear(){this.options.date=null,this.datePicked.length=0,this.updateValues(),this.renderAll(),this.trigger(\"clear\")}handleOptions(){this.options.element instanceof HTMLElement||(this.options.element=this.options.doc.querySelector(this.options.element)),\"function\"==typeof this.options.documentClick&&document.addEventListener(\"click\",this.options.documentClick,!0),this.options.element instanceof HTMLInputElement&&(this.options.element.readOnly=this.options.readonly),this.options.date?this.calendars[0]=new t(this.options.date,this.options.format):this.calendars[0]=new t}handleCSS(){if(Array.isArray(this.options.css))this.options.css.forEach((t=>{const e=document.createElement(\"link\");e.href=t,e.rel=\"stylesheet\";const i=()=>{this.cssLoaded++,this.cssLoaded===this.options.css.length&&(this.ui.wrapper.style.display=\"\")};e.addEventListener(\"load\",i),e.addEventListener(\"error\",i),this.ui.shadowRoot.append(e)}));else if(\"string\"==typeof this.options.css){const t=document.createElement(\"style\"),e=document.createTextNode(this.options.css);t.appendChild(e),this.ui.shadowRoot.append(t),this.ui.wrapper.style.display=\"\"}else\"function\"==typeof this.options.css&&(this.options.css.call(this,this),this.ui.wrapper.style.display=\"\")}adjustPosition(t){const e=t.getBoundingClientRect(),i=this.ui.wrapper.getBoundingClientRect();this.ui.container.classList.add(\"calc\");const n=this.ui.container.getBoundingClientRect();this.ui.container.classList.remove(\"calc\");let s=e.bottom-i.bottom,o=e.left-i.left;return\"undefined\"!=typeof window&&(window.innerHeight=0&&(s=e.top-i.top-n.height),window.innerWidth=0&&(o=e.right-i.right-n.width)),{left:o,top:s}}}var s=Object.freeze({__proto__:null,Core:n,create:n});class o{picker;options;priority=0;dependencies=[];attach(t){const e=this.getName(),i={...this.options};this.options={...this.options,...t.options[e]||{}};for(const n of Object.keys(i))if(null!==i[n]&&\"object\"==typeof i[n]&&Object.keys(i[n]).length&&e in t.options&&n in t.options[e]){const s={...t.options[e][n]};null!==s&&\"object\"==typeof s&&Object.keys(s).length&&Object.keys(s).every((t=>Object.keys(i[n]).includes(t)))&&(this.options[n]={...i[n],...s})}if(this.picker=t,this.dependenciesNotFound()){const t=this.dependencies.filter((t=>!this.pluginsAsStringArray().includes(t)));return void console.warn(`${this.getName()}: required dependencies (${t.join(\", \")}).`)}const n=this.camelCaseToKebab(this.getName());this.picker.ui.container.classList.add(n),this.onAttach()}detach(){const t=this.camelCaseToKebab(this.getName());this.picker.ui.container.classList.remove(t),\"function\"==typeof this.onDetach&&this.onDetach()}dependenciesNotFound(){return this.dependencies.length&&!this.dependencies.every((t=>this.pluginsAsStringArray().includes(t)))}pluginsAsStringArray(){return this.picker.options.plugins.map((t=>\"function\"==typeof t?(new t).getName():t))}camelCaseToKebab(t){return t.replace(/([a-zA-Z])(?=[A-Z])/g,\"$1-\").toLowerCase()}}class a extends o{priority=1;binds={onView:this.onView.bind(this)};options={minDate:null,maxDate:null,minDays:null,maxDays:null,selectForward:null,selectBackward:null,presets:!0,inseparable:!1,filter:null};getName(){return\"LockPlugin\"}onAttach(){if(this.options.minDate&&(this.options.minDate=new t(this.options.minDate,this.picker.options.format,this.picker.options.lang)),this.options.maxDate&&(this.options.maxDate=new t(this.options.maxDate,this.picker.options.format,this.picker.options.lang),this.options.maxDate instanceof t&&this.picker.options.calendars>1&&this.picker.calendars[0].isSame(this.options.maxDate,\"month\"))){const t=this.picker.calendars[0].clone().subtract(1,\"month\");this.picker.gotoDate(t)}if((this.options.minDays||this.options.maxDays||this.options.selectForward||this.options.selectBackward)&&!this.picker.options.plugins.includes(\"RangePlugin\")){const t=[\"minDays\",\"maxDays\",\"selectForward\",\"selectBackward\"];console.warn(`${this.getName()}: options ${t.join(\", \")} required RangePlugin.`)}this.picker.on(\"view\",this.binds.onView)}onDetach(){this.picker.off(\"view\",this.binds.onView)}onView(e){const{view:i,target:n,date:s}=e.detail;if(\"CalendarHeader\"===i&&(this.options.minDate instanceof t&&s.isSameOrBefore(this.options.minDate,\"month\")&&n.classList.add(\"no-previous-month\"),this.options.maxDate instanceof t&&s.isSameOrAfter(this.options.maxDate,\"month\")&&n.classList.add(\"no-next-month\")),\"CalendarDay\"===i){const t=this.picker.datePicked.length?this.picker.datePicked[0]:null;if(this.testFilter(s))return void n.classList.add(\"locked\");if(this.options.inseparable){if(this.options.minDays){const t=s.clone().subtract(this.options.minDays-1,\"day\"),e=s.clone().add(this.options.minDays-1,\"day\");let i=!1,o=!1;for(;t.isBefore(s,\"day\");){if(this.testFilter(t)){i=!0;break}t.add(1,\"day\")}for(;e.isAfter(s,\"day\");){if(this.testFilter(e)){o=!0;break}e.subtract(1,\"day\")}i&&o&&n.classList.add(\"not-available\")}this.rangeIsNotAvailable(s,t)&&n.classList.add(\"not-available\")}this.dateIsNotAvailable(s,t)&&n.classList.add(\"not-available\")}if(this.options.presets&&\"PresetPluginButton\"===i){const e=new t(Number(n.dataset.start)),i=new t(Number(n.dataset.end)),s=i.diff(e,\"day\"),o=this.options.minDays&&sthis.options.maxDays;(o||a||this.lockMinDate(e)||this.lockMaxDate(e)||this.lockMinDate(i)||this.lockMaxDate(i)||this.rangeIsNotAvailable(e,i))&&n.setAttribute(\"disabled\",\"disabled\")}}dateIsNotAvailable(t,e){return this.lockMinDate(t)||this.lockMaxDate(t)||this.lockMinDays(t,e)||this.lockMaxDays(t,e)||this.lockSelectForward(t)||this.lockSelectBackward(t)}rangeIsNotAvailable(t,e){if(!t||!e)return!1;const i=(t.isSameOrBefore(e,\"day\")?t:e).clone(),n=(e.isSameOrAfter(t,\"day\")?e:t).clone();for(;i.isSameOrBefore(n,\"day\");){if(this.testFilter(i))return!0;i.add(1,\"day\")}return!1}lockMinDate(e){return this.options.minDate instanceof t&&e.isBefore(this.options.minDate,\"day\")}lockMaxDate(e){return this.options.maxDate instanceof t&&e.isAfter(this.options.maxDate,\"day\")}lockMinDays(t,e){if(this.options.minDays&&e){const i=e.clone().subtract(this.options.minDays-1,\"day\"),n=e.clone().add(this.options.minDays-1,\"day\");return t.isBetween(i,n)}return!1}lockMaxDays(t,e){if(this.options.maxDays&&e){const i=e.clone().subtract(this.options.maxDays,\"day\"),n=e.clone().add(this.options.maxDays,\"day\");return!t.isBetween(i,n)}return!1}lockSelectForward(t){if(1===this.picker.datePicked.length&&this.options.selectForward){const e=this.picker.datePicked[0].clone();return t.isBefore(e,\"day\")}return!1}lockSelectBackward(t){if(1===this.picker.datePicked.length&&this.options.selectBackward){const e=this.picker.datePicked[0].clone();return t.isAfter(e,\"day\")}return!1}testFilter(t){return\"function\"==typeof this.options.filter&&this.options.filter(t,this.picker.datePicked)}}class r extends o{dependencies=[\"RangePlugin\"];binds={onView:this.onView.bind(this),onClick:this.onClick.bind(this)};options={customLabels:[\"Today\",\"Yesterday\",\"Last 7 Days\",\"Last 30 Days\",\"This Month\",\"Last Month\"],customPreset:{},position:\"left\"};getName(){return\"PresetPlugin\"}onAttach(){if(!Object.keys(this.options.customPreset).length){const e=new t,i=()=>{const i=e.clone();i.setDate(1);const n=new Date(e.getFullYear(),e.getMonth()+1,0);return[new t(i),new t(n)]},n=()=>{const i=e.clone();i.setMonth(i.getMonth()-1),i.setDate(1);const n=new Date(e.getFullYear(),e.getMonth(),0);return[new t(i),new t(n)]},s=[[e.clone(),e.clone()],[e.clone().subtract(1,\"day\"),e.clone().subtract(1,\"day\")],[e.clone().subtract(6,\"day\"),e.clone()],[e.clone().subtract(29,\"day\"),e.clone()],i(),n()];Object.values(this.options.customLabels).forEach(((t,e)=>{this.options.customPreset[t]=s[e]}))}this.picker.on(\"view\",this.binds.onView),this.picker.on(\"click\",this.binds.onClick)}onDetach(){this.picker.off(\"view\",this.binds.onView),this.picker.off(\"click\",this.binds.onClick)}onView(t){const{view:e,target:i}=t.detail;if(\"Main\"===e){const t=document.createElement(\"div\");t.className=\"preset-plugin-container\",Object.keys(this.options.customPreset).forEach((e=>{if(Object.prototype.hasOwnProperty.call(this.options.customPreset,e)){const i=this.options.customPreset[e],n=document.createElement(\"button\");n.className=\"preset-button unit\",n.innerHTML=e,n.dataset.start=i[0].getTime(),n.dataset.end=i[1].getTime(),t.appendChild(n),this.picker.trigger(\"view\",{view:\"PresetPluginButton\",target:n})}})),i.appendChild(t),i.classList.add(`preset-${this.options.position}`),this.picker.trigger(\"view\",{view:\"PresetPluginContainer\",target:t})}}onClick(e){const i=e.target;if(i instanceof HTMLElement){const e=i.closest(\".unit\");if(!(e instanceof HTMLElement))return;if(this.isPresetButton(e)){const i=new t(Number(e.dataset.start)),n=new t(Number(e.dataset.end));this.picker.options.autoApply?(this.picker.setDateRange(i,n),this.picker.trigger(\"select\",{start:this.picker.getStartDate(),end:this.picker.getEndDate()}),this.picker.hide()):(this.picker.datePicked=[i,n],this.picker.renderAll())}}}isPresetButton(t){return t.classList.contains(\"preset-button\")}}class c extends o{tooltipElement;triggerElement;binds={setStartDate:this.setStartDate.bind(this),setEndDate:this.setEndDate.bind(this),setDateRange:this.setDateRange.bind(this),getStartDate:this.getStartDate.bind(this),getEndDate:this.getEndDate.bind(this),onView:this.onView.bind(this),onShow:this.onShow.bind(this),onMouseEnter:this.onMouseEnter.bind(this),onMouseLeave:this.onMouseLeave.bind(this),onClickCalendarDay:this.onClickCalendarDay.bind(this),onClickApplyButton:this.onClickApplyButton.bind(this),parseValues:this.parseValues.bind(this),updateValues:this.updateValues.bind(this),clear:this.clear.bind(this)};options={elementEnd:null,startDate:null,endDate:null,repick:!1,strict:!0,delimiter:\" - \",tooltip:!0,tooltipNumber:t=>t,locale:{zero:\"\",one:\"day\",two:\"\",few:\"\",many:\"\",other:\"days\"},documentClick:this.hidePicker.bind(this)};getName(){return\"RangePlugin\"}onAttach(){this.binds._setStartDate=this.picker.setStartDate,this.binds._setEndDate=this.picker.setEndDate,this.binds._setDateRange=this.picker.setDateRange,this.binds._getStartDate=this.picker.getStartDate,this.binds._getEndDate=this.picker.getEndDate,this.binds._parseValues=this.picker.parseValues,this.binds._updateValues=this.picker.updateValues,this.binds._clear=this.picker.clear,this.binds._onClickCalendarDay=this.picker.onClickCalendarDay,this.binds._onClickApplyButton=this.picker.onClickApplyButton,Object.defineProperties(this.picker,{setStartDate:{configurable:!0,value:this.binds.setStartDate},setEndDate:{configurable:!0,value:this.binds.setEndDate},setDateRange:{configurable:!0,value:this.binds.setDateRange},getStartDate:{configurable:!0,value:this.binds.getStartDate},getEndDate:{configurable:!0,value:this.binds.getEndDate},parseValues:{configurable:!0,value:this.binds.parseValues},updateValues:{configurable:!0,value:this.binds.updateValues},clear:{configurable:!0,value:this.binds.clear},onClickCalendarDay:{configurable:!0,value:this.binds.onClickCalendarDay},onClickApplyButton:{configurable:!0,value:this.binds.onClickApplyButton}}),this.options.elementEnd&&(this.options.elementEnd instanceof HTMLElement||(this.options.elementEnd=this.picker.options.doc.querySelector(this.options.elementEnd)),this.options.elementEnd instanceof HTMLInputElement&&(this.options.elementEnd.readOnly=this.picker.options.readonly),\"function\"==typeof this.picker.options.documentClick&&(document.removeEventListener(\"click\",this.picker.options.documentClick,!0),\"function\"==typeof this.options.documentClick&&document.addEventListener(\"click\",this.options.documentClick,!0)),this.options.elementEnd.addEventListener(\"click\",this.picker.show.bind(this.picker))),this.options.repick=this.options.repick&&this.options.elementEnd instanceof HTMLElement,this.picker.options.date=null,this.picker.on(\"view\",this.binds.onView),this.picker.on(\"show\",this.binds.onShow),this.picker.on(\"mouseenter\",this.binds.onMouseEnter,!0),this.picker.on(\"mouseleave\",this.binds.onMouseLeave,!0),this.checkIntlPluralLocales()}onDetach(){Object.defineProperties(this.picker,{setStartDate:{configurable:!0,value:this.binds._setStartDate},setEndDate:{configurable:!0,value:this.binds._setEndDate},setDateRange:{configurable:!0,value:this.binds._setDateRange},getStartDate:{configurable:!0,value:this.binds._getStartDate},getEndDate:{configurable:!0,value:this.binds._getEndDate},parseValues:{configurable:!0,value:this.binds._parseValues},updateValues:{configurable:!0,value:this.binds._updateValues},clear:{configurable:!0,value:this.binds._clear},onClickCalendarDay:{configurable:!0,value:this.binds._onClickCalendarDay},onClickApplyButton:{configurable:!0,value:this.binds._onClickApplyButton}}),this.picker.off(\"view\",this.binds.onView),this.picker.off(\"show\",this.binds.onShow),this.picker.off(\"mouseenter\",this.binds.onMouseEnter,!0),this.picker.off(\"mouseleave\",this.binds.onMouseLeave,!0)}parseValues(){if(this.options.startDate||this.options.endDate)this.options.strict?this.options.startDate&&this.options.endDate?this.setDateRange(this.options.startDate,this.options.endDate):(this.options.startDate=null,this.options.endDate=null):(this.options.startDate&&this.setStartDate(this.options.startDate),this.options.endDate&&this.setEndDate(this.options.endDate));else if(this.options.elementEnd)this.options.strict?this.picker.options.element instanceof HTMLInputElement&&this.picker.options.element.value.length&&this.options.elementEnd instanceof HTMLInputElement&&this.options.elementEnd.value.length&&this.setDateRange(this.picker.options.element.value,this.options.elementEnd.value):(this.picker.options.element instanceof HTMLInputElement&&this.picker.options.element.value.length&&this.setStartDate(this.picker.options.element.value),this.options.elementEnd instanceof HTMLInputElement&&this.options.elementEnd.value.length&&this.setEndDate(this.options.elementEnd.value));else if(this.picker.options.element instanceof HTMLInputElement&&this.picker.options.element.value.length){const[t,e]=this.picker.options.element.value.split(this.options.delimiter);this.options.strict?t&&e&&this.setDateRange(t,e):(t&&this.setStartDate(t),e&&this.setEndDate(e))}}updateValues(){const t=this.picker.options.element,e=this.options.elementEnd,i=this.picker.getStartDate(),n=this.picker.getEndDate(),s=i instanceof Date?i.format(this.picker.options.format,this.picker.options.lang):\"\",o=n instanceof Date?n.format(this.picker.options.format,this.picker.options.lang):\"\";if(e)t instanceof HTMLInputElement?t.value=s:t instanceof HTMLElement&&(t.innerText=s),e instanceof HTMLInputElement?e.value=o:e instanceof HTMLElement&&(e.innerText=o);else{const e=`${s}${s||o?this.options.delimiter:\"\"}${o}`;t instanceof HTMLInputElement?t.value=e:t instanceof HTMLElement&&(t.innerText=e)}}clear(){this.options.startDate=null,this.options.endDate=null,this.picker.datePicked.length=0,this.updateValues(),this.picker.renderAll(),this.picker.trigger(\"clear\")}onShow(t){const{target:e}=t.detail;this.triggerElement=e,this.picker.options.scrollToDate&&this.getStartDate()instanceof Date&&this.picker.gotoDate(this.getStartDate()),this.initializeRepick()}onView(e){const{view:i,target:n}=e.detail;if(\"Main\"===i&&(this.tooltipElement=document.createElement(\"span\"),this.tooltipElement.className=\"range-plugin-tooltip\",n.appendChild(this.tooltipElement)),\"CalendarDay\"===i){const e=new t(n.dataset.time),i=this.picker.datePicked,s=i.length?this.picker.datePicked[0]:this.getStartDate(),o=i.length?this.picker.datePicked[1]:this.getEndDate();s&&s.isSame(e,\"day\")&&n.classList.add(\"start\"),s&&o&&(o.isSame(e,\"day\")&&n.classList.add(\"end\"),e.isBetween(s,o)&&n.classList.add(\"in-range\"))}if(\"Footer\"===i){const t=1===this.picker.datePicked.length&&!this.options.strict||2===this.picker.datePicked.length;n.querySelector(\".apply-button\").disabled=!t}}hidePicker(t){let e=t.target,i=null;e.shadowRoot&&(e=t.composedPath()[0],i=e.getRootNode().host),this.picker.isShown()&&i!==this.picker.ui.wrapper&&e!==this.picker.options.element&&e!==this.options.elementEnd&&this.picker.hide()}setStartDate(e){const i=new t(e,this.picker.options.format);this.options.startDate=i?i.clone():null,this.updateValues(),this.picker.renderAll()}setEndDate(e){const i=new t(e,this.picker.options.format);this.options.endDate=i?i.clone():null,this.updateValues(),this.picker.renderAll()}setDateRange(e,i){const n=new t(e,this.picker.options.format),s=new t(i,this.picker.options.format);this.options.startDate=n?n.clone():null,this.options.endDate=s?s.clone():null,this.updateValues(),this.picker.renderAll()}getStartDate(){return this.options.startDate instanceof Date?this.options.startDate.clone():null}getEndDate(){return this.options.endDate instanceof Date?this.options.endDate.clone():null}onMouseEnter(e){const i=e.target;if(i instanceof HTMLElement){this.isContainer(i)&&this.initializeRepick();const e=i.closest(\".unit\");if(!(e instanceof HTMLElement))return;if(this.picker.isCalendarDay(e)){if(1!==this.picker.datePicked.length)return;let i=this.picker.datePicked[0].clone(),n=new t(e.dataset.time),s=!1;if(i.isAfter(n,\"day\")){const t=i.clone();i=n.clone(),n=t.clone(),s=!0}if([...this.picker.ui.container.querySelectorAll(\".day\")].forEach((o=>{const a=new t(o.dataset.time),r=this.picker.Calendar.getCalendarDayView(a);a.isBetween(i,n)&&r.classList.add(\"in-range\"),a.isSame(this.picker.datePicked[0],\"day\")&&(r.classList.add(\"start\"),r.classList.toggle(\"flipped\",s)),o===e&&(r.classList.add(\"end\"),r.classList.toggle(\"flipped\",s)),o.className=r.className})),this.options.tooltip){const t=this.options.tooltipNumber(n.diff(i,\"day\")+1);if(t>0){const i=new Intl.PluralRules(this.picker.options.lang).select(t),n=`${t} ${this.options.locale[i]}`;this.showTooltip(e,n)}else this.hideTooltip()}}}}onMouseLeave(t){if(this.isContainer(t.target)&&this.options.repick){const t=this.getStartDate(),e=this.getEndDate();t&&e&&(this.picker.datePicked.length=0,this.picker.renderAll())}}onClickCalendarDay(e){if(this.picker.isCalendarDay(e)){2===this.picker.datePicked.length&&(this.picker.datePicked.length=0);const i=new t(e.dataset.time);if(this.picker.datePicked[this.picker.datePicked.length]=i,2===this.picker.datePicked.length&&this.picker.datePicked[0].isAfter(this.picker.datePicked[1])){const t=this.picker.datePicked[1].clone();this.picker.datePicked[1]=this.picker.datePicked[0].clone(),this.picker.datePicked[0]=t.clone()}1!==this.picker.datePicked.length&&this.picker.options.autoApply||this.picker.trigger(\"preselect\",{start:this.picker.datePicked[0]instanceof Date?this.picker.datePicked[0].clone():null,end:this.picker.datePicked[1]instanceof Date?this.picker.datePicked[1].clone():null}),1===this.picker.datePicked.length&&(!this.options.strict&&this.picker.options.autoApply&&(this.picker.options.element===this.triggerElement&&this.setStartDate(this.picker.datePicked[0]),this.options.elementEnd===this.triggerElement&&this.setEndDate(this.picker.datePicked[0]),this.picker.trigger(\"select\",{start:this.picker.getStartDate(),end:this.picker.getEndDate()})),this.picker.renderAll()),2===this.picker.datePicked.length&&(this.picker.options.autoApply?(this.setDateRange(this.picker.datePicked[0],this.picker.datePicked[1]),this.picker.trigger(\"select\",{start:this.picker.getStartDate(),end:this.picker.getEndDate()}),this.picker.hide()):(this.hideTooltip(),this.picker.renderAll()))}}onClickApplyButton(t){this.picker.isApplyButton(t)&&(1!==this.picker.datePicked.length||this.options.strict||(this.picker.options.element===this.triggerElement&&(this.options.endDate=null,this.setStartDate(this.picker.datePicked[0])),this.options.elementEnd===this.triggerElement&&(this.options.startDate=null,this.setEndDate(this.picker.datePicked[0]))),2===this.picker.datePicked.length&&this.setDateRange(this.picker.datePicked[0],this.picker.datePicked[1]),this.picker.trigger(\"select\",{start:this.picker.getStartDate(),end:this.picker.getEndDate()}),this.picker.hide())}showTooltip(t,e){this.tooltipElement.style.visibility=\"visible\",this.tooltipElement.innerHTML=e;const i=this.picker.ui.container.getBoundingClientRect(),n=this.tooltipElement.getBoundingClientRect(),s=t.getBoundingClientRect();let o=s.top,a=s.left;o-=i.top,a-=i.left,o-=n.height,a-=n.width/2,a+=s.width/2,this.tooltipElement.style.top=`${o}px`,this.tooltipElement.style.left=`${a}px`}hideTooltip(){this.tooltipElement.style.visibility=\"hidden\"}checkIntlPluralLocales(){if(!this.options.tooltip)return;const t=[...new Set([new Intl.PluralRules(this.picker.options.lang).select(0),new Intl.PluralRules(this.picker.options.lang).select(1),new Intl.PluralRules(this.picker.options.lang).select(2),new Intl.PluralRules(this.picker.options.lang).select(6),new Intl.PluralRules(this.picker.options.lang).select(18)])],e=Object.keys(this.options.locale);t.every((t=>e.includes(t)))||console.warn(`${this.getName()}: provide locales (${t.join(\", \")}) for correct tooltip text.`)}initializeRepick(){if(!this.options.repick)return;const t=this.getStartDate(),e=this.getEndDate();e&&this.triggerElement===this.picker.options.element&&(this.picker.datePicked[0]=e),t&&this.triggerElement===this.options.elementEnd&&(this.picker.datePicked[0]=t)}isContainer(t){return t===this.picker.ui.container}}class l extends o{options={native:!1,seconds:!1,stepHours:1,stepMinutes:5,stepSeconds:5,format12:!1};rangePlugin;timePicked={input:null,start:null,end:null};timePrePicked={input:null,start:null,end:null};binds={getDate:this.getDate.bind(this),getStartDate:this.getStartDate.bind(this),getEndDate:this.getEndDate.bind(this),onView:this.onView.bind(this),onInput:this.onInput.bind(this),onChange:this.onChange.bind(this),onClick:this.onClick.bind(this),setTime:this.setTime.bind(this),setStartTime:this.setStartTime.bind(this),setEndTime:this.setEndTime.bind(this)};getName(){return\"TimePlugin\"}onAttach(){this.binds._getDate=this.picker.getDate,this.binds._getStartDate=this.picker.getStartDate,this.binds._getEndDate=this.picker.getEndDate,Object.defineProperties(this.picker,{getDate:{configurable:!0,value:this.binds.getDate},getStartDate:{configurable:!0,value:this.binds.getStartDate},getEndDate:{configurable:!0,value:this.binds.getEndDate},setTime:{configurable:!0,value:this.binds.setTime},setStartTime:{configurable:!0,value:this.binds.setStartTime},setEndTime:{configurable:!0,value:this.binds.setEndTime}}),this.rangePlugin=this.picker.PluginManager.getInstance(\"RangePlugin\"),this.parseValues(),this.picker.on(\"view\",this.binds.onView),this.picker.on(\"input\",this.binds.onInput),this.picker.on(\"change\",this.binds.onChange),this.picker.on(\"click\",this.binds.onClick)}onDetach(){delete this.picker.setTime,delete this.picker.setStartTime,delete this.picker.setEndTime,Object.defineProperties(this.picker,{getDate:{configurable:!0,value:this.binds._getDate},getStartDate:{configurable:!0,value:this.binds._getStartDate},getEndDate:{configurable:!0,value:this.binds._getEndDate}}),this.picker.off(\"view\",this.binds.onView),this.picker.off(\"input\",this.binds.onInput),this.picker.off(\"change\",this.binds.onChange),this.picker.off(\"click\",this.binds.onClick)}onView(t){const{view:e,target:i}=t.detail;if(\"Main\"===e){this.rangePlugin=this.picker.PluginManager.getInstance(\"RangePlugin\");const t=document.createElement(\"div\");if(t.className=\"time-plugin-container\",this.rangePlugin){const e=this.getStartInput();t.appendChild(e),this.picker.trigger(\"view\",{view:\"TimePluginInput\",target:e});const i=this.getEndInput();t.appendChild(i),this.picker.trigger(\"view\",{view:\"TimePluginInput\",target:i})}else{const e=this.getSingleInput();t.appendChild(e),this.picker.trigger(\"view\",{view:\"TimePluginInput\",target:e})}i.appendChild(t),this.picker.trigger(\"view\",{view:\"TimePluginContainer\",target:t})}}onInput(e){const i=e.target;if(i instanceof HTMLInputElement&&i.classList.contains(\"time-plugin-input\")){const e=this.timePicked[i.name]||new t,[n,s]=i.value.split(\":\");e.setHours(Number(n)||0,Number(s)||0,0,0),this.picker.options.autoApply?(this.timePicked[i.name]=e,this.picker.updateValues()):this.timePrePicked[i.name]=e}}onChange(e){const i=e.target;if(i instanceof HTMLSelectElement&&i.classList.contains(\"time-plugin-custom-input\")){const e=/(\\w+)\\[(\\w+)\\]/,[,n,s]=i.name.match(e),o=Number(i.value);let a=new t;switch(!this.picker.options.autoApply&&this.timePrePicked[n]instanceof Date?a=this.timePrePicked[n].clone():this.timePicked[n]instanceof Date&&(a=this.timePicked[n].clone()),s){case\"HH\":if(this.options.format12){const t=i.closest(\".time-plugin-custom-block\").querySelector(`select[name=\"${n}[period]\"]`).value,e=this.handleFormat12(t,a,o);a.setHours(e.getHours(),e.getMinutes(),e.getSeconds(),0)}else a.setHours(o,a.getMinutes(),a.getSeconds(),0);break;case\"mm\":a.setHours(a.getHours(),o,a.getSeconds(),0);break;case\"ss\":a.setHours(a.getHours(),a.getMinutes(),o,0);break;case\"period\":if(this.options.format12){const t=i.closest(\".time-plugin-custom-block\").querySelector(`select[name=\"${n}[HH]\"]`).value,e=this.handleFormat12(i.value,a,Number(t));a.setHours(e.getHours(),e.getMinutes(),e.getSeconds(),0)}}if(this.picker.options.autoApply)this.timePicked[n]=a,this.picker.updateValues();else{this.timePrePicked[n]=a;const t=this.picker.ui.container.querySelector(\".apply-button\");if(this.rangePlugin){const e=this.rangePlugin.options,i=this.picker.datePicked,n=e.strict&&2===i.length||!e.strict&&i.length>0||!i.length&&e.strict&&e.startDate instanceof Date&&e.endDate instanceof Date||!i.length&&!e.strict&&(e.startDate instanceof Date||e.endDate instanceof Date);t.disabled=!n}else this.picker.datePicked.length&&(t.disabled=!1)}}}onClick(t){const e=t.target;if(e instanceof HTMLElement){const t=e.closest(\".unit\");if(!(t instanceof HTMLElement))return;this.picker.isApplyButton(t)&&(Object.keys(this.timePicked).forEach((t=>{this.timePrePicked[t]instanceof Date&&(this.timePicked[t]=this.timePrePicked[t].clone())})),this.picker.updateValues(),this.timePrePicked={input:null,start:null,end:null}),this.picker.isCancelButton(t)&&(this.timePrePicked={input:null,start:null,end:null},this.picker.renderAll())}}setTime(t){const e=this.handleTimeString(t);this.timePicked.input=e.clone(),this.picker.renderAll(),this.picker.updateValues()}setStartTime(t){const e=this.handleTimeString(t);this.timePicked.start=e.clone(),this.picker.renderAll(),this.picker.updateValues()}setEndTime(t){const e=this.handleTimeString(t);this.timePicked.end=e.clone(),this.picker.renderAll(),this.picker.updateValues()}handleTimeString(e){const i=new t,[n,s,o]=e.split(\":\").map((t=>Number(t))),a=n&&!Number.isNaN(n)?n:0,r=s&&!Number.isNaN(s)?s:0,c=o&&!Number.isNaN(o)?o:0;return i.setHours(a,r,c,0),i}getDate(){if(this.picker.options.date instanceof Date){const e=new t(this.picker.options.date,this.picker.options.format);if(this.timePicked.input instanceof Date){const t=this.timePicked.input;e.setHours(t.getHours(),t.getMinutes(),t.getSeconds(),0)}return e}return null}getStartDate(){if(this.rangePlugin.options.startDate instanceof Date){const e=new t(this.rangePlugin.options.startDate,this.picker.options.format);if(this.timePicked.start instanceof Date){const t=this.timePicked.start;e.setHours(t.getHours(),t.getMinutes(),t.getSeconds(),0)}return e}return null}getEndDate(){if(this.rangePlugin.options.endDate instanceof Date){const e=new t(this.rangePlugin.options.endDate,this.picker.options.format);if(this.timePicked.end instanceof Date){const t=this.timePicked.end;e.setHours(t.getHours(),t.getMinutes(),t.getSeconds(),0)}return e}return null}getSingleInput(){return this.options.native?this.getNativeInput(\"input\"):this.getCustomInput(\"input\")}getStartInput(){return this.options.native?this.getNativeInput(\"start\"):this.getCustomInput(\"start\")}getEndInput(){return this.options.native?this.getNativeInput(\"end\"):this.getCustomInput(\"end\")}getNativeInput(t){const e=document.createElement(\"input\");e.type=\"time\",e.name=t,e.className=\"time-plugin-input unit\";const i=this.timePicked[t];if(i){const t=`0${i.getHours()}`.slice(-2),n=`0${i.getMinutes()}`.slice(-2);e.value=`${t}:${n}`}return e}getCustomInput(t){const e=document.createElement(\"div\");e.className=\"time-plugin-custom-block\";const i=document.createElement(\"select\");i.className=\"time-plugin-custom-input unit\",i.name=`${t}[HH]`;const n=this.options.format12?1:0,s=this.options.format12?13:24;let o=null;!this.picker.options.autoApply&&this.timePrePicked[t]instanceof Date?o=this.timePrePicked[t].clone():this.timePicked[t]instanceof Date&&(o=this.timePicked[t].clone());for(let t=n;t{const e=document.createElement(\"option\");e.value=t,e.text=t,o&&\"PM\"===t&&o.getHours()>=12&&(e.selected=!0),i.appendChild(e)})),e.appendChild(i)}return e}handleFormat12(t,e,i){const n=e.clone();switch(t){case\"AM\":12===i?n.setHours(0,n.getMinutes(),n.getSeconds(),0):n.setHours(i,n.getMinutes(),n.getSeconds(),0);break;case\"PM\":12!==i?n.setHours(i+12,n.getMinutes(),n.getSeconds(),0):n.setHours(i,n.getMinutes(),n.getSeconds(),0)}return n}parseValues(){if(this.rangePlugin){if(this.rangePlugin.options.strict){if(this.rangePlugin.options.startDate&&this.rangePlugin.options.endDate){const e=new t(this.rangePlugin.options.startDate,this.picker.options.format),i=new t(this.rangePlugin.options.endDate,this.picker.options.format);this.timePicked.start=e.clone(),this.timePicked.end=i.clone()}}else{if(this.rangePlugin.options.startDate){const e=new t(this.rangePlugin.options.startDate,this.picker.options.format);this.timePicked.start=e.clone()}if(this.rangePlugin.options.endDate){const e=new t(this.rangePlugin.options.endDate,this.picker.options.format);this.timePicked.end=e.clone()}}if(this.rangePlugin.options.elementEnd)if(this.rangePlugin.options.strict){if(this.picker.options.element instanceof HTMLInputElement&&this.picker.options.element.value.length&&this.rangePlugin.options.elementEnd instanceof HTMLInputElement&&this.rangePlugin.options.elementEnd.value.length){const e=new t(this.picker.options.element.value,this.picker.options.format),i=new t(this.rangePlugin.options.elementEnd.value,this.picker.options.format);this.timePicked.start=e.clone(),this.timePicked.end=i.clone()}}else{if(this.picker.options.element instanceof HTMLInputElement&&this.picker.options.element.value.length){const e=new t(this.picker.options.element.value,this.picker.options.format);this.timePicked.start=e.clone()}if(this.rangePlugin.options.elementEnd instanceof HTMLInputElement&&this.rangePlugin.options.elementEnd.value.length){const e=new t(this.rangePlugin.options.elementEnd.value,this.picker.options.format);this.timePicked.start=e.clone()}}else if(this.picker.options.element instanceof HTMLInputElement&&this.picker.options.element.value.length){const[e,i]=this.picker.options.element.value.split(this.rangePlugin.options.delimiter);if(this.rangePlugin.options.strict){if(e&&i){const n=new t(e,this.picker.options.format),s=new t(i,this.picker.options.format);this.timePicked.start=n.clone(),this.timePicked.end=s.clone()}}else{if(e){const i=new t(e,this.picker.options.format);this.timePicked.start=i.clone()}if(i){const e=new t(i,this.picker.options.format);this.timePicked.start=e.clone()}}}}else{if(this.picker.options.date){const e=new t(this.picker.options.date,this.picker.options.format);this.timePicked.input=e.clone()}if(this.picker.options.element instanceof HTMLInputElement&&this.picker.options.element.value.length){const e=new t(this.picker.options.element.value,this.picker.options.format);this.timePicked.input=e.clone()}}}}class h extends o{docElement=null;rangePlugin;binds={onView:this.onView.bind(this),onKeydown:this.onKeydown.bind(this)};options={unitIndex:1,dayIndex:2};getName(){return\"KbdPlugin\"}onAttach(){const t=this.picker.options.element,e=t.getBoundingClientRect();if(this.docElement=document.createElement(\"span\"),this.docElement.style.position=\"absolute\",this.docElement.style.top=`${t.offsetTop}px`,this.docElement.style.left=t.offsetLeft+e.width-25+\"px\",this.docElement.attachShadow({mode:\"open\"}),this.options.html)this.docElement.shadowRoot.innerHTML=this.options.html;else{const t=`\\n \\n\\n \\n `;this.docElement.shadowRoot.innerHTML=t}const i=this.docElement.shadowRoot.querySelector(\"button\");i&&(i.addEventListener(\"click\",(t=>{t.preventDefault(),this.picker.show({target:this.picker.options.element})}),{capture:!0}),i.addEventListener(\"keydown\",(t=>{\"Escape\"===t.code&&this.picker.hide()}),{capture:!0})),this.picker.options.element.after(this.docElement),this.picker.on(\"view\",this.binds.onView),this.picker.on(\"keydown\",this.binds.onKeydown)}onDetach(){this.docElement&&this.docElement.isConnected&&this.docElement.remove(),this.picker.off(\"view\",this.binds.onView),this.picker.off(\"keydown\",this.binds.onKeydown)}onView(t){const{view:e,target:i}=t.detail;i&&\"querySelector\"in i&&(\"CalendarDay\"!==e||[\"locked\",\"not-available\"].some((t=>i.classList.contains(t)))?[...i.querySelectorAll(\".unit:not(.day)\")].forEach((t=>t.tabIndex=this.options.unitIndex)):i.tabIndex=this.options.dayIndex)}onKeydown(t){switch(this.onMouseEnter(t),t.code){case\"ArrowUp\":case\"ArrowDown\":this.verticalMove(t);break;case\"ArrowLeft\":case\"ArrowRight\":this.horizontalMove(t);break;case\"Enter\":case\"Space\":this.handleEnter(t);break;case\"Escape\":this.picker.hide()}}findAllowableDaySibling(t,e,i){const n=Array.from(t.querySelectorAll(`.day[tabindex=\"${this.options.dayIndex}\"]`)),s=n.indexOf(e);return n.filter(((t,e)=>i(e,s)&&t.tabIndex===this.options.dayIndex))[0]}changeMonth(t){const e={ArrowLeft:\"previous\",ArrowRight:\"next\"},i=this.picker.ui.container.querySelector(`.${e[t.code]}-button[tabindex=\"${this.options.unitIndex}\"]`);i&&!i.parentElement.classList.contains(`no-${e[t.code]}-month`)&&(i.dispatchEvent(new Event(\"click\",{bubbles:!0})),setTimeout((()=>{let e=null;switch(t.code){case\"ArrowLeft\":const t=this.picker.ui.container.querySelectorAll(`.day[tabindex=\"${this.options.dayIndex}\"]`);e=t[t.length-1];break;case\"ArrowRight\":e=this.picker.ui.container.querySelector(`.day[tabindex=\"${this.options.dayIndex}\"]`)}e&&e.focus()})))}verticalMove(t){const e=t.target;if(e.classList.contains(\"day\")){t.preventDefault();const i=this.findAllowableDaySibling(this.picker.ui.container,e,((e,i)=>e===(\"ArrowUp\"===t.code?i-7:i+7)));i&&i.focus()}}horizontalMove(t){const e=t.target;if(e.classList.contains(\"day\")){t.preventDefault();const i=this.findAllowableDaySibling(this.picker.ui.container,e,((e,i)=>e===(\"ArrowLeft\"===t.code?i-1:i+1)));i?i.focus():this.changeMonth(t)}}handleEnter(t){const e=t.target;e.classList.contains(\"day\")&&(t.preventDefault(),e.dispatchEvent(new Event(\"click\",{bubbles:!0})),setTimeout((()=>{if(this.rangePlugin=this.picker.PluginManager.getInstance(\"RangePlugin\"),this.rangePlugin||!this.picker.options.autoApply){const t=this.picker.ui.container.querySelector(\".day.selected\");t&&setTimeout((()=>{t.focus()}))}})))}onMouseEnter(t){t.target.classList.contains(\"day\")&&setTimeout((()=>{const t=this.picker.ui.shadowRoot.activeElement;t&&t.dispatchEvent(new Event(\"mouseenter\",{bubbles:!0}))}))}}class d extends o{rangePlugin;lockPlugin;priority=10;binds={onView:this.onView.bind(this),onColorScheme:this.onColorScheme.bind(this)};options={dropdown:{months:!1,years:!1,minYear:1950,maxYear:null},darkMode:!0,locale:{resetButton:''}};matchMedia;getName(){return\"AmpPlugin\"}onAttach(){this.options.darkMode&&window&&\"matchMedia\"in window&&(this.matchMedia=window.matchMedia(\"(prefers-color-scheme: dark)\"),this.matchMedia.matches&&(this.picker.ui.container.dataset.theme=\"dark\"),this.matchMedia.addEventListener(\"change\",this.binds.onColorScheme)),this.options.weekNumbers&&this.picker.ui.container.classList.add(\"week-numbers\"),this.picker.on(\"view\",this.binds.onView)}onDetach(){this.options.darkMode&&window&&\"matchMedia\"in window&&this.matchMedia.removeEventListener(\"change\",this.binds.onColorScheme),this.picker.ui.container.removeAttribute(\"data-theme\"),this.picker.ui.container.classList.remove(\"week-numbers\"),this.picker.off(\"view\",this.binds.onView)}onView(t){this.lockPlugin=this.picker.PluginManager.getInstance(\"LockPlugin\"),this.rangePlugin=this.picker.PluginManager.getInstance(\"RangePlugin\"),this.handleDropdown(t),this.handleResetButton(t),this.handleWeekNumbers(t)}onColorScheme(t){const e=t.matches?\"dark\":\"light\";this.picker.ui.container.dataset.theme=e}handleDropdown(e){const{view:i,target:n,date:s,index:o}=e.detail;if(\"CalendarHeader\"===i){const e=n.querySelector(\".month-name\");if(this.options.dropdown.months){e.childNodes[0].remove();const i=document.createElement(\"select\");i.className=\"month-name--select month-name--dropdown\";for(let e=0;e<12;e+=1){const n=document.createElement(\"option\"),o=new t(new Date(s.getFullYear(),e,2,0,0,0)),a=new t(new Date(s.getFullYear(),e,1,0,0,0));n.value=String(e),n.text=o.toLocaleString(this.picker.options.lang,{month:\"long\"}),this.lockPlugin&&(n.disabled=this.lockPlugin.options.minDate&&a.isBefore(new t(this.lockPlugin.options.minDate),\"month\")||this.lockPlugin.options.maxDate&&a.isAfter(new t(this.lockPlugin.options.maxDate),\"month\")),n.selected=a.getMonth()===s.getMonth(),i.appendChild(n)}i.addEventListener(\"change\",(t=>{const e=t.target;this.picker.calendars[0].setDate(1),this.picker.calendars[0].setMonth(Number(e.value)),this.picker.renderAll()})),e.prepend(i)}if(this.options.dropdown.years){e.childNodes[1].remove();const i=document.createElement(\"select\");i.className=\"month-name--select\";const n=this.options.dropdown.minYear,o=this.options.dropdown.maxYear?this.options.dropdown.maxYear:(new Date).getFullYear();if(s.getFullYear()>o){const t=document.createElement(\"option\");t.value=String(s.getFullYear()),t.text=String(s.getFullYear()),t.selected=!0,t.disabled=!0,i.appendChild(t)}for(let e=o;e>=n;e-=1){const n=document.createElement(\"option\"),o=new t(new Date(e,0,1,0,0,0));n.value=String(e),n.text=String(e),this.lockPlugin&&(n.disabled=this.lockPlugin.options.minDate&&o.isBefore(new t(this.lockPlugin.options.minDate),\"year\")||this.lockPlugin.options.maxDate&&o.isAfter(new t(this.lockPlugin.options.maxDate),\"year\")),n.selected=s.getFullYear()===e,i.appendChild(n)}if(s.getFullYear(){t.innerHTML=t.value,i.appendChild(t)}))}i.addEventListener(\"change\",(t=>{const e=t.target;this.picker.calendars[0].setFullYear(Number(e.value)),this.picker.renderAll()})),e.appendChild(i)}}}handleResetButton(t){const{view:e,target:i}=t.detail;if(\"CalendarHeader\"===e&&this.options.resetButton){const t=document.createElement(\"button\");t.className=\"reset-button unit\",t.innerHTML=this.options.locale.resetButton,t.addEventListener(\"click\",(t=>{t.preventDefault();let e=!0;\"function\"==typeof this.options.resetButton&&(e=this.options.resetButton.call(this)),e&&this.picker.clear()})),i.appendChild(t)}}handleWeekNumbers(e){if(this.options.weekNumbers){const{view:i,target:n}=e.detail;if(\"CalendarDayNames\"===i){const t=document.createElement(\"div\");t.className=\"wnum-header\",t.innerHTML=\"Wk\",n.prepend(t)}\"CalendarDays\"===i&&[...n.children].forEach(((e,i)=>{if(0===i||i%7==0){let i;if(e.classList.contains(\"day\"))i=new t(e.dataset.time);else{const e=n.querySelector(\".day\");i=new t(e.dataset.time)}let s=i.getWeek(this.picker.options.firstDay);53===s&&0===i.getMonth()&&(s=\"53/1\");const o=document.createElement(\"div\");o.className=\"wnum-item\",o.innerHTML=String(s),n.insertBefore(o,e)}}))}}}export{d as AmpPlugin,t as DateTime,h as KbdPlugin,a as LockPlugin,r as PresetPlugin,c as RangePlugin,l as TimePlugin,n as create,s as easepick};\n","class e{picker;options;priority=0;dependencies=[];attach(e){const t=this.getName(),s={...this.options};this.options={...this.options,...e.options[t]||{}};for(const i of Object.keys(s))if(null!==s[i]&&\"object\"==typeof s[i]&&Object.keys(s[i]).length&&t in e.options&&i in e.options[t]){const n={...e.options[t][i]};null!==n&&\"object\"==typeof n&&Object.keys(n).length&&Object.keys(n).every((e=>Object.keys(s[i]).includes(e)))&&(this.options[i]={...s[i],...n})}if(this.picker=e,this.dependenciesNotFound()){const e=this.dependencies.filter((e=>!this.pluginsAsStringArray().includes(e)));return void console.warn(`${this.getName()}: required dependencies (${e.join(\", \")}).`)}const i=this.camelCaseToKebab(this.getName());this.picker.ui.container.classList.add(i),this.onAttach()}detach(){const e=this.camelCaseToKebab(this.getName());this.picker.ui.container.classList.remove(e),\"function\"==typeof this.onDetach&&this.onDetach()}dependenciesNotFound(){return this.dependencies.length&&!this.dependencies.every((e=>this.pluginsAsStringArray().includes(e)))}pluginsAsStringArray(){return this.picker.options.plugins.map((e=>\"function\"==typeof e?(new e).getName():e))}camelCaseToKebab(e){return e.replace(/([a-zA-Z])(?=[A-Z])/g,\"$1-\").toLowerCase()}}export{e as BasePlugin};\n","import{DateTime as t}from\"@easepick/datetime\";import{BasePlugin as i}from\"@easepick/base-plugin\";class s extends i{priority=1;binds={onView:this.onView.bind(this)};options={minDate:null,maxDate:null,minDays:null,maxDays:null,selectForward:null,selectBackward:null,presets:!0,inseparable:!1,filter:null};getName(){return\"LockPlugin\"}onAttach(){if(this.options.minDate&&(this.options.minDate=new t(this.options.minDate,this.picker.options.format,this.picker.options.lang)),this.options.maxDate&&(this.options.maxDate=new t(this.options.maxDate,this.picker.options.format,this.picker.options.lang),this.options.maxDate instanceof t&&this.picker.options.calendars>1&&this.picker.calendars[0].isSame(this.options.maxDate,\"month\"))){const t=this.picker.calendars[0].clone().subtract(1,\"month\");this.picker.gotoDate(t)}if((this.options.minDays||this.options.maxDays||this.options.selectForward||this.options.selectBackward)&&!this.picker.options.plugins.includes(\"RangePlugin\")){const t=[\"minDays\",\"maxDays\",\"selectForward\",\"selectBackward\"];console.warn(`${this.getName()}: options ${t.join(\", \")} required RangePlugin.`)}this.picker.on(\"view\",this.binds.onView)}onDetach(){this.picker.off(\"view\",this.binds.onView)}onView(i){const{view:s,target:e,date:a}=i.detail;if(\"CalendarHeader\"===s&&(this.options.minDate instanceof t&&a.isSameOrBefore(this.options.minDate,\"month\")&&e.classList.add(\"no-previous-month\"),this.options.maxDate instanceof t&&a.isSameOrAfter(this.options.maxDate,\"month\")&&e.classList.add(\"no-next-month\")),\"CalendarDay\"===s){const t=this.picker.datePicked.length?this.picker.datePicked[0]:null;if(this.testFilter(a))return void e.classList.add(\"locked\");if(this.options.inseparable){if(this.options.minDays){const t=a.clone().subtract(this.options.minDays-1,\"day\"),i=a.clone().add(this.options.minDays-1,\"day\");let s=!1,o=!1;for(;t.isBefore(a,\"day\");){if(this.testFilter(t)){s=!0;break}t.add(1,\"day\")}for(;i.isAfter(a,\"day\");){if(this.testFilter(i)){o=!0;break}i.subtract(1,\"day\")}s&&o&&e.classList.add(\"not-available\")}this.rangeIsNotAvailable(a,t)&&e.classList.add(\"not-available\")}this.dateIsNotAvailable(a,t)&&e.classList.add(\"not-available\")}if(this.options.presets&&\"PresetPluginButton\"===s){const i=new t(Number(e.dataset.start)),s=new t(Number(e.dataset.end)),a=s.diff(i,\"day\"),o=this.options.minDays&&athis.options.maxDays;(o||n||this.lockMinDate(i)||this.lockMaxDate(i)||this.lockMinDate(s)||this.lockMaxDate(s)||this.rangeIsNotAvailable(i,s))&&e.setAttribute(\"disabled\",\"disabled\")}}dateIsNotAvailable(t,i){return this.lockMinDate(t)||this.lockMaxDate(t)||this.lockMinDays(t,i)||this.lockMaxDays(t,i)||this.lockSelectForward(t)||this.lockSelectBackward(t)}rangeIsNotAvailable(t,i){if(!t||!i)return!1;const s=(t.isSameOrBefore(i,\"day\")?t:i).clone(),e=(i.isSameOrAfter(t,\"day\")?i:t).clone();for(;s.isSameOrBefore(e,\"day\");){if(this.testFilter(s))return!0;s.add(1,\"day\")}return!1}lockMinDate(i){return this.options.minDate instanceof t&&i.isBefore(this.options.minDate,\"day\")}lockMaxDate(i){return this.options.maxDate instanceof t&&i.isAfter(this.options.maxDate,\"day\")}lockMinDays(t,i){if(this.options.minDays&&i){const s=i.clone().subtract(this.options.minDays-1,\"day\"),e=i.clone().add(this.options.minDays-1,\"day\");return t.isBetween(s,e)}return!1}lockMaxDays(t,i){if(this.options.maxDays&&i){const s=i.clone().subtract(this.options.maxDays,\"day\"),e=i.clone().add(this.options.maxDays,\"day\");return!t.isBetween(s,e)}return!1}lockSelectForward(t){if(1===this.picker.datePicked.length&&this.options.selectForward){const i=this.picker.datePicked[0].clone();return t.isBefore(i,\"day\")}return!1}lockSelectBackward(t){if(1===this.picker.datePicked.length&&this.options.selectBackward){const i=this.picker.datePicked[0].clone();return t.isAfter(i,\"day\")}return!1}testFilter(t){return\"function\"==typeof this.options.filter&&this.options.filter(t,this.picker.datePicked)}}export{s as LockPlugin};\n","import { Controller } from '@hotwired/stimulus';\nimport { easepick } from \"@easepick/bundle\";\nimport { LockPlugin } from \"@easepick/lock-plugin\";\nimport { DateTime } from \"@easepick/datetime\";\n\nexport default class extends Controller {\n static values = { locale: String }\n\n connect () {\n const today = new DateTime();\n\n new easepick.create({\n element: this.element,\n css: [\n \"https://cdn.jsdelivr.net/npm/@easepick/bundle@1.2.1/dist/index.css\",\n ],\n zIndex: 101,\n lang: this.localeValue,\n format: \"DD-MM-YYYY\",\n plugins: [LockPlugin],\n LockPlugin: {\n minDate: today\n }\n });\n }\n}\n","import { Controller } from '@hotwired/stimulus';\n\nexport default class extends Controller {\n connect() {\n const element = this.element\n\n this.stateChangeForms().forEach(function(form) {\n form.addEventListener('ajax:success', (event) => {\n const xhr = event.detail[2]\n element.innerHTML = xhr.responseText;\n })\n })\n }\n\n stateChangeForms() {\n return this.element.querySelectorAll('form.button_to')\n }\n}\n","/* global window */\nimport { Controller } from '@hotwired/stimulus';\n\nexport default class extends Controller {\n connect() {\n if (document.location.hash == \"#share\") {\n this.share();\n }\n }\n\n initializeFacebook() {\n if (typeof FB === 'undefined') {\n setTimeout(this.initializeFacebook.bind(this), 100);\n } else {\n if (window.facebookSdkInitialized) return;\n\n const { facebookAppId } = this.element.dataset;\n\n FB.init({\n appId : facebookAppId,\n autoLogAppEvents : true,\n xfbml : true,\n version : 'v11.0'\n });\n\n window.facebookSdkInitialized = true;\n }\n }\n\n share(event) {\n this.loadSdk();\n this.initializeFacebook();\n this.openShareWidget(this.element);\n\n if (event) {\n event.preventDefault();\n }\n }\n\n loadSdk() {\n if (!document.getElementById('facebook-sdk')) {\n var script = document.createElement('script');\n\n script.id = 'facebook-sdk';\n script.setAttribute('async', 'true');\n script.setAttribute('crossorigin', 'anonymous');\n script.setAttribute('defer', 'true');\n script.src = 'https://connect.facebook.net/en_US/sdk.js';\n\n document.body.append(script);\n }\n }\n\n openShareWidget(element) {\n if (typeof FB === 'undefined' || typeof window.facebookSdkInitialized === 'undefined') {\n setTimeout(this.openShareWidget.bind(this), 100, element);\n } else {\n const { reviewUrl } = this.element.dataset;\n\n FB.ui({\n method: 'share',\n href: reviewUrl,\n });\n }\n }\n}\n","import { Controller } from '@hotwired/stimulus';\nimport { Fancybox } from \"@fancyapps/ui\";\n\nexport default class extends Controller {\n static values = {\n url: String\n }\n\n show(event) {\n event.preventDefault()\n\n return Fancybox.show(\n [{\n src: this.urlValue,\n type: 'ajax',\n }]\n )\n }\n}\n","/* global window */\n/* global document */\nimport { Controller } from '@hotwired/stimulus';\n\nexport default class extends Controller {\n static targets = [\n \"latitudeInput\",\n \"longitudeInput\",\n \"placesAutocompleteInput\",\n \"playingInInput\",\n ]\n\n connect() {\n window.filterGoogleCallback = this.filterGoogleCallback.bind(this);\n }\n\n addComponents (searchParams) {\n var addressComponents = searchParams.addressComponents;\n\n for (var i = 0; i < addressComponents.length; i++) {\n var types = addressComponents[i].types\n var component = addressComponents[i]\n\n if (types.indexOf(\"postal_code\") !== -1) {\n searchParams[\"postalCode\"] = component.short_name;\n }\n\n if (!searchParams[\"locality\"] &&\n (types.indexOf(\"sublocality\") !== -1 || types.indexOf(\"locality\") !== -1)) {\n searchParams[\"locality\"] = component.long_name;\n }\n }\n\n return searchParams;\n }\n\n triggerDropdown () {\n this.placesAutocompleteInputTarget.blur();\n this.placesAutocompleteInputTarget.focus();\n }\n\n dontSubmit (input) {\n // dont submit the form when pressing enter in the autocomplete field\n google.maps.event.addDomListener(input, \"keydown\", function(e) {\n if (e.keyCode == 13) {\n e.preventDefault();\n }\n });\n }\n\n filterGoogleCallback () {\n window.googleMapsIsLoaded = true;\n\n this.setupFilter();\n\n if (this.isInputElementFocused()) {\n setTimeout(this.triggerDropdown.bind(this), 100);\n }\n }\n\n geoPosition (placeLocation) {\n var geoPosition = [placeLocation.lat(), placeLocation.lng()]\n\n return geoPosition;\n }\n\n getFirstAutocompleteResult (input, eventTarget, callback) {\n var options = this.autocompleteOptions(eventTarget);\n options['input'] = input;\n var autocompleter = new google.maps.places.AutocompleteService();\n autocompleter.getPlacePredictions(\n options,\n function(results) {\n if (results) {\n callback(results[0]);\n }\n }\n )\n }\n\n getPlaceFromPrediction (autocompletePrediction, callback) {\n var attributionsContainer = document.createElement(\"div\");\n var placesService = new google.maps.places.PlacesService(attributionsContainer);\n var place = placesService.getDetails(\n {\n placeId: autocompletePrediction.place_id,\n fields: [\n \"address_components\",\n \"geometry\"\n ]\n },\n callback\n )\n }\n\n getSearchParamsFromPlace (place) {\n if (place) {\n var searchParams = {}\n\n searchParams[\"addressComponents\"] = place.address_components;\n searchParams[\"placeLocation\"] = place.geometry.location;\n searchParams[\"geoPosition\"] = this.geoPosition(searchParams.placeLocation);\n searchParams = this.addComponents(searchParams);\n searchParams[\"placeDescription\"] = this.placeDescription(searchParams);\n\n return searchParams\n } else {\n return {};\n };\n }\n\n isInputElementFocused () {\n document.activeElement === this.placesAutocompleteInputTarget\n }\n\n placeDescription (searchParams) {\n var placeDescription = \"\"\n\n if (searchParams.postalCode) {\n placeDescription += (searchParams.postalCode);\n }\n\n if (searchParams.locality) {\n placeDescription += (\" \" + searchParams.locality);\n }\n\n // if we dont have any values, use the users input\n if (placeDescription == \"\") {\n placeDescription = document.getElementById(\"artist_location\").value;\n }\n\n placeDescription = $.trim(placeDescription);\n\n return placeDescription;\n }\n\n resetFormFields() {\n this.latitudeInputTarget.value = \"\";\n this.longitudeInputTarget.value = \"\";\n if (this.hasPlayingInInputTarget) { this.playingInInputTarget.value = \"\"; }\n }\n\n setupFilter() {\n if (!window.googleMapsIsLoaded) {\n this.loadAutoComplete();\n setTimeout(this.setupFilter.bind(this), 100);\n } else {\n if (!this.autocomplete) {\n this.autocomplete = new google.maps.places.Autocomplete(\n this.placesAutocompleteInputTarget,\n this.autocompleteOptions()\n );\n var autoCompleteCallback = this.setSearchParams.bind(this);\n this.autocomplete.addListener(\"place_changed\", autoCompleteCallback);\n this.dontSubmit(this.placesAutocompleteInputTarget);\n }\n }\n }\n\n setSearchParams () {\n var place = this.autocomplete.getPlace();\n this.setSearchParamsFromPlace(place);\n }\n\n setSearchParamsFromPlace(place) {\n var params = this.getSearchParamsFromPlace(place);\n this.updateFormFields(params.geoPosition, params.postalCode);\n }\n\n setSearchParamsFromIncompleteInput(event) {\n var inputValue = this.placesAutocompleteInputTarget.value;\n if (inputValue) {\n this.getFirstAutocompleteResult(\n inputValue,\n this.placesAutocompleteInputTarget,\n this.updateFormFieldsFromPlacePrediction.bind(this)\n );\n } else {\n this.resetFormFields();\n }\n }\n\n updateFormFields (geoPosition, postalCode) {\n var position = geoPosition;\n\n if (position) {\n this.latitudeInputTarget.value = position[0];\n this.longitudeInputTarget.value = position[1];\n if (this.hasPlayingInInputTarget) { this.playingInInputTarget.value = postalCode || \"\"; }\n }\n }\n\n updateFormFieldsFromPlacePrediction (autocompletePrediction) {\n this.getPlaceFromPrediction(\n autocompletePrediction,\n this.setSearchParamsFromPlace.bind(this)\n );\n }\n\n autocompleteOptions() {\n // TODO: Get these using Stimulus values\n var countryCode = this.element.dataset.countryCode;\n var language = this.element.dataset.language;\n var resultTypes = this.element.dataset.types;\n var types = [];\n\n if (resultTypes != \"\") {\n types = [resultTypes];\n }\n\n var options = {\n componentRestrictions: {\n country: countryCode\n },\n fields: [\n \"address_components\",\n \"geometry\"\n ],\n types: types\n }\n\n return options\n }\n\n loadAutoComplete () {\n if (!window.googleMapsIsLoaded) {\n const element = this.element;\n const { googlekey, region } = element.dataset;\n\n if (!document.getElementById('google-maps-sdk')) {\n var script = document.createElement('script');\n\n const urlOptions = `key=${googlekey}&libraries=places&callback=window.filterGoogleCallback®ion=${region}&loading=async`;\n\n script.id = 'google-maps-sdk';\n script.setAttribute('async', 'true');\n script.setAttribute('defer', 'true');\n script.src = `//maps.googleapis.com/maps/api/js?${urlOptions}`;\n\n document.body.append(script);\n }\n }\n }\n}\n","import { Controller } from '@hotwired/stimulus';\nimport { Fancybox } from '@fancyapps/ui';\n\nexport default class extends Controller {\n static targets = ['link']\n\n show (event) {\n event.preventDefault()\n const sources = this.buildSources(this.linkTargets)\n\n const options = {\n mainClass: 'photo-gallery',\n Html: {\n video: {\n autoplay: false,\n },\n },\n startIndex: event.params.index,\n }\n\n return Fancybox.show(sources, options)\n }\n\n buildSources (links) {\n const sources = []\n\n links.forEach((link) => {\n sources.push({ src: link.href, thumb: link.dataset.thumb, type: 'image' })\n })\n\n\n return sources\n }\n}\n","import { Controller } from '@hotwired/stimulus'\n\n// GoogleMapsController\n//\n// This controller is responsible for loading the Google Maps API and\n// initializing the map.\nexport default class extends Controller {\n static targets = ['mapContainer']\n\n static values = {\n coordinates: Array,\n apiKey: String,\n }\n\n connect() {\n // Load the Google Maps API\n if (!window.initMap) {\n window.initMap = this.initializeMap.bind(this)\n const script = document.createElement('script')\n script.src = `https://maps.googleapis.com/maps/api/js?key=${this.apiKeyValue}&callback=initMap&loading=async`;\n script.defer = true\n document.head.appendChild(script)\n } else {\n this.initializeMap()\n }\n }\n\n initializeMap() {\n const venueCoordinates = this.coordinatesValue\n\n if (venueCoordinates) {\n const venueLocation = new google.maps.LatLng(venueCoordinates[0], venueCoordinates[1])\n const mapOptions = {\n center: venueLocation,\n disableDefaultUI: true,\n zoom: 11,\n }\n\n const map = new google.maps.Map(this.mapContainerTarget, mapOptions)\n new google.maps.Marker({ position: venueLocation, map: map })\n }\n\n }\n}\n","import { Controller } from '@hotwired/stimulus';\nimport { Fancybox } from \"@fancyapps/ui\";\n\nexport default class extends Controller {\n static values = {\n url: String\n }\n\n show(event) {\n event.preventDefault()\n\n fetch(this.urlValue).\n then(response => response.json()).\n then(json => new Fancybox(\n json,\n {\n Html: {\n video: {\n autoplay: false,\n },\n },\n }\n ))\n }\n}\n","/* global $ */\n\nexport default function () {\n var that = this;\n var inputElement = document.querySelector('[data-files-input=\"true\"]');\n var outputElement = document.querySelector('[data-files-output=\"true\"]');\n\n this.addNewInputGroup = function (originalNode) {\n var newInputNode = originalNode.cloneNode();\n\n // Make sure we have no files pre-selected. Some browsers preserve the\n // filelist from the original node we've cloned from, and we don't want that\n newInputNode.value = \"\";\n\n // Make the new input element create more input elements when changed\n newInputNode.addEventListener(\"change\", that.onFileSelected);\n\n inputElement.appendChild(newInputNode);\n return newInputNode;\n }\n\n this.moveFileInputToSelectedFiles = function (inputNode) {\n // Remove attributes necessary for a visible input field\n inputNode.removeAttribute(\"id\");\n inputNode.removeEventListener(\"change\", that.onFileSelected);\n\n // Create a delete icon element for the input node\n var deleteIcon = document.createElement(\"span\");\n deleteIcon.classList.add(\"message-remove-icon\");\n\n // Create label node (the visible part of the new input element)\n var labelNode = document.createElement(\"label\");\n labelNode.classList.add(\"message-tag\")\n var textElement = document.createTextNode(inputNode.files[0].name);\n\n // Add the text and icon to the label node\n labelNode.appendChild(textElement);\n labelNode.appendChild(deleteIcon);\n\n // Create parent node for input\n var formGroupNode = document.createElement(\"div\");\n formGroupNode.classList.add(\"form-group\", \"message-file\");\n\n // Add the custom input and label element to the parent node\n formGroupNode.appendChild(inputNode);\n formGroupNode.appendChild(labelNode);\n\n // Remove the file by clicking the new custom element\n formGroupNode.addEventListener(\"click\", function (event) {\n outputElement.removeChild(formGroupNode);\n });\n\n // Add our new custom input node to the output element\n outputElement.appendChild(formGroupNode);\n }\n\n this.onFileSelected = function (event) {\n var originalFileInputElement = event.target;\n\n // Create a new input node, looking like the original\n that.addNewInputGroup(originalFileInputElement);\n\n // Move the original file input to the list of inputs to submit and style it\n // like a tag/selected file.\n that.moveFileInputToSelectedFiles(originalFileInputElement);\n };\n\n this.apply = function () {\n inputElement.\n querySelector(\"input[type='file']\").\n addEventListener(\"change\", this.onFileSelected);\n }\n};\n","export default function () {\n var that = this;\n\n this.apply = function () {\n var element = document.querySelector('[data-validate-text=\"true\"]');\n\n this.disableSubmit(element.form);\n var intervalID = setInterval(this.disableSubmitIfBlank, 50, element);\n this.disableOnClick(element.form, intervalID);\n }\n\n this.disableSubmitIfBlank = function (element) {\n if (!element.value || element.value.trim() == \"\") {\n that.disableSubmit(element.form);\n } else {\n that.enableSubmit(element.form);\n }\n }\n\n this.submitElement = function (form) {\n return form.querySelector('input[type=submit]');\n }\n\n // Enabling and disabling code here seems to mess with :disable_with\n this.disableOnClick = function (form, intervalID) {\n var submit = that.submitElement(form);\n\n // let :disable_with do its thing!\n // (The page refresh after submit will restart the enabling / disabling code)\n submit.addEventListener(\"click\", function() {\n clearInterval(intervalID);\n })\n }\n\n this.enableSubmit = function (form) {\n var submit = that.submitElement(form);\n submit.title = \"\";\n submit.disabled = false;\n }\n\n this.disableSubmit = function (form) {\n var submit = that.submitElement(form);\n submit.title = submit.dataset.submitTitle || \"\";\n submit.disabled = true;\n }\n}\n","import { Controller } from '@hotwired/stimulus';\nimport FilesUpload from '../backend/files_upload';\nimport TextValidator from '../backend/text_validator';\n\nexport default class extends Controller {\n connect() {\n var filesUpload = new FilesUpload;\n filesUpload.apply();\n\n var textValidator = new TextValidator;\n textValidator.apply();\n }\n}\n","import Sortable from 'stimulus-sortable'\nimport Rails from 'rails-ujs'\n\nexport default class extends Sortable {\n static targets = ['movieCard']\n\n static values = {\n updateUrl: String\n }\n\n connect() {\n super.connect()\n }\n\n end() {\n const moviePositions = this.movieCardTargets.map((movieCard, index) => {\n let id = movieCard.dataset.movieId\n let position = index\n\n return {id: id, position: position}\n })\n\n this.persistPositions(moviePositions)\n }\n\n get defaultOptions() {\n return {\n animation: 500,\n handle: '.move-handle'\n }\n }\n\n persistPositions(positions) {\n const formData = new FormData()\n\n positions.forEach(function ({id, position}) {\n formData.append(`movies[${position}][position]`, position)\n formData.append(`movies[${position}][id]`, id)\n })\n\n Rails.ajax({\n data: formData,\n type: 'PATCH',\n url: this.updateUrlValue\n })\n }\n}\n","function camelize(value) {\n return value.replace(/(?:[_-])([a-z0-9])/g, (_, char) => char.toUpperCase());\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 readInheritableStaticArrayValues(constructor, propertyName) {\n const ancestors = getAncestorsForConstructor(constructor);\n return Array.from(ancestors.reduce((values, constructor2) => {\n getOwnStaticArrayValues(constructor2, 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, constructor2) => {\n pairs.push(...getOwnStaticObjectPairs(constructor2, 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(() => {\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 };\n return new b();\n }\n try {\n testReflectExtension();\n return extendWithReflect;\n } catch (error) {\n return (constructor) => class extended extends constructor {\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 } 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}\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 } 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}\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);\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) {\n const definition = parseValueDefinitionPair(valueDefinitionPair);\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 } else {\n return definition.defaultValue;\n }\n },\n set(value) {\n if (value === void 0) {\n this.data.delete(key);\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]) {\n return valueDescriptorForTokenAndTypeDefinition(token, typeDefinition);\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(typeObject) {\n const typeFromObject = parseValueTypeConstant(typeObject.type);\n if (typeFromObject) {\n const defaultValueType = parseValueTypeDefault(typeObject.default);\n if (typeFromObject !== defaultValueType) {\n throw new Error(`Type \"${typeFromObject}\" must match the type of the default value. Given default value: \"${typeObject.default}\" as \"${defaultValueType}\"`);\n }\n return typeFromObject;\n }\n}\nfunction parseValueTypeDefinition(typeDefinition) {\n const typeFromObject = parseValueTypeObject(typeDefinition);\n const typeFromDefaultValue = parseValueTypeDefault(typeDefinition);\n const typeFromConstant = parseValueTypeConstant(typeDefinition);\n const type = typeFromObject || typeFromDefaultValue || typeFromConstant;\n if (type)\n return type;\n throw new Error(`Unknown value type \"${typeDefinition}\"`);\n}\nfunction defaultValueForDefinition(typeDefinition) {\n const constant = parseValueTypeConstant(typeDefinition);\n if (constant)\n return defaultValuesByType[constant];\n const defaultValue = typeDefinition.default;\n if (defaultValue !== void 0)\n return defaultValue;\n return typeDefinition;\n}\nfunction valueDescriptorForTokenAndTypeDefinition(token, typeDefinition) {\n const key = `${dasherize(token)}-value`;\n const type = parseValueTypeDefinition(typeDefinition);\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) !== void 0;\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 array\");\n }\n return array;\n },\n boolean(value) {\n return !(value == \"0\" || value == \"false\");\n },\n number(value) {\n return Number(value);\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 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}\nclass Controller {\n constructor(context) {\n this.context = context;\n }\n static get shouldLoad() {\n return true;\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 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 = [ClassPropertiesBlessing, TargetPropertiesBlessing, ValuePropertiesBlessing];\nController.targets = [];\nController.values = {};\nclass src_default extends Controller {\n add(e) {\n e.preventDefault();\n const content = this.templateTarget.innerHTML.replace(/NEW_RECORD/g, new Date().getTime().toString());\n this.targetTarget.insertAdjacentHTML(\"beforebegin\", content);\n }\n remove(e) {\n e.preventDefault();\n const wrapper = e.target.closest(this.wrapperSelectorValue);\n if (wrapper.dataset.newRecord === \"true\") {\n wrapper.remove();\n } else {\n wrapper.style.display = \"none\";\n const input = wrapper.querySelector(\"input[name*='_destroy']\");\n input.value = \"1\";\n }\n }\n}\nsrc_default.targets = [\"target\", \"template\"];\nsrc_default.values = {\n wrapperSelector: {\n type: String,\n default: \".nested-form-wrapper\"\n }\n};\nexport { src_default as default };\n","import NestedForm from 'stimulus-rails-nested-form'\n\nexport default class extends NestedForm {\n static targets = ['inputs']\n\n connect() {\n super.connect()\n this.intervalId = setInterval(this.addInputsIfNecessary.bind(this), 200)\n }\n\n addInputsIfNecessary (event) {\n const dummyEvent = { preventDefault: function () {} }\n if (this.needsMoreInputs()) {\n this.add(dummyEvent)\n }\n }\n\n disconnect () {\n super.disconnect()\n if (this.intervalId) {\n clearInterval(this.intervalId)\n }\n }\n\n needsMoreInputs () {\n return this.numberOfInputsTargetsWithoutUserInput() < 1\n }\n\n numberOfInputsTargetsWithoutUserInput () {\n return this.inputsTargets.filter(function (inputsTarget) {\n const fields = Array.from(inputsTarget.querySelectorAll('input:not([disabled]):not([type=\"hidden\"]), textarea:not([disabled])'))\n return fields.every(function (input) {\n return input.value === ''\n })\n }).length\n }\n}\n","import { Controller } from '@hotwired/stimulus';\n\nexport default class extends Controller {\n static get targets() {\n return ['code', 'outlet', 'size'];\n }\n\n connect() {\n this.maximumSize = parseInt(this.sizeTarget.getAttribute('max'), 10)\n this.minimumSize = parseInt(this.sizeTarget.getAttribute('min'), 10)\n this.sizeTarget.value = (this.maximumSize + this.minimumSize) / 2\n this.outletTarget.style = `height: ${this.maximumSize}px`\n this.updateSize();\n }\n\n getSize() {\n return this.sizeTarget.value\n }\n\n setMaxWidthOnImage(size) {\n let imgTags = this.outletTarget.getElementsByTagName('img')\n for (var i = imgTags.length - 1; i >= 0; i--) {\n let img = imgTags[i]\n img.style = `max-width: ${size}px`\n }\n }\n\n updateCode() {\n let embed = this.outletTarget\n this.codeTarget.value = embed.innerHTML.trim()\n }\n\n updateSize(event) {\n let size = this.getSize()\n this.setMaxWidthOnImage(size)\n this.updateCode()\n }\n}\n","/* global $ */\n\nimport { Controller } from '@hotwired/stimulus';\n\nexport default class extends Controller {\n static targets = [\"dropdown\", \"from\", \"fixed\", \"priceRow\", \"priceFromRow\"]\n\n connect () {\n this.toggleInputs();\n }\n\n toggleInputs () {\n const selectedValue = this.dropdownTarget.value;\n const ValidValues = [\"fixed\", \"per serving\", \"per piece\"]\n const fromValues = [\"from\", \"from per serving\", \"from per piece\"]\n\n if (ValidValues.includes(selectedValue)) {\n this.enableFixedInput();\n } else if (fromValues.includes(selectedValue)) {\n this.enableFromInput();\n } else {\n this.disableAndHideAllTargets();\n }\n }\n\n fixedTargetsArray () {\n return [this.fixedTarget, this.priceRowTarget]\n }\n\n fromTargetsArray () {\n return [this.fromTarget, this.priceFromRowTarget]\n }\n\n disableAndHideAllTargets () {\n this.hideAndDisable(this.fixedTargetsArray());\n this.hideAndDisable(this.fromTargetsArray());\n }\n\n enableFixedInput () {\n this.showAndEnable(this.fixedTargetsArray());\n this.hideAndDisable(this.fromTargetsArray());\n }\n\n enableFromInput () {\n this.showAndEnable(this.fromTargetsArray());\n this.hideAndDisable(this.fixedTargetsArray());\n }\n\n showAndEnable (targets) {\n targets[0].disabled = false;\n targets[1].classList.remove(\"d-none\");\n }\n\n hideAndDisable (targets) {\n targets[0].disabled = true;\n targets[1].classList.add(\"d-none\");\n }\n}\n","/*\n * International Telephone Input v17.0.21\n * https://github.com/jackocnr/intl-tel-input.git\n * Licensed under the MIT license\n */\n\n// wrap in UMD\n(function(factory) {\n if (typeof module === \"object\" && module.exports) module.exports = factory(); else window.intlTelInput = factory();\n})(function(undefined) {\n \"use strict\";\n return function() {\n // Array of country objects for the flag dropdown.\n // Here is the criteria for the plugin to support a given country/territory\n // - It has an iso2 code: https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2\n // - It has it's own country calling code (it is not a sub-region of another country): https://en.wikipedia.org/wiki/List_of_country_calling_codes\n // - It has a flag in the region-flags project: https://github.com/behdad/region-flags/tree/gh-pages/png\n // - It is supported by libphonenumber (it must be listed on this page): https://github.com/googlei18n/libphonenumber/blob/master/resources/ShortNumberMetadata.xml\n // Each country array has the following information:\n // [\n // Country name,\n // iso2 code,\n // International dial code,\n // Order (if >1 country with same dial code),\n // Area codes\n // ]\n var allCountries = [ [ \"Afghanistan (‫افغانستان‬‎)\", \"af\", \"93\" ], [ \"Albania (Shqipëri)\", \"al\", \"355\" ], [ \"Algeria (‫الجزائر‬‎)\", \"dz\", \"213\" ], [ \"American Samoa\", \"as\", \"1\", 5, [ \"684\" ] ], [ \"Andorra\", \"ad\", \"376\" ], [ \"Angola\", \"ao\", \"244\" ], [ \"Anguilla\", \"ai\", \"1\", 6, [ \"264\" ] ], [ \"Antigua and Barbuda\", \"ag\", \"1\", 7, [ \"268\" ] ], [ \"Argentina\", \"ar\", \"54\" ], [ \"Armenia (Հայաստան)\", \"am\", \"374\" ], [ \"Aruba\", \"aw\", \"297\" ], [ \"Ascension Island\", \"ac\", \"247\" ], [ \"Australia\", \"au\", \"61\", 0 ], [ \"Austria (Österreich)\", \"at\", \"43\" ], [ \"Azerbaijan (Azərbaycan)\", \"az\", \"994\" ], [ \"Bahamas\", \"bs\", \"1\", 8, [ \"242\" ] ], [ \"Bahrain (‫البحرين‬‎)\", \"bh\", \"973\" ], [ \"Bangladesh (বাংলাদেশ)\", \"bd\", \"880\" ], [ \"Barbados\", \"bb\", \"1\", 9, [ \"246\" ] ], [ \"Belarus (Беларусь)\", \"by\", \"375\" ], [ \"Belgium (België)\", \"be\", \"32\" ], [ \"Belize\", \"bz\", \"501\" ], [ \"Benin (Bénin)\", \"bj\", \"229\" ], [ \"Bermuda\", \"bm\", \"1\", 10, [ \"441\" ] ], [ \"Bhutan (འབྲུག)\", \"bt\", \"975\" ], [ \"Bolivia\", \"bo\", \"591\" ], [ \"Bosnia and Herzegovina (Босна и Херцеговина)\", \"ba\", \"387\" ], [ \"Botswana\", \"bw\", \"267\" ], [ \"Brazil (Brasil)\", \"br\", \"55\" ], [ \"British Indian Ocean Territory\", \"io\", \"246\" ], [ \"British Virgin Islands\", \"vg\", \"1\", 11, [ \"284\" ] ], [ \"Brunei\", \"bn\", \"673\" ], [ \"Bulgaria (България)\", \"bg\", \"359\" ], [ \"Burkina Faso\", \"bf\", \"226\" ], [ \"Burundi (Uburundi)\", \"bi\", \"257\" ], [ \"Cambodia (កម្ពុជា)\", \"kh\", \"855\" ], [ \"Cameroon (Cameroun)\", \"cm\", \"237\" ], [ \"Canada\", \"ca\", \"1\", 1, [ \"204\", \"226\", \"236\", \"249\", \"250\", \"289\", \"306\", \"343\", \"365\", \"387\", \"403\", \"416\", \"418\", \"431\", \"437\", \"438\", \"450\", \"506\", \"514\", \"519\", \"548\", \"579\", \"581\", \"587\", \"604\", \"613\", \"639\", \"647\", \"672\", \"705\", \"709\", \"742\", \"778\", \"780\", \"782\", \"807\", \"819\", \"825\", \"867\", \"873\", \"902\", \"905\" ] ], [ \"Cape Verde (Kabu Verdi)\", \"cv\", \"238\" ], [ \"Caribbean Netherlands\", \"bq\", \"599\", 1, [ \"3\", \"4\", \"7\" ] ], [ \"Cayman Islands\", \"ky\", \"1\", 12, [ \"345\" ] ], [ \"Central African Republic (République centrafricaine)\", \"cf\", \"236\" ], [ \"Chad (Tchad)\", \"td\", \"235\" ], [ \"Chile\", \"cl\", \"56\" ], [ \"China (中国)\", \"cn\", \"86\" ], [ \"Christmas Island\", \"cx\", \"61\", 2, [ \"89164\" ] ], [ \"Cocos (Keeling) Islands\", \"cc\", \"61\", 1, [ \"89162\" ] ], [ \"Colombia\", \"co\", \"57\" ], [ \"Comoros (‫جزر القمر‬‎)\", \"km\", \"269\" ], [ \"Congo (DRC) (Jamhuri ya Kidemokrasia ya Kongo)\", \"cd\", \"243\" ], [ \"Congo (Republic) (Congo-Brazzaville)\", \"cg\", \"242\" ], [ \"Cook Islands\", \"ck\", \"682\" ], [ \"Costa Rica\", \"cr\", \"506\" ], [ \"Côte d’Ivoire\", \"ci\", \"225\" ], [ \"Croatia (Hrvatska)\", \"hr\", \"385\" ], [ \"Cuba\", \"cu\", \"53\" ], [ \"Curaçao\", \"cw\", \"599\", 0 ], [ \"Cyprus (Κύπρος)\", \"cy\", \"357\" ], [ \"Czech Republic (Česká republika)\", \"cz\", \"420\" ], [ \"Denmark (Danmark)\", \"dk\", \"45\" ], [ \"Djibouti\", \"dj\", \"253\" ], [ \"Dominica\", \"dm\", \"1\", 13, [ \"767\" ] ], [ \"Dominican Republic (República Dominicana)\", \"do\", \"1\", 2, [ \"809\", \"829\", \"849\" ] ], [ \"Ecuador\", \"ec\", \"593\" ], [ \"Egypt (‫مصر‬‎)\", \"eg\", \"20\" ], [ \"El Salvador\", \"sv\", \"503\" ], [ \"Equatorial Guinea (Guinea Ecuatorial)\", \"gq\", \"240\" ], [ \"Eritrea\", \"er\", \"291\" ], [ \"Estonia (Eesti)\", \"ee\", \"372\" ], [ \"Eswatini\", \"sz\", \"268\" ], [ \"Ethiopia\", \"et\", \"251\" ], [ \"Falkland Islands (Islas Malvinas)\", \"fk\", \"500\" ], [ \"Faroe Islands (Føroyar)\", \"fo\", \"298\" ], [ \"Fiji\", \"fj\", \"679\" ], [ \"Finland (Suomi)\", \"fi\", \"358\", 0 ], [ \"France\", \"fr\", \"33\" ], [ \"French Guiana (Guyane française)\", \"gf\", \"594\" ], [ \"French Polynesia (Polynésie française)\", \"pf\", \"689\" ], [ \"Gabon\", \"ga\", \"241\" ], [ \"Gambia\", \"gm\", \"220\" ], [ \"Georgia (საქართველო)\", \"ge\", \"995\" ], [ \"Germany (Deutschland)\", \"de\", \"49\" ], [ \"Ghana (Gaana)\", \"gh\", \"233\" ], [ \"Gibraltar\", \"gi\", \"350\" ], [ \"Greece (Ελλάδα)\", \"gr\", \"30\" ], [ \"Greenland (Kalaallit Nunaat)\", \"gl\", \"299\" ], [ \"Grenada\", \"gd\", \"1\", 14, [ \"473\" ] ], [ \"Guadeloupe\", \"gp\", \"590\", 0 ], [ \"Guam\", \"gu\", \"1\", 15, [ \"671\" ] ], [ \"Guatemala\", \"gt\", \"502\" ], [ \"Guernsey\", \"gg\", \"44\", 1, [ \"1481\", \"7781\", \"7839\", \"7911\" ] ], [ \"Guinea (Guinée)\", \"gn\", \"224\" ], [ \"Guinea-Bissau (Guiné Bissau)\", \"gw\", \"245\" ], [ \"Guyana\", \"gy\", \"592\" ], [ \"Haiti\", \"ht\", \"509\" ], [ \"Honduras\", \"hn\", \"504\" ], [ \"Hong Kong (香港)\", \"hk\", \"852\" ], [ \"Hungary (Magyarország)\", \"hu\", \"36\" ], [ \"Iceland (Ísland)\", \"is\", \"354\" ], [ \"India (भारत)\", \"in\", \"91\" ], [ \"Indonesia\", \"id\", \"62\" ], [ \"Iran (‫ایران‬‎)\", \"ir\", \"98\" ], [ \"Iraq (‫العراق‬‎)\", \"iq\", \"964\" ], [ \"Ireland\", \"ie\", \"353\" ], [ \"Isle of Man\", \"im\", \"44\", 2, [ \"1624\", \"74576\", \"7524\", \"7924\", \"7624\" ] ], [ \"Israel (‫ישראל‬‎)\", \"il\", \"972\" ], [ \"Italy (Italia)\", \"it\", \"39\", 0 ], [ \"Jamaica\", \"jm\", \"1\", 4, [ \"876\", \"658\" ] ], [ \"Japan (日本)\", \"jp\", \"81\" ], [ \"Jersey\", \"je\", \"44\", 3, [ \"1534\", \"7509\", \"7700\", \"7797\", \"7829\", \"7937\" ] ], [ \"Jordan (‫الأردن‬‎)\", \"jo\", \"962\" ], [ \"Kazakhstan (Казахстан)\", \"kz\", \"7\", 1, [ \"33\", \"7\" ] ], [ \"Kenya\", \"ke\", \"254\" ], [ \"Kiribati\", \"ki\", \"686\" ], [ \"Kosovo\", \"xk\", \"383\" ], [ \"Kuwait (‫الكويت‬‎)\", \"kw\", \"965\" ], [ \"Kyrgyzstan (Кыргызстан)\", \"kg\", \"996\" ], [ \"Laos (ລາວ)\", \"la\", \"856\" ], [ \"Latvia (Latvija)\", \"lv\", \"371\" ], [ \"Lebanon (‫لبنان‬‎)\", \"lb\", \"961\" ], [ \"Lesotho\", \"ls\", \"266\" ], [ \"Liberia\", \"lr\", \"231\" ], [ \"Libya (‫ليبيا‬‎)\", \"ly\", \"218\" ], [ \"Liechtenstein\", \"li\", \"423\" ], [ \"Lithuania (Lietuva)\", \"lt\", \"370\" ], [ \"Luxembourg\", \"lu\", \"352\" ], [ \"Macau (澳門)\", \"mo\", \"853\" ], [ \"Madagascar (Madagasikara)\", \"mg\", \"261\" ], [ \"Malawi\", \"mw\", \"265\" ], [ \"Malaysia\", \"my\", \"60\" ], [ \"Maldives\", \"mv\", \"960\" ], [ \"Mali\", \"ml\", \"223\" ], [ \"Malta\", \"mt\", \"356\" ], [ \"Marshall Islands\", \"mh\", \"692\" ], [ \"Martinique\", \"mq\", \"596\" ], [ \"Mauritania (‫موريتانيا‬‎)\", \"mr\", \"222\" ], [ \"Mauritius (Moris)\", \"mu\", \"230\" ], [ \"Mayotte\", \"yt\", \"262\", 1, [ \"269\", \"639\" ] ], [ \"Mexico (México)\", \"mx\", \"52\" ], [ \"Micronesia\", \"fm\", \"691\" ], [ \"Moldova (Republica Moldova)\", \"md\", \"373\" ], [ \"Monaco\", \"mc\", \"377\" ], [ \"Mongolia (Монгол)\", \"mn\", \"976\" ], [ \"Montenegro (Crna Gora)\", \"me\", \"382\" ], [ \"Montserrat\", \"ms\", \"1\", 16, [ \"664\" ] ], [ \"Morocco (‫المغرب‬‎)\", \"ma\", \"212\", 0 ], [ \"Mozambique (Moçambique)\", \"mz\", \"258\" ], [ \"Myanmar (Burma) (မြန်မာ)\", \"mm\", \"95\" ], [ \"Namibia (Namibië)\", \"na\", \"264\" ], [ \"Nauru\", \"nr\", \"674\" ], [ \"Nepal (नेपाल)\", \"np\", \"977\" ], [ \"Netherlands (Nederland)\", \"nl\", \"31\" ], [ \"New Caledonia (Nouvelle-Calédonie)\", \"nc\", \"687\" ], [ \"New Zealand\", \"nz\", \"64\" ], [ \"Nicaragua\", \"ni\", \"505\" ], [ \"Niger (Nijar)\", \"ne\", \"227\" ], [ \"Nigeria\", \"ng\", \"234\" ], [ \"Niue\", \"nu\", \"683\" ], [ \"Norfolk Island\", \"nf\", \"672\" ], [ \"North Korea (조선 민주주의 인민 공화국)\", \"kp\", \"850\" ], [ \"North Macedonia (Северна Македонија)\", \"mk\", \"389\" ], [ \"Northern Mariana Islands\", \"mp\", \"1\", 17, [ \"670\" ] ], [ \"Norway (Norge)\", \"no\", \"47\", 0 ], [ \"Oman (‫عُمان‬‎)\", \"om\", \"968\" ], [ \"Pakistan (‫پاکستان‬‎)\", \"pk\", \"92\" ], [ \"Palau\", \"pw\", \"680\" ], [ \"Palestine (‫فلسطين‬‎)\", \"ps\", \"970\" ], [ \"Panama (Panamá)\", \"pa\", \"507\" ], [ \"Papua New Guinea\", \"pg\", \"675\" ], [ \"Paraguay\", \"py\", \"595\" ], [ \"Peru (Perú)\", \"pe\", \"51\" ], [ \"Philippines\", \"ph\", \"63\" ], [ \"Poland (Polska)\", \"pl\", \"48\" ], [ \"Portugal\", \"pt\", \"351\" ], [ \"Puerto Rico\", \"pr\", \"1\", 3, [ \"787\", \"939\" ] ], [ \"Qatar (‫قطر‬‎)\", \"qa\", \"974\" ], [ \"Réunion (La Réunion)\", \"re\", \"262\", 0 ], [ \"Romania (România)\", \"ro\", \"40\" ], [ \"Russia (Россия)\", \"ru\", \"7\", 0 ], [ \"Rwanda\", \"rw\", \"250\" ], [ \"Saint Barthélemy\", \"bl\", \"590\", 1 ], [ \"Saint Helena\", \"sh\", \"290\" ], [ \"Saint Kitts and Nevis\", \"kn\", \"1\", 18, [ \"869\" ] ], [ \"Saint Lucia\", \"lc\", \"1\", 19, [ \"758\" ] ], [ \"Saint Martin (Saint-Martin (partie française))\", \"mf\", \"590\", 2 ], [ \"Saint Pierre and Miquelon (Saint-Pierre-et-Miquelon)\", \"pm\", \"508\" ], [ \"Saint Vincent and the Grenadines\", \"vc\", \"1\", 20, [ \"784\" ] ], [ \"Samoa\", \"ws\", \"685\" ], [ \"San Marino\", \"sm\", \"378\" ], [ \"São Tomé and Príncipe (São Tomé e Príncipe)\", \"st\", \"239\" ], [ \"Saudi Arabia (‫المملكة العربية السعودية‬‎)\", \"sa\", \"966\" ], [ \"Senegal (Sénégal)\", \"sn\", \"221\" ], [ \"Serbia (Србија)\", \"rs\", \"381\" ], [ \"Seychelles\", \"sc\", \"248\" ], [ \"Sierra Leone\", \"sl\", \"232\" ], [ \"Singapore\", \"sg\", \"65\" ], [ \"Sint Maarten\", \"sx\", \"1\", 21, [ \"721\" ] ], [ \"Slovakia (Slovensko)\", \"sk\", \"421\" ], [ \"Slovenia (Slovenija)\", \"si\", \"386\" ], [ \"Solomon Islands\", \"sb\", \"677\" ], [ \"Somalia (Soomaaliya)\", \"so\", \"252\" ], [ \"South Africa\", \"za\", \"27\" ], [ \"South Korea (대한민국)\", \"kr\", \"82\" ], [ \"South Sudan (‫جنوب السودان‬‎)\", \"ss\", \"211\" ], [ \"Spain (España)\", \"es\", \"34\" ], [ \"Sri Lanka (ශ්‍රී ලංකාව)\", \"lk\", \"94\" ], [ \"Sudan (‫السودان‬‎)\", \"sd\", \"249\" ], [ \"Suriname\", \"sr\", \"597\" ], [ \"Svalbard and Jan Mayen\", \"sj\", \"47\", 1, [ \"79\" ] ], [ \"Sweden (Sverige)\", \"se\", \"46\" ], [ \"Switzerland (Schweiz)\", \"ch\", \"41\" ], [ \"Syria (‫سوريا‬‎)\", \"sy\", \"963\" ], [ \"Taiwan (台灣)\", \"tw\", \"886\" ], [ \"Tajikistan\", \"tj\", \"992\" ], [ \"Tanzania\", \"tz\", \"255\" ], [ \"Thailand (ไทย)\", \"th\", \"66\" ], [ \"Timor-Leste\", \"tl\", \"670\" ], [ \"Togo\", \"tg\", \"228\" ], [ \"Tokelau\", \"tk\", \"690\" ], [ \"Tonga\", \"to\", \"676\" ], [ \"Trinidad and Tobago\", \"tt\", \"1\", 22, [ \"868\" ] ], [ \"Tunisia (‫تونس‬‎)\", \"tn\", \"216\" ], [ \"Turkey (Türkiye)\", \"tr\", \"90\" ], [ \"Turkmenistan\", \"tm\", \"993\" ], [ \"Turks and Caicos Islands\", \"tc\", \"1\", 23, [ \"649\" ] ], [ \"Tuvalu\", \"tv\", \"688\" ], [ \"U.S. Virgin Islands\", \"vi\", \"1\", 24, [ \"340\" ] ], [ \"Uganda\", \"ug\", \"256\" ], [ \"Ukraine (Україна)\", \"ua\", \"380\" ], [ \"United Arab Emirates (‫الإمارات العربية المتحدة‬‎)\", \"ae\", \"971\" ], [ \"United Kingdom\", \"gb\", \"44\", 0 ], [ \"United States\", \"us\", \"1\", 0 ], [ \"Uruguay\", \"uy\", \"598\" ], [ \"Uzbekistan (Oʻzbekiston)\", \"uz\", \"998\" ], [ \"Vanuatu\", \"vu\", \"678\" ], [ \"Vatican City (Città del Vaticano)\", \"va\", \"39\", 1, [ \"06698\" ] ], [ \"Venezuela\", \"ve\", \"58\" ], [ \"Vietnam (Việt Nam)\", \"vn\", \"84\" ], [ \"Wallis and Futuna (Wallis-et-Futuna)\", \"wf\", \"681\" ], [ \"Western Sahara (‫الصحراء الغربية‬‎)\", \"eh\", \"212\", 1, [ \"5288\", \"5289\" ] ], [ \"Yemen (‫اليمن‬‎)\", \"ye\", \"967\" ], [ \"Zambia\", \"zm\", \"260\" ], [ \"Zimbabwe\", \"zw\", \"263\" ], [ \"Åland Islands\", \"ax\", \"358\", 1, [ \"18\" ] ] ];\n // loop over all of the countries above, restructuring the data to be objects with named keys\n for (var i = 0; i < allCountries.length; i++) {\n var c = allCountries[i];\n allCountries[i] = {\n name: c[0],\n iso2: c[1],\n dialCode: c[2],\n priority: c[3] || 0,\n areaCodes: c[4] || null\n };\n }\n \"use strict\";\n function _classCallCheck(instance, Constructor) {\n if (!(instance instanceof Constructor)) {\n throw new TypeError(\"Cannot call a class as a function\");\n }\n }\n function _defineProperties(target, props) {\n for (var i = 0; i < props.length; i++) {\n var descriptor = props[i];\n descriptor.enumerable = descriptor.enumerable || false;\n descriptor.configurable = true;\n if (\"value\" in descriptor) descriptor.writable = true;\n Object.defineProperty(target, descriptor.key, descriptor);\n }\n }\n function _createClass(Constructor, protoProps, staticProps) {\n if (protoProps) _defineProperties(Constructor.prototype, protoProps);\n if (staticProps) _defineProperties(Constructor, staticProps);\n return Constructor;\n }\n var intlTelInputGlobals = {\n getInstance: function getInstance(input) {\n var id = input.getAttribute(\"data-intl-tel-input-id\");\n return window.intlTelInputGlobals.instances[id];\n },\n instances: {},\n // using a global like this allows us to mock it in the tests\n documentReady: function documentReady() {\n return document.readyState === \"complete\";\n }\n };\n if (typeof window === \"object\") window.intlTelInputGlobals = intlTelInputGlobals;\n // these vars persist through all instances of the plugin\n var id = 0;\n var defaults = {\n // whether or not to allow the dropdown\n allowDropdown: true,\n // if there is just a dial code in the input: remove it on blur\n autoHideDialCode: true,\n // add a placeholder in the input with an example number for the selected country\n autoPlaceholder: \"polite\",\n // modify the parentClass\n customContainer: \"\",\n // modify the auto placeholder\n customPlaceholder: null,\n // append menu to specified element\n dropdownContainer: null,\n // don't display these countries\n excludeCountries: [],\n // format the input value during initialisation and on setNumber\n formatOnDisplay: true,\n // geoIp lookup function\n geoIpLookup: null,\n // inject a hidden input with this name, and on submit, populate it with the result of getNumber\n hiddenInput: \"\",\n // initial country\n initialCountry: \"\",\n // localized country names e.g. { 'de': 'Deutschland' }\n localizedCountries: null,\n // don't insert international dial codes\n nationalMode: true,\n // display only these countries\n onlyCountries: [],\n // number type to use for placeholders\n placeholderNumberType: \"MOBILE\",\n // the countries at the top of the list. defaults to united states and united kingdom\n preferredCountries: [ \"us\", \"gb\" ],\n // display the country dial code next to the selected flag so it's not part of the typed number\n separateDialCode: false,\n // specify the path to the libphonenumber script to enable validation/formatting\n utilsScript: \"\"\n };\n // https://en.wikipedia.org/wiki/List_of_North_American_Numbering_Plan_area_codes#Non-geographic_area_codes\n var regionlessNanpNumbers = [ \"800\", \"822\", \"833\", \"844\", \"855\", \"866\", \"877\", \"880\", \"881\", \"882\", \"883\", \"884\", \"885\", \"886\", \"887\", \"888\", \"889\" ];\n // utility function to iterate over an object. can't use Object.entries or native forEach because\n // of IE11\n var forEachProp = function forEachProp(obj, callback) {\n var keys = Object.keys(obj);\n for (var i = 0; i < keys.length; i++) {\n callback(keys[i], obj[keys[i]]);\n }\n };\n // run a method on each instance of the plugin\n var forEachInstance = function forEachInstance(method) {\n forEachProp(window.intlTelInputGlobals.instances, function(key) {\n window.intlTelInputGlobals.instances[key][method]();\n });\n };\n // this is our plugin class that we will create an instance of\n // eslint-disable-next-line no-unused-vars\n var Iti = /*#__PURE__*/\n function() {\n function Iti(input, options) {\n var _this = this;\n _classCallCheck(this, Iti);\n this.id = id++;\n this.telInput = input;\n this.activeItem = null;\n this.highlightedItem = null;\n // process specified options / defaults\n // alternative to Object.assign, which isn't supported by IE11\n var customOptions = options || {};\n this.options = {};\n forEachProp(defaults, function(key, value) {\n _this.options[key] = customOptions.hasOwnProperty(key) ? customOptions[key] : value;\n });\n this.hadInitialPlaceholder = Boolean(input.getAttribute(\"placeholder\"));\n }\n _createClass(Iti, [ {\n key: \"_init\",\n value: function _init() {\n var _this2 = this;\n // if in nationalMode, disable options relating to dial codes\n if (this.options.nationalMode) this.options.autoHideDialCode = false;\n // if separateDialCode then doesn't make sense to A) insert dial code into input\n // (autoHideDialCode), and B) display national numbers (because we're displaying the country\n // dial code next to them)\n if (this.options.separateDialCode) {\n this.options.autoHideDialCode = this.options.nationalMode = false;\n }\n // we cannot just test screen size as some smartphones/website meta tags will report desktop\n // resolutions\n // Note: for some reason jasmine breaks if you put this in the main Plugin function with the\n // rest of these declarations\n // Note: to target Android Mobiles (and not Tablets), we must find 'Android' and 'Mobile'\n this.isMobile = /Android.+Mobile|webOS|iPhone|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent);\n if (this.isMobile) {\n // trigger the mobile dropdown css\n document.body.classList.add(\"iti-mobile\");\n // on mobile, we want a full screen dropdown, so we must append it to the body\n if (!this.options.dropdownContainer) this.options.dropdownContainer = document.body;\n }\n // these promises get resolved when their individual requests complete\n // this way the dev can do something like iti.promise.then(...) to know when all requests are\n // complete\n if (typeof Promise !== \"undefined\") {\n var autoCountryPromise = new Promise(function(resolve, reject) {\n _this2.resolveAutoCountryPromise = resolve;\n _this2.rejectAutoCountryPromise = reject;\n });\n var utilsScriptPromise = new Promise(function(resolve, reject) {\n _this2.resolveUtilsScriptPromise = resolve;\n _this2.rejectUtilsScriptPromise = reject;\n });\n this.promise = Promise.all([ autoCountryPromise, utilsScriptPromise ]);\n } else {\n // prevent errors when Promise doesn't exist\n this.resolveAutoCountryPromise = this.rejectAutoCountryPromise = function() {};\n this.resolveUtilsScriptPromise = this.rejectUtilsScriptPromise = function() {};\n }\n // in various situations there could be no country selected initially, but we need to be able\n // to assume this variable exists\n this.selectedCountryData = {};\n // process all the data: onlyCountries, excludeCountries, preferredCountries etc\n this._processCountryData();\n // generate the markup\n this._generateMarkup();\n // set the initial state of the input value and the selected flag\n this._setInitialState();\n // start all of the event listeners: autoHideDialCode, input keydown, selectedFlag click\n this._initListeners();\n // utils script, and auto country\n this._initRequests();\n }\n }, {\n key: \"_processCountryData\",\n value: function _processCountryData() {\n // process onlyCountries or excludeCountries array if present\n this._processAllCountries();\n // process the countryCodes map\n this._processCountryCodes();\n // process the preferredCountries\n this._processPreferredCountries();\n // translate countries according to localizedCountries option\n if (this.options.localizedCountries) this._translateCountriesByLocale();\n // sort countries by name\n if (this.options.onlyCountries.length || this.options.localizedCountries) {\n this.countries.sort(this._countryNameSort);\n }\n }\n }, {\n key: \"_addCountryCode\",\n value: function _addCountryCode(iso2, countryCode, priority) {\n if (countryCode.length > this.countryCodeMaxLen) {\n this.countryCodeMaxLen = countryCode.length;\n }\n if (!this.countryCodes.hasOwnProperty(countryCode)) {\n this.countryCodes[countryCode] = [];\n }\n // bail if we already have this country for this countryCode\n for (var i = 0; i < this.countryCodes[countryCode].length; i++) {\n if (this.countryCodes[countryCode][i] === iso2) return;\n }\n // check for undefined as 0 is falsy\n var index = priority !== undefined ? priority : this.countryCodes[countryCode].length;\n this.countryCodes[countryCode][index] = iso2;\n }\n }, {\n key: \"_processAllCountries\",\n value: function _processAllCountries() {\n if (this.options.onlyCountries.length) {\n var lowerCaseOnlyCountries = this.options.onlyCountries.map(function(country) {\n return country.toLowerCase();\n });\n this.countries = allCountries.filter(function(country) {\n return lowerCaseOnlyCountries.indexOf(country.iso2) > -1;\n });\n } else if (this.options.excludeCountries.length) {\n var lowerCaseExcludeCountries = this.options.excludeCountries.map(function(country) {\n return country.toLowerCase();\n });\n this.countries = allCountries.filter(function(country) {\n return lowerCaseExcludeCountries.indexOf(country.iso2) === -1;\n });\n } else {\n this.countries = allCountries;\n }\n }\n }, {\n key: \"_translateCountriesByLocale\",\n value: function _translateCountriesByLocale() {\n for (var i = 0; i < this.countries.length; i++) {\n var iso = this.countries[i].iso2.toLowerCase();\n if (this.options.localizedCountries.hasOwnProperty(iso)) {\n this.countries[i].name = this.options.localizedCountries[iso];\n }\n }\n }\n }, {\n key: \"_countryNameSort\",\n value: function _countryNameSort(a, b) {\n return a.name.localeCompare(b.name);\n }\n }, {\n key: \"_processCountryCodes\",\n value: function _processCountryCodes() {\n this.countryCodeMaxLen = 0;\n // here we store just dial codes\n this.dialCodes = {};\n // here we store \"country codes\" (both dial codes and their area codes)\n this.countryCodes = {};\n // first: add dial codes\n for (var i = 0; i < this.countries.length; i++) {\n var c = this.countries[i];\n if (!this.dialCodes[c.dialCode]) this.dialCodes[c.dialCode] = true;\n this._addCountryCode(c.iso2, c.dialCode, c.priority);\n }\n // next: add area codes\n // this is a second loop over countries, to make sure we have all of the \"root\" countries\n // already in the map, so that we can access them, as each time we add an area code substring\n // to the map, we also need to include the \"root\" country's code, as that also matches\n for (var _i = 0; _i < this.countries.length; _i++) {\n var _c = this.countries[_i];\n // area codes\n if (_c.areaCodes) {\n var rootCountryCode = this.countryCodes[_c.dialCode][0];\n // for each area code\n for (var j = 0; j < _c.areaCodes.length; j++) {\n var areaCode = _c.areaCodes[j];\n // for each digit in the area code to add all partial matches as well\n for (var k = 1; k < areaCode.length; k++) {\n var partialDialCode = _c.dialCode + areaCode.substr(0, k);\n // start with the root country, as that also matches this dial code\n this._addCountryCode(rootCountryCode, partialDialCode);\n this._addCountryCode(_c.iso2, partialDialCode);\n }\n // add the full area code\n this._addCountryCode(_c.iso2, _c.dialCode + areaCode);\n }\n }\n }\n }\n }, {\n key: \"_processPreferredCountries\",\n value: function _processPreferredCountries() {\n this.preferredCountries = [];\n for (var i = 0; i < this.options.preferredCountries.length; i++) {\n var countryCode = this.options.preferredCountries[i].toLowerCase();\n var countryData = this._getCountryData(countryCode, false, true);\n if (countryData) this.preferredCountries.push(countryData);\n }\n }\n }, {\n key: \"_createEl\",\n value: function _createEl(name, attrs, container) {\n var el = document.createElement(name);\n if (attrs) forEachProp(attrs, function(key, value) {\n return el.setAttribute(key, value);\n });\n if (container) container.appendChild(el);\n return el;\n }\n }, {\n key: \"_generateMarkup\",\n value: function _generateMarkup() {\n // if autocomplete does not exist on the element and its form, then\n // prevent autocomplete as there's no safe, cross-browser event we can react to, so it can\n // easily put the plugin in an inconsistent state e.g. the wrong flag selected for the\n // autocompleted number, which on submit could mean wrong number is saved (esp in nationalMode)\n if (!this.telInput.hasAttribute(\"autocomplete\") && !(this.telInput.form && this.telInput.form.hasAttribute(\"autocomplete\"))) {\n this.telInput.setAttribute(\"autocomplete\", \"off\");\n }\n // containers (mostly for positioning)\n var parentClass = \"iti\";\n if (this.options.allowDropdown) parentClass += \" iti--allow-dropdown\";\n if (this.options.separateDialCode) parentClass += \" iti--separate-dial-code\";\n if (this.options.customContainer) {\n parentClass += \" \";\n parentClass += this.options.customContainer;\n }\n var wrapper = this._createEl(\"div\", {\n \"class\": parentClass\n });\n this.telInput.parentNode.insertBefore(wrapper, this.telInput);\n this.flagsContainer = this._createEl(\"div\", {\n \"class\": \"iti__flag-container\"\n }, wrapper);\n wrapper.appendChild(this.telInput);\n // selected flag (displayed to left of input)\n this.selectedFlag = this._createEl(\"div\", {\n \"class\": \"iti__selected-flag\",\n role: \"combobox\",\n \"aria-controls\": \"iti-\".concat(this.id, \"__country-listbox\"),\n \"aria-owns\": \"iti-\".concat(this.id, \"__country-listbox\"),\n \"aria-expanded\": \"false\"\n }, this.flagsContainer);\n this.selectedFlagInner = this._createEl(\"div\", {\n \"class\": \"iti__flag\"\n }, this.selectedFlag);\n if (this.options.separateDialCode) {\n this.selectedDialCode = this._createEl(\"div\", {\n \"class\": \"iti__selected-dial-code\"\n }, this.selectedFlag);\n }\n if (this.options.allowDropdown) {\n // make element focusable and tab navigable\n this.selectedFlag.setAttribute(\"tabindex\", \"0\");\n this.dropdownArrow = this._createEl(\"div\", {\n \"class\": \"iti__arrow\"\n }, this.selectedFlag);\n // country dropdown: preferred countries, then divider, then all countries\n this.countryList = this._createEl(\"ul\", {\n \"class\": \"iti__country-list iti__hide\",\n id: \"iti-\".concat(this.id, \"__country-listbox\"),\n role: \"listbox\",\n \"aria-label\": \"List of countries\"\n });\n if (this.preferredCountries.length) {\n this._appendListItems(this.preferredCountries, \"iti__preferred\", true);\n this._createEl(\"li\", {\n \"class\": \"iti__divider\",\n role: \"separator\",\n \"aria-disabled\": \"true\"\n }, this.countryList);\n }\n this._appendListItems(this.countries, \"iti__standard\");\n // create dropdownContainer markup\n if (this.options.dropdownContainer) {\n this.dropdown = this._createEl(\"div\", {\n \"class\": \"iti iti--container\"\n });\n this.dropdown.appendChild(this.countryList);\n } else {\n this.flagsContainer.appendChild(this.countryList);\n }\n }\n if (this.options.hiddenInput) {\n var hiddenInputName = this.options.hiddenInput;\n var name = this.telInput.getAttribute(\"name\");\n if (name) {\n var i = name.lastIndexOf(\"[\");\n // if input name contains square brackets, then give the hidden input the same name,\n // replacing the contents of the last set of brackets with the given hiddenInput name\n if (i !== -1) hiddenInputName = \"\".concat(name.substr(0, i), \"[\").concat(hiddenInputName, \"]\");\n }\n this.hiddenInput = this._createEl(\"input\", {\n type: \"hidden\",\n name: hiddenInputName\n });\n wrapper.appendChild(this.hiddenInput);\n }\n }\n }, {\n key: \"_appendListItems\",\n value: function _appendListItems(countries, className, preferred) {\n // we create so many DOM elements, it is faster to build a temp string\n // and then add everything to the DOM in one go at the end\n var tmp = \"\";\n // for each country\n for (var i = 0; i < countries.length; i++) {\n var c = countries[i];\n var idSuffix = preferred ? \"-preferred\" : \"\";\n // open the list item\n tmp += \"
  • \");\n // add the flag\n tmp += \"
    \");\n // and the country name and dial code\n tmp += \"\".concat(c.name, \"\");\n tmp += \"+\".concat(c.dialCode, \"\");\n // close the list item\n tmp += \"
  • \";\n }\n this.countryList.insertAdjacentHTML(\"beforeend\", tmp);\n }\n }, {\n key: \"_setInitialState\",\n value: function _setInitialState() {\n // fix firefox bug: when first load page (with input with value set to number with intl dial\n // code) and initialising plugin removes the dial code from the input, then refresh page,\n // and we try to init plugin again but this time on number without dial code so get grey flag\n var attributeValue = this.telInput.getAttribute(\"value\");\n var inputValue = this.telInput.value;\n var useAttribute = attributeValue && attributeValue.charAt(0) === \"+\" && (!inputValue || inputValue.charAt(0) !== \"+\");\n var val = useAttribute ? attributeValue : inputValue;\n var dialCode = this._getDialCode(val);\n var isRegionlessNanp = this._isRegionlessNanp(val);\n var _this$options = this.options, initialCountry = _this$options.initialCountry, nationalMode = _this$options.nationalMode, autoHideDialCode = _this$options.autoHideDialCode, separateDialCode = _this$options.separateDialCode;\n // if we already have a dial code, and it's not a regionlessNanp, we can go ahead and set the\n // flag, else fall back to the default country\n if (dialCode && !isRegionlessNanp) {\n this._updateFlagFromNumber(val);\n } else if (initialCountry !== \"auto\") {\n // see if we should select a flag\n if (initialCountry) {\n this._setFlag(initialCountry.toLowerCase());\n } else {\n if (dialCode && isRegionlessNanp) {\n // has intl dial code, is regionless nanp, and no initialCountry, so default to US\n this._setFlag(\"us\");\n } else {\n // no dial code and no initialCountry, so default to first in list\n this.defaultCountry = this.preferredCountries.length ? this.preferredCountries[0].iso2 : this.countries[0].iso2;\n if (!val) {\n this._setFlag(this.defaultCountry);\n }\n }\n }\n // if empty and no nationalMode and no autoHideDialCode then insert the default dial code\n if (!val && !nationalMode && !autoHideDialCode && !separateDialCode) {\n this.telInput.value = \"+\".concat(this.selectedCountryData.dialCode);\n }\n }\n // NOTE: if initialCountry is set to auto, that will be handled separately\n // format - note this wont be run after _updateDialCode as that's only called if no val\n if (val) this._updateValFromNumber(val);\n }\n }, {\n key: \"_initListeners\",\n value: function _initListeners() {\n this._initKeyListeners();\n if (this.options.autoHideDialCode) this._initBlurListeners();\n if (this.options.allowDropdown) this._initDropdownListeners();\n if (this.hiddenInput) this._initHiddenInputListener();\n }\n }, {\n key: \"_initHiddenInputListener\",\n value: function _initHiddenInputListener() {\n var _this3 = this;\n this._handleHiddenInputSubmit = function() {\n _this3.hiddenInput.value = _this3.getNumber();\n };\n if (this.telInput.form) this.telInput.form.addEventListener(\"submit\", this._handleHiddenInputSubmit);\n }\n }, {\n key: \"_getClosestLabel\",\n value: function _getClosestLabel() {\n var el = this.telInput;\n while (el && el.tagName !== \"LABEL\") {\n el = el.parentNode;\n }\n return el;\n }\n }, {\n key: \"_initDropdownListeners\",\n value: function _initDropdownListeners() {\n var _this4 = this;\n // hack for input nested inside label (which is valid markup): clicking the selected-flag to\n // open the dropdown would then automatically trigger a 2nd click on the input which would\n // close it again\n this._handleLabelClick = function(e) {\n // if the dropdown is closed, then focus the input, else ignore the click\n if (_this4.countryList.classList.contains(\"iti__hide\")) _this4.telInput.focus(); else e.preventDefault();\n };\n var label = this._getClosestLabel();\n if (label) label.addEventListener(\"click\", this._handleLabelClick);\n // toggle country dropdown on click\n this._handleClickSelectedFlag = function() {\n // only intercept this event if we're opening the dropdown\n // else let it bubble up to the top (\"click-off-to-close\" listener)\n // we cannot just stopPropagation as it may be needed to close another instance\n if (_this4.countryList.classList.contains(\"iti__hide\") && !_this4.telInput.disabled && !_this4.telInput.readOnly) {\n _this4._showDropdown();\n }\n };\n this.selectedFlag.addEventListener(\"click\", this._handleClickSelectedFlag);\n // open dropdown list if currently focused\n this._handleFlagsContainerKeydown = function(e) {\n var isDropdownHidden = _this4.countryList.classList.contains(\"iti__hide\");\n if (isDropdownHidden && [ \"ArrowUp\", \"Up\", \"ArrowDown\", \"Down\", \" \", \"Enter\" ].indexOf(e.key) !== -1) {\n // prevent form from being submitted if \"ENTER\" was pressed\n e.preventDefault();\n // prevent event from being handled again by document\n e.stopPropagation();\n _this4._showDropdown();\n }\n // allow navigation from dropdown to input on TAB\n if (e.key === \"Tab\") _this4._closeDropdown();\n };\n this.flagsContainer.addEventListener(\"keydown\", this._handleFlagsContainerKeydown);\n }\n }, {\n key: \"_initRequests\",\n value: function _initRequests() {\n var _this5 = this;\n // if the user has specified the path to the utils script, fetch it on window.load, else resolve\n if (this.options.utilsScript && !window.intlTelInputUtils) {\n // if the plugin is being initialised after the window.load event has already been fired\n if (window.intlTelInputGlobals.documentReady()) {\n window.intlTelInputGlobals.loadUtils(this.options.utilsScript);\n } else {\n // wait until the load event so we don't block any other requests e.g. the flags image\n window.addEventListener(\"load\", function() {\n window.intlTelInputGlobals.loadUtils(_this5.options.utilsScript);\n });\n }\n } else this.resolveUtilsScriptPromise();\n if (this.options.initialCountry === \"auto\") this._loadAutoCountry(); else this.resolveAutoCountryPromise();\n }\n }, {\n key: \"_loadAutoCountry\",\n value: function _loadAutoCountry() {\n // 3 options:\n // 1) already loaded (we're done)\n // 2) not already started loading (start)\n // 3) already started loading (do nothing - just wait for loading callback to fire)\n if (window.intlTelInputGlobals.autoCountry) {\n this.handleAutoCountry();\n } else if (!window.intlTelInputGlobals.startedLoadingAutoCountry) {\n // don't do this twice!\n window.intlTelInputGlobals.startedLoadingAutoCountry = true;\n if (typeof this.options.geoIpLookup === \"function\") {\n this.options.geoIpLookup(function(countryCode) {\n window.intlTelInputGlobals.autoCountry = countryCode.toLowerCase();\n // tell all instances the auto country is ready\n // TODO: this should just be the current instances\n // UPDATE: use setTimeout in case their geoIpLookup function calls this callback straight\n // away (e.g. if they have already done the geo ip lookup somewhere else). Using\n // setTimeout means that the current thread of execution will finish before executing\n // this, which allows the plugin to finish initialising.\n setTimeout(function() {\n return forEachInstance(\"handleAutoCountry\");\n });\n }, function() {\n return forEachInstance(\"rejectAutoCountryPromise\");\n });\n }\n }\n }\n }, {\n key: \"_initKeyListeners\",\n value: function _initKeyListeners() {\n var _this6 = this;\n // update flag on keyup\n this._handleKeyupEvent = function() {\n if (_this6._updateFlagFromNumber(_this6.telInput.value)) {\n _this6._triggerCountryChange();\n }\n };\n this.telInput.addEventListener(\"keyup\", this._handleKeyupEvent);\n // update flag on cut/paste events (now supported in all major browsers)\n this._handleClipboardEvent = function() {\n // hack because \"paste\" event is fired before input is updated\n setTimeout(_this6._handleKeyupEvent);\n };\n this.telInput.addEventListener(\"cut\", this._handleClipboardEvent);\n this.telInput.addEventListener(\"paste\", this._handleClipboardEvent);\n }\n }, {\n key: \"_cap\",\n value: function _cap(number) {\n var max = this.telInput.getAttribute(\"maxlength\");\n return max && number.length > max ? number.substr(0, max) : number;\n }\n }, {\n key: \"_initBlurListeners\",\n value: function _initBlurListeners() {\n var _this7 = this;\n // on blur or form submit: if just a dial code then remove it\n this._handleSubmitOrBlurEvent = function() {\n _this7._removeEmptyDialCode();\n };\n if (this.telInput.form) this.telInput.form.addEventListener(\"submit\", this._handleSubmitOrBlurEvent);\n this.telInput.addEventListener(\"blur\", this._handleSubmitOrBlurEvent);\n }\n }, {\n key: \"_removeEmptyDialCode\",\n value: function _removeEmptyDialCode() {\n if (this.telInput.value.charAt(0) === \"+\") {\n var numeric = this._getNumeric(this.telInput.value);\n // if just a plus, or if just a dial code\n if (!numeric || this.selectedCountryData.dialCode === numeric) {\n this.telInput.value = \"\";\n }\n }\n }\n }, {\n key: \"_getNumeric\",\n value: function _getNumeric(s) {\n return s.replace(/\\D/g, \"\");\n }\n }, {\n key: \"_trigger\",\n value: function _trigger(name) {\n // have to use old school document.createEvent as IE11 doesn't support `new Event()` syntax\n var e = document.createEvent(\"Event\");\n e.initEvent(name, true, true);\n // can bubble, and is cancellable\n this.telInput.dispatchEvent(e);\n }\n }, {\n key: \"_showDropdown\",\n value: function _showDropdown() {\n this.countryList.classList.remove(\"iti__hide\");\n this.selectedFlag.setAttribute(\"aria-expanded\", \"true\");\n this._setDropdownPosition();\n // update highlighting and scroll to active list item\n if (this.activeItem) {\n this._highlightListItem(this.activeItem, false);\n this._scrollTo(this.activeItem, true);\n }\n // bind all the dropdown-related listeners: mouseover, click, click-off, keydown\n this._bindDropdownListeners();\n // update the arrow\n this.dropdownArrow.classList.add(\"iti__arrow--up\");\n this._trigger(\"open:countrydropdown\");\n }\n }, {\n key: \"_toggleClass\",\n value: function _toggleClass(el, className, shouldHaveClass) {\n if (shouldHaveClass && !el.classList.contains(className)) el.classList.add(className); else if (!shouldHaveClass && el.classList.contains(className)) el.classList.remove(className);\n }\n }, {\n key: \"_setDropdownPosition\",\n value: function _setDropdownPosition() {\n var _this8 = this;\n if (this.options.dropdownContainer) {\n this.options.dropdownContainer.appendChild(this.dropdown);\n }\n if (!this.isMobile) {\n var pos = this.telInput.getBoundingClientRect();\n // windowTop from https://stackoverflow.com/a/14384091/217866\n var windowTop = window.pageYOffset || document.documentElement.scrollTop;\n var inputTop = pos.top + windowTop;\n var dropdownHeight = this.countryList.offsetHeight;\n // dropdownFitsBelow = (dropdownBottom < windowBottom)\n var dropdownFitsBelow = inputTop + this.telInput.offsetHeight + dropdownHeight < windowTop + window.innerHeight;\n var dropdownFitsAbove = inputTop - dropdownHeight > windowTop;\n // by default, the dropdown will be below the input. If we want to position it above the\n // input, we add the dropup class.\n this._toggleClass(this.countryList, \"iti__country-list--dropup\", !dropdownFitsBelow && dropdownFitsAbove);\n // if dropdownContainer is enabled, calculate postion\n if (this.options.dropdownContainer) {\n // by default the dropdown will be directly over the input because it's not in the flow.\n // If we want to position it below, we need to add some extra top value.\n var extraTop = !dropdownFitsBelow && dropdownFitsAbove ? 0 : this.telInput.offsetHeight;\n // calculate placement\n this.dropdown.style.top = \"\".concat(inputTop + extraTop, \"px\");\n this.dropdown.style.left = \"\".concat(pos.left + document.body.scrollLeft, \"px\");\n // close menu on window scroll\n this._handleWindowScroll = function() {\n return _this8._closeDropdown();\n };\n window.addEventListener(\"scroll\", this._handleWindowScroll);\n }\n }\n }\n }, {\n key: \"_getClosestListItem\",\n value: function _getClosestListItem(target) {\n var el = target;\n while (el && el !== this.countryList && !el.classList.contains(\"iti__country\")) {\n el = el.parentNode;\n }\n // if we reached the countryList element, then return null\n return el === this.countryList ? null : el;\n }\n }, {\n key: \"_bindDropdownListeners\",\n value: function _bindDropdownListeners() {\n var _this9 = this;\n // when mouse over a list item, just highlight that one\n // we add the class \"highlight\", so if they hit \"enter\" we know which one to select\n this._handleMouseoverCountryList = function(e) {\n // handle event delegation, as we're listening for this event on the countryList\n var listItem = _this9._getClosestListItem(e.target);\n if (listItem) _this9._highlightListItem(listItem, false);\n };\n this.countryList.addEventListener(\"mouseover\", this._handleMouseoverCountryList);\n // listen for country selection\n this._handleClickCountryList = function(e) {\n var listItem = _this9._getClosestListItem(e.target);\n if (listItem) _this9._selectListItem(listItem);\n };\n this.countryList.addEventListener(\"click\", this._handleClickCountryList);\n // click off to close\n // (except when this initial opening click is bubbling up)\n // we cannot just stopPropagation as it may be needed to close another instance\n var isOpening = true;\n this._handleClickOffToClose = function() {\n if (!isOpening) _this9._closeDropdown();\n isOpening = false;\n };\n document.documentElement.addEventListener(\"click\", this._handleClickOffToClose);\n // listen for up/down scrolling, enter to select, or letters to jump to country name.\n // use keydown as keypress doesn't fire for non-char keys and we want to catch if they\n // just hit down and hold it to scroll down (no keyup event).\n // listen on the document because that's where key events are triggered if no input has focus\n var query = \"\";\n var queryTimer = null;\n this._handleKeydownOnDropdown = function(e) {\n // prevent down key from scrolling the whole page,\n // and enter key from submitting a form etc\n e.preventDefault();\n // up and down to navigate\n if (e.key === \"ArrowUp\" || e.key === \"Up\" || e.key === \"ArrowDown\" || e.key === \"Down\") _this9._handleUpDownKey(e.key); else if (e.key === \"Enter\") _this9._handleEnterKey(); else if (e.key === \"Escape\") _this9._closeDropdown(); else if (/^[a-zA-ZÀ-ÿа-яА-Я ]$/.test(e.key)) {\n // jump to countries that start with the query string\n if (queryTimer) clearTimeout(queryTimer);\n query += e.key.toLowerCase();\n _this9._searchForCountry(query);\n // if the timer hits 1 second, reset the query\n queryTimer = setTimeout(function() {\n query = \"\";\n }, 1e3);\n }\n };\n document.addEventListener(\"keydown\", this._handleKeydownOnDropdown);\n }\n }, {\n key: \"_handleUpDownKey\",\n value: function _handleUpDownKey(key) {\n var next = key === \"ArrowUp\" || key === \"Up\" ? this.highlightedItem.previousElementSibling : this.highlightedItem.nextElementSibling;\n if (next) {\n // skip the divider\n if (next.classList.contains(\"iti__divider\")) {\n next = key === \"ArrowUp\" || key === \"Up\" ? next.previousElementSibling : next.nextElementSibling;\n }\n this._highlightListItem(next, true);\n }\n }\n }, {\n key: \"_handleEnterKey\",\n value: function _handleEnterKey() {\n if (this.highlightedItem) this._selectListItem(this.highlightedItem);\n }\n }, {\n key: \"_searchForCountry\",\n value: function _searchForCountry(query) {\n for (var i = 0; i < this.countries.length; i++) {\n if (this._startsWith(this.countries[i].name, query)) {\n var listItem = this.countryList.querySelector(\"#iti-\".concat(this.id, \"__item-\").concat(this.countries[i].iso2));\n // update highlighting and scroll\n this._highlightListItem(listItem, false);\n this._scrollTo(listItem, true);\n break;\n }\n }\n }\n }, {\n key: \"_startsWith\",\n value: function _startsWith(a, b) {\n return a.substr(0, b.length).toLowerCase() === b;\n }\n }, {\n key: \"_updateValFromNumber\",\n value: function _updateValFromNumber(originalNumber) {\n var number = originalNumber;\n if (this.options.formatOnDisplay && window.intlTelInputUtils && this.selectedCountryData) {\n var useNational = !this.options.separateDialCode && (this.options.nationalMode || number.charAt(0) !== \"+\");\n var _intlTelInputUtils$nu = intlTelInputUtils.numberFormat, NATIONAL = _intlTelInputUtils$nu.NATIONAL, INTERNATIONAL = _intlTelInputUtils$nu.INTERNATIONAL;\n var format = useNational ? NATIONAL : INTERNATIONAL;\n number = intlTelInputUtils.formatNumber(number, this.selectedCountryData.iso2, format);\n }\n number = this._beforeSetNumber(number);\n this.telInput.value = number;\n }\n }, {\n key: \"_updateFlagFromNumber\",\n value: function _updateFlagFromNumber(originalNumber) {\n // if we're in nationalMode and we already have US/Canada selected, make sure the number starts\n // with a +1 so _getDialCode will be able to extract the area code\n // update: if we dont yet have selectedCountryData, but we're here (trying to update the flag\n // from the number), that means we're initialising the plugin with a number that already has a\n // dial code, so fine to ignore this bit\n var number = originalNumber;\n var selectedDialCode = this.selectedCountryData.dialCode;\n var isNanp = selectedDialCode === \"1\";\n if (number && this.options.nationalMode && isNanp && number.charAt(0) !== \"+\") {\n if (number.charAt(0) !== \"1\") number = \"1\".concat(number);\n number = \"+\".concat(number);\n }\n // update flag if user types area code for another country\n if (this.options.separateDialCode && selectedDialCode && number.charAt(0) !== \"+\") {\n number = \"+\".concat(selectedDialCode).concat(number);\n }\n // try and extract valid dial code from input\n var dialCode = this._getDialCode(number, true);\n var numeric = this._getNumeric(number);\n var countryCode = null;\n if (dialCode) {\n var countryCodes = this.countryCodes[this._getNumeric(dialCode)];\n // check if the right country is already selected. this should be false if the number is\n // longer than the matched dial code because in this case we need to make sure that if\n // there are multiple country matches, that the first one is selected (note: we could\n // just check that here, but it requires the same loop that we already have later)\n var alreadySelected = countryCodes.indexOf(this.selectedCountryData.iso2) !== -1 && numeric.length <= dialCode.length - 1;\n var isRegionlessNanpNumber = selectedDialCode === \"1\" && this._isRegionlessNanp(numeric);\n // only update the flag if:\n // A) NOT (we currently have a NANP flag selected, and the number is a regionlessNanp)\n // AND\n // B) the right country is not already selected\n if (!isRegionlessNanpNumber && !alreadySelected) {\n // if using onlyCountries option, countryCodes[0] may be empty, so we must find the first\n // non-empty index\n for (var j = 0; j < countryCodes.length; j++) {\n if (countryCodes[j]) {\n countryCode = countryCodes[j];\n break;\n }\n }\n }\n } else if (number.charAt(0) === \"+\" && numeric.length) {\n // invalid dial code, so empty\n // Note: use getNumeric here because the number has not been formatted yet, so could contain\n // bad chars\n countryCode = \"\";\n } else if (!number || number === \"+\") {\n // empty, or just a plus, so default\n countryCode = this.defaultCountry;\n }\n if (countryCode !== null) {\n return this._setFlag(countryCode);\n }\n return false;\n }\n }, {\n key: \"_isRegionlessNanp\",\n value: function _isRegionlessNanp(number) {\n var numeric = this._getNumeric(number);\n if (numeric.charAt(0) === \"1\") {\n var areaCode = numeric.substr(1, 3);\n return regionlessNanpNumbers.indexOf(areaCode) !== -1;\n }\n return false;\n }\n }, {\n key: \"_highlightListItem\",\n value: function _highlightListItem(listItem, shouldFocus) {\n var prevItem = this.highlightedItem;\n if (prevItem) prevItem.classList.remove(\"iti__highlight\");\n this.highlightedItem = listItem;\n this.highlightedItem.classList.add(\"iti__highlight\");\n if (shouldFocus) this.highlightedItem.focus();\n }\n }, {\n key: \"_getCountryData\",\n value: function _getCountryData(countryCode, ignoreOnlyCountriesOption, allowFail) {\n var countryList = ignoreOnlyCountriesOption ? allCountries : this.countries;\n for (var i = 0; i < countryList.length; i++) {\n if (countryList[i].iso2 === countryCode) {\n return countryList[i];\n }\n }\n if (allowFail) {\n return null;\n }\n throw new Error(\"No country data for '\".concat(countryCode, \"'\"));\n }\n }, {\n key: \"_setFlag\",\n value: function _setFlag(countryCode) {\n var prevCountry = this.selectedCountryData.iso2 ? this.selectedCountryData : {};\n // do this first as it will throw an error and stop if countryCode is invalid\n this.selectedCountryData = countryCode ? this._getCountryData(countryCode, false, false) : {};\n // update the defaultCountry - we only need the iso2 from now on, so just store that\n if (this.selectedCountryData.iso2) {\n this.defaultCountry = this.selectedCountryData.iso2;\n }\n this.selectedFlagInner.setAttribute(\"class\", \"iti__flag iti__\".concat(countryCode));\n // update the selected country's title attribute\n var title = countryCode ? \"\".concat(this.selectedCountryData.name, \": +\").concat(this.selectedCountryData.dialCode) : \"Unknown\";\n this.selectedFlag.setAttribute(\"title\", title);\n if (this.options.separateDialCode) {\n var dialCode = this.selectedCountryData.dialCode ? \"+\".concat(this.selectedCountryData.dialCode) : \"\";\n this.selectedDialCode.innerHTML = dialCode;\n // offsetWidth is zero if input is in a hidden container during initialisation\n var selectedFlagWidth = this.selectedFlag.offsetWidth || this._getHiddenSelectedFlagWidth();\n // add 6px of padding after the grey selected-dial-code box, as this is what we use in the css\n this.telInput.style.paddingLeft = \"\".concat(selectedFlagWidth + 6, \"px\");\n }\n // and the input's placeholder\n this._updatePlaceholder();\n // update the active list item\n if (this.options.allowDropdown) {\n var prevItem = this.activeItem;\n if (prevItem) {\n prevItem.classList.remove(\"iti__active\");\n prevItem.setAttribute(\"aria-selected\", \"false\");\n }\n if (countryCode) {\n // check if there is a preferred item first, else fall back to standard\n var nextItem = this.countryList.querySelector(\"#iti-\".concat(this.id, \"__item-\").concat(countryCode, \"-preferred\")) || this.countryList.querySelector(\"#iti-\".concat(this.id, \"__item-\").concat(countryCode));\n nextItem.setAttribute(\"aria-selected\", \"true\");\n nextItem.classList.add(\"iti__active\");\n this.activeItem = nextItem;\n this.selectedFlag.setAttribute(\"aria-activedescendant\", nextItem.getAttribute(\"id\"));\n }\n }\n // return if the flag has changed or not\n return prevCountry.iso2 !== countryCode;\n }\n }, {\n key: \"_getHiddenSelectedFlagWidth\",\n value: function _getHiddenSelectedFlagWidth() {\n // to get the right styling to apply, all we need is a shallow clone of the container,\n // and then to inject a deep clone of the selectedFlag element\n var containerClone = this.telInput.parentNode.cloneNode();\n containerClone.style.visibility = \"hidden\";\n document.body.appendChild(containerClone);\n var flagsContainerClone = this.flagsContainer.cloneNode();\n containerClone.appendChild(flagsContainerClone);\n var selectedFlagClone = this.selectedFlag.cloneNode(true);\n flagsContainerClone.appendChild(selectedFlagClone);\n var width = selectedFlagClone.offsetWidth;\n containerClone.parentNode.removeChild(containerClone);\n return width;\n }\n }, {\n key: \"_updatePlaceholder\",\n value: function _updatePlaceholder() {\n var shouldSetPlaceholder = this.options.autoPlaceholder === \"aggressive\" || !this.hadInitialPlaceholder && this.options.autoPlaceholder === \"polite\";\n if (window.intlTelInputUtils && shouldSetPlaceholder) {\n var numberType = intlTelInputUtils.numberType[this.options.placeholderNumberType];\n var placeholder = this.selectedCountryData.iso2 ? intlTelInputUtils.getExampleNumber(this.selectedCountryData.iso2, this.options.nationalMode, numberType) : \"\";\n placeholder = this._beforeSetNumber(placeholder);\n if (typeof this.options.customPlaceholder === \"function\") {\n placeholder = this.options.customPlaceholder(placeholder, this.selectedCountryData);\n }\n this.telInput.setAttribute(\"placeholder\", placeholder);\n }\n }\n }, {\n key: \"_selectListItem\",\n value: function _selectListItem(listItem) {\n // update selected flag and active list item\n var flagChanged = this._setFlag(listItem.getAttribute(\"data-country-code\"));\n this._closeDropdown();\n this._updateDialCode(listItem.getAttribute(\"data-dial-code\"), true);\n // focus the input\n this.telInput.focus();\n // put cursor at end - this fix is required for FF and IE11 (with nationalMode=false i.e. auto\n // inserting dial code), who try to put the cursor at the beginning the first time\n var len = this.telInput.value.length;\n this.telInput.setSelectionRange(len, len);\n if (flagChanged) {\n this._triggerCountryChange();\n }\n }\n }, {\n key: \"_closeDropdown\",\n value: function _closeDropdown() {\n this.countryList.classList.add(\"iti__hide\");\n this.selectedFlag.setAttribute(\"aria-expanded\", \"false\");\n // update the arrow\n this.dropdownArrow.classList.remove(\"iti__arrow--up\");\n // unbind key events\n document.removeEventListener(\"keydown\", this._handleKeydownOnDropdown);\n document.documentElement.removeEventListener(\"click\", this._handleClickOffToClose);\n this.countryList.removeEventListener(\"mouseover\", this._handleMouseoverCountryList);\n this.countryList.removeEventListener(\"click\", this._handleClickCountryList);\n // remove menu from container\n if (this.options.dropdownContainer) {\n if (!this.isMobile) window.removeEventListener(\"scroll\", this._handleWindowScroll);\n if (this.dropdown.parentNode) this.dropdown.parentNode.removeChild(this.dropdown);\n }\n this._trigger(\"close:countrydropdown\");\n }\n }, {\n key: \"_scrollTo\",\n value: function _scrollTo(element, middle) {\n var container = this.countryList;\n // windowTop from https://stackoverflow.com/a/14384091/217866\n var windowTop = window.pageYOffset || document.documentElement.scrollTop;\n var containerHeight = container.offsetHeight;\n var containerTop = container.getBoundingClientRect().top + windowTop;\n var containerBottom = containerTop + containerHeight;\n var elementHeight = element.offsetHeight;\n var elementTop = element.getBoundingClientRect().top + windowTop;\n var elementBottom = elementTop + elementHeight;\n var newScrollTop = elementTop - containerTop + container.scrollTop;\n var middleOffset = containerHeight / 2 - elementHeight / 2;\n if (elementTop < containerTop) {\n // scroll up\n if (middle) newScrollTop -= middleOffset;\n container.scrollTop = newScrollTop;\n } else if (elementBottom > containerBottom) {\n // scroll down\n if (middle) newScrollTop += middleOffset;\n var heightDifference = containerHeight - elementHeight;\n container.scrollTop = newScrollTop - heightDifference;\n }\n }\n }, {\n key: \"_updateDialCode\",\n value: function _updateDialCode(newDialCodeBare, hasSelectedListItem) {\n var inputVal = this.telInput.value;\n // save having to pass this every time\n var newDialCode = \"+\".concat(newDialCodeBare);\n var newNumber;\n if (inputVal.charAt(0) === \"+\") {\n // there's a plus so we're dealing with a replacement (doesn't matter if nationalMode or not)\n var prevDialCode = this._getDialCode(inputVal);\n if (prevDialCode) {\n // current number contains a valid dial code, so replace it\n newNumber = inputVal.replace(prevDialCode, newDialCode);\n } else {\n // current number contains an invalid dial code, so ditch it\n // (no way to determine where the invalid dial code ends and the rest of the number begins)\n newNumber = newDialCode;\n }\n } else if (this.options.nationalMode || this.options.separateDialCode) {\n // don't do anything\n return;\n } else {\n // nationalMode is disabled\n if (inputVal) {\n // there is an existing value with no dial code: prefix the new dial code\n newNumber = newDialCode + inputVal;\n } else if (hasSelectedListItem || !this.options.autoHideDialCode) {\n // no existing value and either they've just selected a list item, or autoHideDialCode is\n // disabled: insert new dial code\n newNumber = newDialCode;\n } else {\n return;\n }\n }\n this.telInput.value = newNumber;\n }\n }, {\n key: \"_getDialCode\",\n value: function _getDialCode(number, includeAreaCode) {\n var dialCode = \"\";\n // only interested in international numbers (starting with a plus)\n if (number.charAt(0) === \"+\") {\n var numericChars = \"\";\n // iterate over chars\n for (var i = 0; i < number.length; i++) {\n var c = number.charAt(i);\n // if char is number (https://stackoverflow.com/a/8935649/217866)\n if (!isNaN(parseInt(c, 10))) {\n numericChars += c;\n // if current numericChars make a valid dial code\n if (includeAreaCode) {\n if (this.countryCodes[numericChars]) {\n // store the actual raw string (useful for matching later)\n dialCode = number.substr(0, i + 1);\n }\n } else {\n if (this.dialCodes[numericChars]) {\n dialCode = number.substr(0, i + 1);\n // if we're just looking for a dial code, we can break as soon as we find one\n break;\n }\n }\n // stop searching as soon as we can - in this case when we hit max len\n if (numericChars.length === this.countryCodeMaxLen) {\n break;\n }\n }\n }\n }\n return dialCode;\n }\n }, {\n key: \"_getFullNumber\",\n value: function _getFullNumber() {\n var val = this.telInput.value.trim();\n var dialCode = this.selectedCountryData.dialCode;\n var prefix;\n var numericVal = this._getNumeric(val);\n if (this.options.separateDialCode && val.charAt(0) !== \"+\" && dialCode && numericVal) {\n // when using separateDialCode, it is visible so is effectively part of the typed number\n prefix = \"+\".concat(dialCode);\n } else {\n prefix = \"\";\n }\n return prefix + val;\n }\n }, {\n key: \"_beforeSetNumber\",\n value: function _beforeSetNumber(originalNumber) {\n var number = originalNumber;\n if (this.options.separateDialCode) {\n var dialCode = this._getDialCode(number);\n // if there is a valid dial code\n if (dialCode) {\n // in case _getDialCode returned an area code as well\n dialCode = \"+\".concat(this.selectedCountryData.dialCode);\n // a lot of numbers will have a space separating the dial code and the main number, and\n // some NANP numbers will have a hyphen e.g. +1 684-733-1234 - in both cases we want to get\n // rid of it\n // NOTE: don't just trim all non-numerics as may want to preserve an open parenthesis etc\n var start = number[dialCode.length] === \" \" || number[dialCode.length] === \"-\" ? dialCode.length + 1 : dialCode.length;\n number = number.substr(start);\n }\n }\n return this._cap(number);\n }\n }, {\n key: \"_triggerCountryChange\",\n value: function _triggerCountryChange() {\n this._trigger(\"countrychange\");\n }\n }, {\n key: \"handleAutoCountry\",\n value: function handleAutoCountry() {\n if (this.options.initialCountry === \"auto\") {\n // we must set this even if there is an initial val in the input: in case the initial val is\n // invalid and they delete it - they should see their auto country\n this.defaultCountry = window.intlTelInputGlobals.autoCountry;\n // if there's no initial value in the input, then update the flag\n if (!this.telInput.value) {\n this.setCountry(this.defaultCountry);\n }\n this.resolveAutoCountryPromise();\n }\n }\n }, {\n key: \"handleUtils\",\n value: function handleUtils() {\n // if the request was successful\n if (window.intlTelInputUtils) {\n // if there's an initial value in the input, then format it\n if (this.telInput.value) {\n this._updateValFromNumber(this.telInput.value);\n }\n this._updatePlaceholder();\n }\n this.resolveUtilsScriptPromise();\n }\n }, {\n key: \"destroy\",\n value: function destroy() {\n var form = this.telInput.form;\n if (this.options.allowDropdown) {\n // make sure the dropdown is closed (and unbind listeners)\n this._closeDropdown();\n this.selectedFlag.removeEventListener(\"click\", this._handleClickSelectedFlag);\n this.flagsContainer.removeEventListener(\"keydown\", this._handleFlagsContainerKeydown);\n // label click hack\n var label = this._getClosestLabel();\n if (label) label.removeEventListener(\"click\", this._handleLabelClick);\n }\n // unbind hiddenInput listeners\n if (this.hiddenInput && form) form.removeEventListener(\"submit\", this._handleHiddenInputSubmit);\n // unbind autoHideDialCode listeners\n if (this.options.autoHideDialCode) {\n if (form) form.removeEventListener(\"submit\", this._handleSubmitOrBlurEvent);\n this.telInput.removeEventListener(\"blur\", this._handleSubmitOrBlurEvent);\n }\n // unbind key events, and cut/paste events\n this.telInput.removeEventListener(\"keyup\", this._handleKeyupEvent);\n this.telInput.removeEventListener(\"cut\", this._handleClipboardEvent);\n this.telInput.removeEventListener(\"paste\", this._handleClipboardEvent);\n // remove attribute of id instance: data-intl-tel-input-id\n this.telInput.removeAttribute(\"data-intl-tel-input-id\");\n // remove markup (but leave the original input)\n var wrapper = this.telInput.parentNode;\n wrapper.parentNode.insertBefore(this.telInput, wrapper);\n wrapper.parentNode.removeChild(wrapper);\n delete window.intlTelInputGlobals.instances[this.id];\n }\n }, {\n key: \"getExtension\",\n value: function getExtension() {\n if (window.intlTelInputUtils) {\n return intlTelInputUtils.getExtension(this._getFullNumber(), this.selectedCountryData.iso2);\n }\n return \"\";\n }\n }, {\n key: \"getNumber\",\n value: function getNumber(format) {\n if (window.intlTelInputUtils) {\n var iso2 = this.selectedCountryData.iso2;\n return intlTelInputUtils.formatNumber(this._getFullNumber(), iso2, format);\n }\n return \"\";\n }\n }, {\n key: \"getNumberType\",\n value: function getNumberType() {\n if (window.intlTelInputUtils) {\n return intlTelInputUtils.getNumberType(this._getFullNumber(), this.selectedCountryData.iso2);\n }\n return -99;\n }\n }, {\n key: \"getSelectedCountryData\",\n value: function getSelectedCountryData() {\n return this.selectedCountryData;\n }\n }, {\n key: \"getValidationError\",\n value: function getValidationError() {\n if (window.intlTelInputUtils) {\n var iso2 = this.selectedCountryData.iso2;\n return intlTelInputUtils.getValidationError(this._getFullNumber(), iso2);\n }\n return -99;\n }\n }, {\n key: \"isValidNumber\",\n value: function isValidNumber() {\n var val = this._getFullNumber().trim();\n var countryCode = this.options.nationalMode ? this.selectedCountryData.iso2 : \"\";\n return window.intlTelInputUtils ? intlTelInputUtils.isValidNumber(val, countryCode) : null;\n }\n }, {\n key: \"setCountry\",\n value: function setCountry(originalCountryCode) {\n var countryCode = originalCountryCode.toLowerCase();\n // check if already selected\n if (!this.selectedFlagInner.classList.contains(\"iti__\".concat(countryCode))) {\n this._setFlag(countryCode);\n this._updateDialCode(this.selectedCountryData.dialCode, false);\n this._triggerCountryChange();\n }\n }\n }, {\n key: \"setNumber\",\n value: function setNumber(number) {\n // we must update the flag first, which updates this.selectedCountryData, which is used for\n // formatting the number before displaying it\n var flagChanged = this._updateFlagFromNumber(number);\n this._updateValFromNumber(number);\n if (flagChanged) {\n this._triggerCountryChange();\n }\n }\n }, {\n key: \"setPlaceholderNumberType\",\n value: function setPlaceholderNumberType(type) {\n this.options.placeholderNumberType = type;\n this._updatePlaceholder();\n }\n } ]);\n return Iti;\n }();\n /********************\n * STATIC METHODS\n ********************/\n // get the country data object\n intlTelInputGlobals.getCountryData = function() {\n return allCountries;\n };\n // inject a