{ "version": 3, "sources": ["../../../node_modules/@rails/actioncable/src/adapters.js", "../../../node_modules/@rails/actioncable/src/logger.js", "../../../node_modules/@rails/actioncable/src/connection_monitor.js", "../../../node_modules/@rails/actioncable/src/internal.js", "../../../node_modules/@rails/actioncable/src/connection.js", "../../../node_modules/@rails/actioncable/src/subscription.js", "../../../node_modules/@rails/actioncable/src/subscription_guarantor.js", "../../../node_modules/@rails/actioncable/src/subscriptions.js", "../../../node_modules/@rails/actioncable/src/consumer.js", "../../../node_modules/@rails/actioncable/src/index.js", "../../../node_modules/@rails/activestorage/app/assets/javascripts/activestorage.js", "../../../node_modules/mutation-events/src/mutation_events.min.js", "../../../node_modules/@rails/ujs/lib/assets/compiled/rails-ujs.js", "../../../node_modules/pikaday/pikaday.js", "../../../node_modules/nouislider/dist/nouislider.js", "../../../node_modules/@hotwired/turbo/dist/turbo.es2017-esm.js", "../../../node_modules/@hotwired/turbo-rails/app/javascript/turbo/cable.js", "../../../node_modules/@hotwired/turbo-rails/app/javascript/turbo/snakeize.js", "../../../node_modules/@hotwired/turbo-rails/app/javascript/turbo/cable_stream_source_element.js", "../../../node_modules/@hotwired/turbo-rails/app/javascript/turbo/form_submissions.js", "../../../node_modules/@hotwired/turbo-rails/app/javascript/turbo/index.js", "../../../node_modules/@rails/actiontext/app/javascript/actiontext/attachment_upload.js", "../../../node_modules/@rails/actiontext/app/javascript/actiontext/index.js", "../../../node_modules/@hotwired/stimulus/dist/stimulus.js", "../../javascript/controllers/application.js", "../../javascript/controllers/banner_img_controller.js", "../../javascript/controllers/dialog_controller.js", "../../javascript/controllers/event_access_controller.js", "../../javascript/controllers/expand_toggle_controller.js", "../../javascript/controllers/expnd_txt_controller.js", "../../javascript/controllers/flash_controller.js", "../../javascript/controllers/hello_controller.js", "../../javascript/controllers/iframe_loading_controller.js", "../../javascript/controllers/jump_btn_controller.js", "../../javascript/controllers/link_share_controller.js", "../../javascript/controllers/mobile_filters_toggle_controller.js", "../../javascript/controllers/process_feedback_controller.js", "../../javascript/controllers/recite_me_controller.js", "../../javascript/controllers/reset_cookie_controller.js", "../../../node_modules/trix/dist/trix.js", "../../javascript/controllers/rich_text_table_controller.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", "../../javascript/controllers/select_controller.js", "../../javascript/controllers/soc_exp_controller.js", "../../javascript/controllers/swipercontent_controller.js", "../../javascript/controllers/table_editor_controller.js", "../../javascript/controllers/index.js", "../../javascript/modules/navbar/ctas.js", "../../javascript/modules/navbar/header.js", "../../javascript/modules/navbar/menuoverlay.js", "../../javascript/modules/navbar/index.js", "../../../node_modules/ssr-window/ssr-window.esm.js", "../../../node_modules/swiper/shared/utils.js", "../../../node_modules/swiper/shared/get-support.js", "../../../node_modules/swiper/shared/get-device.js", "../../../node_modules/swiper/shared/get-browser.js", "../../../node_modules/swiper/core/modules/resize/resize.js", "../../../node_modules/swiper/core/modules/observer/observer.js", "../../../node_modules/swiper/core/events-emitter.js", "../../../node_modules/swiper/core/update/updateSize.js", "../../../node_modules/swiper/core/update/updateSlides.js", "../../../node_modules/swiper/core/update/updateAutoHeight.js", "../../../node_modules/swiper/core/update/updateSlidesOffset.js", "../../../node_modules/swiper/core/update/updateSlidesProgress.js", "../../../node_modules/swiper/core/update/updateProgress.js", "../../../node_modules/swiper/core/update/updateSlidesClasses.js", "../../../node_modules/swiper/core/update/updateActiveIndex.js", "../../../node_modules/swiper/core/update/updateClickedSlide.js", "../../../node_modules/swiper/core/update/index.js", "../../../node_modules/swiper/core/translate/getTranslate.js", "../../../node_modules/swiper/core/translate/setTranslate.js", "../../../node_modules/swiper/core/translate/minTranslate.js", "../../../node_modules/swiper/core/translate/maxTranslate.js", "../../../node_modules/swiper/core/translate/translateTo.js", "../../../node_modules/swiper/core/translate/index.js", "../../../node_modules/swiper/core/transition/setTransition.js", "../../../node_modules/swiper/core/transition/transitionEmit.js", "../../../node_modules/swiper/core/transition/transitionStart.js", "../../../node_modules/swiper/core/transition/transitionEnd.js", "../../../node_modules/swiper/core/transition/index.js", "../../../node_modules/swiper/core/slide/slideTo.js", "../../../node_modules/swiper/core/slide/slideToLoop.js", "../../../node_modules/swiper/core/slide/slideNext.js", "../../../node_modules/swiper/core/slide/slidePrev.js", "../../../node_modules/swiper/core/slide/slideReset.js", "../../../node_modules/swiper/core/slide/slideToClosest.js", "../../../node_modules/swiper/core/slide/slideToClickedSlide.js", "../../../node_modules/swiper/core/slide/index.js", "../../../node_modules/swiper/core/loop/loopCreate.js", "../../../node_modules/swiper/core/loop/loopFix.js", "../../../node_modules/swiper/core/loop/loopDestroy.js", "../../../node_modules/swiper/core/loop/index.js", "../../../node_modules/swiper/core/grab-cursor/setGrabCursor.js", "../../../node_modules/swiper/core/grab-cursor/unsetGrabCursor.js", "../../../node_modules/swiper/core/grab-cursor/index.js", "../../../node_modules/swiper/core/events/onTouchStart.js", "../../../node_modules/swiper/core/events/onTouchMove.js", "../../../node_modules/swiper/core/events/onTouchEnd.js", "../../../node_modules/swiper/core/events/onResize.js", "../../../node_modules/swiper/core/events/onClick.js", "../../../node_modules/swiper/core/events/onScroll.js", "../../../node_modules/swiper/shared/process-lazy-preloader.js", "../../../node_modules/swiper/core/events/onLoad.js", "../../../node_modules/swiper/core/events/index.js", "../../../node_modules/swiper/core/breakpoints/setBreakpoint.js", "../../../node_modules/swiper/core/breakpoints/getBreakpoint.js", "../../../node_modules/swiper/core/breakpoints/index.js", "../../../node_modules/swiper/core/classes/addClasses.js", "../../../node_modules/swiper/core/classes/removeClasses.js", "../../../node_modules/swiper/core/classes/index.js", "../../../node_modules/swiper/core/check-overflow/index.js", "../../../node_modules/swiper/core/defaults.js", "../../../node_modules/swiper/core/moduleExtendParams.js", "../../../node_modules/swiper/core/core.js", "../../../node_modules/swiper/shared/create-element-if-not-defined.js", "../../../node_modules/swiper/modules/navigation/navigation.js", "../../../node_modules/swiper/shared/classes-to-selector.js", "../../../node_modules/swiper/modules/pagination/pagination.js", "../../../node_modules/swiper/modules/autoplay/autoplay.js", "../../javascript/modules/swiper/index.js", "../../javascript/modules/pikadayFilters/index.js", "../../javascript/modules/price_range_slider/index.js", "../../javascript/modules/checkbox_insert/index.js", "../../javascript/modules/safari/index.js", "../../javascript/modules/index.js", "../../../node_modules/@fancyapps/ui/dist/index.esm.js", "../../javascript/application.js"], "sourcesContent": ["export default {\n logger: self.console,\n WebSocket: self.WebSocket\n}\n", "import adapters from \"./adapters\"\n\n// The logger is disabled by default. You can enable it with:\n//\n// ActionCable.logger.enabled = true\n//\n// Example:\n//\n// import * as ActionCable from '@rails/actioncable'\n//\n// ActionCable.logger.enabled = true\n// ActionCable.logger.log('Connection Established.')\n//\n\nexport default {\n log(...messages) {\n if (this.enabled) {\n messages.push(Date.now())\n adapters.logger.log(\"[ActionCable]\", ...messages)\n }\n },\n}\n", "import logger from \"./logger\"\n\n// Responsible for ensuring the cable connection is in good health by validating the heartbeat pings sent from the server, and attempting\n// revival reconnections if things go astray. Internal class, not intended for direct user manipulation.\n\nconst now = () => new Date().getTime()\n\nconst secondsSince = time => (now() - time) / 1000\n\nclass ConnectionMonitor {\n constructor(connection) {\n this.visibilityDidChange = this.visibilityDidChange.bind(this)\n this.connection = connection\n this.reconnectAttempts = 0\n }\n\n start() {\n if (!this.isRunning()) {\n this.startedAt = now()\n delete this.stoppedAt\n this.startPolling()\n addEventListener(\"visibilitychange\", this.visibilityDidChange)\n logger.log(`ConnectionMonitor started. stale threshold = ${this.constructor.staleThreshold} s`)\n }\n }\n\n stop() {\n if (this.isRunning()) {\n this.stoppedAt = now()\n this.stopPolling()\n removeEventListener(\"visibilitychange\", this.visibilityDidChange)\n logger.log(\"ConnectionMonitor stopped\")\n }\n }\n\n isRunning() {\n return this.startedAt && !this.stoppedAt\n }\n\n recordPing() {\n this.pingedAt = now()\n }\n\n recordConnect() {\n this.reconnectAttempts = 0\n this.recordPing()\n delete this.disconnectedAt\n logger.log(\"ConnectionMonitor recorded connect\")\n }\n\n recordDisconnect() {\n this.disconnectedAt = now()\n logger.log(\"ConnectionMonitor recorded disconnect\")\n }\n\n // Private\n\n startPolling() {\n this.stopPolling()\n this.poll()\n }\n\n stopPolling() {\n clearTimeout(this.pollTimeout)\n }\n\n poll() {\n this.pollTimeout = setTimeout(() => {\n this.reconnectIfStale()\n this.poll()\n }\n , this.getPollInterval())\n }\n\n getPollInterval() {\n const { staleThreshold, reconnectionBackoffRate } = this.constructor\n const backoff = Math.pow(1 + reconnectionBackoffRate, Math.min(this.reconnectAttempts, 10))\n const jitterMax = this.reconnectAttempts === 0 ? 1.0 : reconnectionBackoffRate\n const jitter = jitterMax * Math.random()\n return staleThreshold * 1000 * backoff * (1 + jitter)\n }\n\n reconnectIfStale() {\n if (this.connectionIsStale()) {\n logger.log(`ConnectionMonitor detected stale connection. reconnectAttempts = ${this.reconnectAttempts}, time stale = ${secondsSince(this.refreshedAt)} s, stale threshold = ${this.constructor.staleThreshold} s`)\n this.reconnectAttempts++\n if (this.disconnectedRecently()) {\n logger.log(`ConnectionMonitor skipping reopening recent disconnect. time disconnected = ${secondsSince(this.disconnectedAt)} s`)\n } else {\n logger.log(\"ConnectionMonitor reopening\")\n this.connection.reopen()\n }\n }\n }\n\n get refreshedAt() {\n return this.pingedAt ? this.pingedAt : this.startedAt\n }\n\n connectionIsStale() {\n return secondsSince(this.refreshedAt) > this.constructor.staleThreshold\n }\n\n disconnectedRecently() {\n return this.disconnectedAt && (secondsSince(this.disconnectedAt) < this.constructor.staleThreshold)\n }\n\n visibilityDidChange() {\n if (document.visibilityState === \"visible\") {\n setTimeout(() => {\n if (this.connectionIsStale() || !this.connection.isOpen()) {\n logger.log(`ConnectionMonitor reopening stale connection on visibilitychange. visibilityState = ${document.visibilityState}`)\n this.connection.reopen()\n }\n }\n , 200)\n }\n }\n\n}\n\nConnectionMonitor.staleThreshold = 6 // Server::Connections::BEAT_INTERVAL * 2 (missed two pings)\nConnectionMonitor.reconnectionBackoffRate = 0.15\n\nexport default ConnectionMonitor\n", "export default {\n \"message_types\": {\n \"welcome\": \"welcome\",\n \"disconnect\": \"disconnect\",\n \"ping\": \"ping\",\n \"confirmation\": \"confirm_subscription\",\n \"rejection\": \"reject_subscription\"\n },\n \"disconnect_reasons\": {\n \"unauthorized\": \"unauthorized\",\n \"invalid_request\": \"invalid_request\",\n \"server_restart\": \"server_restart\"\n },\n \"default_mount_path\": \"/cable\",\n \"protocols\": [\n \"actioncable-v1-json\",\n \"actioncable-unsupported\"\n ]\n}\n", "import adapters from \"./adapters\"\nimport ConnectionMonitor from \"./connection_monitor\"\nimport INTERNAL from \"./internal\"\nimport logger from \"./logger\"\n\n// Encapsulate the cable connection held by the consumer. This is an internal class not intended for direct user manipulation.\n\nconst {message_types, protocols} = INTERNAL\nconst supportedProtocols = protocols.slice(0, protocols.length - 1)\n\nconst indexOf = [].indexOf\n\nclass Connection {\n constructor(consumer) {\n this.open = this.open.bind(this)\n this.consumer = consumer\n this.subscriptions = this.consumer.subscriptions\n this.monitor = new ConnectionMonitor(this)\n this.disconnected = true\n }\n\n send(data) {\n if (this.isOpen()) {\n this.webSocket.send(JSON.stringify(data))\n return true\n } else {\n return false\n }\n }\n\n open() {\n if (this.isActive()) {\n logger.log(`Attempted to open WebSocket, but existing socket is ${this.getState()}`)\n return false\n } else {\n logger.log(`Opening WebSocket, current state is ${this.getState()}, subprotocols: ${protocols}`)\n if (this.webSocket) { this.uninstallEventHandlers() }\n this.webSocket = new adapters.WebSocket(this.consumer.url, protocols)\n this.installEventHandlers()\n this.monitor.start()\n return true\n }\n }\n\n close({allowReconnect} = {allowReconnect: true}) {\n if (!allowReconnect) { this.monitor.stop() }\n // Avoid closing websockets in a \"connecting\" state due to Safari 15.1+ bug. See: https://github.com/rails/rails/issues/43835#issuecomment-1002288478\n if (this.isOpen()) {\n return this.webSocket.close()\n }\n }\n\n reopen() {\n logger.log(`Reopening WebSocket, current state is ${this.getState()}`)\n if (this.isActive()) {\n try {\n return this.close()\n } catch (error) {\n logger.log(\"Failed to reopen WebSocket\", error)\n }\n finally {\n logger.log(`Reopening WebSocket in ${this.constructor.reopenDelay}ms`)\n setTimeout(this.open, this.constructor.reopenDelay)\n }\n } else {\n return this.open()\n }\n }\n\n getProtocol() {\n if (this.webSocket) {\n return this.webSocket.protocol\n }\n }\n\n isOpen() {\n return this.isState(\"open\")\n }\n\n isActive() {\n return this.isState(\"open\", \"connecting\")\n }\n\n // Private\n\n isProtocolSupported() {\n return indexOf.call(supportedProtocols, this.getProtocol()) >= 0\n }\n\n isState(...states) {\n return indexOf.call(states, this.getState()) >= 0\n }\n\n getState() {\n if (this.webSocket) {\n for (let state in adapters.WebSocket) {\n if (adapters.WebSocket[state] === this.webSocket.readyState) {\n return state.toLowerCase()\n }\n }\n }\n return null\n }\n\n installEventHandlers() {\n for (let eventName in this.events) {\n const handler = this.events[eventName].bind(this)\n this.webSocket[`on${eventName}`] = handler\n }\n }\n\n uninstallEventHandlers() {\n for (let eventName in this.events) {\n this.webSocket[`on${eventName}`] = function() {}\n }\n }\n\n}\n\nConnection.reopenDelay = 500\n\nConnection.prototype.events = {\n message(event) {\n if (!this.isProtocolSupported()) { return }\n const {identifier, message, reason, reconnect, type} = JSON.parse(event.data)\n switch (type) {\n case message_types.welcome:\n this.monitor.recordConnect()\n return this.subscriptions.reload()\n case message_types.disconnect:\n logger.log(`Disconnecting. Reason: ${reason}`)\n return this.close({allowReconnect: reconnect})\n case message_types.ping:\n return this.monitor.recordPing()\n case message_types.confirmation:\n this.subscriptions.confirmSubscription(identifier)\n return this.subscriptions.notify(identifier, \"connected\")\n case message_types.rejection:\n return this.subscriptions.reject(identifier)\n default:\n return this.subscriptions.notify(identifier, \"received\", message)\n }\n },\n\n open() {\n logger.log(`WebSocket onopen event, using '${this.getProtocol()}' subprotocol`)\n this.disconnected = false\n if (!this.isProtocolSupported()) {\n logger.log(\"Protocol is unsupported. Stopping monitor and disconnecting.\")\n return this.close({allowReconnect: false})\n }\n },\n\n close(event) {\n logger.log(\"WebSocket onclose event\")\n if (this.disconnected) { return }\n this.disconnected = true\n this.monitor.recordDisconnect()\n return this.subscriptions.notifyAll(\"disconnected\", {willAttemptReconnect: this.monitor.isRunning()})\n },\n\n error() {\n logger.log(\"WebSocket onerror event\")\n }\n}\n\nexport default Connection\n", "// A new subscription is created through the ActionCable.Subscriptions instance available on the consumer.\n// It provides a number of callbacks and a method for calling remote procedure calls on the corresponding\n// Channel instance on the server side.\n//\n// An example demonstrates the basic functionality:\n//\n// App.appearance = App.cable.subscriptions.create(\"AppearanceChannel\", {\n// connected() {\n// // Called once the subscription has been successfully completed\n// },\n//\n// disconnected({ willAttemptReconnect: boolean }) {\n// // Called when the client has disconnected with the server.\n// // The object will have an `willAttemptReconnect` property which\n// // says whether the client has the intention of attempting\n// // to reconnect.\n// },\n//\n// appear() {\n// this.perform('appear', {appearing_on: this.appearingOn()})\n// },\n//\n// away() {\n// this.perform('away')\n// },\n//\n// appearingOn() {\n// $('main').data('appearing-on')\n// }\n// })\n//\n// The methods #appear and #away forward their intent to the remote AppearanceChannel instance on the server\n// by calling the `perform` method with the first parameter being the action (which maps to AppearanceChannel#appear/away).\n// The second parameter is a hash that'll get JSON encoded and made available on the server in the data parameter.\n//\n// This is how the server component would look:\n//\n// class AppearanceChannel < ApplicationActionCable::Channel\n// def subscribed\n// current_user.appear\n// end\n//\n// def unsubscribed\n// current_user.disappear\n// end\n//\n// def appear(data)\n// current_user.appear on: data['appearing_on']\n// end\n//\n// def away\n// current_user.away\n// end\n// end\n//\n// The \"AppearanceChannel\" name is automatically mapped between the client-side subscription creation and the server-side Ruby class name.\n// The AppearanceChannel#appear/away public methods are exposed automatically to client-side invocation through the perform method.\n\nconst extend = function(object, properties) {\n if (properties != null) {\n for (let key in properties) {\n const value = properties[key]\n object[key] = value\n }\n }\n return object\n}\n\nexport default class Subscription {\n constructor(consumer, params = {}, mixin) {\n this.consumer = consumer\n this.identifier = JSON.stringify(params)\n extend(this, mixin)\n }\n\n // Perform a channel action with the optional data passed as an attribute\n perform(action, data = {}) {\n data.action = action\n return this.send(data)\n }\n\n send(data) {\n return this.consumer.send({command: \"message\", identifier: this.identifier, data: JSON.stringify(data)})\n }\n\n unsubscribe() {\n return this.consumer.subscriptions.remove(this)\n }\n}\n", "import logger from \"./logger\"\n\n// Responsible for ensuring channel subscribe command is confirmed, retrying until confirmation is received.\n// Internal class, not intended for direct user manipulation.\n\nclass SubscriptionGuarantor {\n constructor(subscriptions) {\n this.subscriptions = subscriptions\n this.pendingSubscriptions = []\n }\n\n guarantee(subscription) {\n if(this.pendingSubscriptions.indexOf(subscription) == -1){ \n logger.log(`SubscriptionGuarantor guaranteeing ${subscription.identifier}`)\n this.pendingSubscriptions.push(subscription) \n }\n else {\n logger.log(`SubscriptionGuarantor already guaranteeing ${subscription.identifier}`)\n }\n this.startGuaranteeing()\n }\n\n forget(subscription) {\n logger.log(`SubscriptionGuarantor forgetting ${subscription.identifier}`)\n this.pendingSubscriptions = (this.pendingSubscriptions.filter((s) => s !== subscription))\n }\n\n startGuaranteeing() {\n this.stopGuaranteeing()\n this.retrySubscribing()\n }\n \n stopGuaranteeing() {\n clearTimeout(this.retryTimeout)\n }\n\n retrySubscribing() {\n this.retryTimeout = setTimeout(() => {\n if (this.subscriptions && typeof(this.subscriptions.subscribe) === \"function\") {\n this.pendingSubscriptions.map((subscription) => {\n logger.log(`SubscriptionGuarantor resubscribing ${subscription.identifier}`)\n this.subscriptions.subscribe(subscription)\n })\n }\n }\n , 500)\n }\n}\n\nexport default SubscriptionGuarantor", "import Subscription from \"./subscription\"\nimport SubscriptionGuarantor from \"./subscription_guarantor\"\nimport logger from \"./logger\"\n\n// Collection class for creating (and internally managing) channel subscriptions.\n// The only method intended to be triggered by the user is ActionCable.Subscriptions#create,\n// and it should be called through the consumer like so:\n//\n// App = {}\n// App.cable = ActionCable.createConsumer(\"ws://example.com/accounts/1\")\n// App.appearance = App.cable.subscriptions.create(\"AppearanceChannel\")\n//\n// For more details on how you'd configure an actual channel subscription, see ActionCable.Subscription.\n\nexport default class Subscriptions {\n constructor(consumer) {\n this.consumer = consumer\n this.guarantor = new SubscriptionGuarantor(this)\n this.subscriptions = []\n }\n\n create(channelName, mixin) {\n const channel = channelName\n const params = typeof channel === \"object\" ? channel : {channel}\n const subscription = new Subscription(this.consumer, params, mixin)\n return this.add(subscription)\n }\n\n // Private\n\n add(subscription) {\n this.subscriptions.push(subscription)\n this.consumer.ensureActiveConnection()\n this.notify(subscription, \"initialized\")\n this.subscribe(subscription)\n return subscription\n }\n\n remove(subscription) {\n this.forget(subscription)\n if (!this.findAll(subscription.identifier).length) {\n this.sendCommand(subscription, \"unsubscribe\")\n }\n return subscription\n }\n\n reject(identifier) {\n return this.findAll(identifier).map((subscription) => {\n this.forget(subscription)\n this.notify(subscription, \"rejected\")\n return subscription\n })\n }\n\n forget(subscription) {\n this.guarantor.forget(subscription)\n this.subscriptions = (this.subscriptions.filter((s) => s !== subscription))\n return subscription\n }\n\n findAll(identifier) {\n return this.subscriptions.filter((s) => s.identifier === identifier)\n }\n\n reload() {\n return this.subscriptions.map((subscription) =>\n this.subscribe(subscription))\n }\n\n notifyAll(callbackName, ...args) {\n return this.subscriptions.map((subscription) =>\n this.notify(subscription, callbackName, ...args))\n }\n\n notify(subscription, callbackName, ...args) {\n let subscriptions\n if (typeof subscription === \"string\") {\n subscriptions = this.findAll(subscription)\n } else {\n subscriptions = [subscription]\n }\n\n return subscriptions.map((subscription) =>\n (typeof subscription[callbackName] === \"function\" ? subscription[callbackName](...args) : undefined))\n }\n\n subscribe(subscription) {\n if (this.sendCommand(subscription, \"subscribe\")) {\n this.guarantor.guarantee(subscription)\n }\n }\n\n confirmSubscription(identifier) {\n logger.log(`Subscription confirmed ${identifier}`)\n this.findAll(identifier).map((subscription) =>\n this.guarantor.forget(subscription))\n }\n\n sendCommand(subscription, command) {\n const {identifier} = subscription\n return this.consumer.send({command, identifier})\n }\n}\n", "import Connection from \"./connection\"\nimport Subscriptions from \"./subscriptions\"\n\n// The ActionCable.Consumer establishes the connection to a server-side Ruby Connection object. Once established,\n// the ActionCable.ConnectionMonitor will ensure that its properly maintained through heartbeats and checking for stale updates.\n// The Consumer instance is also the gateway to establishing subscriptions to desired channels through the #createSubscription\n// method.\n//\n// The following example shows how this can be set up:\n//\n// App = {}\n// App.cable = ActionCable.createConsumer(\"ws://example.com/accounts/1\")\n// App.appearance = App.cable.subscriptions.create(\"AppearanceChannel\")\n//\n// For more details on how you'd configure an actual channel subscription, see ActionCable.Subscription.\n//\n// When a consumer is created, it automatically connects with the server.\n//\n// To disconnect from the server, call\n//\n// App.cable.disconnect()\n//\n// and to restart the connection:\n//\n// App.cable.connect()\n//\n// Any channel subscriptions which existed prior to disconnecting will\n// automatically resubscribe.\n\nexport default class Consumer {\n constructor(url) {\n this._url = url\n this.subscriptions = new Subscriptions(this)\n this.connection = new Connection(this)\n }\n\n get url() {\n return createWebSocketURL(this._url)\n }\n\n send(data) {\n return this.connection.send(data)\n }\n\n connect() {\n return this.connection.open()\n }\n\n disconnect() {\n return this.connection.close({allowReconnect: false})\n }\n\n ensureActiveConnection() {\n if (!this.connection.isActive()) {\n return this.connection.open()\n }\n }\n}\n\nexport function createWebSocketURL(url) {\n if (typeof url === \"function\") {\n url = url()\n }\n\n if (url && !/^wss?:/i.test(url)) {\n const a = document.createElement(\"a\")\n a.href = url\n // Fix populating Location properties in IE. Otherwise, protocol will be blank.\n a.href = a.href\n a.protocol = a.protocol.replace(\"http\", \"ws\")\n return a.href\n } else {\n return url\n }\n}\n", "import Connection from \"./connection\"\nimport ConnectionMonitor from \"./connection_monitor\"\nimport Consumer, { createWebSocketURL } from \"./consumer\"\nimport INTERNAL from \"./internal\"\nimport Subscription from \"./subscription\"\nimport Subscriptions from \"./subscriptions\"\nimport SubscriptionGuarantor from \"./subscription_guarantor\"\nimport adapters from \"./adapters\"\nimport logger from \"./logger\"\n\nexport {\n Connection,\n ConnectionMonitor,\n Consumer,\n INTERNAL,\n Subscription,\n Subscriptions,\n SubscriptionGuarantor,\n adapters,\n createWebSocketURL,\n logger,\n}\n\nexport function createConsumer(url = getConfig(\"url\") || INTERNAL.default_mount_path) {\n return new Consumer(url)\n}\n\nexport function getConfig(name) {\n const element = document.head.querySelector(`meta[name='action-cable-${name}']`)\n if (element) {\n return element.getAttribute(\"content\")\n }\n}\n", "(function(global, factory) {\n typeof exports === \"object\" && typeof module !== \"undefined\" ? factory(exports) : typeof define === \"function\" && define.amd ? define([ \"exports\" ], factory) : factory(global.ActiveStorage = {});\n})(this, function(exports) {\n \"use strict\";\n function createCommonjsModule(fn, module) {\n return module = {\n exports: {}\n }, fn(module, module.exports), module.exports;\n }\n var sparkMd5 = createCommonjsModule(function(module, exports) {\n (function(factory) {\n {\n module.exports = factory();\n }\n })(function(undefined) {\n var hex_chr = [ \"0\", \"1\", \"2\", \"3\", \"4\", \"5\", \"6\", \"7\", \"8\", \"9\", \"a\", \"b\", \"c\", \"d\", \"e\", \"f\" ];\n function md5cycle(x, k) {\n var a = x[0], b = x[1], c = x[2], d = x[3];\n a += (b & c | ~b & d) + k[0] - 680876936 | 0;\n a = (a << 7 | a >>> 25) + b | 0;\n d += (a & b | ~a & c) + k[1] - 389564586 | 0;\n d = (d << 12 | d >>> 20) + a | 0;\n c += (d & a | ~d & b) + k[2] + 606105819 | 0;\n c = (c << 17 | c >>> 15) + d | 0;\n b += (c & d | ~c & a) + k[3] - 1044525330 | 0;\n b = (b << 22 | b >>> 10) + c | 0;\n a += (b & c | ~b & d) + k[4] - 176418897 | 0;\n a = (a << 7 | a >>> 25) + b | 0;\n d += (a & b | ~a & c) + k[5] + 1200080426 | 0;\n d = (d << 12 | d >>> 20) + a | 0;\n c += (d & a | ~d & b) + k[6] - 1473231341 | 0;\n c = (c << 17 | c >>> 15) + d | 0;\n b += (c & d | ~c & a) + k[7] - 45705983 | 0;\n b = (b << 22 | b >>> 10) + c | 0;\n a += (b & c | ~b & d) + k[8] + 1770035416 | 0;\n a = (a << 7 | a >>> 25) + b | 0;\n d += (a & b | ~a & c) + k[9] - 1958414417 | 0;\n d = (d << 12 | d >>> 20) + a | 0;\n c += (d & a | ~d & b) + k[10] - 42063 | 0;\n c = (c << 17 | c >>> 15) + d | 0;\n b += (c & d | ~c & a) + k[11] - 1990404162 | 0;\n b = (b << 22 | b >>> 10) + c | 0;\n a += (b & c | ~b & d) + k[12] + 1804603682 | 0;\n a = (a << 7 | a >>> 25) + b | 0;\n d += (a & b | ~a & c) + k[13] - 40341101 | 0;\n d = (d << 12 | d >>> 20) + a | 0;\n c += (d & a | ~d & b) + k[14] - 1502002290 | 0;\n c = (c << 17 | c >>> 15) + d | 0;\n b += (c & d | ~c & a) + k[15] + 1236535329 | 0;\n b = (b << 22 | b >>> 10) + c | 0;\n a += (b & d | c & ~d) + k[1] - 165796510 | 0;\n a = (a << 5 | a >>> 27) + b | 0;\n d += (a & c | b & ~c) + k[6] - 1069501632 | 0;\n d = (d << 9 | d >>> 23) + a | 0;\n c += (d & b | a & ~b) + k[11] + 643717713 | 0;\n c = (c << 14 | c >>> 18) + d | 0;\n b += (c & a | d & ~a) + k[0] - 373897302 | 0;\n b = (b << 20 | b >>> 12) + c | 0;\n a += (b & d | c & ~d) + k[5] - 701558691 | 0;\n a = (a << 5 | a >>> 27) + b | 0;\n d += (a & c | b & ~c) + k[10] + 38016083 | 0;\n d = (d << 9 | d >>> 23) + a | 0;\n c += (d & b | a & ~b) + k[15] - 660478335 | 0;\n c = (c << 14 | c >>> 18) + d | 0;\n b += (c & a | d & ~a) + k[4] - 405537848 | 0;\n b = (b << 20 | b >>> 12) + c | 0;\n a += (b & d | c & ~d) + k[9] + 568446438 | 0;\n a = (a << 5 | a >>> 27) + b | 0;\n d += (a & c | b & ~c) + k[14] - 1019803690 | 0;\n d = (d << 9 | d >>> 23) + a | 0;\n c += (d & b | a & ~b) + k[3] - 187363961 | 0;\n c = (c << 14 | c >>> 18) + d | 0;\n b += (c & a | d & ~a) + k[8] + 1163531501 | 0;\n b = (b << 20 | b >>> 12) + c | 0;\n a += (b & d | c & ~d) + k[13] - 1444681467 | 0;\n a = (a << 5 | a >>> 27) + b | 0;\n d += (a & c | b & ~c) + k[2] - 51403784 | 0;\n d = (d << 9 | d >>> 23) + a | 0;\n c += (d & b | a & ~b) + k[7] + 1735328473 | 0;\n c = (c << 14 | c >>> 18) + d | 0;\n b += (c & a | d & ~a) + k[12] - 1926607734 | 0;\n b = (b << 20 | b >>> 12) + c | 0;\n a += (b ^ c ^ d) + k[5] - 378558 | 0;\n a = (a << 4 | a >>> 28) + b | 0;\n d += (a ^ b ^ c) + k[8] - 2022574463 | 0;\n d = (d << 11 | d >>> 21) + a | 0;\n c += (d ^ a ^ b) + k[11] + 1839030562 | 0;\n c = (c << 16 | c >>> 16) + d | 0;\n b += (c ^ d ^ a) + k[14] - 35309556 | 0;\n b = (b << 23 | b >>> 9) + c | 0;\n a += (b ^ c ^ d) + k[1] - 1530992060 | 0;\n a = (a << 4 | a >>> 28) + b | 0;\n d += (a ^ b ^ c) + k[4] + 1272893353 | 0;\n d = (d << 11 | d >>> 21) + a | 0;\n c += (d ^ a ^ b) + k[7] - 155497632 | 0;\n c = (c << 16 | c >>> 16) + d | 0;\n b += (c ^ d ^ a) + k[10] - 1094730640 | 0;\n b = (b << 23 | b >>> 9) + c | 0;\n a += (b ^ c ^ d) + k[13] + 681279174 | 0;\n a = (a << 4 | a >>> 28) + b | 0;\n d += (a ^ b ^ c) + k[0] - 358537222 | 0;\n d = (d << 11 | d >>> 21) + a | 0;\n c += (d ^ a ^ b) + k[3] - 722521979 | 0;\n c = (c << 16 | c >>> 16) + d | 0;\n b += (c ^ d ^ a) + k[6] + 76029189 | 0;\n b = (b << 23 | b >>> 9) + c | 0;\n a += (b ^ c ^ d) + k[9] - 640364487 | 0;\n a = (a << 4 | a >>> 28) + b | 0;\n d += (a ^ b ^ c) + k[12] - 421815835 | 0;\n d = (d << 11 | d >>> 21) + a | 0;\n c += (d ^ a ^ b) + k[15] + 530742520 | 0;\n c = (c << 16 | c >>> 16) + d | 0;\n b += (c ^ d ^ a) + k[2] - 995338651 | 0;\n b = (b << 23 | b >>> 9) + c | 0;\n a += (c ^ (b | ~d)) + k[0] - 198630844 | 0;\n a = (a << 6 | a >>> 26) + b | 0;\n d += (b ^ (a | ~c)) + k[7] + 1126891415 | 0;\n d = (d << 10 | d >>> 22) + a | 0;\n c += (a ^ (d | ~b)) + k[14] - 1416354905 | 0;\n c = (c << 15 | c >>> 17) + d | 0;\n b += (d ^ (c | ~a)) + k[5] - 57434055 | 0;\n b = (b << 21 | b >>> 11) + c | 0;\n a += (c ^ (b | ~d)) + k[12] + 1700485571 | 0;\n a = (a << 6 | a >>> 26) + b | 0;\n d += (b ^ (a | ~c)) + k[3] - 1894986606 | 0;\n d = (d << 10 | d >>> 22) + a | 0;\n c += (a ^ (d | ~b)) + k[10] - 1051523 | 0;\n c = (c << 15 | c >>> 17) + d | 0;\n b += (d ^ (c | ~a)) + k[1] - 2054922799 | 0;\n b = (b << 21 | b >>> 11) + c | 0;\n a += (c ^ (b | ~d)) + k[8] + 1873313359 | 0;\n a = (a << 6 | a >>> 26) + b | 0;\n d += (b ^ (a | ~c)) + k[15] - 30611744 | 0;\n d = (d << 10 | d >>> 22) + a | 0;\n c += (a ^ (d | ~b)) + k[6] - 1560198380 | 0;\n c = (c << 15 | c >>> 17) + d | 0;\n b += (d ^ (c | ~a)) + k[13] + 1309151649 | 0;\n b = (b << 21 | b >>> 11) + c | 0;\n a += (c ^ (b | ~d)) + k[4] - 145523070 | 0;\n a = (a << 6 | a >>> 26) + b | 0;\n d += (b ^ (a | ~c)) + k[11] - 1120210379 | 0;\n d = (d << 10 | d >>> 22) + a | 0;\n c += (a ^ (d | ~b)) + k[2] + 718787259 | 0;\n c = (c << 15 | c >>> 17) + d | 0;\n b += (d ^ (c | ~a)) + k[9] - 343485551 | 0;\n b = (b << 21 | b >>> 11) + c | 0;\n x[0] = a + x[0] | 0;\n x[1] = b + x[1] | 0;\n x[2] = c + x[2] | 0;\n x[3] = d + x[3] | 0;\n }\n function md5blk(s) {\n var md5blks = [], i;\n for (i = 0; i < 64; i += 4) {\n md5blks[i >> 2] = s.charCodeAt(i) + (s.charCodeAt(i + 1) << 8) + (s.charCodeAt(i + 2) << 16) + (s.charCodeAt(i + 3) << 24);\n }\n return md5blks;\n }\n function md5blk_array(a) {\n var md5blks = [], i;\n for (i = 0; i < 64; i += 4) {\n md5blks[i >> 2] = a[i] + (a[i + 1] << 8) + (a[i + 2] << 16) + (a[i + 3] << 24);\n }\n return md5blks;\n }\n function md51(s) {\n var n = s.length, state = [ 1732584193, -271733879, -1732584194, 271733878 ], i, length, tail, tmp, lo, hi;\n for (i = 64; i <= n; i += 64) {\n md5cycle(state, md5blk(s.substring(i - 64, i)));\n }\n s = s.substring(i - 64);\n length = s.length;\n tail = [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ];\n for (i = 0; i < length; i += 1) {\n tail[i >> 2] |= s.charCodeAt(i) << (i % 4 << 3);\n }\n tail[i >> 2] |= 128 << (i % 4 << 3);\n if (i > 55) {\n md5cycle(state, tail);\n for (i = 0; i < 16; i += 1) {\n tail[i] = 0;\n }\n }\n tmp = n * 8;\n tmp = tmp.toString(16).match(/(.*?)(.{0,8})$/);\n lo = parseInt(tmp[2], 16);\n hi = parseInt(tmp[1], 16) || 0;\n tail[14] = lo;\n tail[15] = hi;\n md5cycle(state, tail);\n return state;\n }\n function md51_array(a) {\n var n = a.length, state = [ 1732584193, -271733879, -1732584194, 271733878 ], i, length, tail, tmp, lo, hi;\n for (i = 64; i <= n; i += 64) {\n md5cycle(state, md5blk_array(a.subarray(i - 64, i)));\n }\n a = i - 64 < n ? a.subarray(i - 64) : new Uint8Array(0);\n length = a.length;\n tail = [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ];\n for (i = 0; i < length; i += 1) {\n tail[i >> 2] |= a[i] << (i % 4 << 3);\n }\n tail[i >> 2] |= 128 << (i % 4 << 3);\n if (i > 55) {\n md5cycle(state, tail);\n for (i = 0; i < 16; i += 1) {\n tail[i] = 0;\n }\n }\n tmp = n * 8;\n tmp = tmp.toString(16).match(/(.*?)(.{0,8})$/);\n lo = parseInt(tmp[2], 16);\n hi = parseInt(tmp[1], 16) || 0;\n tail[14] = lo;\n tail[15] = hi;\n md5cycle(state, tail);\n return state;\n }\n function rhex(n) {\n var s = \"\", j;\n for (j = 0; j < 4; j += 1) {\n s += hex_chr[n >> j * 8 + 4 & 15] + hex_chr[n >> j * 8 & 15];\n }\n return s;\n }\n function hex(x) {\n var i;\n for (i = 0; i < x.length; i += 1) {\n x[i] = rhex(x[i]);\n }\n return x.join(\"\");\n }\n if (hex(md51(\"hello\")) !== \"5d41402abc4b2a76b9719d911017c592\") ;\n if (typeof ArrayBuffer !== \"undefined\" && !ArrayBuffer.prototype.slice) {\n (function() {\n function clamp(val, length) {\n val = val | 0 || 0;\n if (val < 0) {\n return Math.max(val + length, 0);\n }\n return Math.min(val, length);\n }\n ArrayBuffer.prototype.slice = function(from, to) {\n var length = this.byteLength, begin = clamp(from, length), end = length, num, target, targetArray, sourceArray;\n if (to !== undefined) {\n end = clamp(to, length);\n }\n if (begin > end) {\n return new ArrayBuffer(0);\n }\n num = end - begin;\n target = new ArrayBuffer(num);\n targetArray = new Uint8Array(target);\n sourceArray = new Uint8Array(this, begin, num);\n targetArray.set(sourceArray);\n return target;\n };\n })();\n }\n function toUtf8(str) {\n if (/[\\u0080-\\uFFFF]/.test(str)) {\n str = unescape(encodeURIComponent(str));\n }\n return str;\n }\n function utf8Str2ArrayBuffer(str, returnUInt8Array) {\n var length = str.length, buff = new ArrayBuffer(length), arr = new Uint8Array(buff), i;\n for (i = 0; i < length; i += 1) {\n arr[i] = str.charCodeAt(i);\n }\n return returnUInt8Array ? arr : buff;\n }\n function arrayBuffer2Utf8Str(buff) {\n return String.fromCharCode.apply(null, new Uint8Array(buff));\n }\n function concatenateArrayBuffers(first, second, returnUInt8Array) {\n var result = new Uint8Array(first.byteLength + second.byteLength);\n result.set(new Uint8Array(first));\n result.set(new Uint8Array(second), first.byteLength);\n return returnUInt8Array ? result : result.buffer;\n }\n function hexToBinaryString(hex) {\n var bytes = [], length = hex.length, x;\n for (x = 0; x < length - 1; x += 2) {\n bytes.push(parseInt(hex.substr(x, 2), 16));\n }\n return String.fromCharCode.apply(String, bytes);\n }\n function SparkMD5() {\n this.reset();\n }\n SparkMD5.prototype.append = function(str) {\n this.appendBinary(toUtf8(str));\n return this;\n };\n SparkMD5.prototype.appendBinary = function(contents) {\n this._buff += contents;\n this._length += contents.length;\n var length = this._buff.length, i;\n for (i = 64; i <= length; i += 64) {\n md5cycle(this._hash, md5blk(this._buff.substring(i - 64, i)));\n }\n this._buff = this._buff.substring(i - 64);\n return this;\n };\n SparkMD5.prototype.end = function(raw) {\n var buff = this._buff, length = buff.length, i, tail = [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ], ret;\n for (i = 0; i < length; i += 1) {\n tail[i >> 2] |= buff.charCodeAt(i) << (i % 4 << 3);\n }\n this._finish(tail, length);\n ret = hex(this._hash);\n if (raw) {\n ret = hexToBinaryString(ret);\n }\n this.reset();\n return ret;\n };\n SparkMD5.prototype.reset = function() {\n this._buff = \"\";\n this._length = 0;\n this._hash = [ 1732584193, -271733879, -1732584194, 271733878 ];\n return this;\n };\n SparkMD5.prototype.getState = function() {\n return {\n buff: this._buff,\n length: this._length,\n hash: this._hash\n };\n };\n SparkMD5.prototype.setState = function(state) {\n this._buff = state.buff;\n this._length = state.length;\n this._hash = state.hash;\n return this;\n };\n SparkMD5.prototype.destroy = function() {\n delete this._hash;\n delete this._buff;\n delete this._length;\n };\n SparkMD5.prototype._finish = function(tail, length) {\n var i = length, tmp, lo, hi;\n tail[i >> 2] |= 128 << (i % 4 << 3);\n if (i > 55) {\n md5cycle(this._hash, tail);\n for (i = 0; i < 16; i += 1) {\n tail[i] = 0;\n }\n }\n tmp = this._length * 8;\n tmp = tmp.toString(16).match(/(.*?)(.{0,8})$/);\n lo = parseInt(tmp[2], 16);\n hi = parseInt(tmp[1], 16) || 0;\n tail[14] = lo;\n tail[15] = hi;\n md5cycle(this._hash, tail);\n };\n SparkMD5.hash = function(str, raw) {\n return SparkMD5.hashBinary(toUtf8(str), raw);\n };\n SparkMD5.hashBinary = function(content, raw) {\n var hash = md51(content), ret = hex(hash);\n return raw ? hexToBinaryString(ret) : ret;\n };\n SparkMD5.ArrayBuffer = function() {\n this.reset();\n };\n SparkMD5.ArrayBuffer.prototype.append = function(arr) {\n var buff = concatenateArrayBuffers(this._buff.buffer, arr, true), length = buff.length, i;\n this._length += arr.byteLength;\n for (i = 64; i <= length; i += 64) {\n md5cycle(this._hash, md5blk_array(buff.subarray(i - 64, i)));\n }\n this._buff = i - 64 < length ? new Uint8Array(buff.buffer.slice(i - 64)) : new Uint8Array(0);\n return this;\n };\n SparkMD5.ArrayBuffer.prototype.end = function(raw) {\n var buff = this._buff, length = buff.length, tail = [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ], i, ret;\n for (i = 0; i < length; i += 1) {\n tail[i >> 2] |= buff[i] << (i % 4 << 3);\n }\n this._finish(tail, length);\n ret = hex(this._hash);\n if (raw) {\n ret = hexToBinaryString(ret);\n }\n this.reset();\n return ret;\n };\n SparkMD5.ArrayBuffer.prototype.reset = function() {\n this._buff = new Uint8Array(0);\n this._length = 0;\n this._hash = [ 1732584193, -271733879, -1732584194, 271733878 ];\n return this;\n };\n SparkMD5.ArrayBuffer.prototype.getState = function() {\n var state = SparkMD5.prototype.getState.call(this);\n state.buff = arrayBuffer2Utf8Str(state.buff);\n return state;\n };\n SparkMD5.ArrayBuffer.prototype.setState = function(state) {\n state.buff = utf8Str2ArrayBuffer(state.buff, true);\n return SparkMD5.prototype.setState.call(this, state);\n };\n SparkMD5.ArrayBuffer.prototype.destroy = SparkMD5.prototype.destroy;\n SparkMD5.ArrayBuffer.prototype._finish = SparkMD5.prototype._finish;\n SparkMD5.ArrayBuffer.hash = function(arr, raw) {\n var hash = md51_array(new Uint8Array(arr)), ret = hex(hash);\n return raw ? hexToBinaryString(ret) : ret;\n };\n return SparkMD5;\n });\n });\n var classCallCheck = function(instance, Constructor) {\n if (!(instance instanceof Constructor)) {\n throw new TypeError(\"Cannot call a class as a function\");\n }\n };\n var createClass = function() {\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 return function(Constructor, protoProps, staticProps) {\n if (protoProps) defineProperties(Constructor.prototype, protoProps);\n if (staticProps) defineProperties(Constructor, staticProps);\n return Constructor;\n };\n }();\n var fileSlice = File.prototype.slice || File.prototype.mozSlice || File.prototype.webkitSlice;\n var FileChecksum = function() {\n createClass(FileChecksum, null, [ {\n key: \"create\",\n value: function create(file, callback) {\n var instance = new FileChecksum(file);\n instance.create(callback);\n }\n } ]);\n function FileChecksum(file) {\n classCallCheck(this, FileChecksum);\n this.file = file;\n this.chunkSize = 2097152;\n this.chunkCount = Math.ceil(this.file.size / this.chunkSize);\n this.chunkIndex = 0;\n }\n createClass(FileChecksum, [ {\n key: \"create\",\n value: function create(callback) {\n var _this = this;\n this.callback = callback;\n this.md5Buffer = new sparkMd5.ArrayBuffer();\n this.fileReader = new FileReader();\n this.fileReader.addEventListener(\"load\", function(event) {\n return _this.fileReaderDidLoad(event);\n });\n this.fileReader.addEventListener(\"error\", function(event) {\n return _this.fileReaderDidError(event);\n });\n this.readNextChunk();\n }\n }, {\n key: \"fileReaderDidLoad\",\n value: function fileReaderDidLoad(event) {\n this.md5Buffer.append(event.target.result);\n if (!this.readNextChunk()) {\n var binaryDigest = this.md5Buffer.end(true);\n var base64digest = btoa(binaryDigest);\n this.callback(null, base64digest);\n }\n }\n }, {\n key: \"fileReaderDidError\",\n value: function fileReaderDidError(event) {\n this.callback(\"Error reading \" + this.file.name);\n }\n }, {\n key: \"readNextChunk\",\n value: function readNextChunk() {\n if (this.chunkIndex < this.chunkCount || this.chunkIndex == 0 && this.chunkCount == 0) {\n var start = this.chunkIndex * this.chunkSize;\n var end = Math.min(start + this.chunkSize, this.file.size);\n var bytes = fileSlice.call(this.file, start, end);\n this.fileReader.readAsArrayBuffer(bytes);\n this.chunkIndex++;\n return true;\n } else {\n return false;\n }\n }\n } ]);\n return FileChecksum;\n }();\n function getMetaValue(name) {\n var element = findElement(document.head, 'meta[name=\"' + name + '\"]');\n if (element) {\n return element.getAttribute(\"content\");\n }\n }\n function findElements(root, selector) {\n if (typeof root == \"string\") {\n selector = root;\n root = document;\n }\n var elements = root.querySelectorAll(selector);\n return toArray$1(elements);\n }\n function findElement(root, selector) {\n if (typeof root == \"string\") {\n selector = root;\n root = document;\n }\n return root.querySelector(selector);\n }\n function dispatchEvent(element, type) {\n var eventInit = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};\n var disabled = element.disabled;\n var bubbles = eventInit.bubbles, cancelable = eventInit.cancelable, detail = eventInit.detail;\n var event = document.createEvent(\"Event\");\n event.initEvent(type, bubbles || true, cancelable || true);\n event.detail = detail || {};\n try {\n element.disabled = false;\n element.dispatchEvent(event);\n } finally {\n element.disabled = disabled;\n }\n return event;\n }\n function toArray$1(value) {\n if (Array.isArray(value)) {\n return value;\n } else if (Array.from) {\n return Array.from(value);\n } else {\n return [].slice.call(value);\n }\n }\n var BlobRecord = function() {\n function BlobRecord(file, checksum, url) {\n var _this = this;\n classCallCheck(this, BlobRecord);\n this.file = file;\n this.attributes = {\n filename: file.name,\n content_type: file.type || \"application/octet-stream\",\n byte_size: file.size,\n checksum: checksum\n };\n this.xhr = new XMLHttpRequest();\n this.xhr.open(\"POST\", url, true);\n this.xhr.responseType = \"json\";\n this.xhr.setRequestHeader(\"Content-Type\", \"application/json\");\n this.xhr.setRequestHeader(\"Accept\", \"application/json\");\n this.xhr.setRequestHeader(\"X-Requested-With\", \"XMLHttpRequest\");\n var csrfToken = getMetaValue(\"csrf-token\");\n if (csrfToken != undefined) {\n this.xhr.setRequestHeader(\"X-CSRF-Token\", csrfToken);\n }\n this.xhr.addEventListener(\"load\", function(event) {\n return _this.requestDidLoad(event);\n });\n this.xhr.addEventListener(\"error\", function(event) {\n return _this.requestDidError(event);\n });\n }\n createClass(BlobRecord, [ {\n key: \"create\",\n value: function create(callback) {\n this.callback = callback;\n this.xhr.send(JSON.stringify({\n blob: this.attributes\n }));\n }\n }, {\n key: \"requestDidLoad\",\n value: function requestDidLoad(event) {\n if (this.status >= 200 && this.status < 300) {\n var response = this.response;\n var direct_upload = response.direct_upload;\n delete response.direct_upload;\n this.attributes = response;\n this.directUploadData = direct_upload;\n this.callback(null, this.toJSON());\n } else {\n this.requestDidError(event);\n }\n }\n }, {\n key: \"requestDidError\",\n value: function requestDidError(event) {\n this.callback('Error creating Blob for \"' + this.file.name + '\". Status: ' + this.status);\n }\n }, {\n key: \"toJSON\",\n value: function toJSON() {\n var result = {};\n for (var key in this.attributes) {\n result[key] = this.attributes[key];\n }\n return result;\n }\n }, {\n key: \"status\",\n get: function get$$1() {\n return this.xhr.status;\n }\n }, {\n key: \"response\",\n get: function get$$1() {\n var _xhr = this.xhr, responseType = _xhr.responseType, response = _xhr.response;\n if (responseType == \"json\") {\n return response;\n } else {\n return JSON.parse(response);\n }\n }\n } ]);\n return BlobRecord;\n }();\n var BlobUpload = function() {\n function BlobUpload(blob) {\n var _this = this;\n classCallCheck(this, BlobUpload);\n this.blob = blob;\n this.file = blob.file;\n var _blob$directUploadDat = blob.directUploadData, url = _blob$directUploadDat.url, headers = _blob$directUploadDat.headers;\n this.xhr = new XMLHttpRequest();\n this.xhr.open(\"PUT\", url, true);\n this.xhr.responseType = \"text\";\n for (var key in headers) {\n this.xhr.setRequestHeader(key, headers[key]);\n }\n this.xhr.addEventListener(\"load\", function(event) {\n return _this.requestDidLoad(event);\n });\n this.xhr.addEventListener(\"error\", function(event) {\n return _this.requestDidError(event);\n });\n }\n createClass(BlobUpload, [ {\n key: \"create\",\n value: function create(callback) {\n this.callback = callback;\n this.xhr.send(this.file.slice());\n }\n }, {\n key: \"requestDidLoad\",\n value: function requestDidLoad(event) {\n var _xhr = this.xhr, status = _xhr.status, response = _xhr.response;\n if (status >= 200 && status < 300) {\n this.callback(null, response);\n } else {\n this.requestDidError(event);\n }\n }\n }, {\n key: \"requestDidError\",\n value: function requestDidError(event) {\n this.callback('Error storing \"' + this.file.name + '\". Status: ' + this.xhr.status);\n }\n } ]);\n return BlobUpload;\n }();\n var id = 0;\n var DirectUpload = function() {\n function DirectUpload(file, url, delegate) {\n classCallCheck(this, DirectUpload);\n this.id = ++id;\n this.file = file;\n this.url = url;\n this.delegate = delegate;\n }\n createClass(DirectUpload, [ {\n key: \"create\",\n value: function create(callback) {\n var _this = this;\n FileChecksum.create(this.file, function(error, checksum) {\n if (error) {\n callback(error);\n return;\n }\n var blob = new BlobRecord(_this.file, checksum, _this.url);\n notify(_this.delegate, \"directUploadWillCreateBlobWithXHR\", blob.xhr);\n blob.create(function(error) {\n if (error) {\n callback(error);\n } else {\n var upload = new BlobUpload(blob);\n notify(_this.delegate, \"directUploadWillStoreFileWithXHR\", upload.xhr);\n upload.create(function(error) {\n if (error) {\n callback(error);\n } else {\n callback(null, blob.toJSON());\n }\n });\n }\n });\n });\n }\n } ]);\n return DirectUpload;\n }();\n function notify(object, methodName) {\n if (object && typeof object[methodName] == \"function\") {\n for (var _len = arguments.length, messages = Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++) {\n messages[_key - 2] = arguments[_key];\n }\n return object[methodName].apply(object, messages);\n }\n }\n var DirectUploadController = function() {\n function DirectUploadController(input, file) {\n classCallCheck(this, DirectUploadController);\n this.input = input;\n this.file = file;\n this.directUpload = new DirectUpload(this.file, this.url, this);\n this.dispatch(\"initialize\");\n }\n createClass(DirectUploadController, [ {\n key: \"start\",\n value: function start(callback) {\n var _this = this;\n var hiddenInput = document.createElement(\"input\");\n hiddenInput.type = \"hidden\";\n hiddenInput.name = this.input.name;\n this.input.insertAdjacentElement(\"beforebegin\", hiddenInput);\n this.dispatch(\"start\");\n this.directUpload.create(function(error, attributes) {\n if (error) {\n hiddenInput.parentNode.removeChild(hiddenInput);\n _this.dispatchError(error);\n } else {\n hiddenInput.value = attributes.signed_id;\n }\n _this.dispatch(\"end\");\n callback(error);\n });\n }\n }, {\n key: \"uploadRequestDidProgress\",\n value: function uploadRequestDidProgress(event) {\n var progress = event.loaded / event.total * 100;\n if (progress) {\n this.dispatch(\"progress\", {\n progress: progress\n });\n }\n }\n }, {\n key: \"dispatch\",\n value: function dispatch(name) {\n var detail = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};\n detail.file = this.file;\n detail.id = this.directUpload.id;\n return dispatchEvent(this.input, \"direct-upload:\" + name, {\n detail: detail\n });\n }\n }, {\n key: \"dispatchError\",\n value: function dispatchError(error) {\n var event = this.dispatch(\"error\", {\n error: error\n });\n if (!event.defaultPrevented) {\n alert(error);\n }\n }\n }, {\n key: \"directUploadWillCreateBlobWithXHR\",\n value: function directUploadWillCreateBlobWithXHR(xhr) {\n this.dispatch(\"before-blob-request\", {\n xhr: xhr\n });\n }\n }, {\n key: \"directUploadWillStoreFileWithXHR\",\n value: function directUploadWillStoreFileWithXHR(xhr) {\n var _this2 = this;\n this.dispatch(\"before-storage-request\", {\n xhr: xhr\n });\n xhr.upload.addEventListener(\"progress\", function(event) {\n return _this2.uploadRequestDidProgress(event);\n });\n }\n }, {\n key: \"url\",\n get: function get$$1() {\n return this.input.getAttribute(\"data-direct-upload-url\");\n }\n } ]);\n return DirectUploadController;\n }();\n var inputSelector = \"input[type=file][data-direct-upload-url]:not([disabled])\";\n var DirectUploadsController = function() {\n function DirectUploadsController(form) {\n classCallCheck(this, DirectUploadsController);\n this.form = form;\n this.inputs = findElements(form, inputSelector).filter(function(input) {\n return input.files.length;\n });\n }\n createClass(DirectUploadsController, [ {\n key: \"start\",\n value: function start(callback) {\n var _this = this;\n var controllers = this.createDirectUploadControllers();\n var startNextController = function startNextController() {\n var controller = controllers.shift();\n if (controller) {\n controller.start(function(error) {\n if (error) {\n callback(error);\n _this.dispatch(\"end\");\n } else {\n startNextController();\n }\n });\n } else {\n callback();\n _this.dispatch(\"end\");\n }\n };\n this.dispatch(\"start\");\n startNextController();\n }\n }, {\n key: \"createDirectUploadControllers\",\n value: function createDirectUploadControllers() {\n var controllers = [];\n this.inputs.forEach(function(input) {\n toArray$1(input.files).forEach(function(file) {\n var controller = new DirectUploadController(input, file);\n controllers.push(controller);\n });\n });\n return controllers;\n }\n }, {\n key: \"dispatch\",\n value: function dispatch(name) {\n var detail = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};\n return dispatchEvent(this.form, \"direct-uploads:\" + name, {\n detail: detail\n });\n }\n } ]);\n return DirectUploadsController;\n }();\n var processingAttribute = \"data-direct-uploads-processing\";\n var submitButtonsByForm = new WeakMap();\n var started = false;\n function start() {\n if (!started) {\n started = true;\n document.addEventListener(\"click\", didClick, true);\n document.addEventListener(\"submit\", didSubmitForm);\n document.addEventListener(\"ajax:before\", didSubmitRemoteElement);\n }\n }\n function didClick(event) {\n var target = event.target;\n if ((target.tagName == \"INPUT\" || target.tagName == \"BUTTON\") && target.type == \"submit\" && target.form) {\n submitButtonsByForm.set(target.form, target);\n }\n }\n function didSubmitForm(event) {\n handleFormSubmissionEvent(event);\n }\n function didSubmitRemoteElement(event) {\n if (event.target.tagName == \"FORM\") {\n handleFormSubmissionEvent(event);\n }\n }\n function handleFormSubmissionEvent(event) {\n var form = event.target;\n if (form.hasAttribute(processingAttribute)) {\n event.preventDefault();\n return;\n }\n var controller = new DirectUploadsController(form);\n var inputs = controller.inputs;\n if (inputs.length) {\n event.preventDefault();\n form.setAttribute(processingAttribute, \"\");\n inputs.forEach(disable);\n controller.start(function(error) {\n form.removeAttribute(processingAttribute);\n if (error) {\n inputs.forEach(enable);\n } else {\n submitForm(form);\n }\n });\n }\n }\n function submitForm(form) {\n var button = submitButtonsByForm.get(form) || findElement(form, \"input[type=submit], button[type=submit]\");\n if (button) {\n var _button = button, disabled = _button.disabled;\n button.disabled = false;\n button.focus();\n button.click();\n button.disabled = disabled;\n } else {\n button = document.createElement(\"input\");\n button.type = \"submit\";\n button.style.display = \"none\";\n form.appendChild(button);\n button.click();\n form.removeChild(button);\n }\n submitButtonsByForm.delete(form);\n }\n function disable(input) {\n input.disabled = true;\n }\n function enable(input) {\n input.disabled = false;\n }\n function autostart() {\n if (window.ActiveStorage) {\n start();\n }\n }\n setTimeout(autostart, 1);\n exports.start = start;\n exports.DirectUpload = DirectUpload;\n Object.defineProperty(exports, \"__esModule\", {\n value: true\n });\n});\n", "// Copyright (c) 2024, Mason Freed\n// All rights reserved.\n//\n// This source code is licensed under the BSD-style license found in the\n// LICENSE file in the root directory of this source tree.\n!function(){if(window.mutationEventsPolyfillInstalled)return;window.mutationEventsPolyfillInstalled=!0;let e=\"MutationEvent\"in window;if(e&&!window.mutationEventsUsePolyfillAlways)return;let t=new Set([\"DOMCharacterDataModified\",\"DOMNodeInserted\",\"DOMNodeInsertedIntoDocument\",\"DOMNodeRemoved\",\"DOMNodeRemovedFromDocument\",\"DOMSubtreeModified\",]),n=\"Polyfilled\",o={attrChange:0,bubbles:!0,cancelable:!1,newValue:\"\",prevValue:\"\",relatedNode:null};function a(e,t,a,r){let l=Object.assign({},o);a&&(l=Object.assign(l,a));let i=new Event(e+n,l);i.attrChange=l.attrChange,i.newValue=l.newValue,i.prevValue=l.prevValue,i.relatedNode=l.relatedNode,r&&Object.defineProperty(i,\"target\",{writable:!1,value:r}),t.dispatchEvent(i)}function r(e,t){let n=document.createTreeWalker(e,NodeFilter.SHOW_ALL);do t(n.currentNode);while(n.nextNode())}let l=new Map,i=new Set;function u(e){let t=[];for(let n of(e.forEach(function(e){let n=e.target,o=e.type;\"attributes\"===o?(null===e.oldValue||null===n.getAttribute(e.attributeName))&&a(\"DOMSubtreeModified\",n,{attributeName:e.attributeName}):\"characterData\"===o?(a(\"DOMCharacterDataModified\",n,{prevValue:e.oldValue,newValue:n.textContent}),t.push(n)):\"childList\"===o&&(e.removedNodes.forEach(e=>{t.push(n),a(\"DOMNodeRemoved\",e),a(\"DOMNodeRemoved\",n,void 0,e),r(e,e=>a(\"DOMNodeRemovedFromDocument\",e,{bubbles:!1})),a(\"DOMNodeRemovedFromDocument\",n,{bubbles:!1},e)}),e.addedNodes.forEach(e=>{t.push(n),a(\"DOMNodeInserted\",e),r(e,e=>a(\"DOMNodeInsertedIntoDocument\",e,{bubbles:!1}))}))}),t))a(\"DOMSubtreeModified\",n)}function d(e){let t=e.getRootNode();for(;t instanceof ShadowRoot;)t=t.host.getRootNode();return t instanceof Document?t.documentElement:t}let s={subtree:!0,childList:!0,attributes:!0,attributeOldValue:!0,characterData:!0,characterDataOldValue:!0},c=Element.prototype.addEventListener;function f(e,o,a){return t.has(e)?{fullEventName:e+n,augmentedListener(t){Object.defineProperty(t,\"type\",{writable:!1,value:e}),o(t)}}:{fullEventName:e,augmentedListener:o}}Element.prototype.addEventListener=function(e,n,o){if(t.has(e)){!function e(t){if(i.has(t))return;i.add(t);let n=d(t);if(l.has(n)){l.get(n).count++;return}let o=new MutationObserver(u);l.set(n,{observer:o,count:1}),o.observe(n,s)}(this);let{augmentedListener:a,fullEventName:r}=f(e,n,o);c.apply(this,[r,a,o]);return}c.call(this,e,n,o)};let v=window.removeEventListener;Element.prototype.removeEventListener=function(e,n,o){if(t.has(e)){!function e(t){if(!i.has(t))return;i.delete(t);let n=d(t);if(l.has(n)&&0==--l.get(n).count){let o=l.get(n).observer;l.delete(n),o.disconnect()}}(this);let{augmentedListener:a,fullEventName:r}=f(e,n,o);v.apply(this,[r,a,o]);return}v.call(this,e,n,o)},window.MutationEvent=class extends CustomEvent{constructor(e,t){if(\"MagicString\"!==e)throw\"Illegal constructor\";super(\"\",t)}initMutationEvent(...e){this.initCustomEvent(...e)}static MODIFICATION=1;static ADDITION=2;static REMOVAL=3},window.initMutationEvent=()=>new MutationEvent;let h=Document.prototype.createEvent;Document.prototype.createEvent=function(e,...t){return\"MutationEvent\"===e?new MutationEvent(\"MagicString\"):h.call(this,e,...t)},console.log(`Mutation Events polyfill installed (native feature: ${e?\"supported\":\"not present\"}).`)}();\n", "/*\nUnobtrusive JavaScript\nhttps://github.com/rails/rails/blob/main/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:not([data-turbo=true])',\n formInputClickSelector: 'form:not([data-turbo=true]) input[type=submit], form:not([data-turbo=true]) input[type=image], form:not([data-turbo=true]) button[type=submit], form:not([data-turbo=true]) 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.isContentEditable = function(element) {\n var isEditable;\n isEditable = false;\n while (true) {\n if (element.isContentEditable) {\n isEditable = true;\n break;\n }\n element = element.parentElement;\n if (!element) {\n break;\n }\n }\n return isEditable;\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, 'fieldset[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 Rails.confirm = function(message, element) {\n return confirm(message);\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 = Rails.confirm(message, element);\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, isContentEditable, isXhrRedirect, matches, setData, stopEverything;\n\n matches = Rails.matches, getData = Rails.getData, setData = Rails.setData, stopEverything = Rails.stopEverything, formElements = Rails.formElements, isContentEditable = Rails.isContentEditable;\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 if (e instanceof Event) {\n if (isXhrRedirect(e)) {\n return;\n }\n element = e.target;\n } else {\n element = e;\n }\n if (isContentEditable(element)) {\n return;\n }\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 (isContentEditable(element)) {\n return;\n }\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 if (getData(element, 'ujs:disabled')) {\n return;\n }\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 if (getData(element, 'ujs:disabled')) {\n return;\n }\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 isXhrRedirect = function(event) {\n var ref, xhr;\n xhr = (ref = event.detail) != null ? ref[0] : void 0;\n return (xhr != null ? xhr.getResponseHeader(\"X-Xhr-Redirect\") : void 0) != null;\n };\n\n }).call(this);\n (function() {\n var isContentEditable, stopEverything;\n\n stopEverything = Rails.stopEverything;\n\n isContentEditable = Rails.isContentEditable;\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 if (isContentEditable(this)) {\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, isContentEditable, 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, isContentEditable = Rails.isContentEditable;\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 if (isContentEditable(element)) {\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", "/*!\n * Pikaday\n *\n * Copyright \u00A9 2014 David Bushell | BSD & MIT license | https://github.com/Pikaday/Pikaday\n */\n\n(function (root, factory)\n{\n 'use strict';\n\n var moment;\n if (typeof exports === 'object') {\n // CommonJS module\n // Load moment.js as an optional dependency\n try { moment = require('moment'); } catch (e) {}\n module.exports = factory(moment);\n } else if (typeof define === 'function' && define.amd) {\n // AMD. Register as an anonymous module.\n define(function (req)\n {\n // Load moment.js as an optional dependency\n var id = 'moment';\n try { moment = req(id); } catch (e) {}\n return factory(moment);\n });\n } else {\n root.Pikaday = factory(root.moment);\n }\n}(this, function (moment)\n{\n 'use strict';\n\n /**\n * feature detection and helper functions\n */\n var hasMoment = typeof moment === 'function',\n\n hasEventListeners = !!window.addEventListener,\n\n document = window.document,\n\n sto = window.setTimeout,\n\n addEvent = function(el, e, callback, capture)\n {\n if (hasEventListeners) {\n el.addEventListener(e, callback, !!capture);\n } else {\n el.attachEvent('on' + e, callback);\n }\n },\n\n removeEvent = function(el, e, callback, capture)\n {\n if (hasEventListeners) {\n el.removeEventListener(e, callback, !!capture);\n } else {\n el.detachEvent('on' + e, callback);\n }\n },\n\n trim = function(str)\n {\n return str.trim ? str.trim() : str.replace(/^\\s+|\\s+$/g,'');\n },\n\n hasClass = function(el, cn)\n {\n return (' ' + el.className + ' ').indexOf(' ' + cn + ' ') !== -1;\n },\n\n addClass = function(el, cn)\n {\n if (!hasClass(el, cn)) {\n el.className = (el.className === '') ? cn : el.className + ' ' + cn;\n }\n },\n\n removeClass = function(el, cn)\n {\n el.className = trim((' ' + el.className + ' ').replace(' ' + cn + ' ', ' '));\n },\n\n isArray = function(obj)\n {\n return (/Array/).test(Object.prototype.toString.call(obj));\n },\n\n isDate = function(obj)\n {\n return (/Date/).test(Object.prototype.toString.call(obj)) && !isNaN(obj.getTime());\n },\n\n isWeekend = function(date)\n {\n var day = date.getDay();\n return day === 0 || day === 6;\n },\n\n isLeapYear = function(year)\n {\n // solution lifted from date.js (MIT license): https://github.com/datejs/Datejs\n return ((year % 4 === 0 && year % 100 !== 0) || year % 400 === 0);\n },\n\n getDaysInMonth = function(year, month)\n {\n return [31, isLeapYear(year) ? 29 : 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31][month];\n },\n\n setToStartOfDay = function(date)\n {\n if (isDate(date)) date.setHours(0,0,0,0);\n },\n\n compareDates = function(a,b)\n {\n // weak date comparison (use setToStartOfDay(date) to ensure correct result)\n return a.getTime() === b.getTime();\n },\n\n extend = function(to, from, overwrite)\n {\n var prop, hasProp;\n for (prop in from) {\n hasProp = to[prop] !== undefined;\n if (hasProp && typeof from[prop] === 'object' && from[prop] !== null && from[prop].nodeName === undefined) {\n if (isDate(from[prop])) {\n if (overwrite) {\n to[prop] = new Date(from[prop].getTime());\n }\n }\n else if (isArray(from[prop])) {\n if (overwrite) {\n to[prop] = from[prop].slice(0);\n }\n } else {\n to[prop] = extend({}, from[prop], overwrite);\n }\n } else if (overwrite || !hasProp) {\n to[prop] = from[prop];\n }\n }\n return to;\n },\n\n fireEvent = function(el, eventName, data)\n {\n var ev;\n\n if (document.createEvent) {\n ev = document.createEvent('HTMLEvents');\n ev.initEvent(eventName, true, false);\n ev = extend(ev, data);\n el.dispatchEvent(ev);\n } else if (document.createEventObject) {\n ev = document.createEventObject();\n ev = extend(ev, data);\n el.fireEvent('on' + eventName, ev);\n }\n },\n\n adjustCalendar = function(calendar) {\n if (calendar.month < 0) {\n calendar.year -= Math.ceil(Math.abs(calendar.month)/12);\n calendar.month += 12;\n }\n if (calendar.month > 11) {\n calendar.year += Math.floor(Math.abs(calendar.month)/12);\n calendar.month -= 12;\n }\n return calendar;\n },\n\n /**\n * defaults and localisation\n */\n defaults = {\n\n // bind the picker to a form field\n field: null,\n\n // automatically show/hide the picker on `field` focus (default `true` if `field` is set)\n bound: undefined,\n\n // data-attribute on the input field with an aria assistance text (only applied when `bound` is set)\n ariaLabel: 'Use the arrow keys to pick a date',\n\n // position of the datepicker, relative to the field (default to bottom & left)\n // ('bottom' & 'left' keywords are not used, 'top' & 'right' are modifier on the bottom/left position)\n position: 'bottom left',\n\n // automatically fit in the viewport even if it means repositioning from the position option\n reposition: true,\n\n // the default output format for `.toString()` and `field` value\n format: 'YYYY-MM-DD',\n\n // the toString function which gets passed a current date object and format\n // and returns a string\n toString: null,\n\n // used to create date object from current input string\n parse: null,\n\n // the initial date to view when first opened\n defaultDate: null,\n\n // make the `defaultDate` the initial selected value\n setDefaultDate: false,\n\n // first day of week (0: Sunday, 1: Monday etc)\n firstDay: 0,\n\n // minimum number of days in the week that gets week number one\n // default ISO 8601, week 01 is the week with the first Thursday (4)\n firstWeekOfYearMinDays: 4,\n\n // the default flag for moment's strict date parsing\n formatStrict: false,\n\n // the minimum/earliest date that can be selected\n minDate: null,\n // the maximum/latest date that can be selected\n maxDate: null,\n\n // number of years either side, or array of upper/lower range\n yearRange: 10,\n\n // show week numbers at head of row\n showWeekNumber: false,\n\n // Week picker mode\n pickWholeWeek: false,\n\n // used internally (don't config outside)\n minYear: 0,\n maxYear: 9999,\n minMonth: undefined,\n maxMonth: undefined,\n\n startRange: null,\n endRange: null,\n\n isRTL: false,\n\n // Additional text to append to the year in the calendar title\n yearSuffix: '',\n\n // Render the month after year in the calendar title\n showMonthAfterYear: false,\n\n // Render days of the calendar grid that fall in the next or previous month\n showDaysInNextAndPreviousMonths: false,\n\n // Allows user to select days that fall in the next or previous month\n enableSelectionDaysInNextAndPreviousMonths: false,\n\n // how many months are visible\n numberOfMonths: 1,\n\n // when numberOfMonths is used, this will help you to choose where the main calendar will be (default `left`, can be set to `right`)\n // only used for the first display or when a selected date is not visible\n mainCalendar: 'left',\n\n // Specify a DOM element to render the calendar in\n container: undefined,\n\n // Blur field when date is selected\n blurFieldOnSelect : true,\n\n // internationalization\n i18n: {\n previousMonth : 'Previous Month',\n nextMonth : 'Next Month',\n months : ['January','February','March','April','May','June','July','August','September','October','November','December'],\n weekdays : ['Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday'],\n weekdaysShort : ['Sun','Mon','Tue','Wed','Thu','Fri','Sat']\n },\n\n // Theme Classname\n theme: null,\n\n // events array\n events: [],\n\n // callback function\n onSelect: null,\n onOpen: null,\n onClose: null,\n onDraw: null,\n\n // Enable keyboard input\n keyboardInput: true\n },\n\n\n /**\n * templating functions to abstract HTML rendering\n */\n renderDayName = function(opts, day, abbr)\n {\n day += opts.firstDay;\n while (day >= 7) {\n day -= 7;\n }\n return abbr ? opts.i18n.weekdaysShort[day] : opts.i18n.weekdays[day];\n },\n\n renderDay = function(opts)\n {\n var arr = [];\n var ariaSelected = 'false';\n if (opts.isEmpty) {\n if (opts.showDaysInNextAndPreviousMonths) {\n arr.push('is-outside-current-month');\n\n if(!opts.enableSelectionDaysInNextAndPreviousMonths) {\n arr.push('is-selection-disabled');\n }\n\n } else {\n return '';\n }\n }\n if (opts.isDisabled) {\n arr.push('is-disabled');\n }\n if (opts.isToday) {\n arr.push('is-today');\n }\n if (opts.isSelected) {\n arr.push('is-selected');\n ariaSelected = 'true';\n }\n if (opts.hasEvent) {\n arr.push('has-event');\n }\n if (opts.isInRange) {\n arr.push('is-inrange');\n }\n if (opts.isStartRange) {\n arr.push('is-startrange');\n }\n if (opts.isEndRange) {\n arr.push('is-endrange');\n }\n return '' +\n '' +\n '';\n },\n\n isoWeek = function(date, firstWeekOfYearMinDays) {\n // Ensure we're at the start of the day.\n date.setHours(0, 0, 0, 0);\n\n // Thursday in current week decides the year because January 4th\n // is always in the first week according to ISO8601.\n var yearDay = date.getDate(),\n weekDay = date.getDay(),\n dayInFirstWeek = firstWeekOfYearMinDays,\n dayShift = dayInFirstWeek - 1, // counting starts at 0\n daysPerWeek = 7,\n prevWeekDay = function(day) { return (day + daysPerWeek - 1) % daysPerWeek; };\n\n // Adjust to Thursday in week 1 and count number of weeks from date to week 1.\n date.setDate(yearDay + dayShift - prevWeekDay(weekDay));\n\n var jan4th = new Date(date.getFullYear(), 0, dayInFirstWeek),\n msPerDay = 24 * 60 * 60 * 1000,\n daysBetween = (date.getTime() - jan4th.getTime()) / msPerDay,\n weekNum = 1 + Math.round((daysBetween - dayShift + prevWeekDay(jan4th.getDay())) / daysPerWeek);\n\n return weekNum;\n },\n\n renderWeek = function (d, m, y, firstWeekOfYearMinDays) {\n var date = new Date(y, m, d),\n week = hasMoment ? moment(date).isoWeek() : isoWeek(date, firstWeekOfYearMinDays);\n\n return '' + week + '';\n },\n\n renderRow = function(days, isRTL, pickWholeWeek, isRowSelected)\n {\n return '' + (isRTL ? days.reverse() : days).join('') + '';\n },\n\n renderBody = function(rows)\n {\n return '' + rows.join('') + '';\n },\n\n renderHead = function(opts)\n {\n var i, arr = [];\n if (opts.showWeekNumber) {\n arr.push('');\n }\n for (i = 0; i < 7; i++) {\n arr.push('' + renderDayName(opts, i, true) + '');\n }\n return '' + (opts.isRTL ? arr.reverse() : arr).join('') + '';\n },\n\n renderTitle = function(instance, c, year, month, refYear, randId)\n {\n var i, j, arr,\n opts = instance._o,\n isMinYear = year === opts.minYear,\n isMaxYear = year === opts.maxYear,\n html = '
',\n monthHtml,\n yearHtml,\n prev = true,\n next = true;\n\n for (arr = [], i = 0; i < 12; i++) {\n arr.push('');\n }\n\n monthHtml = '
' + opts.i18n.months[month] + '
';\n\n if (isArray(opts.yearRange)) {\n i = opts.yearRange[0];\n j = opts.yearRange[1] + 1;\n } else {\n i = year - opts.yearRange;\n j = 1 + year + opts.yearRange;\n }\n\n for (arr = []; i < j && i <= opts.maxYear; i++) {\n if (i >= opts.minYear) {\n arr.push('');\n }\n }\n yearHtml = '
' + year + opts.yearSuffix + '
';\n\n if (opts.showMonthAfterYear) {\n html += yearHtml + monthHtml;\n } else {\n html += monthHtml + yearHtml;\n }\n\n if (isMinYear && (month === 0 || opts.minMonth >= month)) {\n prev = false;\n }\n\n if (isMaxYear && (month === 11 || opts.maxMonth <= month)) {\n next = false;\n }\n\n if (c === 0) {\n html += '';\n }\n if (c === (instance._o.numberOfMonths - 1) ) {\n html += '';\n }\n\n return html += '
';\n },\n\n renderTable = function(opts, data, randId)\n {\n return '' + renderHead(opts) + renderBody(data) + '
';\n },\n\n\n /**\n * Pikaday constructor\n */\n Pikaday = function(options)\n {\n var self = this,\n opts = self.config(options);\n\n self._onMouseDown = function(e)\n {\n if (!self._v) {\n return;\n }\n e = e || window.event;\n var target = e.target || e.srcElement;\n if (!target) {\n return;\n }\n\n if (!hasClass(target, 'is-disabled')) {\n if (hasClass(target, 'pika-button') && !hasClass(target, 'is-empty') && !hasClass(target.parentNode, 'is-disabled')) {\n self.setDate(new Date(target.getAttribute('data-pika-year'), target.getAttribute('data-pika-month'), target.getAttribute('data-pika-day')));\n if (opts.bound) {\n sto(function() {\n self.hide();\n if (opts.blurFieldOnSelect && opts.field) {\n opts.field.blur();\n }\n }, 100);\n }\n }\n else if (hasClass(target, 'pika-prev')) {\n self.prevMonth();\n }\n else if (hasClass(target, 'pika-next')) {\n self.nextMonth();\n }\n }\n if (!hasClass(target, 'pika-select')) {\n // if this is touch event prevent mouse events emulation\n if (e.preventDefault) {\n e.preventDefault();\n } else {\n e.returnValue = false;\n return false;\n }\n } else {\n self._c = true;\n }\n };\n\n self._onChange = function(e)\n {\n e = e || window.event;\n var target = e.target || e.srcElement;\n if (!target) {\n return;\n }\n if (hasClass(target, 'pika-select-month')) {\n self.gotoMonth(target.value);\n }\n else if (hasClass(target, 'pika-select-year')) {\n self.gotoYear(target.value);\n }\n };\n\n self._onKeyChange = function(e)\n {\n e = e || window.event;\n\n if (self.isVisible()) {\n\n switch(e.keyCode){\n case 13:\n case 27:\n if (opts.field) {\n opts.field.blur();\n }\n break;\n case 37:\n self.adjustDate('subtract', 1);\n break;\n case 38:\n self.adjustDate('subtract', 7);\n break;\n case 39:\n self.adjustDate('add', 1);\n break;\n case 40:\n self.adjustDate('add', 7);\n break;\n case 8:\n case 46:\n self.setDate(null);\n break;\n }\n }\n };\n\n self._parseFieldValue = function()\n {\n if (opts.parse) {\n return opts.parse(opts.field.value, opts.format);\n } else if (hasMoment) {\n var date = moment(opts.field.value, opts.format, opts.formatStrict);\n return (date && date.isValid()) ? date.toDate() : null;\n } else {\n return new Date(Date.parse(opts.field.value));\n }\n };\n\n self._onInputChange = function(e)\n {\n var date;\n\n if (e.firedBy === self) {\n return;\n }\n date = self._parseFieldValue();\n if (isDate(date)) {\n self.setDate(date);\n }\n if (!self._v) {\n self.show();\n }\n };\n\n self._onInputFocus = function()\n {\n self.show();\n };\n\n self._onInputClick = function()\n {\n self.show();\n };\n\n self._onInputBlur = function()\n {\n // IE allows pika div to gain focus; catch blur the input field\n var pEl = document.activeElement;\n do {\n if (hasClass(pEl, 'pika-single')) {\n return;\n }\n }\n while ((pEl = pEl.parentNode));\n\n if (!self._c) {\n self._b = sto(function() {\n self.hide();\n }, 50);\n }\n self._c = false;\n };\n\n self._onClick = function(e)\n {\n e = e || window.event;\n var target = e.target || e.srcElement,\n pEl = target;\n if (!target) {\n return;\n }\n if (!hasEventListeners && hasClass(target, 'pika-select')) {\n if (!target.onchange) {\n target.setAttribute('onchange', 'return;');\n addEvent(target, 'change', self._onChange);\n }\n }\n do {\n if (hasClass(pEl, 'pika-single') || pEl === opts.trigger) {\n return;\n }\n }\n while ((pEl = pEl.parentNode));\n if (self._v && target !== opts.trigger && pEl !== opts.trigger) {\n self.hide();\n }\n };\n\n self.el = document.createElement('div');\n self.el.className = 'pika-single' + (opts.isRTL ? ' is-rtl' : '') + (opts.theme ? ' ' + opts.theme : '');\n\n addEvent(self.el, 'mousedown', self._onMouseDown, true);\n addEvent(self.el, 'touchend', self._onMouseDown, true);\n addEvent(self.el, 'change', self._onChange);\n\n if (opts.keyboardInput) {\n addEvent(document, 'keydown', self._onKeyChange);\n }\n\n if (opts.field) {\n if (opts.container) {\n opts.container.appendChild(self.el);\n } else if (opts.bound) {\n document.body.appendChild(self.el);\n } else {\n opts.field.parentNode.insertBefore(self.el, opts.field.nextSibling);\n }\n addEvent(opts.field, 'change', self._onInputChange);\n\n if (!opts.defaultDate) {\n opts.defaultDate = self._parseFieldValue();\n opts.setDefaultDate = true;\n }\n }\n\n var defDate = opts.defaultDate;\n\n if (isDate(defDate)) {\n if (opts.setDefaultDate) {\n self.setDate(defDate, true);\n } else {\n self.gotoDate(defDate);\n }\n } else {\n self.gotoDate(new Date());\n }\n\n if (opts.bound) {\n this.hide();\n self.el.className += ' is-bound';\n addEvent(opts.trigger, 'click', self._onInputClick);\n addEvent(opts.trigger, 'focus', self._onInputFocus);\n addEvent(opts.trigger, 'blur', self._onInputBlur);\n } else {\n this.show();\n }\n };\n\n\n /**\n * public Pikaday API\n */\n Pikaday.prototype = {\n\n\n /**\n * configure functionality\n */\n config: function(options)\n {\n if (!this._o) {\n this._o = extend({}, defaults, true);\n }\n\n var opts = extend(this._o, options, true);\n\n opts.isRTL = !!opts.isRTL;\n\n opts.field = (opts.field && opts.field.nodeName) ? opts.field : null;\n\n opts.theme = (typeof opts.theme) === 'string' && opts.theme ? opts.theme : null;\n\n opts.bound = !!(opts.bound !== undefined ? opts.field && opts.bound : opts.field);\n\n opts.trigger = (opts.trigger && opts.trigger.nodeName) ? opts.trigger : opts.field;\n\n opts.disableWeekends = !!opts.disableWeekends;\n\n opts.disableDayFn = (typeof opts.disableDayFn) === 'function' ? opts.disableDayFn : null;\n\n var nom = parseInt(opts.numberOfMonths, 10) || 1;\n opts.numberOfMonths = nom > 4 ? 4 : nom;\n\n if (!isDate(opts.minDate)) {\n opts.minDate = false;\n }\n if (!isDate(opts.maxDate)) {\n opts.maxDate = false;\n }\n if ((opts.minDate && opts.maxDate) && opts.maxDate < opts.minDate) {\n opts.maxDate = opts.minDate = false;\n }\n if (opts.minDate) {\n this.setMinDate(opts.minDate);\n }\n if (opts.maxDate) {\n this.setMaxDate(opts.maxDate);\n }\n\n if (isArray(opts.yearRange)) {\n var fallback = new Date().getFullYear() - 10;\n opts.yearRange[0] = parseInt(opts.yearRange[0], 10) || fallback;\n opts.yearRange[1] = parseInt(opts.yearRange[1], 10) || fallback;\n } else {\n opts.yearRange = Math.abs(parseInt(opts.yearRange, 10)) || defaults.yearRange;\n if (opts.yearRange > 100) {\n opts.yearRange = 100;\n }\n }\n\n return opts;\n },\n\n /**\n * return a formatted string of the current selection (using Moment.js if available)\n */\n toString: function(format)\n {\n format = format || this._o.format;\n if (!isDate(this._d)) {\n return '';\n }\n if (this._o.toString) {\n return this._o.toString(this._d, format);\n }\n if (hasMoment) {\n return moment(this._d).format(format);\n }\n return this._d.toDateString();\n },\n\n /**\n * return a Moment.js object of the current selection (if available)\n */\n getMoment: function()\n {\n return hasMoment ? moment(this._d) : null;\n },\n\n /**\n * set the current selection from a Moment.js object (if available)\n */\n setMoment: function(date, preventOnSelect)\n {\n if (hasMoment && moment.isMoment(date)) {\n this.setDate(date.toDate(), preventOnSelect);\n }\n },\n\n /**\n * return a Date object of the current selection\n */\n getDate: function()\n {\n return isDate(this._d) ? new Date(this._d.getTime()) : null;\n },\n\n /**\n * set the current selection\n */\n setDate: function(date, preventOnSelect)\n {\n if (!date) {\n this._d = null;\n\n if (this._o.field) {\n this._o.field.value = '';\n fireEvent(this._o.field, 'change', { firedBy: this });\n }\n\n return this.draw();\n }\n if (typeof date === 'string') {\n date = new Date(Date.parse(date));\n }\n if (!isDate(date)) {\n return;\n }\n\n var min = this._o.minDate,\n max = this._o.maxDate;\n\n if (isDate(min) && date < min) {\n date = min;\n } else if (isDate(max) && date > max) {\n date = max;\n }\n\n this._d = new Date(date.getTime());\n setToStartOfDay(this._d);\n this.gotoDate(this._d);\n\n if (this._o.field) {\n this._o.field.value = this.toString();\n fireEvent(this._o.field, 'change', { firedBy: this });\n }\n if (!preventOnSelect && typeof this._o.onSelect === 'function') {\n this._o.onSelect.call(this, this.getDate());\n }\n },\n\n /**\n * clear and reset the date\n */\n clear: function()\n {\n this.setDate(null);\n },\n\n /**\n * change view to a specific date\n */\n gotoDate: function(date)\n {\n var newCalendar = true;\n\n if (!isDate(date)) {\n return;\n }\n\n if (this.calendars) {\n var firstVisibleDate = new Date(this.calendars[0].year, this.calendars[0].month, 1),\n lastVisibleDate = new Date(this.calendars[this.calendars.length-1].year, this.calendars[this.calendars.length-1].month, 1),\n visibleDate = date.getTime();\n // get the end of the month\n lastVisibleDate.setMonth(lastVisibleDate.getMonth()+1);\n lastVisibleDate.setDate(lastVisibleDate.getDate()-1);\n newCalendar = (visibleDate < firstVisibleDate.getTime() || lastVisibleDate.getTime() < visibleDate);\n }\n\n if (newCalendar) {\n this.calendars = [{\n month: date.getMonth(),\n year: date.getFullYear()\n }];\n if (this._o.mainCalendar === 'right') {\n this.calendars[0].month += 1 - this._o.numberOfMonths;\n }\n }\n\n this.adjustCalendars();\n },\n\n adjustDate: function(sign, days) {\n\n var day = this.getDate() || new Date();\n var difference = parseInt(days)*24*60*60*1000;\n\n var newDay;\n\n if (sign === 'add') {\n newDay = new Date(day.valueOf() + difference);\n } else if (sign === 'subtract') {\n newDay = new Date(day.valueOf() - difference);\n }\n\n this.setDate(newDay);\n },\n\n adjustCalendars: function() {\n this.calendars[0] = adjustCalendar(this.calendars[0]);\n for (var c = 1; c < this._o.numberOfMonths; c++) {\n this.calendars[c] = adjustCalendar({\n month: this.calendars[0].month + c,\n year: this.calendars[0].year\n });\n }\n this.draw();\n },\n\n gotoToday: function()\n {\n this.gotoDate(new Date());\n },\n\n /**\n * change view to a specific month (zero-index, e.g. 0: January)\n */\n gotoMonth: function(month)\n {\n if (!isNaN(month)) {\n this.calendars[0].month = parseInt(month, 10);\n this.adjustCalendars();\n }\n },\n\n nextMonth: function()\n {\n this.calendars[0].month++;\n this.adjustCalendars();\n },\n\n prevMonth: function()\n {\n this.calendars[0].month--;\n this.adjustCalendars();\n },\n\n /**\n * change view to a specific full year (e.g. \"2012\")\n */\n gotoYear: function(year)\n {\n if (!isNaN(year)) {\n this.calendars[0].year = parseInt(year, 10);\n this.adjustCalendars();\n }\n },\n\n /**\n * change the minDate\n */\n setMinDate: function(value)\n {\n if(value instanceof Date) {\n setToStartOfDay(value);\n this._o.minDate = value;\n this._o.minYear = value.getFullYear();\n this._o.minMonth = value.getMonth();\n } else {\n this._o.minDate = defaults.minDate;\n this._o.minYear = defaults.minYear;\n this._o.minMonth = defaults.minMonth;\n this._o.startRange = defaults.startRange;\n }\n\n this.draw();\n },\n\n /**\n * change the maxDate\n */\n setMaxDate: function(value)\n {\n if(value instanceof Date) {\n setToStartOfDay(value);\n this._o.maxDate = value;\n this._o.maxYear = value.getFullYear();\n this._o.maxMonth = value.getMonth();\n } else {\n this._o.maxDate = defaults.maxDate;\n this._o.maxYear = defaults.maxYear;\n this._o.maxMonth = defaults.maxMonth;\n this._o.endRange = defaults.endRange;\n }\n\n this.draw();\n },\n\n setStartRange: function(value)\n {\n this._o.startRange = value;\n },\n\n setEndRange: function(value)\n {\n this._o.endRange = value;\n },\n\n /**\n * refresh the HTML\n */\n draw: function(force)\n {\n if (!this._v && !force) {\n return;\n }\n var opts = this._o,\n minYear = opts.minYear,\n maxYear = opts.maxYear,\n minMonth = opts.minMonth,\n maxMonth = opts.maxMonth,\n html = '',\n randId;\n\n if (this._y <= minYear) {\n this._y = minYear;\n if (!isNaN(minMonth) && this._m < minMonth) {\n this._m = minMonth;\n }\n }\n if (this._y >= maxYear) {\n this._y = maxYear;\n if (!isNaN(maxMonth) && this._m > maxMonth) {\n this._m = maxMonth;\n }\n }\n\n for (var c = 0; c < opts.numberOfMonths; c++) {\n randId = 'pika-title-' + Math.random().toString(36).replace(/[^a-z]+/g, '').substr(0, 2);\n html += '
' + renderTitle(this, c, this.calendars[c].year, this.calendars[c].month, this.calendars[0].year, randId) + this.render(this.calendars[c].year, this.calendars[c].month, randId) + '
';\n }\n\n this.el.innerHTML = html;\n\n if (opts.bound) {\n if(opts.field.type !== 'hidden') {\n sto(function() {\n opts.trigger.focus();\n }, 1);\n }\n }\n\n if (typeof this._o.onDraw === 'function') {\n this._o.onDraw(this);\n }\n\n if (opts.bound) {\n // let the screen reader user know to use arrow keys\n opts.field.setAttribute('aria-label', opts.ariaLabel);\n }\n },\n\n adjustPosition: function()\n {\n var field, pEl, width, height, viewportWidth, viewportHeight, scrollTop, left, top, clientRect, leftAligned, bottomAligned;\n\n if (this._o.container) return;\n\n this.el.style.position = 'absolute';\n\n field = this._o.trigger;\n pEl = field;\n width = this.el.offsetWidth;\n height = this.el.offsetHeight;\n viewportWidth = window.innerWidth || document.documentElement.clientWidth;\n viewportHeight = window.innerHeight || document.documentElement.clientHeight;\n scrollTop = window.pageYOffset || document.body.scrollTop || document.documentElement.scrollTop;\n leftAligned = true;\n bottomAligned = true;\n\n if (typeof field.getBoundingClientRect === 'function') {\n clientRect = field.getBoundingClientRect();\n left = clientRect.left + window.pageXOffset;\n top = clientRect.bottom + window.pageYOffset;\n } else {\n left = pEl.offsetLeft;\n top = pEl.offsetTop + pEl.offsetHeight;\n while((pEl = pEl.offsetParent)) {\n left += pEl.offsetLeft;\n top += pEl.offsetTop;\n }\n }\n\n // default position is bottom & left\n if ((this._o.reposition && left + width > viewportWidth) ||\n (\n this._o.position.indexOf('right') > -1 &&\n left - width + field.offsetWidth > 0\n )\n ) {\n left = left - width + field.offsetWidth;\n leftAligned = false;\n }\n if ((this._o.reposition && top + height > viewportHeight + scrollTop) ||\n (\n this._o.position.indexOf('top') > -1 &&\n top - height - field.offsetHeight > 0\n )\n ) {\n top = top - height - field.offsetHeight;\n bottomAligned = false;\n }\n\n this.el.style.left = left + 'px';\n this.el.style.top = top + 'px';\n\n addClass(this.el, leftAligned ? 'left-aligned' : 'right-aligned');\n addClass(this.el, bottomAligned ? 'bottom-aligned' : 'top-aligned');\n removeClass(this.el, !leftAligned ? 'left-aligned' : 'right-aligned');\n removeClass(this.el, !bottomAligned ? 'bottom-aligned' : 'top-aligned');\n },\n\n /**\n * render HTML for a particular month\n */\n render: function(year, month, randId)\n {\n var opts = this._o,\n now = new Date(),\n days = getDaysInMonth(year, month),\n before = new Date(year, month, 1).getDay(),\n data = [],\n row = [];\n setToStartOfDay(now);\n if (opts.firstDay > 0) {\n before -= opts.firstDay;\n if (before < 0) {\n before += 7;\n }\n }\n var previousMonth = month === 0 ? 11 : month - 1,\n nextMonth = month === 11 ? 0 : month + 1,\n yearOfPreviousMonth = month === 0 ? year - 1 : year,\n yearOfNextMonth = month === 11 ? year + 1 : year,\n daysInPreviousMonth = getDaysInMonth(yearOfPreviousMonth, previousMonth);\n var cells = days + before,\n after = cells;\n while(after > 7) {\n after -= 7;\n }\n cells += 7 - after;\n var isWeekSelected = false;\n for (var i = 0, r = 0; i < cells; i++)\n {\n var day = new Date(year, month, 1 + (i - before)),\n isSelected = isDate(this._d) ? compareDates(day, this._d) : false,\n isToday = compareDates(day, now),\n hasEvent = opts.events.indexOf(day.toDateString()) !== -1 ? true : false,\n isEmpty = i < before || i >= (days + before),\n dayNumber = 1 + (i - before),\n monthNumber = month,\n yearNumber = year,\n isStartRange = opts.startRange && compareDates(opts.startRange, day),\n isEndRange = opts.endRange && compareDates(opts.endRange, day),\n isInRange = opts.startRange && opts.endRange && opts.startRange < day && day < opts.endRange,\n isDisabled = (opts.minDate && day < opts.minDate) ||\n (opts.maxDate && day > opts.maxDate) ||\n (opts.disableWeekends && isWeekend(day)) ||\n (opts.disableDayFn && opts.disableDayFn(day));\n\n if (isEmpty) {\n if (i < before) {\n dayNumber = daysInPreviousMonth + dayNumber;\n monthNumber = previousMonth;\n yearNumber = yearOfPreviousMonth;\n } else {\n dayNumber = dayNumber - days;\n monthNumber = nextMonth;\n yearNumber = yearOfNextMonth;\n }\n }\n\n var dayConfig = {\n day: dayNumber,\n month: monthNumber,\n year: yearNumber,\n hasEvent: hasEvent,\n isSelected: isSelected,\n isToday: isToday,\n isDisabled: isDisabled,\n isEmpty: isEmpty,\n isStartRange: isStartRange,\n isEndRange: isEndRange,\n isInRange: isInRange,\n showDaysInNextAndPreviousMonths: opts.showDaysInNextAndPreviousMonths,\n enableSelectionDaysInNextAndPreviousMonths: opts.enableSelectionDaysInNextAndPreviousMonths\n };\n\n if (opts.pickWholeWeek && isSelected) {\n isWeekSelected = true;\n }\n\n row.push(renderDay(dayConfig));\n\n if (++r === 7) {\n if (opts.showWeekNumber) {\n row.unshift(renderWeek(i - before, month, year, opts.firstWeekOfYearMinDays));\n }\n data.push(renderRow(row, opts.isRTL, opts.pickWholeWeek, isWeekSelected));\n row = [];\n r = 0;\n isWeekSelected = false;\n }\n }\n return renderTable(opts, data, randId);\n },\n\n isVisible: function()\n {\n return this._v;\n },\n\n show: function()\n {\n if (!this.isVisible()) {\n this._v = true;\n this.draw();\n removeClass(this.el, 'is-hidden');\n if (this._o.bound) {\n addEvent(document, 'click', this._onClick);\n this.adjustPosition();\n }\n if (typeof this._o.onOpen === 'function') {\n this._o.onOpen.call(this);\n }\n }\n },\n\n hide: function()\n {\n var v = this._v;\n if (v !== false) {\n if (this._o.bound) {\n removeEvent(document, 'click', this._onClick);\n }\n\n if (!this._o.container) {\n this.el.style.position = 'static'; // reset\n this.el.style.left = 'auto';\n this.el.style.top = 'auto';\n }\n addClass(this.el, 'is-hidden');\n this._v = false;\n if (v !== undefined && typeof this._o.onClose === 'function') {\n this._o.onClose.call(this);\n }\n }\n },\n\n /**\n * GAME OVER\n */\n destroy: function()\n {\n var opts = this._o;\n\n this.hide();\n removeEvent(this.el, 'mousedown', this._onMouseDown, true);\n removeEvent(this.el, 'touchend', this._onMouseDown, true);\n removeEvent(this.el, 'change', this._onChange);\n if (opts.keyboardInput) {\n removeEvent(document, 'keydown', this._onKeyChange);\n }\n if (opts.field) {\n removeEvent(opts.field, 'change', this._onInputChange);\n if (opts.bound) {\n removeEvent(opts.trigger, 'click', this._onInputClick);\n removeEvent(opts.trigger, 'focus', this._onInputFocus);\n removeEvent(opts.trigger, 'blur', this._onInputBlur);\n }\n }\n if (this.el.parentNode) {\n this.el.parentNode.removeChild(this.el);\n }\n }\n\n };\n\n return Pikaday;\n}));\n", "(function (global, factory) {\n typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :\n typeof define === 'function' && define.amd ? define(['exports'], factory) :\n (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.noUiSlider = {}));\n})(this, (function (exports) { 'use strict';\n\n exports.PipsMode = void 0;\n (function (PipsMode) {\n PipsMode[\"Range\"] = \"range\";\n PipsMode[\"Steps\"] = \"steps\";\n PipsMode[\"Positions\"] = \"positions\";\n PipsMode[\"Count\"] = \"count\";\n PipsMode[\"Values\"] = \"values\";\n })(exports.PipsMode || (exports.PipsMode = {}));\n exports.PipsType = void 0;\n (function (PipsType) {\n PipsType[PipsType[\"None\"] = -1] = \"None\";\n PipsType[PipsType[\"NoValue\"] = 0] = \"NoValue\";\n PipsType[PipsType[\"LargeValue\"] = 1] = \"LargeValue\";\n PipsType[PipsType[\"SmallValue\"] = 2] = \"SmallValue\";\n })(exports.PipsType || (exports.PipsType = {}));\n //region Helper Methods\n function isValidFormatter(entry) {\n return isValidPartialFormatter(entry) && typeof entry.from === \"function\";\n }\n function isValidPartialFormatter(entry) {\n // partial formatters only need a to function and not a from function\n return typeof entry === \"object\" && typeof entry.to === \"function\";\n }\n function removeElement(el) {\n el.parentElement.removeChild(el);\n }\n function isSet(value) {\n return value !== null && value !== undefined;\n }\n // Bindable version\n function preventDefault(e) {\n e.preventDefault();\n }\n // Removes duplicates from an array.\n function unique(array) {\n return array.filter(function (a) {\n return !this[a] ? (this[a] = true) : false;\n }, {});\n }\n // Round a value to the closest 'to'.\n function closest(value, to) {\n return Math.round(value / to) * to;\n }\n // Current position of an element relative to the document.\n function offset(elem, orientation) {\n var rect = elem.getBoundingClientRect();\n var doc = elem.ownerDocument;\n var docElem = doc.documentElement;\n var pageOffset = getPageOffset(doc);\n // getBoundingClientRect contains left scroll in Chrome on Android.\n // I haven't found a feature detection that proves this. Worst case\n // scenario on mis-match: the 'tap' feature on horizontal sliders breaks.\n if (/webkit.*Chrome.*Mobile/i.test(navigator.userAgent)) {\n pageOffset.x = 0;\n }\n return orientation ? rect.top + pageOffset.y - docElem.clientTop : rect.left + pageOffset.x - docElem.clientLeft;\n }\n // Checks whether a value is numerical.\n function isNumeric(a) {\n return typeof a === \"number\" && !isNaN(a) && isFinite(a);\n }\n // Sets a class and removes it after [duration] ms.\n function addClassFor(element, className, duration) {\n if (duration > 0) {\n addClass(element, className);\n setTimeout(function () {\n removeClass(element, className);\n }, duration);\n }\n }\n // Limits a value to 0 - 100\n function limit(a) {\n return Math.max(Math.min(a, 100), 0);\n }\n // Wraps a variable as an array, if it isn't one yet.\n // Note that an input array is returned by reference!\n function asArray(a) {\n return Array.isArray(a) ? a : [a];\n }\n // Counts decimals\n function countDecimals(numStr) {\n numStr = String(numStr);\n var pieces = numStr.split(\".\");\n return pieces.length > 1 ? pieces[1].length : 0;\n }\n // http://youmightnotneedjquery.com/#add_class\n function addClass(el, className) {\n if (el.classList && !/\\s/.test(className)) {\n el.classList.add(className);\n }\n else {\n el.className += \" \" + className;\n }\n }\n // http://youmightnotneedjquery.com/#remove_class\n function removeClass(el, className) {\n if (el.classList && !/\\s/.test(className)) {\n el.classList.remove(className);\n }\n else {\n el.className = el.className.replace(new RegExp(\"(^|\\\\b)\" + className.split(\" \").join(\"|\") + \"(\\\\b|$)\", \"gi\"), \" \");\n }\n }\n // https://plainjs.com/javascript/attributes/adding-removing-and-testing-for-classes-9/\n function hasClass(el, className) {\n return el.classList ? el.classList.contains(className) : new RegExp(\"\\\\b\" + className + \"\\\\b\").test(el.className);\n }\n // https://developer.mozilla.org/en-US/docs/Web/API/Window/scrollY#Notes\n function getPageOffset(doc) {\n var supportPageOffset = window.pageXOffset !== undefined;\n var isCSS1Compat = (doc.compatMode || \"\") === \"CSS1Compat\";\n var x = supportPageOffset\n ? window.pageXOffset\n : isCSS1Compat\n ? doc.documentElement.scrollLeft\n : doc.body.scrollLeft;\n var y = supportPageOffset\n ? window.pageYOffset\n : isCSS1Compat\n ? doc.documentElement.scrollTop\n : doc.body.scrollTop;\n return {\n x: x,\n y: y,\n };\n }\n // we provide a function to compute constants instead\n // of accessing window.* as soon as the module needs it\n // so that we do not compute anything if not needed\n function getActions() {\n // Determine the events to bind. IE11 implements pointerEvents without\n // a prefix, which breaks compatibility with the IE10 implementation.\n return window.navigator.pointerEnabled\n ? {\n start: \"pointerdown\",\n move: \"pointermove\",\n end: \"pointerup\",\n }\n : window.navigator.msPointerEnabled\n ? {\n start: \"MSPointerDown\",\n move: \"MSPointerMove\",\n end: \"MSPointerUp\",\n }\n : {\n start: \"mousedown touchstart\",\n move: \"mousemove touchmove\",\n end: \"mouseup touchend\",\n };\n }\n // https://github.com/WICG/EventListenerOptions/blob/gh-pages/explainer.md\n // Issue #785\n function getSupportsPassive() {\n var supportsPassive = false;\n /* eslint-disable */\n try {\n var opts = Object.defineProperty({}, \"passive\", {\n get: function () {\n supportsPassive = true;\n },\n });\n // @ts-ignore\n window.addEventListener(\"test\", null, opts);\n }\n catch (e) { }\n /* eslint-enable */\n return supportsPassive;\n }\n function getSupportsTouchActionNone() {\n return window.CSS && CSS.supports && CSS.supports(\"touch-action\", \"none\");\n }\n //endregion\n //region Range Calculation\n // Determine the size of a sub-range in relation to a full range.\n function subRangeRatio(pa, pb) {\n return 100 / (pb - pa);\n }\n // (percentage) How many percent is this value of this range?\n function fromPercentage(range, value, startRange) {\n return (value * 100) / (range[startRange + 1] - range[startRange]);\n }\n // (percentage) Where is this value on this range?\n function toPercentage(range, value) {\n return fromPercentage(range, range[0] < 0 ? value + Math.abs(range[0]) : value - range[0], 0);\n }\n // (value) How much is this percentage on this range?\n function isPercentage(range, value) {\n return (value * (range[1] - range[0])) / 100 + range[0];\n }\n function getJ(value, arr) {\n var j = 1;\n while (value >= arr[j]) {\n j += 1;\n }\n return j;\n }\n // (percentage) Input a value, find where, on a scale of 0-100, it applies.\n function toStepping(xVal, xPct, value) {\n if (value >= xVal.slice(-1)[0]) {\n return 100;\n }\n var j = getJ(value, xVal);\n var va = xVal[j - 1];\n var vb = xVal[j];\n var pa = xPct[j - 1];\n var pb = xPct[j];\n return pa + toPercentage([va, vb], value) / subRangeRatio(pa, pb);\n }\n // (value) Input a percentage, find where it is on the specified range.\n function fromStepping(xVal, xPct, value) {\n // There is no range group that fits 100\n if (value >= 100) {\n return xVal.slice(-1)[0];\n }\n var j = getJ(value, xPct);\n var va = xVal[j - 1];\n var vb = xVal[j];\n var pa = xPct[j - 1];\n var pb = xPct[j];\n return isPercentage([va, vb], (value - pa) * subRangeRatio(pa, pb));\n }\n // (percentage) Get the step that applies at a certain value.\n function getStep(xPct, xSteps, snap, value) {\n if (value === 100) {\n return value;\n }\n var j = getJ(value, xPct);\n var a = xPct[j - 1];\n var b = xPct[j];\n // If 'snap' is set, steps are used as fixed points on the slider.\n if (snap) {\n // Find the closest position, a or b.\n if (value - a > (b - a) / 2) {\n return b;\n }\n return a;\n }\n if (!xSteps[j - 1]) {\n return value;\n }\n return xPct[j - 1] + closest(value - xPct[j - 1], xSteps[j - 1]);\n }\n //endregion\n //region Spectrum\n var Spectrum = /** @class */ (function () {\n function Spectrum(entry, snap, singleStep) {\n this.xPct = [];\n this.xVal = [];\n this.xSteps = [];\n this.xNumSteps = [];\n this.xHighestCompleteStep = [];\n this.xSteps = [singleStep || false];\n this.xNumSteps = [false];\n this.snap = snap;\n var index;\n var ordered = [];\n // Map the object keys to an array.\n Object.keys(entry).forEach(function (index) {\n ordered.push([asArray(entry[index]), index]);\n });\n // Sort all entries by value (numeric sort).\n ordered.sort(function (a, b) {\n return a[0][0] - b[0][0];\n });\n // Convert all entries to subranges.\n for (index = 0; index < ordered.length; index++) {\n this.handleEntryPoint(ordered[index][1], ordered[index][0]);\n }\n // Store the actual step values.\n // xSteps is sorted in the same order as xPct and xVal.\n this.xNumSteps = this.xSteps.slice(0);\n // Convert all numeric steps to the percentage of the subrange they represent.\n for (index = 0; index < this.xNumSteps.length; index++) {\n this.handleStepPoint(index, this.xNumSteps[index]);\n }\n }\n Spectrum.prototype.getDistance = function (value) {\n var distances = [];\n for (var index = 0; index < this.xNumSteps.length - 1; index++) {\n distances[index] = fromPercentage(this.xVal, value, index);\n }\n return distances;\n };\n // Calculate the percentual distance over the whole scale of ranges.\n // direction: 0 = backwards / 1 = forwards\n Spectrum.prototype.getAbsoluteDistance = function (value, distances, direction) {\n var xPct_index = 0;\n // Calculate range where to start calculation\n if (value < this.xPct[this.xPct.length - 1]) {\n while (value > this.xPct[xPct_index + 1]) {\n xPct_index++;\n }\n }\n else if (value === this.xPct[this.xPct.length - 1]) {\n xPct_index = this.xPct.length - 2;\n }\n // If looking backwards and the value is exactly at a range separator then look one range further\n if (!direction && value === this.xPct[xPct_index + 1]) {\n xPct_index++;\n }\n if (distances === null) {\n distances = [];\n }\n var start_factor;\n var rest_factor = 1;\n var rest_rel_distance = distances[xPct_index];\n var range_pct = 0;\n var rel_range_distance = 0;\n var abs_distance_counter = 0;\n var range_counter = 0;\n // Calculate what part of the start range the value is\n if (direction) {\n start_factor = (value - this.xPct[xPct_index]) / (this.xPct[xPct_index + 1] - this.xPct[xPct_index]);\n }\n else {\n start_factor = (this.xPct[xPct_index + 1] - value) / (this.xPct[xPct_index + 1] - this.xPct[xPct_index]);\n }\n // Do until the complete distance across ranges is calculated\n while (rest_rel_distance > 0) {\n // Calculate the percentage of total range\n range_pct = this.xPct[xPct_index + 1 + range_counter] - this.xPct[xPct_index + range_counter];\n // Detect if the margin, padding or limit is larger then the current range and calculate\n if (distances[xPct_index + range_counter] * rest_factor + 100 - start_factor * 100 > 100) {\n // If larger then take the percentual distance of the whole range\n rel_range_distance = range_pct * start_factor;\n // Rest factor of relative percentual distance still to be calculated\n rest_factor = (rest_rel_distance - 100 * start_factor) / distances[xPct_index + range_counter];\n // Set start factor to 1 as for next range it does not apply.\n start_factor = 1;\n }\n else {\n // If smaller or equal then take the percentual distance of the calculate percentual part of that range\n rel_range_distance = ((distances[xPct_index + range_counter] * range_pct) / 100) * rest_factor;\n // No rest left as the rest fits in current range\n rest_factor = 0;\n }\n if (direction) {\n abs_distance_counter = abs_distance_counter - rel_range_distance;\n // Limit range to first range when distance becomes outside of minimum range\n if (this.xPct.length + range_counter >= 1) {\n range_counter--;\n }\n }\n else {\n abs_distance_counter = abs_distance_counter + rel_range_distance;\n // Limit range to last range when distance becomes outside of maximum range\n if (this.xPct.length - range_counter >= 1) {\n range_counter++;\n }\n }\n // Rest of relative percentual distance still to be calculated\n rest_rel_distance = distances[xPct_index + range_counter] * rest_factor;\n }\n return value + abs_distance_counter;\n };\n Spectrum.prototype.toStepping = function (value) {\n value = toStepping(this.xVal, this.xPct, value);\n return value;\n };\n Spectrum.prototype.fromStepping = function (value) {\n return fromStepping(this.xVal, this.xPct, value);\n };\n Spectrum.prototype.getStep = function (value) {\n value = getStep(this.xPct, this.xSteps, this.snap, value);\n return value;\n };\n Spectrum.prototype.getDefaultStep = function (value, isDown, size) {\n var j = getJ(value, this.xPct);\n // When at the top or stepping down, look at the previous sub-range\n if (value === 100 || (isDown && value === this.xPct[j - 1])) {\n j = Math.max(j - 1, 1);\n }\n return (this.xVal[j] - this.xVal[j - 1]) / size;\n };\n Spectrum.prototype.getNearbySteps = function (value) {\n var j = getJ(value, this.xPct);\n return {\n stepBefore: {\n startValue: this.xVal[j - 2],\n step: this.xNumSteps[j - 2],\n highestStep: this.xHighestCompleteStep[j - 2],\n },\n thisStep: {\n startValue: this.xVal[j - 1],\n step: this.xNumSteps[j - 1],\n highestStep: this.xHighestCompleteStep[j - 1],\n },\n stepAfter: {\n startValue: this.xVal[j],\n step: this.xNumSteps[j],\n highestStep: this.xHighestCompleteStep[j],\n },\n };\n };\n Spectrum.prototype.countStepDecimals = function () {\n var stepDecimals = this.xNumSteps.map(countDecimals);\n return Math.max.apply(null, stepDecimals);\n };\n Spectrum.prototype.hasNoSize = function () {\n return this.xVal[0] === this.xVal[this.xVal.length - 1];\n };\n // Outside testing\n Spectrum.prototype.convert = function (value) {\n return this.getStep(this.toStepping(value));\n };\n Spectrum.prototype.handleEntryPoint = function (index, value) {\n var percentage;\n // Covert min/max syntax to 0 and 100.\n if (index === \"min\") {\n percentage = 0;\n }\n else if (index === \"max\") {\n percentage = 100;\n }\n else {\n percentage = parseFloat(index);\n }\n // Check for correct input.\n if (!isNumeric(percentage) || !isNumeric(value[0])) {\n throw new Error(\"noUiSlider: 'range' value isn't numeric.\");\n }\n // Store values.\n this.xPct.push(percentage);\n this.xVal.push(value[0]);\n var value1 = Number(value[1]);\n // NaN will evaluate to false too, but to keep\n // logging clear, set step explicitly. Make sure\n // not to override the 'step' setting with false.\n if (!percentage) {\n if (!isNaN(value1)) {\n this.xSteps[0] = value1;\n }\n }\n else {\n this.xSteps.push(isNaN(value1) ? false : value1);\n }\n this.xHighestCompleteStep.push(0);\n };\n Spectrum.prototype.handleStepPoint = function (i, n) {\n // Ignore 'false' stepping.\n if (!n) {\n return;\n }\n // Step over zero-length ranges (#948);\n if (this.xVal[i] === this.xVal[i + 1]) {\n this.xSteps[i] = this.xHighestCompleteStep[i] = this.xVal[i];\n return;\n }\n // Factor to range ratio\n this.xSteps[i] =\n fromPercentage([this.xVal[i], this.xVal[i + 1]], n, 0) / subRangeRatio(this.xPct[i], this.xPct[i + 1]);\n var totalSteps = (this.xVal[i + 1] - this.xVal[i]) / this.xNumSteps[i];\n var highestStep = Math.ceil(Number(totalSteps.toFixed(3)) - 1);\n var step = this.xVal[i] + this.xNumSteps[i] * highestStep;\n this.xHighestCompleteStep[i] = step;\n };\n return Spectrum;\n }());\n //endregion\n //region Options\n /*\tEvery input option is tested and parsed. This will prevent\n endless validation in internal methods. These tests are\n structured with an item for every option available. An\n option can be marked as required by setting the 'r' flag.\n The testing function is provided with three arguments:\n - The provided value for the option;\n - A reference to the options object;\n - The name for the option;\n\n The testing function returns false when an error is detected,\n or true when everything is OK. It can also modify the option\n object, to make sure all values can be correctly looped elsewhere. */\n //region Defaults\n var defaultFormatter = {\n to: function (value) {\n return value === undefined ? \"\" : value.toFixed(2);\n },\n from: Number,\n };\n var cssClasses = {\n target: \"target\",\n base: \"base\",\n origin: \"origin\",\n handle: \"handle\",\n handleLower: \"handle-lower\",\n handleUpper: \"handle-upper\",\n touchArea: \"touch-area\",\n horizontal: \"horizontal\",\n vertical: \"vertical\",\n background: \"background\",\n connect: \"connect\",\n connects: \"connects\",\n ltr: \"ltr\",\n rtl: \"rtl\",\n textDirectionLtr: \"txt-dir-ltr\",\n textDirectionRtl: \"txt-dir-rtl\",\n draggable: \"draggable\",\n drag: \"state-drag\",\n tap: \"state-tap\",\n active: \"active\",\n tooltip: \"tooltip\",\n pips: \"pips\",\n pipsHorizontal: \"pips-horizontal\",\n pipsVertical: \"pips-vertical\",\n marker: \"marker\",\n markerHorizontal: \"marker-horizontal\",\n markerVertical: \"marker-vertical\",\n markerNormal: \"marker-normal\",\n markerLarge: \"marker-large\",\n markerSub: \"marker-sub\",\n value: \"value\",\n valueHorizontal: \"value-horizontal\",\n valueVertical: \"value-vertical\",\n valueNormal: \"value-normal\",\n valueLarge: \"value-large\",\n valueSub: \"value-sub\",\n };\n // Namespaces of internal event listeners\n var INTERNAL_EVENT_NS = {\n tooltips: \".__tooltips\",\n aria: \".__aria\",\n };\n //endregion\n function testStep(parsed, entry) {\n if (!isNumeric(entry)) {\n throw new Error(\"noUiSlider: 'step' is not numeric.\");\n }\n // The step option can still be used to set stepping\n // for linear sliders. Overwritten if set in 'range'.\n parsed.singleStep = entry;\n }\n function testKeyboardPageMultiplier(parsed, entry) {\n if (!isNumeric(entry)) {\n throw new Error(\"noUiSlider: 'keyboardPageMultiplier' is not numeric.\");\n }\n parsed.keyboardPageMultiplier = entry;\n }\n function testKeyboardMultiplier(parsed, entry) {\n if (!isNumeric(entry)) {\n throw new Error(\"noUiSlider: 'keyboardMultiplier' is not numeric.\");\n }\n parsed.keyboardMultiplier = entry;\n }\n function testKeyboardDefaultStep(parsed, entry) {\n if (!isNumeric(entry)) {\n throw new Error(\"noUiSlider: 'keyboardDefaultStep' is not numeric.\");\n }\n parsed.keyboardDefaultStep = entry;\n }\n function testRange(parsed, entry) {\n // Filter incorrect input.\n if (typeof entry !== \"object\" || Array.isArray(entry)) {\n throw new Error(\"noUiSlider: 'range' is not an object.\");\n }\n // Catch missing start or end.\n if (entry.min === undefined || entry.max === undefined) {\n throw new Error(\"noUiSlider: Missing 'min' or 'max' in 'range'.\");\n }\n parsed.spectrum = new Spectrum(entry, parsed.snap || false, parsed.singleStep);\n }\n function testStart(parsed, entry) {\n entry = asArray(entry);\n // Validate input. Values aren't tested, as the public .val method\n // will always provide a valid location.\n if (!Array.isArray(entry) || !entry.length) {\n throw new Error(\"noUiSlider: 'start' option is incorrect.\");\n }\n // Store the number of handles.\n parsed.handles = entry.length;\n // When the slider is initialized, the .val method will\n // be called with the start options.\n parsed.start = entry;\n }\n function testSnap(parsed, entry) {\n if (typeof entry !== \"boolean\") {\n throw new Error(\"noUiSlider: 'snap' option must be a boolean.\");\n }\n // Enforce 100% stepping within subranges.\n parsed.snap = entry;\n }\n function testAnimate(parsed, entry) {\n if (typeof entry !== \"boolean\") {\n throw new Error(\"noUiSlider: 'animate' option must be a boolean.\");\n }\n // Enforce 100% stepping within subranges.\n parsed.animate = entry;\n }\n function testAnimationDuration(parsed, entry) {\n if (typeof entry !== \"number\") {\n throw new Error(\"noUiSlider: 'animationDuration' option must be a number.\");\n }\n parsed.animationDuration = entry;\n }\n function testConnect(parsed, entry) {\n var connect = [false];\n var i;\n // Map legacy options\n if (entry === \"lower\") {\n entry = [true, false];\n }\n else if (entry === \"upper\") {\n entry = [false, true];\n }\n // Handle boolean options\n if (entry === true || entry === false) {\n for (i = 1; i < parsed.handles; i++) {\n connect.push(entry);\n }\n connect.push(false);\n }\n // Reject invalid input\n else if (!Array.isArray(entry) || !entry.length || entry.length !== parsed.handles + 1) {\n throw new Error(\"noUiSlider: 'connect' option doesn't match handle count.\");\n }\n else {\n connect = entry;\n }\n parsed.connect = connect;\n }\n function testOrientation(parsed, entry) {\n // Set orientation to an a numerical value for easy\n // array selection.\n switch (entry) {\n case \"horizontal\":\n parsed.ort = 0;\n break;\n case \"vertical\":\n parsed.ort = 1;\n break;\n default:\n throw new Error(\"noUiSlider: 'orientation' option is invalid.\");\n }\n }\n function testMargin(parsed, entry) {\n if (!isNumeric(entry)) {\n throw new Error(\"noUiSlider: 'margin' option must be numeric.\");\n }\n // Issue #582\n if (entry === 0) {\n return;\n }\n parsed.margin = parsed.spectrum.getDistance(entry);\n }\n function testLimit(parsed, entry) {\n if (!isNumeric(entry)) {\n throw new Error(\"noUiSlider: 'limit' option must be numeric.\");\n }\n parsed.limit = parsed.spectrum.getDistance(entry);\n if (!parsed.limit || parsed.handles < 2) {\n throw new Error(\"noUiSlider: 'limit' option is only supported on linear sliders with 2 or more handles.\");\n }\n }\n function testPadding(parsed, entry) {\n var index;\n if (!isNumeric(entry) && !Array.isArray(entry)) {\n throw new Error(\"noUiSlider: 'padding' option must be numeric or array of exactly 2 numbers.\");\n }\n if (Array.isArray(entry) && !(entry.length === 2 || isNumeric(entry[0]) || isNumeric(entry[1]))) {\n throw new Error(\"noUiSlider: 'padding' option must be numeric or array of exactly 2 numbers.\");\n }\n if (entry === 0) {\n return;\n }\n if (!Array.isArray(entry)) {\n entry = [entry, entry];\n }\n // 'getDistance' returns false for invalid values.\n parsed.padding = [parsed.spectrum.getDistance(entry[0]), parsed.spectrum.getDistance(entry[1])];\n for (index = 0; index < parsed.spectrum.xNumSteps.length - 1; index++) {\n // last \"range\" can't contain step size as it is purely an endpoint.\n if (parsed.padding[0][index] < 0 || parsed.padding[1][index] < 0) {\n throw new Error(\"noUiSlider: 'padding' option must be a positive number(s).\");\n }\n }\n var totalPadding = entry[0] + entry[1];\n var firstValue = parsed.spectrum.xVal[0];\n var lastValue = parsed.spectrum.xVal[parsed.spectrum.xVal.length - 1];\n if (totalPadding / (lastValue - firstValue) > 1) {\n throw new Error(\"noUiSlider: 'padding' option must not exceed 100% of the range.\");\n }\n }\n function testDirection(parsed, entry) {\n // Set direction as a numerical value for easy parsing.\n // Invert connection for RTL sliders, so that the proper\n // handles get the connect/background classes.\n switch (entry) {\n case \"ltr\":\n parsed.dir = 0;\n break;\n case \"rtl\":\n parsed.dir = 1;\n break;\n default:\n throw new Error(\"noUiSlider: 'direction' option was not recognized.\");\n }\n }\n function testBehaviour(parsed, entry) {\n // Make sure the input is a string.\n if (typeof entry !== \"string\") {\n throw new Error(\"noUiSlider: 'behaviour' must be a string containing options.\");\n }\n // Check if the string contains any keywords.\n // None are required.\n var tap = entry.indexOf(\"tap\") >= 0;\n var drag = entry.indexOf(\"drag\") >= 0;\n var fixed = entry.indexOf(\"fixed\") >= 0;\n var snap = entry.indexOf(\"snap\") >= 0;\n var hover = entry.indexOf(\"hover\") >= 0;\n var unconstrained = entry.indexOf(\"unconstrained\") >= 0;\n var dragAll = entry.indexOf(\"drag-all\") >= 0;\n var smoothSteps = entry.indexOf(\"smooth-steps\") >= 0;\n if (fixed) {\n if (parsed.handles !== 2) {\n throw new Error(\"noUiSlider: 'fixed' behaviour must be used with 2 handles\");\n }\n // Use margin to enforce fixed state\n testMargin(parsed, parsed.start[1] - parsed.start[0]);\n }\n if (unconstrained && (parsed.margin || parsed.limit)) {\n throw new Error(\"noUiSlider: 'unconstrained' behaviour cannot be used with margin or limit\");\n }\n parsed.events = {\n tap: tap || snap,\n drag: drag,\n dragAll: dragAll,\n smoothSteps: smoothSteps,\n fixed: fixed,\n snap: snap,\n hover: hover,\n unconstrained: unconstrained,\n };\n }\n function testTooltips(parsed, entry) {\n if (entry === false) {\n return;\n }\n if (entry === true || isValidPartialFormatter(entry)) {\n parsed.tooltips = [];\n for (var i = 0; i < parsed.handles; i++) {\n parsed.tooltips.push(entry);\n }\n }\n else {\n entry = asArray(entry);\n if (entry.length !== parsed.handles) {\n throw new Error(\"noUiSlider: must pass a formatter for all handles.\");\n }\n entry.forEach(function (formatter) {\n if (typeof formatter !== \"boolean\" && !isValidPartialFormatter(formatter)) {\n throw new Error(\"noUiSlider: 'tooltips' must be passed a formatter or 'false'.\");\n }\n });\n parsed.tooltips = entry;\n }\n }\n function testHandleAttributes(parsed, entry) {\n if (entry.length !== parsed.handles) {\n throw new Error(\"noUiSlider: must pass a attributes for all handles.\");\n }\n parsed.handleAttributes = entry;\n }\n function testAriaFormat(parsed, entry) {\n if (!isValidPartialFormatter(entry)) {\n throw new Error(\"noUiSlider: 'ariaFormat' requires 'to' method.\");\n }\n parsed.ariaFormat = entry;\n }\n function testFormat(parsed, entry) {\n if (!isValidFormatter(entry)) {\n throw new Error(\"noUiSlider: 'format' requires 'to' and 'from' methods.\");\n }\n parsed.format = entry;\n }\n function testKeyboardSupport(parsed, entry) {\n if (typeof entry !== \"boolean\") {\n throw new Error(\"noUiSlider: 'keyboardSupport' option must be a boolean.\");\n }\n parsed.keyboardSupport = entry;\n }\n function testDocumentElement(parsed, entry) {\n // This is an advanced option. Passed values are used without validation.\n parsed.documentElement = entry;\n }\n function testCssPrefix(parsed, entry) {\n if (typeof entry !== \"string\" && entry !== false) {\n throw new Error(\"noUiSlider: 'cssPrefix' must be a string or `false`.\");\n }\n parsed.cssPrefix = entry;\n }\n function testCssClasses(parsed, entry) {\n if (typeof entry !== \"object\") {\n throw new Error(\"noUiSlider: 'cssClasses' must be an object.\");\n }\n if (typeof parsed.cssPrefix === \"string\") {\n parsed.cssClasses = {};\n Object.keys(entry).forEach(function (key) {\n parsed.cssClasses[key] = parsed.cssPrefix + entry[key];\n });\n }\n else {\n parsed.cssClasses = entry;\n }\n }\n // Test all developer settings and parse to assumption-safe values.\n function testOptions(options) {\n // To prove a fix for #537, freeze options here.\n // If the object is modified, an error will be thrown.\n // Object.freeze(options);\n var parsed = {\n margin: null,\n limit: null,\n padding: null,\n animate: true,\n animationDuration: 300,\n ariaFormat: defaultFormatter,\n format: defaultFormatter,\n };\n // Tests are executed in the order they are presented here.\n var tests = {\n step: { r: false, t: testStep },\n keyboardPageMultiplier: { r: false, t: testKeyboardPageMultiplier },\n keyboardMultiplier: { r: false, t: testKeyboardMultiplier },\n keyboardDefaultStep: { r: false, t: testKeyboardDefaultStep },\n start: { r: true, t: testStart },\n connect: { r: true, t: testConnect },\n direction: { r: true, t: testDirection },\n snap: { r: false, t: testSnap },\n animate: { r: false, t: testAnimate },\n animationDuration: { r: false, t: testAnimationDuration },\n range: { r: true, t: testRange },\n orientation: { r: false, t: testOrientation },\n margin: { r: false, t: testMargin },\n limit: { r: false, t: testLimit },\n padding: { r: false, t: testPadding },\n behaviour: { r: true, t: testBehaviour },\n ariaFormat: { r: false, t: testAriaFormat },\n format: { r: false, t: testFormat },\n tooltips: { r: false, t: testTooltips },\n keyboardSupport: { r: true, t: testKeyboardSupport },\n documentElement: { r: false, t: testDocumentElement },\n cssPrefix: { r: true, t: testCssPrefix },\n cssClasses: { r: true, t: testCssClasses },\n handleAttributes: { r: false, t: testHandleAttributes },\n };\n var defaults = {\n connect: false,\n direction: \"ltr\",\n behaviour: \"tap\",\n orientation: \"horizontal\",\n keyboardSupport: true,\n cssPrefix: \"noUi-\",\n cssClasses: cssClasses,\n keyboardPageMultiplier: 5,\n keyboardMultiplier: 1,\n keyboardDefaultStep: 10,\n };\n // AriaFormat defaults to regular format, if any.\n if (options.format && !options.ariaFormat) {\n options.ariaFormat = options.format;\n }\n // Run all options through a testing mechanism to ensure correct\n // input. It should be noted that options might get modified to\n // be handled properly. E.g. wrapping integers in arrays.\n Object.keys(tests).forEach(function (name) {\n // If the option isn't set, but it is required, throw an error.\n if (!isSet(options[name]) && defaults[name] === undefined) {\n if (tests[name].r) {\n throw new Error(\"noUiSlider: '\" + name + \"' is required.\");\n }\n return;\n }\n tests[name].t(parsed, !isSet(options[name]) ? defaults[name] : options[name]);\n });\n // Forward pips options\n parsed.pips = options.pips;\n // All recent browsers accept unprefixed transform.\n // We need -ms- for IE9 and -webkit- for older Android;\n // Assume use of -webkit- if unprefixed and -ms- are not supported.\n // https://caniuse.com/#feat=transforms2d\n var d = document.createElement(\"div\");\n var msPrefix = d.style.msTransform !== undefined;\n var noPrefix = d.style.transform !== undefined;\n parsed.transformRule = noPrefix ? \"transform\" : msPrefix ? \"msTransform\" : \"webkitTransform\";\n // Pips don't move, so we can place them using left/top.\n var styles = [\n [\"left\", \"top\"],\n [\"right\", \"bottom\"],\n ];\n parsed.style = styles[parsed.dir][parsed.ort];\n return parsed;\n }\n //endregion\n function scope(target, options, originalOptions) {\n var actions = getActions();\n var supportsTouchActionNone = getSupportsTouchActionNone();\n var supportsPassive = supportsTouchActionNone && getSupportsPassive();\n // All variables local to 'scope' are prefixed with 'scope_'\n // Slider DOM Nodes\n var scope_Target = target;\n var scope_Base;\n var scope_Handles;\n var scope_Connects;\n var scope_Pips;\n var scope_Tooltips;\n // Slider state values\n var scope_Spectrum = options.spectrum;\n var scope_Values = [];\n var scope_Locations = [];\n var scope_HandleNumbers = [];\n var scope_ActiveHandlesCount = 0;\n var scope_Events = {};\n // Document Nodes\n var scope_Document = target.ownerDocument;\n var scope_DocumentElement = options.documentElement || scope_Document.documentElement;\n var scope_Body = scope_Document.body;\n // For horizontal sliders in standard ltr documents,\n // make .noUi-origin overflow to the left so the document doesn't scroll.\n var scope_DirOffset = scope_Document.dir === \"rtl\" || options.ort === 1 ? 0 : 100;\n // Creates a node, adds it to target, returns the new node.\n function addNodeTo(addTarget, className) {\n var div = scope_Document.createElement(\"div\");\n if (className) {\n addClass(div, className);\n }\n addTarget.appendChild(div);\n return div;\n }\n // Append a origin to the base\n function addOrigin(base, handleNumber) {\n var origin = addNodeTo(base, options.cssClasses.origin);\n var handle = addNodeTo(origin, options.cssClasses.handle);\n addNodeTo(handle, options.cssClasses.touchArea);\n handle.setAttribute(\"data-handle\", String(handleNumber));\n if (options.keyboardSupport) {\n // https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/tabindex\n // 0 = focusable and reachable\n handle.setAttribute(\"tabindex\", \"0\");\n handle.addEventListener(\"keydown\", function (event) {\n return eventKeydown(event, handleNumber);\n });\n }\n if (options.handleAttributes !== undefined) {\n var attributes_1 = options.handleAttributes[handleNumber];\n Object.keys(attributes_1).forEach(function (attribute) {\n handle.setAttribute(attribute, attributes_1[attribute]);\n });\n }\n handle.setAttribute(\"role\", \"slider\");\n handle.setAttribute(\"aria-orientation\", options.ort ? \"vertical\" : \"horizontal\");\n if (handleNumber === 0) {\n addClass(handle, options.cssClasses.handleLower);\n }\n else if (handleNumber === options.handles - 1) {\n addClass(handle, options.cssClasses.handleUpper);\n }\n origin.handle = handle;\n return origin;\n }\n // Insert nodes for connect elements\n function addConnect(base, add) {\n if (!add) {\n return false;\n }\n return addNodeTo(base, options.cssClasses.connect);\n }\n // Add handles to the slider base.\n function addElements(connectOptions, base) {\n var connectBase = addNodeTo(base, options.cssClasses.connects);\n scope_Handles = [];\n scope_Connects = [];\n scope_Connects.push(addConnect(connectBase, connectOptions[0]));\n // [::::O====O====O====]\n // connectOptions = [0, 1, 1, 1]\n for (var i = 0; i < options.handles; i++) {\n // Keep a list of all added handles.\n scope_Handles.push(addOrigin(base, i));\n scope_HandleNumbers[i] = i;\n scope_Connects.push(addConnect(connectBase, connectOptions[i + 1]));\n }\n }\n // Initialize a single slider.\n function addSlider(addTarget) {\n // Apply classes and data to the target.\n addClass(addTarget, options.cssClasses.target);\n if (options.dir === 0) {\n addClass(addTarget, options.cssClasses.ltr);\n }\n else {\n addClass(addTarget, options.cssClasses.rtl);\n }\n if (options.ort === 0) {\n addClass(addTarget, options.cssClasses.horizontal);\n }\n else {\n addClass(addTarget, options.cssClasses.vertical);\n }\n var textDirection = getComputedStyle(addTarget).direction;\n if (textDirection === \"rtl\") {\n addClass(addTarget, options.cssClasses.textDirectionRtl);\n }\n else {\n addClass(addTarget, options.cssClasses.textDirectionLtr);\n }\n return addNodeTo(addTarget, options.cssClasses.base);\n }\n function addTooltip(handle, handleNumber) {\n if (!options.tooltips || !options.tooltips[handleNumber]) {\n return false;\n }\n return addNodeTo(handle.firstChild, options.cssClasses.tooltip);\n }\n function isSliderDisabled() {\n return scope_Target.hasAttribute(\"disabled\");\n }\n // Disable the slider dragging if any handle is disabled\n function isHandleDisabled(handleNumber) {\n var handleOrigin = scope_Handles[handleNumber];\n return handleOrigin.hasAttribute(\"disabled\");\n }\n function disable(handleNumber) {\n if (handleNumber !== null && handleNumber !== undefined) {\n scope_Handles[handleNumber].setAttribute(\"disabled\", \"\");\n scope_Handles[handleNumber].handle.removeAttribute(\"tabindex\");\n }\n else {\n scope_Target.setAttribute(\"disabled\", \"\");\n scope_Handles.forEach(function (handle) {\n handle.handle.removeAttribute(\"tabindex\");\n });\n }\n }\n function enable(handleNumber) {\n if (handleNumber !== null && handleNumber !== undefined) {\n scope_Handles[handleNumber].removeAttribute(\"disabled\");\n scope_Handles[handleNumber].handle.setAttribute(\"tabindex\", \"0\");\n }\n else {\n scope_Target.removeAttribute(\"disabled\");\n scope_Handles.forEach(function (handle) {\n handle.removeAttribute(\"disabled\");\n handle.handle.setAttribute(\"tabindex\", \"0\");\n });\n }\n }\n function removeTooltips() {\n if (scope_Tooltips) {\n removeEvent(\"update\" + INTERNAL_EVENT_NS.tooltips);\n scope_Tooltips.forEach(function (tooltip) {\n if (tooltip) {\n removeElement(tooltip);\n }\n });\n scope_Tooltips = null;\n }\n }\n // The tooltips option is a shorthand for using the 'update' event.\n function tooltips() {\n removeTooltips();\n // Tooltips are added with options.tooltips in original order.\n scope_Tooltips = scope_Handles.map(addTooltip);\n bindEvent(\"update\" + INTERNAL_EVENT_NS.tooltips, function (values, handleNumber, unencoded) {\n if (!scope_Tooltips || !options.tooltips) {\n return;\n }\n if (scope_Tooltips[handleNumber] === false) {\n return;\n }\n var formattedValue = values[handleNumber];\n if (options.tooltips[handleNumber] !== true) {\n formattedValue = options.tooltips[handleNumber].to(unencoded[handleNumber]);\n }\n scope_Tooltips[handleNumber].innerHTML = formattedValue;\n });\n }\n function aria() {\n removeEvent(\"update\" + INTERNAL_EVENT_NS.aria);\n bindEvent(\"update\" + INTERNAL_EVENT_NS.aria, function (values, handleNumber, unencoded, tap, positions) {\n // Update Aria Values for all handles, as a change in one changes min and max values for the next.\n scope_HandleNumbers.forEach(function (index) {\n var handle = scope_Handles[index];\n var min = checkHandlePosition(scope_Locations, index, 0, true, true, true);\n var max = checkHandlePosition(scope_Locations, index, 100, true, true, true);\n var now = positions[index];\n // Formatted value for display\n var text = String(options.ariaFormat.to(unencoded[index]));\n // Map to slider range values\n min = scope_Spectrum.fromStepping(min).toFixed(1);\n max = scope_Spectrum.fromStepping(max).toFixed(1);\n now = scope_Spectrum.fromStepping(now).toFixed(1);\n handle.children[0].setAttribute(\"aria-valuemin\", min);\n handle.children[0].setAttribute(\"aria-valuemax\", max);\n handle.children[0].setAttribute(\"aria-valuenow\", now);\n handle.children[0].setAttribute(\"aria-valuetext\", text);\n });\n });\n }\n function getGroup(pips) {\n // Use the range.\n if (pips.mode === exports.PipsMode.Range || pips.mode === exports.PipsMode.Steps) {\n return scope_Spectrum.xVal;\n }\n if (pips.mode === exports.PipsMode.Count) {\n if (pips.values < 2) {\n throw new Error(\"noUiSlider: 'values' (>= 2) required for mode 'count'.\");\n }\n // Divide 0 - 100 in 'count' parts.\n var interval = pips.values - 1;\n var spread = 100 / interval;\n var values = [];\n // List these parts and have them handled as 'positions'.\n while (interval--) {\n values[interval] = interval * spread;\n }\n values.push(100);\n return mapToRange(values, pips.stepped);\n }\n if (pips.mode === exports.PipsMode.Positions) {\n // Map all percentages to on-range values.\n return mapToRange(pips.values, pips.stepped);\n }\n if (pips.mode === exports.PipsMode.Values) {\n // If the value must be stepped, it needs to be converted to a percentage first.\n if (pips.stepped) {\n return pips.values.map(function (value) {\n // Convert to percentage, apply step, return to value.\n return scope_Spectrum.fromStepping(scope_Spectrum.getStep(scope_Spectrum.toStepping(value)));\n });\n }\n // Otherwise, we can simply use the values.\n return pips.values;\n }\n return []; // pips.mode = never\n }\n function mapToRange(values, stepped) {\n return values.map(function (value) {\n return scope_Spectrum.fromStepping(stepped ? scope_Spectrum.getStep(value) : value);\n });\n }\n function generateSpread(pips) {\n function safeIncrement(value, increment) {\n // Avoid floating point variance by dropping the smallest decimal places.\n return Number((value + increment).toFixed(7));\n }\n var group = getGroup(pips);\n var indexes = {};\n var firstInRange = scope_Spectrum.xVal[0];\n var lastInRange = scope_Spectrum.xVal[scope_Spectrum.xVal.length - 1];\n var ignoreFirst = false;\n var ignoreLast = false;\n var prevPct = 0;\n // Create a copy of the group, sort it and filter away all duplicates.\n group = unique(group.slice().sort(function (a, b) {\n return a - b;\n }));\n // Make sure the range starts with the first element.\n if (group[0] !== firstInRange) {\n group.unshift(firstInRange);\n ignoreFirst = true;\n }\n // Likewise for the last one.\n if (group[group.length - 1] !== lastInRange) {\n group.push(lastInRange);\n ignoreLast = true;\n }\n group.forEach(function (current, index) {\n // Get the current step and the lower + upper positions.\n var step;\n var i;\n var q;\n var low = current;\n var high = group[index + 1];\n var newPct;\n var pctDifference;\n var pctPos;\n var type;\n var steps;\n var realSteps;\n var stepSize;\n var isSteps = pips.mode === exports.PipsMode.Steps;\n // When using 'steps' mode, use the provided steps.\n // Otherwise, we'll step on to the next subrange.\n if (isSteps) {\n step = scope_Spectrum.xNumSteps[index];\n }\n // Default to a 'full' step.\n if (!step) {\n step = high - low;\n }\n // If high is undefined we are at the last subrange. Make sure it iterates once (#1088)\n if (high === undefined) {\n high = low;\n }\n // Make sure step isn't 0, which would cause an infinite loop (#654)\n step = Math.max(step, 0.0000001);\n // Find all steps in the subrange.\n for (i = low; i <= high; i = safeIncrement(i, step)) {\n // Get the percentage value for the current step,\n // calculate the size for the subrange.\n newPct = scope_Spectrum.toStepping(i);\n pctDifference = newPct - prevPct;\n steps = pctDifference / (pips.density || 1);\n realSteps = Math.round(steps);\n // This ratio represents the amount of percentage-space a point indicates.\n // For a density 1 the points/percentage = 1. For density 2, that percentage needs to be re-divided.\n // Round the percentage offset to an even number, then divide by two\n // to spread the offset on both sides of the range.\n stepSize = pctDifference / realSteps;\n // Divide all points evenly, adding the correct number to this subrange.\n // Run up to <= so that 100% gets a point, event if ignoreLast is set.\n for (q = 1; q <= realSteps; q += 1) {\n // The ratio between the rounded value and the actual size might be ~1% off.\n // Correct the percentage offset by the number of points\n // per subrange. density = 1 will result in 100 points on the\n // full range, 2 for 50, 4 for 25, etc.\n pctPos = prevPct + q * stepSize;\n indexes[pctPos.toFixed(5)] = [scope_Spectrum.fromStepping(pctPos), 0];\n }\n // Determine the point type.\n type = group.indexOf(i) > -1 ? exports.PipsType.LargeValue : isSteps ? exports.PipsType.SmallValue : exports.PipsType.NoValue;\n // Enforce the 'ignoreFirst' option by overwriting the type for 0.\n if (!index && ignoreFirst && i !== high) {\n type = 0;\n }\n if (!(i === high && ignoreLast)) {\n // Mark the 'type' of this point. 0 = plain, 1 = real value, 2 = step value.\n indexes[newPct.toFixed(5)] = [i, type];\n }\n // Update the percentage count.\n prevPct = newPct;\n }\n });\n return indexes;\n }\n function addMarking(spread, filterFunc, formatter) {\n var _a, _b;\n var element = scope_Document.createElement(\"div\");\n var valueSizeClasses = (_a = {},\n _a[exports.PipsType.None] = \"\",\n _a[exports.PipsType.NoValue] = options.cssClasses.valueNormal,\n _a[exports.PipsType.LargeValue] = options.cssClasses.valueLarge,\n _a[exports.PipsType.SmallValue] = options.cssClasses.valueSub,\n _a);\n var markerSizeClasses = (_b = {},\n _b[exports.PipsType.None] = \"\",\n _b[exports.PipsType.NoValue] = options.cssClasses.markerNormal,\n _b[exports.PipsType.LargeValue] = options.cssClasses.markerLarge,\n _b[exports.PipsType.SmallValue] = options.cssClasses.markerSub,\n _b);\n var valueOrientationClasses = [options.cssClasses.valueHorizontal, options.cssClasses.valueVertical];\n var markerOrientationClasses = [options.cssClasses.markerHorizontal, options.cssClasses.markerVertical];\n addClass(element, options.cssClasses.pips);\n addClass(element, options.ort === 0 ? options.cssClasses.pipsHorizontal : options.cssClasses.pipsVertical);\n function getClasses(type, source) {\n var a = source === options.cssClasses.value;\n var orientationClasses = a ? valueOrientationClasses : markerOrientationClasses;\n var sizeClasses = a ? valueSizeClasses : markerSizeClasses;\n return source + \" \" + orientationClasses[options.ort] + \" \" + sizeClasses[type];\n }\n function addSpread(offset, value, type) {\n // Apply the filter function, if it is set.\n type = filterFunc ? filterFunc(value, type) : type;\n if (type === exports.PipsType.None) {\n return;\n }\n // Add a marker for every point\n var node = addNodeTo(element, false);\n node.className = getClasses(type, options.cssClasses.marker);\n node.style[options.style] = offset + \"%\";\n // Values are only appended for points marked '1' or '2'.\n if (type > exports.PipsType.NoValue) {\n node = addNodeTo(element, false);\n node.className = getClasses(type, options.cssClasses.value);\n node.setAttribute(\"data-value\", String(value));\n node.style[options.style] = offset + \"%\";\n node.innerHTML = String(formatter.to(value));\n }\n }\n // Append all points.\n Object.keys(spread).forEach(function (offset) {\n addSpread(offset, spread[offset][0], spread[offset][1]);\n });\n return element;\n }\n function removePips() {\n if (scope_Pips) {\n removeElement(scope_Pips);\n scope_Pips = null;\n }\n }\n function pips(pips) {\n // Fix #669\n removePips();\n var spread = generateSpread(pips);\n var filter = pips.filter;\n var format = pips.format || {\n to: function (value) {\n return String(Math.round(value));\n },\n };\n scope_Pips = scope_Target.appendChild(addMarking(spread, filter, format));\n return scope_Pips;\n }\n // Shorthand for base dimensions.\n function baseSize() {\n var rect = scope_Base.getBoundingClientRect();\n var alt = (\"offset\" + [\"Width\", \"Height\"][options.ort]);\n return options.ort === 0 ? rect.width || scope_Base[alt] : rect.height || scope_Base[alt];\n }\n // Handler for attaching events trough a proxy.\n function attachEvent(events, element, callback, data) {\n // This function can be used to 'filter' events to the slider.\n // element is a node, not a nodeList\n var method = function (event) {\n var e = fixEvent(event, data.pageOffset, data.target || element);\n // fixEvent returns false if this event has a different target\n // when handling (multi-) touch events;\n if (!e) {\n return false;\n }\n // doNotReject is passed by all end events to make sure released touches\n // are not rejected, leaving the slider \"stuck\" to the cursor;\n if (isSliderDisabled() && !data.doNotReject) {\n return false;\n }\n // Stop if an active 'tap' transition is taking place.\n if (hasClass(scope_Target, options.cssClasses.tap) && !data.doNotReject) {\n return false;\n }\n // Ignore right or middle clicks on start #454\n if (events === actions.start && e.buttons !== undefined && e.buttons > 1) {\n return false;\n }\n // Ignore right or middle clicks on start #454\n if (data.hover && e.buttons) {\n return false;\n }\n // 'supportsPassive' is only true if a browser also supports touch-action: none in CSS.\n // iOS safari does not, so it doesn't get to benefit from passive scrolling. iOS does support\n // touch-action: manipulation, but that allows panning, which breaks\n // sliders after zooming/on non-responsive pages.\n // See: https://bugs.webkit.org/show_bug.cgi?id=133112\n if (!supportsPassive) {\n e.preventDefault();\n }\n e.calcPoint = e.points[options.ort];\n // Call the event handler with the event [ and additional data ].\n callback(e, data);\n return;\n };\n var methods = [];\n // Bind a closure on the target for every event type.\n events.split(\" \").forEach(function (eventName) {\n element.addEventListener(eventName, method, supportsPassive ? { passive: true } : false);\n methods.push([eventName, method]);\n });\n return methods;\n }\n // Provide a clean event with standardized offset values.\n function fixEvent(e, pageOffset, eventTarget) {\n // Filter the event to register the type, which can be\n // touch, mouse or pointer. Offset changes need to be\n // made on an event specific basis.\n var touch = e.type.indexOf(\"touch\") === 0;\n var mouse = e.type.indexOf(\"mouse\") === 0;\n var pointer = e.type.indexOf(\"pointer\") === 0;\n var x = 0;\n var y = 0;\n // IE10 implemented pointer events with a prefix;\n if (e.type.indexOf(\"MSPointer\") === 0) {\n pointer = true;\n }\n // Erroneous events seem to be passed in occasionally on iOS/iPadOS after user finishes interacting with\n // the slider. They appear to be of type MouseEvent, yet they don't have usual properties set. Ignore\n // events that have no touches or buttons associated with them. (#1057, #1079, #1095)\n if (e.type === \"mousedown\" && !e.buttons && !e.touches) {\n return false;\n }\n // The only thing one handle should be concerned about is the touches that originated on top of it.\n if (touch) {\n // Returns true if a touch originated on the target.\n var isTouchOnTarget = function (checkTouch) {\n var target = checkTouch.target;\n return (target === eventTarget ||\n eventTarget.contains(target) ||\n (e.composed && e.composedPath().shift() === eventTarget));\n };\n // In the case of touchstart events, we need to make sure there is still no more than one\n // touch on the target so we look amongst all touches.\n if (e.type === \"touchstart\") {\n var targetTouches = Array.prototype.filter.call(e.touches, isTouchOnTarget);\n // Do not support more than one touch per handle.\n if (targetTouches.length > 1) {\n return false;\n }\n x = targetTouches[0].pageX;\n y = targetTouches[0].pageY;\n }\n else {\n // In the other cases, find on changedTouches is enough.\n var targetTouch = Array.prototype.find.call(e.changedTouches, isTouchOnTarget);\n // Cancel if the target touch has not moved.\n if (!targetTouch) {\n return false;\n }\n x = targetTouch.pageX;\n y = targetTouch.pageY;\n }\n }\n pageOffset = pageOffset || getPageOffset(scope_Document);\n if (mouse || pointer) {\n x = e.clientX + pageOffset.x;\n y = e.clientY + pageOffset.y;\n }\n e.pageOffset = pageOffset;\n e.points = [x, y];\n e.cursor = mouse || pointer; // Fix #435\n return e;\n }\n // Translate a coordinate in the document to a percentage on the slider\n function calcPointToPercentage(calcPoint) {\n var location = calcPoint - offset(scope_Base, options.ort);\n var proposal = (location * 100) / baseSize();\n // Clamp proposal between 0% and 100%\n // Out-of-bound coordinates may occur when .noUi-base pseudo-elements\n // are used (e.g. contained handles feature)\n proposal = limit(proposal);\n return options.dir ? 100 - proposal : proposal;\n }\n // Find handle closest to a certain percentage on the slider\n function getClosestHandle(clickedPosition) {\n var smallestDifference = 100;\n var handleNumber = false;\n scope_Handles.forEach(function (handle, index) {\n // Disabled handles are ignored\n if (isHandleDisabled(index)) {\n return;\n }\n var handlePosition = scope_Locations[index];\n var differenceWithThisHandle = Math.abs(handlePosition - clickedPosition);\n // Initial state\n var clickAtEdge = differenceWithThisHandle === 100 && smallestDifference === 100;\n // Difference with this handle is smaller than the previously checked handle\n var isCloser = differenceWithThisHandle < smallestDifference;\n var isCloserAfter = differenceWithThisHandle <= smallestDifference && clickedPosition > handlePosition;\n if (isCloser || isCloserAfter || clickAtEdge) {\n handleNumber = index;\n smallestDifference = differenceWithThisHandle;\n }\n });\n return handleNumber;\n }\n // Fire 'end' when a mouse or pen leaves the document.\n function documentLeave(event, data) {\n if (event.type === \"mouseout\" &&\n event.target.nodeName === \"HTML\" &&\n event.relatedTarget === null) {\n eventEnd(event, data);\n }\n }\n // Handle movement on document for handle and range drag.\n function eventMove(event, data) {\n // Fix #498\n // Check value of .buttons in 'start' to work around a bug in IE10 mobile (data.buttonsProperty).\n // https://connect.microsoft.com/IE/feedback/details/927005/mobile-ie10-windows-phone-buttons-property-of-pointermove-event-always-zero\n // IE9 has .buttons and .which zero on mousemove.\n // Firefox breaks the spec MDN defines.\n if (navigator.appVersion.indexOf(\"MSIE 9\") === -1 && event.buttons === 0 && data.buttonsProperty !== 0) {\n return eventEnd(event, data);\n }\n // Check if we are moving up or down\n var movement = (options.dir ? -1 : 1) * (event.calcPoint - data.startCalcPoint);\n // Convert the movement into a percentage of the slider width/height\n var proposal = (movement * 100) / data.baseSize;\n moveHandles(movement > 0, proposal, data.locations, data.handleNumbers, data.connect);\n }\n // Unbind move events on document, call callbacks.\n function eventEnd(event, data) {\n // The handle is no longer active, so remove the class.\n if (data.handle) {\n removeClass(data.handle, options.cssClasses.active);\n scope_ActiveHandlesCount -= 1;\n }\n // Unbind the move and end events, which are added on 'start'.\n data.listeners.forEach(function (c) {\n scope_DocumentElement.removeEventListener(c[0], c[1]);\n });\n if (scope_ActiveHandlesCount === 0) {\n // Remove dragging class.\n removeClass(scope_Target, options.cssClasses.drag);\n setZindex();\n // Remove cursor styles and text-selection events bound to the body.\n if (event.cursor) {\n scope_Body.style.cursor = \"\";\n scope_Body.removeEventListener(\"selectstart\", preventDefault);\n }\n }\n if (options.events.smoothSteps) {\n data.handleNumbers.forEach(function (handleNumber) {\n setHandle(handleNumber, scope_Locations[handleNumber], true, true, false, false);\n });\n data.handleNumbers.forEach(function (handleNumber) {\n fireEvent(\"update\", handleNumber);\n });\n }\n data.handleNumbers.forEach(function (handleNumber) {\n fireEvent(\"change\", handleNumber);\n fireEvent(\"set\", handleNumber);\n fireEvent(\"end\", handleNumber);\n });\n }\n // Bind move events on document.\n function eventStart(event, data) {\n // Ignore event if any handle is disabled\n if (data.handleNumbers.some(isHandleDisabled)) {\n return;\n }\n var handle;\n if (data.handleNumbers.length === 1) {\n var handleOrigin = scope_Handles[data.handleNumbers[0]];\n handle = handleOrigin.children[0];\n scope_ActiveHandlesCount += 1;\n // Mark the handle as 'active' so it can be styled.\n addClass(handle, options.cssClasses.active);\n }\n // A drag should never propagate up to the 'tap' event.\n event.stopPropagation();\n // Record the event listeners.\n var listeners = [];\n // Attach the move and end events.\n var moveEvent = attachEvent(actions.move, scope_DocumentElement, eventMove, {\n // The event target has changed so we need to propagate the original one so that we keep\n // relying on it to extract target touches.\n target: event.target,\n handle: handle,\n connect: data.connect,\n listeners: listeners,\n startCalcPoint: event.calcPoint,\n baseSize: baseSize(),\n pageOffset: event.pageOffset,\n handleNumbers: data.handleNumbers,\n buttonsProperty: event.buttons,\n locations: scope_Locations.slice(),\n });\n var endEvent = attachEvent(actions.end, scope_DocumentElement, eventEnd, {\n target: event.target,\n handle: handle,\n listeners: listeners,\n doNotReject: true,\n handleNumbers: data.handleNumbers,\n });\n var outEvent = attachEvent(\"mouseout\", scope_DocumentElement, documentLeave, {\n target: event.target,\n handle: handle,\n listeners: listeners,\n doNotReject: true,\n handleNumbers: data.handleNumbers,\n });\n // We want to make sure we pushed the listeners in the listener list rather than creating\n // a new one as it has already been passed to the event handlers.\n listeners.push.apply(listeners, moveEvent.concat(endEvent, outEvent));\n // Text selection isn't an issue on touch devices,\n // so adding cursor styles can be skipped.\n if (event.cursor) {\n // Prevent the 'I' cursor and extend the range-drag cursor.\n scope_Body.style.cursor = getComputedStyle(event.target).cursor;\n // Mark the target with a dragging state.\n if (scope_Handles.length > 1) {\n addClass(scope_Target, options.cssClasses.drag);\n }\n // Prevent text selection when dragging the handles.\n // In noUiSlider <= 9.2.0, this was handled by calling preventDefault on mouse/touch start/move,\n // which is scroll blocking. The selectstart event is supported by FireFox starting from version 52,\n // meaning the only holdout is iOS Safari. This doesn't matter: text selection isn't triggered there.\n // The 'cursor' flag is false.\n // See: http://caniuse.com/#search=selectstart\n scope_Body.addEventListener(\"selectstart\", preventDefault, false);\n }\n data.handleNumbers.forEach(function (handleNumber) {\n fireEvent(\"start\", handleNumber);\n });\n }\n // Move closest handle to tapped location.\n function eventTap(event) {\n // The tap event shouldn't propagate up\n event.stopPropagation();\n var proposal = calcPointToPercentage(event.calcPoint);\n var handleNumber = getClosestHandle(proposal);\n // Tackle the case that all handles are 'disabled'.\n if (handleNumber === false) {\n return;\n }\n // Flag the slider as it is now in a transitional state.\n // Transition takes a configurable amount of ms (default 300). Re-enable the slider after that.\n if (!options.events.snap) {\n addClassFor(scope_Target, options.cssClasses.tap, options.animationDuration);\n }\n setHandle(handleNumber, proposal, true, true);\n setZindex();\n fireEvent(\"slide\", handleNumber, true);\n fireEvent(\"update\", handleNumber, true);\n if (!options.events.snap) {\n fireEvent(\"change\", handleNumber, true);\n fireEvent(\"set\", handleNumber, true);\n }\n else {\n eventStart(event, { handleNumbers: [handleNumber] });\n }\n }\n // Fires a 'hover' event for a hovered mouse/pen position.\n function eventHover(event) {\n var proposal = calcPointToPercentage(event.calcPoint);\n var to = scope_Spectrum.getStep(proposal);\n var value = scope_Spectrum.fromStepping(to);\n Object.keys(scope_Events).forEach(function (targetEvent) {\n if (\"hover\" === targetEvent.split(\".\")[0]) {\n scope_Events[targetEvent].forEach(function (callback) {\n callback.call(scope_Self, value);\n });\n }\n });\n }\n // Handles keydown on focused handles\n // Don't move the document when pressing arrow keys on focused handles\n function eventKeydown(event, handleNumber) {\n if (isSliderDisabled() || isHandleDisabled(handleNumber)) {\n return false;\n }\n var horizontalKeys = [\"Left\", \"Right\"];\n var verticalKeys = [\"Down\", \"Up\"];\n var largeStepKeys = [\"PageDown\", \"PageUp\"];\n var edgeKeys = [\"Home\", \"End\"];\n if (options.dir && !options.ort) {\n // On an right-to-left slider, the left and right keys act inverted\n horizontalKeys.reverse();\n }\n else if (options.ort && !options.dir) {\n // On a top-to-bottom slider, the up and down keys act inverted\n verticalKeys.reverse();\n largeStepKeys.reverse();\n }\n // Strip \"Arrow\" for IE compatibility. https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/key\n var key = event.key.replace(\"Arrow\", \"\");\n var isLargeDown = key === largeStepKeys[0];\n var isLargeUp = key === largeStepKeys[1];\n var isDown = key === verticalKeys[0] || key === horizontalKeys[0] || isLargeDown;\n var isUp = key === verticalKeys[1] || key === horizontalKeys[1] || isLargeUp;\n var isMin = key === edgeKeys[0];\n var isMax = key === edgeKeys[1];\n if (!isDown && !isUp && !isMin && !isMax) {\n return true;\n }\n event.preventDefault();\n var to;\n if (isUp || isDown) {\n var direction = isDown ? 0 : 1;\n var steps = getNextStepsForHandle(handleNumber);\n var step = steps[direction];\n // At the edge of a slider, do nothing\n if (step === null) {\n return false;\n }\n // No step set, use the default of 10% of the sub-range\n if (step === false) {\n step = scope_Spectrum.getDefaultStep(scope_Locations[handleNumber], isDown, options.keyboardDefaultStep);\n }\n if (isLargeUp || isLargeDown) {\n step *= options.keyboardPageMultiplier;\n }\n else {\n step *= options.keyboardMultiplier;\n }\n // Step over zero-length ranges (#948);\n step = Math.max(step, 0.0000001);\n // Decrement for down steps\n step = (isDown ? -1 : 1) * step;\n to = scope_Values[handleNumber] + step;\n }\n else if (isMax) {\n // End key\n to = options.spectrum.xVal[options.spectrum.xVal.length - 1];\n }\n else {\n // Home key\n to = options.spectrum.xVal[0];\n }\n setHandle(handleNumber, scope_Spectrum.toStepping(to), true, true);\n fireEvent(\"slide\", handleNumber);\n fireEvent(\"update\", handleNumber);\n fireEvent(\"change\", handleNumber);\n fireEvent(\"set\", handleNumber);\n return false;\n }\n // Attach events to several slider parts.\n function bindSliderEvents(behaviour) {\n // Attach the standard drag event to the handles.\n if (!behaviour.fixed) {\n scope_Handles.forEach(function (handle, index) {\n // These events are only bound to the visual handle\n // element, not the 'real' origin element.\n attachEvent(actions.start, handle.children[0], eventStart, {\n handleNumbers: [index],\n });\n });\n }\n // Attach the tap event to the slider base.\n if (behaviour.tap) {\n attachEvent(actions.start, scope_Base, eventTap, {});\n }\n // Fire hover events\n if (behaviour.hover) {\n attachEvent(actions.move, scope_Base, eventHover, {\n hover: true,\n });\n }\n // Make the range draggable.\n if (behaviour.drag) {\n scope_Connects.forEach(function (connect, index) {\n if (connect === false || index === 0 || index === scope_Connects.length - 1) {\n return;\n }\n var handleBefore = scope_Handles[index - 1];\n var handleAfter = scope_Handles[index];\n var eventHolders = [connect];\n var handlesToDrag = [handleBefore, handleAfter];\n var handleNumbersToDrag = [index - 1, index];\n addClass(connect, options.cssClasses.draggable);\n // When the range is fixed, the entire range can\n // be dragged by the handles. The handle in the first\n // origin will propagate the start event upward,\n // but it needs to be bound manually on the other.\n if (behaviour.fixed) {\n eventHolders.push(handleBefore.children[0]);\n eventHolders.push(handleAfter.children[0]);\n }\n if (behaviour.dragAll) {\n handlesToDrag = scope_Handles;\n handleNumbersToDrag = scope_HandleNumbers;\n }\n eventHolders.forEach(function (eventHolder) {\n attachEvent(actions.start, eventHolder, eventStart, {\n handles: handlesToDrag,\n handleNumbers: handleNumbersToDrag,\n connect: connect,\n });\n });\n });\n }\n }\n // Attach an event to this slider, possibly including a namespace\n function bindEvent(namespacedEvent, callback) {\n scope_Events[namespacedEvent] = scope_Events[namespacedEvent] || [];\n scope_Events[namespacedEvent].push(callback);\n // If the event bound is 'update,' fire it immediately for all handles.\n if (namespacedEvent.split(\".\")[0] === \"update\") {\n scope_Handles.forEach(function (a, index) {\n fireEvent(\"update\", index);\n });\n }\n }\n function isInternalNamespace(namespace) {\n return namespace === INTERNAL_EVENT_NS.aria || namespace === INTERNAL_EVENT_NS.tooltips;\n }\n // Undo attachment of event\n function removeEvent(namespacedEvent) {\n var event = namespacedEvent && namespacedEvent.split(\".\")[0];\n var namespace = event ? namespacedEvent.substring(event.length) : namespacedEvent;\n Object.keys(scope_Events).forEach(function (bind) {\n var tEvent = bind.split(\".\")[0];\n var tNamespace = bind.substring(tEvent.length);\n if ((!event || event === tEvent) && (!namespace || namespace === tNamespace)) {\n // only delete protected internal event if intentional\n if (!isInternalNamespace(tNamespace) || namespace === tNamespace) {\n delete scope_Events[bind];\n }\n }\n });\n }\n // External event handling\n function fireEvent(eventName, handleNumber, tap) {\n Object.keys(scope_Events).forEach(function (targetEvent) {\n var eventType = targetEvent.split(\".\")[0];\n if (eventName === eventType) {\n scope_Events[targetEvent].forEach(function (callback) {\n callback.call(\n // Use the slider public API as the scope ('this')\n scope_Self, \n // Return values as array, so arg_1[arg_2] is always valid.\n scope_Values.map(options.format.to), \n // Handle index, 0 or 1\n handleNumber, \n // Un-formatted slider values\n scope_Values.slice(), \n // Event is fired by tap, true or false\n tap || false, \n // Left offset of the handle, in relation to the slider\n scope_Locations.slice(), \n // add the slider public API to an accessible parameter when this is unavailable\n scope_Self);\n });\n }\n });\n }\n // Split out the handle positioning logic so the Move event can use it, too\n function checkHandlePosition(reference, handleNumber, to, lookBackward, lookForward, getValue, smoothSteps) {\n var distance;\n // For sliders with multiple handles, limit movement to the other handle.\n // Apply the margin option by adding it to the handle positions.\n if (scope_Handles.length > 1 && !options.events.unconstrained) {\n if (lookBackward && handleNumber > 0) {\n distance = scope_Spectrum.getAbsoluteDistance(reference[handleNumber - 1], options.margin, false);\n to = Math.max(to, distance);\n }\n if (lookForward && handleNumber < scope_Handles.length - 1) {\n distance = scope_Spectrum.getAbsoluteDistance(reference[handleNumber + 1], options.margin, true);\n to = Math.min(to, distance);\n }\n }\n // The limit option has the opposite effect, limiting handles to a\n // maximum distance from another. Limit must be > 0, as otherwise\n // handles would be unmovable.\n if (scope_Handles.length > 1 && options.limit) {\n if (lookBackward && handleNumber > 0) {\n distance = scope_Spectrum.getAbsoluteDistance(reference[handleNumber - 1], options.limit, false);\n to = Math.min(to, distance);\n }\n if (lookForward && handleNumber < scope_Handles.length - 1) {\n distance = scope_Spectrum.getAbsoluteDistance(reference[handleNumber + 1], options.limit, true);\n to = Math.max(to, distance);\n }\n }\n // The padding option keeps the handles a certain distance from the\n // edges of the slider. Padding must be > 0.\n if (options.padding) {\n if (handleNumber === 0) {\n distance = scope_Spectrum.getAbsoluteDistance(0, options.padding[0], false);\n to = Math.max(to, distance);\n }\n if (handleNumber === scope_Handles.length - 1) {\n distance = scope_Spectrum.getAbsoluteDistance(100, options.padding[1], true);\n to = Math.min(to, distance);\n }\n }\n if (!smoothSteps) {\n to = scope_Spectrum.getStep(to);\n }\n // Limit percentage to the 0 - 100 range\n to = limit(to);\n // Return false if handle can't move\n if (to === reference[handleNumber] && !getValue) {\n return false;\n }\n return to;\n }\n // Uses slider orientation to create CSS rules. a = base value;\n function inRuleOrder(v, a) {\n var o = options.ort;\n return (o ? a : v) + \", \" + (o ? v : a);\n }\n // Moves handle(s) by a percentage\n // (bool, % to move, [% where handle started, ...], [index in scope_Handles, ...])\n function moveHandles(upward, proposal, locations, handleNumbers, connect) {\n var proposals = locations.slice();\n // Store first handle now, so we still have it in case handleNumbers is reversed\n var firstHandle = handleNumbers[0];\n var smoothSteps = options.events.smoothSteps;\n var b = [!upward, upward];\n var f = [upward, !upward];\n // Copy handleNumbers so we don't change the dataset\n handleNumbers = handleNumbers.slice();\n // Check to see which handle is 'leading'.\n // If that one can't move the second can't either.\n if (upward) {\n handleNumbers.reverse();\n }\n // Step 1: get the maximum percentage that any of the handles can move\n if (handleNumbers.length > 1) {\n handleNumbers.forEach(function (handleNumber, o) {\n var to = checkHandlePosition(proposals, handleNumber, proposals[handleNumber] + proposal, b[o], f[o], false, smoothSteps);\n // Stop if one of the handles can't move.\n if (to === false) {\n proposal = 0;\n }\n else {\n proposal = to - proposals[handleNumber];\n proposals[handleNumber] = to;\n }\n });\n }\n // If using one handle, check backward AND forward\n else {\n b = f = [true];\n }\n var state = false;\n // Step 2: Try to set the handles with the found percentage\n handleNumbers.forEach(function (handleNumber, o) {\n state =\n setHandle(handleNumber, locations[handleNumber] + proposal, b[o], f[o], false, smoothSteps) || state;\n });\n // Step 3: If a handle moved, fire events\n if (state) {\n handleNumbers.forEach(function (handleNumber) {\n fireEvent(\"update\", handleNumber);\n fireEvent(\"slide\", handleNumber);\n });\n // If target is a connect, then fire drag event\n if (connect != undefined) {\n fireEvent(\"drag\", firstHandle);\n }\n }\n }\n // Takes a base value and an offset. This offset is used for the connect bar size.\n // In the initial design for this feature, the origin element was 1% wide.\n // Unfortunately, a rounding bug in Chrome makes it impossible to implement this feature\n // in this manner: https://bugs.chromium.org/p/chromium/issues/detail?id=798223\n function transformDirection(a, b) {\n return options.dir ? 100 - a - b : a;\n }\n // Updates scope_Locations and scope_Values, updates visual state\n function updateHandlePosition(handleNumber, to) {\n // Update locations.\n scope_Locations[handleNumber] = to;\n // Convert the value to the slider stepping/range.\n scope_Values[handleNumber] = scope_Spectrum.fromStepping(to);\n var translation = transformDirection(to, 0) - scope_DirOffset;\n var translateRule = \"translate(\" + inRuleOrder(translation + \"%\", \"0\") + \")\";\n scope_Handles[handleNumber].style[options.transformRule] = translateRule;\n updateConnect(handleNumber);\n updateConnect(handleNumber + 1);\n }\n // Handles before the slider middle are stacked later = higher,\n // Handles after the middle later is lower\n // [[7] [8] .......... | .......... [5] [4]\n function setZindex() {\n scope_HandleNumbers.forEach(function (handleNumber) {\n var dir = scope_Locations[handleNumber] > 50 ? -1 : 1;\n var zIndex = 3 + (scope_Handles.length + dir * handleNumber);\n scope_Handles[handleNumber].style.zIndex = String(zIndex);\n });\n }\n // Test suggested values and apply margin, step.\n // if exactInput is true, don't run checkHandlePosition, then the handle can be placed in between steps (#436)\n function setHandle(handleNumber, to, lookBackward, lookForward, exactInput, smoothSteps) {\n if (!exactInput) {\n to = checkHandlePosition(scope_Locations, handleNumber, to, lookBackward, lookForward, false, smoothSteps);\n }\n if (to === false) {\n return false;\n }\n updateHandlePosition(handleNumber, to);\n return true;\n }\n // Updates style attribute for connect nodes\n function updateConnect(index) {\n // Skip connects set to false\n if (!scope_Connects[index]) {\n return;\n }\n var l = 0;\n var h = 100;\n if (index !== 0) {\n l = scope_Locations[index - 1];\n }\n if (index !== scope_Connects.length - 1) {\n h = scope_Locations[index];\n }\n // We use two rules:\n // 'translate' to change the left/top offset;\n // 'scale' to change the width of the element;\n // As the element has a width of 100%, a translation of 100% is equal to 100% of the parent (.noUi-base)\n var connectWidth = h - l;\n var translateRule = \"translate(\" + inRuleOrder(transformDirection(l, connectWidth) + \"%\", \"0\") + \")\";\n var scaleRule = \"scale(\" + inRuleOrder(connectWidth / 100, \"1\") + \")\";\n scope_Connects[index].style[options.transformRule] =\n translateRule + \" \" + scaleRule;\n }\n // Parses value passed to .set method. Returns current value if not parse-able.\n function resolveToValue(to, handleNumber) {\n // Setting with null indicates an 'ignore'.\n // Inputting 'false' is invalid.\n if (to === null || to === false || to === undefined) {\n return scope_Locations[handleNumber];\n }\n // If a formatted number was passed, attempt to decode it.\n if (typeof to === \"number\") {\n to = String(to);\n }\n to = options.format.from(to);\n if (to !== false) {\n to = scope_Spectrum.toStepping(to);\n }\n // If parsing the number failed, use the current value.\n if (to === false || isNaN(to)) {\n return scope_Locations[handleNumber];\n }\n return to;\n }\n // Set the slider value.\n function valueSet(input, fireSetEvent, exactInput) {\n var values = asArray(input);\n var isInit = scope_Locations[0] === undefined;\n // Event fires by default\n fireSetEvent = fireSetEvent === undefined ? true : fireSetEvent;\n // Animation is optional.\n // Make sure the initial values were set before using animated placement.\n if (options.animate && !isInit) {\n addClassFor(scope_Target, options.cssClasses.tap, options.animationDuration);\n }\n // First pass, without lookAhead but with lookBackward. Values are set from left to right.\n scope_HandleNumbers.forEach(function (handleNumber) {\n setHandle(handleNumber, resolveToValue(values[handleNumber], handleNumber), true, false, exactInput);\n });\n var i = scope_HandleNumbers.length === 1 ? 0 : 1;\n // Spread handles evenly across the slider if the range has no size (min=max)\n if (isInit && scope_Spectrum.hasNoSize()) {\n exactInput = true;\n scope_Locations[0] = 0;\n if (scope_HandleNumbers.length > 1) {\n var space_1 = 100 / (scope_HandleNumbers.length - 1);\n scope_HandleNumbers.forEach(function (handleNumber) {\n scope_Locations[handleNumber] = handleNumber * space_1;\n });\n }\n }\n // Secondary passes. Now that all base values are set, apply constraints.\n // Iterate all handles to ensure constraints are applied for the entire slider (Issue #1009)\n for (; i < scope_HandleNumbers.length; ++i) {\n scope_HandleNumbers.forEach(function (handleNumber) {\n setHandle(handleNumber, scope_Locations[handleNumber], true, true, exactInput);\n });\n }\n setZindex();\n scope_HandleNumbers.forEach(function (handleNumber) {\n fireEvent(\"update\", handleNumber);\n // Fire the event only for handles that received a new value, as per #579\n if (values[handleNumber] !== null && fireSetEvent) {\n fireEvent(\"set\", handleNumber);\n }\n });\n }\n // Reset slider to initial values\n function valueReset(fireSetEvent) {\n valueSet(options.start, fireSetEvent);\n }\n // Set value for a single handle\n function valueSetHandle(handleNumber, value, fireSetEvent, exactInput) {\n // Ensure numeric input\n handleNumber = Number(handleNumber);\n if (!(handleNumber >= 0 && handleNumber < scope_HandleNumbers.length)) {\n throw new Error(\"noUiSlider: invalid handle number, got: \" + handleNumber);\n }\n // Look both backward and forward, since we don't want this handle to \"push\" other handles (#960);\n // The exactInput argument can be used to ignore slider stepping (#436)\n setHandle(handleNumber, resolveToValue(value, handleNumber), true, true, exactInput);\n fireEvent(\"update\", handleNumber);\n if (fireSetEvent) {\n fireEvent(\"set\", handleNumber);\n }\n }\n // Get the slider value.\n function valueGet(unencoded) {\n if (unencoded === void 0) { unencoded = false; }\n if (unencoded) {\n // return a copy of the raw values\n return scope_Values.length === 1 ? scope_Values[0] : scope_Values.slice(0);\n }\n var values = scope_Values.map(options.format.to);\n // If only one handle is used, return a single value.\n if (values.length === 1) {\n return values[0];\n }\n return values;\n }\n // Removes classes from the root and empties it.\n function destroy() {\n // remove protected internal listeners\n removeEvent(INTERNAL_EVENT_NS.aria);\n removeEvent(INTERNAL_EVENT_NS.tooltips);\n Object.keys(options.cssClasses).forEach(function (key) {\n removeClass(scope_Target, options.cssClasses[key]);\n });\n while (scope_Target.firstChild) {\n scope_Target.removeChild(scope_Target.firstChild);\n }\n delete scope_Target.noUiSlider;\n }\n function getNextStepsForHandle(handleNumber) {\n var location = scope_Locations[handleNumber];\n var nearbySteps = scope_Spectrum.getNearbySteps(location);\n var value = scope_Values[handleNumber];\n var increment = nearbySteps.thisStep.step;\n var decrement = null;\n // If snapped, directly use defined step value\n if (options.snap) {\n return [\n value - nearbySteps.stepBefore.startValue || null,\n nearbySteps.stepAfter.startValue - value || null,\n ];\n }\n // If the next value in this step moves into the next step,\n // the increment is the start of the next step - the current value\n if (increment !== false) {\n if (value + increment > nearbySteps.stepAfter.startValue) {\n increment = nearbySteps.stepAfter.startValue - value;\n }\n }\n // If the value is beyond the starting point\n if (value > nearbySteps.thisStep.startValue) {\n decrement = nearbySteps.thisStep.step;\n }\n else if (nearbySteps.stepBefore.step === false) {\n decrement = false;\n }\n // If a handle is at the start of a step, it always steps back into the previous step first\n else {\n decrement = value - nearbySteps.stepBefore.highestStep;\n }\n // Now, if at the slider edges, there is no in/decrement\n if (location === 100) {\n increment = null;\n }\n else if (location === 0) {\n decrement = null;\n }\n // As per #391, the comparison for the decrement step can have some rounding issues.\n var stepDecimals = scope_Spectrum.countStepDecimals();\n // Round per #391\n if (increment !== null && increment !== false) {\n increment = Number(increment.toFixed(stepDecimals));\n }\n if (decrement !== null && decrement !== false) {\n decrement = Number(decrement.toFixed(stepDecimals));\n }\n return [decrement, increment];\n }\n // Get the current step size for the slider.\n function getNextSteps() {\n return scope_HandleNumbers.map(getNextStepsForHandle);\n }\n // Updatable: margin, limit, padding, step, range, animate, snap\n function updateOptions(optionsToUpdate, fireSetEvent) {\n // Spectrum is created using the range, snap, direction and step options.\n // 'snap' and 'step' can be updated.\n // If 'snap' and 'step' are not passed, they should remain unchanged.\n var v = valueGet();\n var updateAble = [\n \"margin\",\n \"limit\",\n \"padding\",\n \"range\",\n \"animate\",\n \"snap\",\n \"step\",\n \"format\",\n \"pips\",\n \"tooltips\",\n ];\n // Only change options that we're actually passed to update.\n updateAble.forEach(function (name) {\n // Check for undefined. null removes the value.\n if (optionsToUpdate[name] !== undefined) {\n originalOptions[name] = optionsToUpdate[name];\n }\n });\n var newOptions = testOptions(originalOptions);\n // Load new options into the slider state\n updateAble.forEach(function (name) {\n if (optionsToUpdate[name] !== undefined) {\n options[name] = newOptions[name];\n }\n });\n scope_Spectrum = newOptions.spectrum;\n // Limit, margin and padding depend on the spectrum but are stored outside of it. (#677)\n options.margin = newOptions.margin;\n options.limit = newOptions.limit;\n options.padding = newOptions.padding;\n // Update pips, removes existing.\n if (options.pips) {\n pips(options.pips);\n }\n else {\n removePips();\n }\n // Update tooltips, removes existing.\n if (options.tooltips) {\n tooltips();\n }\n else {\n removeTooltips();\n }\n // Invalidate the current positioning so valueSet forces an update.\n scope_Locations = [];\n valueSet(isSet(optionsToUpdate.start) ? optionsToUpdate.start : v, fireSetEvent);\n }\n // Initialization steps\n function setupSlider() {\n // Create the base element, initialize HTML and set classes.\n // Add handles and connect elements.\n scope_Base = addSlider(scope_Target);\n addElements(options.connect, scope_Base);\n // Attach user events.\n bindSliderEvents(options.events);\n // Use the public value method to set the start values.\n valueSet(options.start);\n if (options.pips) {\n pips(options.pips);\n }\n if (options.tooltips) {\n tooltips();\n }\n aria();\n }\n setupSlider();\n var scope_Self = {\n destroy: destroy,\n steps: getNextSteps,\n on: bindEvent,\n off: removeEvent,\n get: valueGet,\n set: valueSet,\n setHandle: valueSetHandle,\n reset: valueReset,\n disable: disable,\n enable: enable,\n // Exposed for unit testing, don't use this in your application.\n __moveHandles: function (upward, proposal, handleNumbers) {\n moveHandles(upward, proposal, scope_Locations, handleNumbers);\n },\n options: originalOptions,\n updateOptions: updateOptions,\n target: scope_Target,\n removePips: removePips,\n removeTooltips: removeTooltips,\n getPositions: function () {\n return scope_Locations.slice();\n },\n getTooltips: function () {\n return scope_Tooltips;\n },\n getOrigins: function () {\n return scope_Handles;\n },\n pips: pips, // Issue #594\n };\n return scope_Self;\n }\n // Run the standard initializer\n function initialize(target, originalOptions) {\n if (!target || !target.nodeName) {\n throw new Error(\"noUiSlider: create requires a single element, got: \" + target);\n }\n // Throw an error if the slider was already initialized.\n if (target.noUiSlider) {\n throw new Error(\"noUiSlider: Slider was already initialized.\");\n }\n // Test the options and create the slider environment;\n var options = testOptions(originalOptions);\n var api = scope(target, options, originalOptions);\n target.noUiSlider = api;\n return api;\n }\n var nouislider = {\n // Exposed for unit testing, don't use this in your application.\n __spectrum: Spectrum,\n // A reference to the default classes, allows global changes.\n // Use the cssClasses option for changes to one slider.\n cssClasses: cssClasses,\n create: initialize,\n };\n\n exports.create = initialize;\n exports.cssClasses = cssClasses;\n exports[\"default\"] = nouislider;\n\n Object.defineProperty(exports, '__esModule', { value: true });\n\n}));\n", "/*\nTurbo 7.1.0\nCopyright \u00A9 2021 Basecamp, LLC\n */\n(function () {\n if (window.Reflect === undefined || window.customElements === undefined ||\n window.customElements.polyfillWrapFlushCallback) {\n return;\n }\n const BuiltInHTMLElement = HTMLElement;\n const wrapperForTheName = {\n 'HTMLElement': function HTMLElement() {\n return Reflect.construct(BuiltInHTMLElement, [], this.constructor);\n }\n };\n window.HTMLElement =\n wrapperForTheName['HTMLElement'];\n HTMLElement.prototype = BuiltInHTMLElement.prototype;\n HTMLElement.prototype.constructor = HTMLElement;\n Object.setPrototypeOf(HTMLElement, BuiltInHTMLElement);\n})();\n\n/**\n * The MIT License (MIT)\n * \n * Copyright (c) 2019 Javan Makhmali\n * \n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n * \n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n * \n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n */\n\n(function(prototype) {\n if (typeof prototype.requestSubmit == \"function\") return\n\n prototype.requestSubmit = function(submitter) {\n if (submitter) {\n validateSubmitter(submitter, this);\n submitter.click();\n } else {\n submitter = document.createElement(\"input\");\n submitter.type = \"submit\";\n submitter.hidden = true;\n this.appendChild(submitter);\n submitter.click();\n this.removeChild(submitter);\n }\n };\n\n function validateSubmitter(submitter, form) {\n submitter instanceof HTMLElement || raise(TypeError, \"parameter 1 is not of type 'HTMLElement'\");\n submitter.type == \"submit\" || raise(TypeError, \"The specified element is not a submit button\");\n submitter.form == form || raise(DOMException, \"The specified element is not owned by this form element\", \"NotFoundError\");\n }\n\n function raise(errorConstructor, message, name) {\n throw new errorConstructor(\"Failed to execute 'requestSubmit' on 'HTMLFormElement': \" + message + \".\", name)\n }\n})(HTMLFormElement.prototype);\n\nconst submittersByForm = new WeakMap;\nfunction findSubmitterFromClickTarget(target) {\n const element = target instanceof Element ? target : target instanceof Node ? target.parentElement : null;\n const candidate = element ? element.closest(\"input, button\") : null;\n return (candidate === null || candidate === void 0 ? void 0 : candidate.type) == \"submit\" ? candidate : null;\n}\nfunction clickCaptured(event) {\n const submitter = findSubmitterFromClickTarget(event.target);\n if (submitter && submitter.form) {\n submittersByForm.set(submitter.form, submitter);\n }\n}\n(function () {\n if (\"submitter\" in Event.prototype)\n return;\n let prototype;\n if (\"SubmitEvent\" in window && /Apple Computer/.test(navigator.vendor)) {\n prototype = window.SubmitEvent.prototype;\n }\n else if (\"SubmitEvent\" in window) {\n return;\n }\n else {\n prototype = window.Event.prototype;\n }\n addEventListener(\"click\", clickCaptured, true);\n Object.defineProperty(prototype, \"submitter\", {\n get() {\n if (this.type == \"submit\" && this.target instanceof HTMLFormElement) {\n return submittersByForm.get(this.target);\n }\n }\n });\n})();\n\nvar FrameLoadingStyle;\n(function (FrameLoadingStyle) {\n FrameLoadingStyle[\"eager\"] = \"eager\";\n FrameLoadingStyle[\"lazy\"] = \"lazy\";\n})(FrameLoadingStyle || (FrameLoadingStyle = {}));\nclass FrameElement extends HTMLElement {\n constructor() {\n super();\n this.loaded = Promise.resolve();\n this.delegate = new FrameElement.delegateConstructor(this);\n }\n static get observedAttributes() {\n return [\"disabled\", \"loading\", \"src\"];\n }\n connectedCallback() {\n this.delegate.connect();\n }\n disconnectedCallback() {\n this.delegate.disconnect();\n }\n reload() {\n const { src } = this;\n this.src = null;\n this.src = src;\n }\n attributeChangedCallback(name) {\n if (name == \"loading\") {\n this.delegate.loadingStyleChanged();\n }\n else if (name == \"src\") {\n this.delegate.sourceURLChanged();\n }\n else {\n this.delegate.disabledChanged();\n }\n }\n get src() {\n return this.getAttribute(\"src\");\n }\n set src(value) {\n if (value) {\n this.setAttribute(\"src\", value);\n }\n else {\n this.removeAttribute(\"src\");\n }\n }\n get loading() {\n return frameLoadingStyleFromString(this.getAttribute(\"loading\") || \"\");\n }\n set loading(value) {\n if (value) {\n this.setAttribute(\"loading\", value);\n }\n else {\n this.removeAttribute(\"loading\");\n }\n }\n get disabled() {\n return this.hasAttribute(\"disabled\");\n }\n set disabled(value) {\n if (value) {\n this.setAttribute(\"disabled\", \"\");\n }\n else {\n this.removeAttribute(\"disabled\");\n }\n }\n get autoscroll() {\n return this.hasAttribute(\"autoscroll\");\n }\n set autoscroll(value) {\n if (value) {\n this.setAttribute(\"autoscroll\", \"\");\n }\n else {\n this.removeAttribute(\"autoscroll\");\n }\n }\n get complete() {\n return !this.delegate.isLoading;\n }\n get isActive() {\n return this.ownerDocument === document && !this.isPreview;\n }\n get isPreview() {\n var _a, _b;\n return (_b = (_a = this.ownerDocument) === null || _a === void 0 ? void 0 : _a.documentElement) === null || _b === void 0 ? void 0 : _b.hasAttribute(\"data-turbo-preview\");\n }\n}\nfunction frameLoadingStyleFromString(style) {\n switch (style.toLowerCase()) {\n case \"lazy\": return FrameLoadingStyle.lazy;\n default: return FrameLoadingStyle.eager;\n }\n}\n\nfunction expandURL(locatable) {\n return new URL(locatable.toString(), document.baseURI);\n}\nfunction getAnchor(url) {\n let anchorMatch;\n if (url.hash) {\n return url.hash.slice(1);\n }\n else if (anchorMatch = url.href.match(/#(.*)$/)) {\n return anchorMatch[1];\n }\n}\nfunction getAction(form, submitter) {\n const action = (submitter === null || submitter === void 0 ? void 0 : submitter.getAttribute(\"formaction\")) || form.getAttribute(\"action\") || form.action;\n return expandURL(action);\n}\nfunction getExtension(url) {\n return (getLastPathComponent(url).match(/\\.[^.]*$/) || [])[0] || \"\";\n}\nfunction isHTML(url) {\n return !!getExtension(url).match(/^(?:|\\.(?:htm|html|xhtml))$/);\n}\nfunction isPrefixedBy(baseURL, url) {\n const prefix = getPrefix(url);\n return baseURL.href === expandURL(prefix).href || baseURL.href.startsWith(prefix);\n}\nfunction locationIsVisitable(location, rootLocation) {\n return isPrefixedBy(location, rootLocation) && isHTML(location);\n}\nfunction getRequestURL(url) {\n const anchor = getAnchor(url);\n return anchor != null\n ? url.href.slice(0, -(anchor.length + 1))\n : url.href;\n}\nfunction toCacheKey(url) {\n return getRequestURL(url);\n}\nfunction urlsAreEqual(left, right) {\n return expandURL(left).href == expandURL(right).href;\n}\nfunction getPathComponents(url) {\n return url.pathname.split(\"/\").slice(1);\n}\nfunction getLastPathComponent(url) {\n return getPathComponents(url).slice(-1)[0];\n}\nfunction getPrefix(url) {\n return addTrailingSlash(url.origin + url.pathname);\n}\nfunction addTrailingSlash(value) {\n return value.endsWith(\"/\") ? value : value + \"/\";\n}\n\nclass FetchResponse {\n constructor(response) {\n this.response = response;\n }\n get succeeded() {\n return this.response.ok;\n }\n get failed() {\n return !this.succeeded;\n }\n get clientError() {\n return this.statusCode >= 400 && this.statusCode <= 499;\n }\n get serverError() {\n return this.statusCode >= 500 && this.statusCode <= 599;\n }\n get redirected() {\n return this.response.redirected;\n }\n get location() {\n return expandURL(this.response.url);\n }\n get isHTML() {\n return this.contentType && this.contentType.match(/^(?:text\\/([^\\s;,]+\\b)?html|application\\/xhtml\\+xml)\\b/);\n }\n get statusCode() {\n return this.response.status;\n }\n get contentType() {\n return this.header(\"Content-Type\");\n }\n get responseText() {\n return this.response.clone().text();\n }\n get responseHTML() {\n if (this.isHTML) {\n return this.response.clone().text();\n }\n else {\n return Promise.resolve(undefined);\n }\n }\n header(name) {\n return this.response.headers.get(name);\n }\n}\n\nfunction dispatch(eventName, { target, cancelable, detail } = {}) {\n const event = new CustomEvent(eventName, { cancelable, bubbles: true, detail });\n if (target && target.isConnected) {\n target.dispatchEvent(event);\n }\n else {\n document.documentElement.dispatchEvent(event);\n }\n return event;\n}\nfunction nextAnimationFrame() {\n return new Promise(resolve => requestAnimationFrame(() => resolve()));\n}\nfunction nextEventLoopTick() {\n return new Promise(resolve => setTimeout(() => resolve(), 0));\n}\nfunction nextMicrotask() {\n return Promise.resolve();\n}\nfunction parseHTMLDocument(html = \"\") {\n return new DOMParser().parseFromString(html, \"text/html\");\n}\nfunction unindent(strings, ...values) {\n const lines = interpolate(strings, values).replace(/^\\n/, \"\").split(\"\\n\");\n const match = lines[0].match(/^\\s+/);\n const indent = match ? match[0].length : 0;\n return lines.map(line => line.slice(indent)).join(\"\\n\");\n}\nfunction interpolate(strings, values) {\n return strings.reduce((result, string, i) => {\n const value = values[i] == undefined ? \"\" : values[i];\n return result + string + value;\n }, \"\");\n}\nfunction uuid() {\n return Array.apply(null, { length: 36 }).map((_, i) => {\n if (i == 8 || i == 13 || i == 18 || i == 23) {\n return \"-\";\n }\n else if (i == 14) {\n return \"4\";\n }\n else if (i == 19) {\n return (Math.floor(Math.random() * 4) + 8).toString(16);\n }\n else {\n return Math.floor(Math.random() * 15).toString(16);\n }\n }).join(\"\");\n}\nfunction getAttribute(attributeName, ...elements) {\n for (const value of elements.map(element => element === null || element === void 0 ? void 0 : element.getAttribute(attributeName))) {\n if (typeof value == \"string\")\n return value;\n }\n return null;\n}\nfunction markAsBusy(...elements) {\n for (const element of elements) {\n if (element.localName == \"turbo-frame\") {\n element.setAttribute(\"busy\", \"\");\n }\n element.setAttribute(\"aria-busy\", \"true\");\n }\n}\nfunction clearBusyState(...elements) {\n for (const element of elements) {\n if (element.localName == \"turbo-frame\") {\n element.removeAttribute(\"busy\");\n }\n element.removeAttribute(\"aria-busy\");\n }\n}\n\nvar FetchMethod;\n(function (FetchMethod) {\n FetchMethod[FetchMethod[\"get\"] = 0] = \"get\";\n FetchMethod[FetchMethod[\"post\"] = 1] = \"post\";\n FetchMethod[FetchMethod[\"put\"] = 2] = \"put\";\n FetchMethod[FetchMethod[\"patch\"] = 3] = \"patch\";\n FetchMethod[FetchMethod[\"delete\"] = 4] = \"delete\";\n})(FetchMethod || (FetchMethod = {}));\nfunction fetchMethodFromString(method) {\n switch (method.toLowerCase()) {\n case \"get\": return FetchMethod.get;\n case \"post\": return FetchMethod.post;\n case \"put\": return FetchMethod.put;\n case \"patch\": return FetchMethod.patch;\n case \"delete\": return FetchMethod.delete;\n }\n}\nclass FetchRequest {\n constructor(delegate, method, location, body = new URLSearchParams, target = null) {\n this.abortController = new AbortController;\n this.resolveRequestPromise = (value) => { };\n this.delegate = delegate;\n this.method = method;\n this.headers = this.defaultHeaders;\n this.body = body;\n this.url = location;\n this.target = target;\n }\n get location() {\n return this.url;\n }\n get params() {\n return this.url.searchParams;\n }\n get entries() {\n return this.body ? Array.from(this.body.entries()) : [];\n }\n cancel() {\n this.abortController.abort();\n }\n async perform() {\n var _a, _b;\n const { fetchOptions } = this;\n (_b = (_a = this.delegate).prepareHeadersForRequest) === null || _b === void 0 ? void 0 : _b.call(_a, this.headers, this);\n await this.allowRequestToBeIntercepted(fetchOptions);\n try {\n this.delegate.requestStarted(this);\n const response = await fetch(this.url.href, fetchOptions);\n return await this.receive(response);\n }\n catch (error) {\n if (error.name !== 'AbortError') {\n this.delegate.requestErrored(this, error);\n throw error;\n }\n }\n finally {\n this.delegate.requestFinished(this);\n }\n }\n async receive(response) {\n const fetchResponse = new FetchResponse(response);\n const event = dispatch(\"turbo:before-fetch-response\", { cancelable: true, detail: { fetchResponse }, target: this.target });\n if (event.defaultPrevented) {\n this.delegate.requestPreventedHandlingResponse(this, fetchResponse);\n }\n else if (fetchResponse.succeeded) {\n this.delegate.requestSucceededWithResponse(this, fetchResponse);\n }\n else {\n this.delegate.requestFailedWithResponse(this, fetchResponse);\n }\n return fetchResponse;\n }\n get fetchOptions() {\n var _a;\n return {\n method: FetchMethod[this.method].toUpperCase(),\n credentials: \"same-origin\",\n headers: this.headers,\n redirect: \"follow\",\n body: this.isIdempotent ? null : this.body,\n signal: this.abortSignal,\n referrer: (_a = this.delegate.referrer) === null || _a === void 0 ? void 0 : _a.href\n };\n }\n get defaultHeaders() {\n return {\n \"Accept\": \"text/html, application/xhtml+xml\"\n };\n }\n get isIdempotent() {\n return this.method == FetchMethod.get;\n }\n get abortSignal() {\n return this.abortController.signal;\n }\n async allowRequestToBeIntercepted(fetchOptions) {\n const requestInterception = new Promise(resolve => this.resolveRequestPromise = resolve);\n const event = dispatch(\"turbo:before-fetch-request\", {\n cancelable: true,\n detail: {\n fetchOptions,\n url: this.url,\n resume: this.resolveRequestPromise\n },\n target: this.target\n });\n if (event.defaultPrevented)\n await requestInterception;\n }\n}\n\nclass AppearanceObserver {\n constructor(delegate, element) {\n this.started = false;\n this.intersect = entries => {\n const lastEntry = entries.slice(-1)[0];\n if (lastEntry === null || lastEntry === void 0 ? void 0 : lastEntry.isIntersecting) {\n this.delegate.elementAppearedInViewport(this.element);\n }\n };\n this.delegate = delegate;\n this.element = element;\n this.intersectionObserver = new IntersectionObserver(this.intersect);\n }\n start() {\n if (!this.started) {\n this.started = true;\n this.intersectionObserver.observe(this.element);\n }\n }\n stop() {\n if (this.started) {\n this.started = false;\n this.intersectionObserver.unobserve(this.element);\n }\n }\n}\n\nclass StreamMessage {\n constructor(html) {\n this.templateElement = document.createElement(\"template\");\n this.templateElement.innerHTML = html;\n }\n static wrap(message) {\n if (typeof message == \"string\") {\n return new this(message);\n }\n else {\n return message;\n }\n }\n get fragment() {\n const fragment = document.createDocumentFragment();\n for (const element of this.foreignElements) {\n fragment.appendChild(document.importNode(element, true));\n }\n return fragment;\n }\n get foreignElements() {\n return this.templateChildren.reduce((streamElements, child) => {\n if (child.tagName.toLowerCase() == \"turbo-stream\") {\n return [...streamElements, child];\n }\n else {\n return streamElements;\n }\n }, []);\n }\n get templateChildren() {\n return Array.from(this.templateElement.content.children);\n }\n}\nStreamMessage.contentType = \"text/vnd.turbo-stream.html\";\n\nvar FormSubmissionState;\n(function (FormSubmissionState) {\n FormSubmissionState[FormSubmissionState[\"initialized\"] = 0] = \"initialized\";\n FormSubmissionState[FormSubmissionState[\"requesting\"] = 1] = \"requesting\";\n FormSubmissionState[FormSubmissionState[\"waiting\"] = 2] = \"waiting\";\n FormSubmissionState[FormSubmissionState[\"receiving\"] = 3] = \"receiving\";\n FormSubmissionState[FormSubmissionState[\"stopping\"] = 4] = \"stopping\";\n FormSubmissionState[FormSubmissionState[\"stopped\"] = 5] = \"stopped\";\n})(FormSubmissionState || (FormSubmissionState = {}));\nvar FormEnctype;\n(function (FormEnctype) {\n FormEnctype[\"urlEncoded\"] = \"application/x-www-form-urlencoded\";\n FormEnctype[\"multipart\"] = \"multipart/form-data\";\n FormEnctype[\"plain\"] = \"text/plain\";\n})(FormEnctype || (FormEnctype = {}));\nfunction formEnctypeFromString(encoding) {\n switch (encoding.toLowerCase()) {\n case FormEnctype.multipart: return FormEnctype.multipart;\n case FormEnctype.plain: return FormEnctype.plain;\n default: return FormEnctype.urlEncoded;\n }\n}\nclass FormSubmission {\n constructor(delegate, formElement, submitter, mustRedirect = false) {\n this.state = FormSubmissionState.initialized;\n this.delegate = delegate;\n this.formElement = formElement;\n this.submitter = submitter;\n this.formData = buildFormData(formElement, submitter);\n this.location = expandURL(this.action);\n if (this.method == FetchMethod.get) {\n mergeFormDataEntries(this.location, [...this.body.entries()]);\n }\n this.fetchRequest = new FetchRequest(this, this.method, this.location, this.body, this.formElement);\n this.mustRedirect = mustRedirect;\n }\n static confirmMethod(message, element) {\n return confirm(message);\n }\n get method() {\n var _a;\n const method = ((_a = this.submitter) === null || _a === void 0 ? void 0 : _a.getAttribute(\"formmethod\")) || this.formElement.getAttribute(\"method\") || \"\";\n return fetchMethodFromString(method.toLowerCase()) || FetchMethod.get;\n }\n get action() {\n var _a;\n const formElementAction = typeof this.formElement.action === 'string' ? this.formElement.action : null;\n return ((_a = this.submitter) === null || _a === void 0 ? void 0 : _a.getAttribute(\"formaction\")) || this.formElement.getAttribute(\"action\") || formElementAction || \"\";\n }\n get body() {\n if (this.enctype == FormEnctype.urlEncoded || this.method == FetchMethod.get) {\n return new URLSearchParams(this.stringFormData);\n }\n else {\n return this.formData;\n }\n }\n get enctype() {\n var _a;\n return formEnctypeFromString(((_a = this.submitter) === null || _a === void 0 ? void 0 : _a.getAttribute(\"formenctype\")) || this.formElement.enctype);\n }\n get isIdempotent() {\n return this.fetchRequest.isIdempotent;\n }\n get stringFormData() {\n return [...this.formData].reduce((entries, [name, value]) => {\n return entries.concat(typeof value == \"string\" ? [[name, value]] : []);\n }, []);\n }\n get confirmationMessage() {\n return this.formElement.getAttribute(\"data-turbo-confirm\");\n }\n get needsConfirmation() {\n return this.confirmationMessage !== null;\n }\n async start() {\n const { initialized, requesting } = FormSubmissionState;\n if (this.needsConfirmation) {\n const answer = FormSubmission.confirmMethod(this.confirmationMessage, this.formElement);\n if (!answer) {\n return;\n }\n }\n if (this.state == initialized) {\n this.state = requesting;\n return this.fetchRequest.perform();\n }\n }\n stop() {\n const { stopping, stopped } = FormSubmissionState;\n if (this.state != stopping && this.state != stopped) {\n this.state = stopping;\n this.fetchRequest.cancel();\n return true;\n }\n }\n prepareHeadersForRequest(headers, request) {\n if (!request.isIdempotent) {\n const token = getCookieValue(getMetaContent(\"csrf-param\")) || getMetaContent(\"csrf-token\");\n if (token) {\n headers[\"X-CSRF-Token\"] = token;\n }\n headers[\"Accept\"] = [StreamMessage.contentType, headers[\"Accept\"]].join(\", \");\n }\n }\n requestStarted(request) {\n var _a;\n this.state = FormSubmissionState.waiting;\n (_a = this.submitter) === null || _a === void 0 ? void 0 : _a.setAttribute(\"disabled\", \"\");\n dispatch(\"turbo:submit-start\", { target: this.formElement, detail: { formSubmission: this } });\n this.delegate.formSubmissionStarted(this);\n }\n requestPreventedHandlingResponse(request, response) {\n this.result = { success: response.succeeded, fetchResponse: response };\n }\n requestSucceededWithResponse(request, response) {\n if (response.clientError || response.serverError) {\n this.delegate.formSubmissionFailedWithResponse(this, response);\n }\n else if (this.requestMustRedirect(request) && responseSucceededWithoutRedirect(response)) {\n const error = new Error(\"Form responses must redirect to another location\");\n this.delegate.formSubmissionErrored(this, error);\n }\n else {\n this.state = FormSubmissionState.receiving;\n this.result = { success: true, fetchResponse: response };\n this.delegate.formSubmissionSucceededWithResponse(this, response);\n }\n }\n requestFailedWithResponse(request, response) {\n this.result = { success: false, fetchResponse: response };\n this.delegate.formSubmissionFailedWithResponse(this, response);\n }\n requestErrored(request, error) {\n this.result = { success: false, error };\n this.delegate.formSubmissionErrored(this, error);\n }\n requestFinished(request) {\n var _a;\n this.state = FormSubmissionState.stopped;\n (_a = this.submitter) === null || _a === void 0 ? void 0 : _a.removeAttribute(\"disabled\");\n dispatch(\"turbo:submit-end\", { target: this.formElement, detail: Object.assign({ formSubmission: this }, this.result) });\n this.delegate.formSubmissionFinished(this);\n }\n requestMustRedirect(request) {\n return !request.isIdempotent && this.mustRedirect;\n }\n}\nfunction buildFormData(formElement, submitter) {\n const formData = new FormData(formElement);\n const name = submitter === null || submitter === void 0 ? void 0 : submitter.getAttribute(\"name\");\n const value = submitter === null || submitter === void 0 ? void 0 : submitter.getAttribute(\"value\");\n if (name && value != null && formData.get(name) != value) {\n formData.append(name, value);\n }\n return formData;\n}\nfunction getCookieValue(cookieName) {\n if (cookieName != null) {\n const cookies = document.cookie ? document.cookie.split(\"; \") : [];\n const cookie = cookies.find((cookie) => cookie.startsWith(cookieName));\n if (cookie) {\n const value = cookie.split(\"=\").slice(1).join(\"=\");\n return value ? decodeURIComponent(value) : undefined;\n }\n }\n}\nfunction getMetaContent(name) {\n const element = document.querySelector(`meta[name=\"${name}\"]`);\n return element && element.content;\n}\nfunction responseSucceededWithoutRedirect(response) {\n return response.statusCode == 200 && !response.redirected;\n}\nfunction mergeFormDataEntries(url, entries) {\n const searchParams = new URLSearchParams;\n for (const [name, value] of entries) {\n if (value instanceof File)\n continue;\n searchParams.append(name, value);\n }\n url.search = searchParams.toString();\n return url;\n}\n\nclass Snapshot {\n constructor(element) {\n this.element = element;\n }\n get children() {\n return [...this.element.children];\n }\n hasAnchor(anchor) {\n return this.getElementForAnchor(anchor) != null;\n }\n getElementForAnchor(anchor) {\n return anchor ? this.element.querySelector(`[id='${anchor}'], a[name='${anchor}']`) : null;\n }\n get isConnected() {\n return this.element.isConnected;\n }\n get firstAutofocusableElement() {\n return this.element.querySelector(\"[autofocus]\");\n }\n get permanentElements() {\n return [...this.element.querySelectorAll(\"[id][data-turbo-permanent]\")];\n }\n getPermanentElementById(id) {\n return this.element.querySelector(`#${id}[data-turbo-permanent]`);\n }\n getPermanentElementMapForSnapshot(snapshot) {\n const permanentElementMap = {};\n for (const currentPermanentElement of this.permanentElements) {\n const { id } = currentPermanentElement;\n const newPermanentElement = snapshot.getPermanentElementById(id);\n if (newPermanentElement) {\n permanentElementMap[id] = [currentPermanentElement, newPermanentElement];\n }\n }\n return permanentElementMap;\n }\n}\n\nclass FormInterceptor {\n constructor(delegate, element) {\n this.submitBubbled = ((event) => {\n const form = event.target;\n if (!event.defaultPrevented && form instanceof HTMLFormElement && form.closest(\"turbo-frame, html\") == this.element) {\n const submitter = event.submitter || undefined;\n const method = (submitter === null || submitter === void 0 ? void 0 : submitter.getAttribute(\"formmethod\")) || form.method;\n if (method != \"dialog\" && this.delegate.shouldInterceptFormSubmission(form, submitter)) {\n event.preventDefault();\n event.stopImmediatePropagation();\n this.delegate.formSubmissionIntercepted(form, submitter);\n }\n }\n });\n this.delegate = delegate;\n this.element = element;\n }\n start() {\n this.element.addEventListener(\"submit\", this.submitBubbled);\n }\n stop() {\n this.element.removeEventListener(\"submit\", this.submitBubbled);\n }\n}\n\nclass View {\n constructor(delegate, element) {\n this.resolveRenderPromise = (value) => { };\n this.resolveInterceptionPromise = (value) => { };\n this.delegate = delegate;\n this.element = element;\n }\n scrollToAnchor(anchor) {\n const element = this.snapshot.getElementForAnchor(anchor);\n if (element) {\n this.scrollToElement(element);\n this.focusElement(element);\n }\n else {\n this.scrollToPosition({ x: 0, y: 0 });\n }\n }\n scrollToAnchorFromLocation(location) {\n this.scrollToAnchor(getAnchor(location));\n }\n scrollToElement(element) {\n element.scrollIntoView();\n }\n focusElement(element) {\n if (element instanceof HTMLElement) {\n if (element.hasAttribute(\"tabindex\")) {\n element.focus();\n }\n else {\n element.setAttribute(\"tabindex\", \"-1\");\n element.focus();\n element.removeAttribute(\"tabindex\");\n }\n }\n }\n scrollToPosition({ x, y }) {\n this.scrollRoot.scrollTo(x, y);\n }\n scrollToTop() {\n this.scrollToPosition({ x: 0, y: 0 });\n }\n get scrollRoot() {\n return window;\n }\n async render(renderer) {\n const { isPreview, shouldRender, newSnapshot: snapshot } = renderer;\n if (shouldRender) {\n try {\n this.renderPromise = new Promise(resolve => this.resolveRenderPromise = resolve);\n this.renderer = renderer;\n this.prepareToRenderSnapshot(renderer);\n const renderInterception = new Promise(resolve => this.resolveInterceptionPromise = resolve);\n const immediateRender = this.delegate.allowsImmediateRender(snapshot, this.resolveInterceptionPromise);\n if (!immediateRender)\n await renderInterception;\n await this.renderSnapshot(renderer);\n this.delegate.viewRenderedSnapshot(snapshot, isPreview);\n this.finishRenderingSnapshot(renderer);\n }\n finally {\n delete this.renderer;\n this.resolveRenderPromise(undefined);\n delete this.renderPromise;\n }\n }\n else {\n this.invalidate();\n }\n }\n invalidate() {\n this.delegate.viewInvalidated();\n }\n prepareToRenderSnapshot(renderer) {\n this.markAsPreview(renderer.isPreview);\n renderer.prepareToRender();\n }\n markAsPreview(isPreview) {\n if (isPreview) {\n this.element.setAttribute(\"data-turbo-preview\", \"\");\n }\n else {\n this.element.removeAttribute(\"data-turbo-preview\");\n }\n }\n async renderSnapshot(renderer) {\n await renderer.render();\n }\n finishRenderingSnapshot(renderer) {\n renderer.finishRendering();\n }\n}\n\nclass FrameView extends View {\n invalidate() {\n this.element.innerHTML = \"\";\n }\n get snapshot() {\n return new Snapshot(this.element);\n }\n}\n\nclass LinkInterceptor {\n constructor(delegate, element) {\n this.clickBubbled = (event) => {\n if (this.respondsToEventTarget(event.target)) {\n this.clickEvent = event;\n }\n else {\n delete this.clickEvent;\n }\n };\n this.linkClicked = ((event) => {\n if (this.clickEvent && this.respondsToEventTarget(event.target) && event.target instanceof Element) {\n if (this.delegate.shouldInterceptLinkClick(event.target, event.detail.url)) {\n this.clickEvent.preventDefault();\n event.preventDefault();\n this.delegate.linkClickIntercepted(event.target, event.detail.url);\n }\n }\n delete this.clickEvent;\n });\n this.willVisit = () => {\n delete this.clickEvent;\n };\n this.delegate = delegate;\n this.element = element;\n }\n start() {\n this.element.addEventListener(\"click\", this.clickBubbled);\n document.addEventListener(\"turbo:click\", this.linkClicked);\n document.addEventListener(\"turbo:before-visit\", this.willVisit);\n }\n stop() {\n this.element.removeEventListener(\"click\", this.clickBubbled);\n document.removeEventListener(\"turbo:click\", this.linkClicked);\n document.removeEventListener(\"turbo:before-visit\", this.willVisit);\n }\n respondsToEventTarget(target) {\n const element = target instanceof Element\n ? target\n : target instanceof Node\n ? target.parentElement\n : null;\n return element && element.closest(\"turbo-frame, html\") == this.element;\n }\n}\n\nclass Bardo {\n constructor(permanentElementMap) {\n this.permanentElementMap = permanentElementMap;\n }\n static preservingPermanentElements(permanentElementMap, callback) {\n const bardo = new this(permanentElementMap);\n bardo.enter();\n callback();\n bardo.leave();\n }\n enter() {\n for (const id in this.permanentElementMap) {\n const [, newPermanentElement] = this.permanentElementMap[id];\n this.replaceNewPermanentElementWithPlaceholder(newPermanentElement);\n }\n }\n leave() {\n for (const id in this.permanentElementMap) {\n const [currentPermanentElement] = this.permanentElementMap[id];\n this.replaceCurrentPermanentElementWithClone(currentPermanentElement);\n this.replacePlaceholderWithPermanentElement(currentPermanentElement);\n }\n }\n replaceNewPermanentElementWithPlaceholder(permanentElement) {\n const placeholder = createPlaceholderForPermanentElement(permanentElement);\n permanentElement.replaceWith(placeholder);\n }\n replaceCurrentPermanentElementWithClone(permanentElement) {\n const clone = permanentElement.cloneNode(true);\n permanentElement.replaceWith(clone);\n }\n replacePlaceholderWithPermanentElement(permanentElement) {\n const placeholder = this.getPlaceholderById(permanentElement.id);\n placeholder === null || placeholder === void 0 ? void 0 : placeholder.replaceWith(permanentElement);\n }\n getPlaceholderById(id) {\n return this.placeholders.find(element => element.content == id);\n }\n get placeholders() {\n return [...document.querySelectorAll(\"meta[name=turbo-permanent-placeholder][content]\")];\n }\n}\nfunction createPlaceholderForPermanentElement(permanentElement) {\n const element = document.createElement(\"meta\");\n element.setAttribute(\"name\", \"turbo-permanent-placeholder\");\n element.setAttribute(\"content\", permanentElement.id);\n return element;\n}\n\nclass Renderer {\n constructor(currentSnapshot, newSnapshot, isPreview, willRender = true) {\n this.currentSnapshot = currentSnapshot;\n this.newSnapshot = newSnapshot;\n this.isPreview = isPreview;\n this.willRender = willRender;\n this.promise = new Promise((resolve, reject) => this.resolvingFunctions = { resolve, reject });\n }\n get shouldRender() {\n return true;\n }\n prepareToRender() {\n return;\n }\n finishRendering() {\n if (this.resolvingFunctions) {\n this.resolvingFunctions.resolve();\n delete this.resolvingFunctions;\n }\n }\n createScriptElement(element) {\n if (element.getAttribute(\"data-turbo-eval\") == \"false\") {\n return element;\n }\n else {\n const createdScriptElement = document.createElement(\"script\");\n if (this.cspNonce) {\n createdScriptElement.nonce = this.cspNonce;\n }\n createdScriptElement.textContent = element.textContent;\n createdScriptElement.async = false;\n copyElementAttributes(createdScriptElement, element);\n return createdScriptElement;\n }\n }\n preservingPermanentElements(callback) {\n Bardo.preservingPermanentElements(this.permanentElementMap, callback);\n }\n focusFirstAutofocusableElement() {\n const element = this.connectedSnapshot.firstAutofocusableElement;\n if (elementIsFocusable(element)) {\n element.focus();\n }\n }\n get connectedSnapshot() {\n return this.newSnapshot.isConnected ? this.newSnapshot : this.currentSnapshot;\n }\n get currentElement() {\n return this.currentSnapshot.element;\n }\n get newElement() {\n return this.newSnapshot.element;\n }\n get permanentElementMap() {\n return this.currentSnapshot.getPermanentElementMapForSnapshot(this.newSnapshot);\n }\n get cspNonce() {\n var _a;\n return (_a = document.head.querySelector('meta[name=\"csp-nonce\"]')) === null || _a === void 0 ? void 0 : _a.getAttribute(\"content\");\n }\n}\nfunction copyElementAttributes(destinationElement, sourceElement) {\n for (const { name, value } of [...sourceElement.attributes]) {\n destinationElement.setAttribute(name, value);\n }\n}\nfunction elementIsFocusable(element) {\n return element && typeof element.focus == \"function\";\n}\n\nclass FrameRenderer extends Renderer {\n get shouldRender() {\n return true;\n }\n async render() {\n await nextAnimationFrame();\n this.preservingPermanentElements(() => {\n this.loadFrameElement();\n });\n this.scrollFrameIntoView();\n await nextAnimationFrame();\n this.focusFirstAutofocusableElement();\n await nextAnimationFrame();\n this.activateScriptElements();\n }\n loadFrameElement() {\n var _a;\n const destinationRange = document.createRange();\n destinationRange.selectNodeContents(this.currentElement);\n destinationRange.deleteContents();\n const frameElement = this.newElement;\n const sourceRange = (_a = frameElement.ownerDocument) === null || _a === void 0 ? void 0 : _a.createRange();\n if (sourceRange) {\n sourceRange.selectNodeContents(frameElement);\n this.currentElement.appendChild(sourceRange.extractContents());\n }\n }\n scrollFrameIntoView() {\n if (this.currentElement.autoscroll || this.newElement.autoscroll) {\n const element = this.currentElement.firstElementChild;\n const block = readScrollLogicalPosition(this.currentElement.getAttribute(\"data-autoscroll-block\"), \"end\");\n if (element) {\n element.scrollIntoView({ block });\n return true;\n }\n }\n return false;\n }\n activateScriptElements() {\n for (const inertScriptElement of this.newScriptElements) {\n const activatedScriptElement = this.createScriptElement(inertScriptElement);\n inertScriptElement.replaceWith(activatedScriptElement);\n }\n }\n get newScriptElements() {\n return this.currentElement.querySelectorAll(\"script\");\n }\n}\nfunction readScrollLogicalPosition(value, defaultValue) {\n if (value == \"end\" || value == \"start\" || value == \"center\" || value == \"nearest\") {\n return value;\n }\n else {\n return defaultValue;\n }\n}\n\nclass ProgressBar {\n constructor() {\n this.hiding = false;\n this.value = 0;\n this.visible = false;\n this.trickle = () => {\n this.setValue(this.value + Math.random() / 100);\n };\n this.stylesheetElement = this.createStylesheetElement();\n this.progressElement = this.createProgressElement();\n this.installStylesheetElement();\n this.setValue(0);\n }\n static get defaultCSS() {\n return unindent `\n .turbo-progress-bar {\n position: fixed;\n display: block;\n top: 0;\n left: 0;\n height: 3px;\n background: #0076ff;\n z-index: 9999;\n transition:\n width ${ProgressBar.animationDuration}ms ease-out,\n opacity ${ProgressBar.animationDuration / 2}ms ${ProgressBar.animationDuration / 2}ms ease-in;\n transform: translate3d(0, 0, 0);\n }\n `;\n }\n show() {\n if (!this.visible) {\n this.visible = true;\n this.installProgressElement();\n this.startTrickling();\n }\n }\n hide() {\n if (this.visible && !this.hiding) {\n this.hiding = true;\n this.fadeProgressElement(() => {\n this.uninstallProgressElement();\n this.stopTrickling();\n this.visible = false;\n this.hiding = false;\n });\n }\n }\n setValue(value) {\n this.value = value;\n this.refresh();\n }\n installStylesheetElement() {\n document.head.insertBefore(this.stylesheetElement, document.head.firstChild);\n }\n installProgressElement() {\n this.progressElement.style.width = \"0\";\n this.progressElement.style.opacity = \"1\";\n document.documentElement.insertBefore(this.progressElement, document.body);\n this.refresh();\n }\n fadeProgressElement(callback) {\n this.progressElement.style.opacity = \"0\";\n setTimeout(callback, ProgressBar.animationDuration * 1.5);\n }\n uninstallProgressElement() {\n if (this.progressElement.parentNode) {\n document.documentElement.removeChild(this.progressElement);\n }\n }\n startTrickling() {\n if (!this.trickleInterval) {\n this.trickleInterval = window.setInterval(this.trickle, ProgressBar.animationDuration);\n }\n }\n stopTrickling() {\n window.clearInterval(this.trickleInterval);\n delete this.trickleInterval;\n }\n refresh() {\n requestAnimationFrame(() => {\n this.progressElement.style.width = `${10 + (this.value * 90)}%`;\n });\n }\n createStylesheetElement() {\n const element = document.createElement(\"style\");\n element.type = \"text/css\";\n element.textContent = ProgressBar.defaultCSS;\n return element;\n }\n createProgressElement() {\n const element = document.createElement(\"div\");\n element.className = \"turbo-progress-bar\";\n return element;\n }\n}\nProgressBar.animationDuration = 300;\n\nclass HeadSnapshot extends Snapshot {\n constructor() {\n super(...arguments);\n this.detailsByOuterHTML = this.children\n .filter((element) => !elementIsNoscript(element))\n .map((element) => elementWithoutNonce(element))\n .reduce((result, element) => {\n const { outerHTML } = element;\n const details = outerHTML in result\n ? result[outerHTML]\n : {\n type: elementType(element),\n tracked: elementIsTracked(element),\n elements: []\n };\n return Object.assign(Object.assign({}, result), { [outerHTML]: Object.assign(Object.assign({}, details), { elements: [...details.elements, element] }) });\n }, {});\n }\n get trackedElementSignature() {\n return Object.keys(this.detailsByOuterHTML)\n .filter(outerHTML => this.detailsByOuterHTML[outerHTML].tracked)\n .join(\"\");\n }\n getScriptElementsNotInSnapshot(snapshot) {\n return this.getElementsMatchingTypeNotInSnapshot(\"script\", snapshot);\n }\n getStylesheetElementsNotInSnapshot(snapshot) {\n return this.getElementsMatchingTypeNotInSnapshot(\"stylesheet\", snapshot);\n }\n getElementsMatchingTypeNotInSnapshot(matchedType, snapshot) {\n return Object.keys(this.detailsByOuterHTML)\n .filter(outerHTML => !(outerHTML in snapshot.detailsByOuterHTML))\n .map(outerHTML => this.detailsByOuterHTML[outerHTML])\n .filter(({ type }) => type == matchedType)\n .map(({ elements: [element] }) => element);\n }\n get provisionalElements() {\n return Object.keys(this.detailsByOuterHTML).reduce((result, outerHTML) => {\n const { type, tracked, elements } = this.detailsByOuterHTML[outerHTML];\n if (type == null && !tracked) {\n return [...result, ...elements];\n }\n else if (elements.length > 1) {\n return [...result, ...elements.slice(1)];\n }\n else {\n return result;\n }\n }, []);\n }\n getMetaValue(name) {\n const element = this.findMetaElementByName(name);\n return element\n ? element.getAttribute(\"content\")\n : null;\n }\n findMetaElementByName(name) {\n return Object.keys(this.detailsByOuterHTML).reduce((result, outerHTML) => {\n const { elements: [element] } = this.detailsByOuterHTML[outerHTML];\n return elementIsMetaElementWithName(element, name) ? element : result;\n }, undefined);\n }\n}\nfunction elementType(element) {\n if (elementIsScript(element)) {\n return \"script\";\n }\n else if (elementIsStylesheet(element)) {\n return \"stylesheet\";\n }\n}\nfunction elementIsTracked(element) {\n return element.getAttribute(\"data-turbo-track\") == \"reload\";\n}\nfunction elementIsScript(element) {\n const tagName = element.tagName.toLowerCase();\n return tagName == \"script\";\n}\nfunction elementIsNoscript(element) {\n const tagName = element.tagName.toLowerCase();\n return tagName == \"noscript\";\n}\nfunction elementIsStylesheet(element) {\n const tagName = element.tagName.toLowerCase();\n return tagName == \"style\" || (tagName == \"link\" && element.getAttribute(\"rel\") == \"stylesheet\");\n}\nfunction elementIsMetaElementWithName(element, name) {\n const tagName = element.tagName.toLowerCase();\n return tagName == \"meta\" && element.getAttribute(\"name\") == name;\n}\nfunction elementWithoutNonce(element) {\n if (element.hasAttribute(\"nonce\")) {\n element.setAttribute(\"nonce\", \"\");\n }\n return element;\n}\n\nclass PageSnapshot extends Snapshot {\n constructor(element, headSnapshot) {\n super(element);\n this.headSnapshot = headSnapshot;\n }\n static fromHTMLString(html = \"\") {\n return this.fromDocument(parseHTMLDocument(html));\n }\n static fromElement(element) {\n return this.fromDocument(element.ownerDocument);\n }\n static fromDocument({ head, body }) {\n return new this(body, new HeadSnapshot(head));\n }\n clone() {\n return new PageSnapshot(this.element.cloneNode(true), this.headSnapshot);\n }\n get headElement() {\n return this.headSnapshot.element;\n }\n get rootLocation() {\n var _a;\n const root = (_a = this.getSetting(\"root\")) !== null && _a !== void 0 ? _a : \"/\";\n return expandURL(root);\n }\n get cacheControlValue() {\n return this.getSetting(\"cache-control\");\n }\n get isPreviewable() {\n return this.cacheControlValue != \"no-preview\";\n }\n get isCacheable() {\n return this.cacheControlValue != \"no-cache\";\n }\n get isVisitable() {\n return this.getSetting(\"visit-control\") != \"reload\";\n }\n getSetting(name) {\n return this.headSnapshot.getMetaValue(`turbo-${name}`);\n }\n}\n\nvar TimingMetric;\n(function (TimingMetric) {\n TimingMetric[\"visitStart\"] = \"visitStart\";\n TimingMetric[\"requestStart\"] = \"requestStart\";\n TimingMetric[\"requestEnd\"] = \"requestEnd\";\n TimingMetric[\"visitEnd\"] = \"visitEnd\";\n})(TimingMetric || (TimingMetric = {}));\nvar VisitState;\n(function (VisitState) {\n VisitState[\"initialized\"] = \"initialized\";\n VisitState[\"started\"] = \"started\";\n VisitState[\"canceled\"] = \"canceled\";\n VisitState[\"failed\"] = \"failed\";\n VisitState[\"completed\"] = \"completed\";\n})(VisitState || (VisitState = {}));\nconst defaultOptions = {\n action: \"advance\",\n historyChanged: false,\n visitCachedSnapshot: () => { },\n willRender: true,\n};\nvar SystemStatusCode;\n(function (SystemStatusCode) {\n SystemStatusCode[SystemStatusCode[\"networkFailure\"] = 0] = \"networkFailure\";\n SystemStatusCode[SystemStatusCode[\"timeoutFailure\"] = -1] = \"timeoutFailure\";\n SystemStatusCode[SystemStatusCode[\"contentTypeMismatch\"] = -2] = \"contentTypeMismatch\";\n})(SystemStatusCode || (SystemStatusCode = {}));\nclass Visit {\n constructor(delegate, location, restorationIdentifier, options = {}) {\n this.identifier = uuid();\n this.timingMetrics = {};\n this.followedRedirect = false;\n this.historyChanged = false;\n this.scrolled = false;\n this.snapshotCached = false;\n this.state = VisitState.initialized;\n this.delegate = delegate;\n this.location = location;\n this.restorationIdentifier = restorationIdentifier || uuid();\n const { action, historyChanged, referrer, snapshotHTML, response, visitCachedSnapshot, willRender } = Object.assign(Object.assign({}, defaultOptions), options);\n this.action = action;\n this.historyChanged = historyChanged;\n this.referrer = referrer;\n this.snapshotHTML = snapshotHTML;\n this.response = response;\n this.isSamePage = this.delegate.locationWithActionIsSamePage(this.location, this.action);\n this.visitCachedSnapshot = visitCachedSnapshot;\n this.willRender = willRender;\n this.scrolled = !willRender;\n }\n get adapter() {\n return this.delegate.adapter;\n }\n get view() {\n return this.delegate.view;\n }\n get history() {\n return this.delegate.history;\n }\n get restorationData() {\n return this.history.getRestorationDataForIdentifier(this.restorationIdentifier);\n }\n get silent() {\n return this.isSamePage;\n }\n start() {\n if (this.state == VisitState.initialized) {\n this.recordTimingMetric(TimingMetric.visitStart);\n this.state = VisitState.started;\n this.adapter.visitStarted(this);\n this.delegate.visitStarted(this);\n }\n }\n cancel() {\n if (this.state == VisitState.started) {\n if (this.request) {\n this.request.cancel();\n }\n this.cancelRender();\n this.state = VisitState.canceled;\n }\n }\n complete() {\n if (this.state == VisitState.started) {\n this.recordTimingMetric(TimingMetric.visitEnd);\n this.state = VisitState.completed;\n this.adapter.visitCompleted(this);\n this.delegate.visitCompleted(this);\n this.followRedirect();\n }\n }\n fail() {\n if (this.state == VisitState.started) {\n this.state = VisitState.failed;\n this.adapter.visitFailed(this);\n }\n }\n changeHistory() {\n var _a;\n if (!this.historyChanged) {\n const actionForHistory = this.location.href === ((_a = this.referrer) === null || _a === void 0 ? void 0 : _a.href) ? \"replace\" : this.action;\n const method = this.getHistoryMethodForAction(actionForHistory);\n this.history.update(method, this.location, this.restorationIdentifier);\n this.historyChanged = true;\n }\n }\n issueRequest() {\n if (this.hasPreloadedResponse()) {\n this.simulateRequest();\n }\n else if (this.shouldIssueRequest() && !this.request) {\n this.request = new FetchRequest(this, FetchMethod.get, this.location);\n this.request.perform();\n }\n }\n simulateRequest() {\n if (this.response) {\n this.startRequest();\n this.recordResponse();\n this.finishRequest();\n }\n }\n startRequest() {\n this.recordTimingMetric(TimingMetric.requestStart);\n this.adapter.visitRequestStarted(this);\n }\n recordResponse(response = this.response) {\n this.response = response;\n if (response) {\n const { statusCode } = response;\n if (isSuccessful(statusCode)) {\n this.adapter.visitRequestCompleted(this);\n }\n else {\n this.adapter.visitRequestFailedWithStatusCode(this, statusCode);\n }\n }\n }\n finishRequest() {\n this.recordTimingMetric(TimingMetric.requestEnd);\n this.adapter.visitRequestFinished(this);\n }\n loadResponse() {\n if (this.response) {\n const { statusCode, responseHTML } = this.response;\n this.render(async () => {\n this.cacheSnapshot();\n if (this.view.renderPromise)\n await this.view.renderPromise;\n if (isSuccessful(statusCode) && responseHTML != null) {\n await this.view.renderPage(PageSnapshot.fromHTMLString(responseHTML), false, this.willRender);\n this.adapter.visitRendered(this);\n this.complete();\n }\n else {\n await this.view.renderError(PageSnapshot.fromHTMLString(responseHTML));\n this.adapter.visitRendered(this);\n this.fail();\n }\n });\n }\n }\n getCachedSnapshot() {\n const snapshot = this.view.getCachedSnapshotForLocation(this.location) || this.getPreloadedSnapshot();\n if (snapshot && (!getAnchor(this.location) || snapshot.hasAnchor(getAnchor(this.location)))) {\n if (this.action == \"restore\" || snapshot.isPreviewable) {\n return snapshot;\n }\n }\n }\n getPreloadedSnapshot() {\n if (this.snapshotHTML) {\n return PageSnapshot.fromHTMLString(this.snapshotHTML);\n }\n }\n hasCachedSnapshot() {\n return this.getCachedSnapshot() != null;\n }\n loadCachedSnapshot() {\n const snapshot = this.getCachedSnapshot();\n if (snapshot) {\n const isPreview = this.shouldIssueRequest();\n this.render(async () => {\n this.cacheSnapshot();\n if (this.isSamePage) {\n this.adapter.visitRendered(this);\n }\n else {\n if (this.view.renderPromise)\n await this.view.renderPromise;\n await this.view.renderPage(snapshot, isPreview, this.willRender);\n this.adapter.visitRendered(this);\n if (!isPreview) {\n this.complete();\n }\n }\n });\n }\n }\n followRedirect() {\n var _a;\n if (this.redirectedToLocation && !this.followedRedirect && ((_a = this.response) === null || _a === void 0 ? void 0 : _a.redirected)) {\n this.adapter.visitProposedToLocation(this.redirectedToLocation, {\n action: 'replace',\n response: this.response\n });\n this.followedRedirect = true;\n }\n }\n goToSamePageAnchor() {\n if (this.isSamePage) {\n this.render(async () => {\n this.cacheSnapshot();\n this.adapter.visitRendered(this);\n });\n }\n }\n requestStarted() {\n this.startRequest();\n }\n requestPreventedHandlingResponse(request, response) {\n }\n async requestSucceededWithResponse(request, response) {\n const responseHTML = await response.responseHTML;\n const { redirected, statusCode } = response;\n if (responseHTML == undefined) {\n this.recordResponse({ statusCode: SystemStatusCode.contentTypeMismatch, redirected });\n }\n else {\n this.redirectedToLocation = response.redirected ? response.location : undefined;\n this.recordResponse({ statusCode: statusCode, responseHTML, redirected });\n }\n }\n async requestFailedWithResponse(request, response) {\n const responseHTML = await response.responseHTML;\n const { redirected, statusCode } = response;\n if (responseHTML == undefined) {\n this.recordResponse({ statusCode: SystemStatusCode.contentTypeMismatch, redirected });\n }\n else {\n this.recordResponse({ statusCode: statusCode, responseHTML, redirected });\n }\n }\n requestErrored(request, error) {\n this.recordResponse({ statusCode: SystemStatusCode.networkFailure, redirected: false });\n }\n requestFinished() {\n this.finishRequest();\n }\n performScroll() {\n if (!this.scrolled) {\n if (this.action == \"restore\") {\n this.scrollToRestoredPosition() || this.scrollToAnchor() || this.view.scrollToTop();\n }\n else {\n this.scrollToAnchor() || this.view.scrollToTop();\n }\n if (this.isSamePage) {\n this.delegate.visitScrolledToSamePageLocation(this.view.lastRenderedLocation, this.location);\n }\n this.scrolled = true;\n }\n }\n scrollToRestoredPosition() {\n const { scrollPosition } = this.restorationData;\n if (scrollPosition) {\n this.view.scrollToPosition(scrollPosition);\n return true;\n }\n }\n scrollToAnchor() {\n const anchor = getAnchor(this.location);\n if (anchor != null) {\n this.view.scrollToAnchor(anchor);\n return true;\n }\n }\n recordTimingMetric(metric) {\n this.timingMetrics[metric] = new Date().getTime();\n }\n getTimingMetrics() {\n return Object.assign({}, this.timingMetrics);\n }\n getHistoryMethodForAction(action) {\n switch (action) {\n case \"replace\": return history.replaceState;\n case \"advance\":\n case \"restore\": return history.pushState;\n }\n }\n hasPreloadedResponse() {\n return typeof this.response == \"object\";\n }\n shouldIssueRequest() {\n if (this.isSamePage) {\n return false;\n }\n else if (this.action == \"restore\") {\n return !this.hasCachedSnapshot();\n }\n else {\n return this.willRender;\n }\n }\n cacheSnapshot() {\n if (!this.snapshotCached) {\n this.view.cacheSnapshot().then(snapshot => snapshot && this.visitCachedSnapshot(snapshot));\n this.snapshotCached = true;\n }\n }\n async render(callback) {\n this.cancelRender();\n await new Promise(resolve => {\n this.frame = requestAnimationFrame(() => resolve());\n });\n await callback();\n delete this.frame;\n this.performScroll();\n }\n cancelRender() {\n if (this.frame) {\n cancelAnimationFrame(this.frame);\n delete this.frame;\n }\n }\n}\nfunction isSuccessful(statusCode) {\n return statusCode >= 200 && statusCode < 300;\n}\n\nclass BrowserAdapter {\n constructor(session) {\n this.progressBar = new ProgressBar;\n this.showProgressBar = () => {\n this.progressBar.show();\n };\n this.session = session;\n }\n visitProposedToLocation(location, options) {\n this.navigator.startVisit(location, uuid(), options);\n }\n visitStarted(visit) {\n visit.loadCachedSnapshot();\n visit.issueRequest();\n visit.changeHistory();\n visit.goToSamePageAnchor();\n }\n visitRequestStarted(visit) {\n this.progressBar.setValue(0);\n if (visit.hasCachedSnapshot() || visit.action != \"restore\") {\n this.showVisitProgressBarAfterDelay();\n }\n else {\n this.showProgressBar();\n }\n }\n visitRequestCompleted(visit) {\n visit.loadResponse();\n }\n visitRequestFailedWithStatusCode(visit, statusCode) {\n switch (statusCode) {\n case SystemStatusCode.networkFailure:\n case SystemStatusCode.timeoutFailure:\n case SystemStatusCode.contentTypeMismatch:\n return this.reload();\n default:\n return visit.loadResponse();\n }\n }\n visitRequestFinished(visit) {\n this.progressBar.setValue(1);\n this.hideVisitProgressBar();\n }\n visitCompleted(visit) {\n }\n pageInvalidated() {\n this.reload();\n }\n visitFailed(visit) {\n }\n visitRendered(visit) {\n }\n formSubmissionStarted(formSubmission) {\n this.progressBar.setValue(0);\n this.showFormProgressBarAfterDelay();\n }\n formSubmissionFinished(formSubmission) {\n this.progressBar.setValue(1);\n this.hideFormProgressBar();\n }\n showVisitProgressBarAfterDelay() {\n this.visitProgressBarTimeout = window.setTimeout(this.showProgressBar, this.session.progressBarDelay);\n }\n hideVisitProgressBar() {\n this.progressBar.hide();\n if (this.visitProgressBarTimeout != null) {\n window.clearTimeout(this.visitProgressBarTimeout);\n delete this.visitProgressBarTimeout;\n }\n }\n showFormProgressBarAfterDelay() {\n if (this.formProgressBarTimeout == null) {\n this.formProgressBarTimeout = window.setTimeout(this.showProgressBar, this.session.progressBarDelay);\n }\n }\n hideFormProgressBar() {\n this.progressBar.hide();\n if (this.formProgressBarTimeout != null) {\n window.clearTimeout(this.formProgressBarTimeout);\n delete this.formProgressBarTimeout;\n }\n }\n reload() {\n window.location.reload();\n }\n get navigator() {\n return this.session.navigator;\n }\n}\n\nclass CacheObserver {\n constructor() {\n this.started = false;\n }\n start() {\n if (!this.started) {\n this.started = true;\n addEventListener(\"turbo:before-cache\", this.removeStaleElements, false);\n }\n }\n stop() {\n if (this.started) {\n this.started = false;\n removeEventListener(\"turbo:before-cache\", this.removeStaleElements, false);\n }\n }\n removeStaleElements() {\n const staleElements = [...document.querySelectorAll('[data-turbo-cache=\"false\"]')];\n for (const element of staleElements) {\n element.remove();\n }\n }\n}\n\nclass FormSubmitObserver {\n constructor(delegate) {\n this.started = false;\n this.submitCaptured = () => {\n removeEventListener(\"submit\", this.submitBubbled, false);\n addEventListener(\"submit\", this.submitBubbled, false);\n };\n this.submitBubbled = ((event) => {\n if (!event.defaultPrevented) {\n const form = event.target instanceof HTMLFormElement ? event.target : undefined;\n const submitter = event.submitter || undefined;\n if (form) {\n const method = (submitter === null || submitter === void 0 ? void 0 : submitter.getAttribute(\"formmethod\")) || form.getAttribute(\"method\");\n if (method != \"dialog\" && this.delegate.willSubmitForm(form, submitter)) {\n event.preventDefault();\n this.delegate.formSubmitted(form, submitter);\n }\n }\n }\n });\n this.delegate = delegate;\n }\n start() {\n if (!this.started) {\n addEventListener(\"submit\", this.submitCaptured, true);\n this.started = true;\n }\n }\n stop() {\n if (this.started) {\n removeEventListener(\"submit\", this.submitCaptured, true);\n this.started = false;\n }\n }\n}\n\nclass FrameRedirector {\n constructor(element) {\n this.element = element;\n this.linkInterceptor = new LinkInterceptor(this, element);\n this.formInterceptor = new FormInterceptor(this, element);\n }\n start() {\n this.linkInterceptor.start();\n this.formInterceptor.start();\n }\n stop() {\n this.linkInterceptor.stop();\n this.formInterceptor.stop();\n }\n shouldInterceptLinkClick(element, url) {\n return this.shouldRedirect(element);\n }\n linkClickIntercepted(element, url) {\n const frame = this.findFrameElement(element);\n if (frame) {\n frame.delegate.linkClickIntercepted(element, url);\n }\n }\n shouldInterceptFormSubmission(element, submitter) {\n return this.shouldSubmit(element, submitter);\n }\n formSubmissionIntercepted(element, submitter) {\n const frame = this.findFrameElement(element, submitter);\n if (frame) {\n frame.removeAttribute(\"reloadable\");\n frame.delegate.formSubmissionIntercepted(element, submitter);\n }\n }\n shouldSubmit(form, submitter) {\n var _a;\n const action = getAction(form, submitter);\n const meta = this.element.ownerDocument.querySelector(`meta[name=\"turbo-root\"]`);\n const rootLocation = expandURL((_a = meta === null || meta === void 0 ? void 0 : meta.content) !== null && _a !== void 0 ? _a : \"/\");\n return this.shouldRedirect(form, submitter) && locationIsVisitable(action, rootLocation);\n }\n shouldRedirect(element, submitter) {\n const frame = this.findFrameElement(element, submitter);\n return frame ? frame != element.closest(\"turbo-frame\") : false;\n }\n findFrameElement(element, submitter) {\n const id = (submitter === null || submitter === void 0 ? void 0 : submitter.getAttribute(\"data-turbo-frame\")) || element.getAttribute(\"data-turbo-frame\");\n if (id && id != \"_top\") {\n const frame = this.element.querySelector(`#${id}:not([disabled])`);\n if (frame instanceof FrameElement) {\n return frame;\n }\n }\n }\n}\n\nclass History {\n constructor(delegate) {\n this.restorationIdentifier = uuid();\n this.restorationData = {};\n this.started = false;\n this.pageLoaded = false;\n this.onPopState = (event) => {\n if (this.shouldHandlePopState()) {\n const { turbo } = event.state || {};\n if (turbo) {\n this.location = new URL(window.location.href);\n const { restorationIdentifier } = turbo;\n this.restorationIdentifier = restorationIdentifier;\n this.delegate.historyPoppedToLocationWithRestorationIdentifier(this.location, restorationIdentifier);\n }\n }\n };\n this.onPageLoad = async (event) => {\n await nextMicrotask();\n this.pageLoaded = true;\n };\n this.delegate = delegate;\n }\n start() {\n if (!this.started) {\n addEventListener(\"popstate\", this.onPopState, false);\n addEventListener(\"load\", this.onPageLoad, false);\n this.started = true;\n this.replace(new URL(window.location.href));\n }\n }\n stop() {\n if (this.started) {\n removeEventListener(\"popstate\", this.onPopState, false);\n removeEventListener(\"load\", this.onPageLoad, false);\n this.started = false;\n }\n }\n push(location, restorationIdentifier) {\n this.update(history.pushState, location, restorationIdentifier);\n }\n replace(location, restorationIdentifier) {\n this.update(history.replaceState, location, restorationIdentifier);\n }\n update(method, location, restorationIdentifier = uuid()) {\n const state = { turbo: { restorationIdentifier } };\n method.call(history, state, \"\", location.href);\n this.location = location;\n this.restorationIdentifier = restorationIdentifier;\n }\n getRestorationDataForIdentifier(restorationIdentifier) {\n return this.restorationData[restorationIdentifier] || {};\n }\n updateRestorationData(additionalData) {\n const { restorationIdentifier } = this;\n const restorationData = this.restorationData[restorationIdentifier];\n this.restorationData[restorationIdentifier] = Object.assign(Object.assign({}, restorationData), additionalData);\n }\n assumeControlOfScrollRestoration() {\n var _a;\n if (!this.previousScrollRestoration) {\n this.previousScrollRestoration = (_a = history.scrollRestoration) !== null && _a !== void 0 ? _a : \"auto\";\n history.scrollRestoration = \"manual\";\n }\n }\n relinquishControlOfScrollRestoration() {\n if (this.previousScrollRestoration) {\n history.scrollRestoration = this.previousScrollRestoration;\n delete this.previousScrollRestoration;\n }\n }\n shouldHandlePopState() {\n return this.pageIsLoaded();\n }\n pageIsLoaded() {\n return this.pageLoaded || document.readyState == \"complete\";\n }\n}\n\nclass LinkClickObserver {\n constructor(delegate) {\n this.started = false;\n this.clickCaptured = () => {\n removeEventListener(\"click\", this.clickBubbled, false);\n addEventListener(\"click\", this.clickBubbled, false);\n };\n this.clickBubbled = (event) => {\n if (this.clickEventIsSignificant(event)) {\n const target = (event.composedPath && event.composedPath()[0]) || event.target;\n const link = this.findLinkFromClickTarget(target);\n if (link) {\n const location = this.getLocationForLink(link);\n if (this.delegate.willFollowLinkToLocation(link, location)) {\n event.preventDefault();\n this.delegate.followedLinkToLocation(link, location);\n }\n }\n }\n };\n this.delegate = delegate;\n }\n start() {\n if (!this.started) {\n addEventListener(\"click\", this.clickCaptured, true);\n this.started = true;\n }\n }\n stop() {\n if (this.started) {\n removeEventListener(\"click\", this.clickCaptured, true);\n this.started = false;\n }\n }\n clickEventIsSignificant(event) {\n return !((event.target && event.target.isContentEditable)\n || event.defaultPrevented\n || event.which > 1\n || event.altKey\n || event.ctrlKey\n || event.metaKey\n || event.shiftKey);\n }\n findLinkFromClickTarget(target) {\n if (target instanceof Element) {\n return target.closest(\"a[href]:not([target^=_]):not([download])\");\n }\n }\n getLocationForLink(link) {\n return expandURL(link.getAttribute(\"href\") || \"\");\n }\n}\n\nfunction isAction(action) {\n return action == \"advance\" || action == \"replace\" || action == \"restore\";\n}\n\nclass Navigator {\n constructor(delegate) {\n this.delegate = delegate;\n }\n proposeVisit(location, options = {}) {\n if (this.delegate.allowsVisitingLocationWithAction(location, options.action)) {\n if (locationIsVisitable(location, this.view.snapshot.rootLocation)) {\n this.delegate.visitProposedToLocation(location, options);\n }\n else {\n window.location.href = location.toString();\n }\n }\n }\n startVisit(locatable, restorationIdentifier, options = {}) {\n this.stop();\n this.currentVisit = new Visit(this, expandURL(locatable), restorationIdentifier, Object.assign({ referrer: this.location }, options));\n this.currentVisit.start();\n }\n submitForm(form, submitter) {\n this.stop();\n this.formSubmission = new FormSubmission(this, form, submitter, true);\n this.formSubmission.start();\n }\n stop() {\n if (this.formSubmission) {\n this.formSubmission.stop();\n delete this.formSubmission;\n }\n if (this.currentVisit) {\n this.currentVisit.cancel();\n delete this.currentVisit;\n }\n }\n get adapter() {\n return this.delegate.adapter;\n }\n get view() {\n return this.delegate.view;\n }\n get history() {\n return this.delegate.history;\n }\n formSubmissionStarted(formSubmission) {\n if (typeof this.adapter.formSubmissionStarted === 'function') {\n this.adapter.formSubmissionStarted(formSubmission);\n }\n }\n async formSubmissionSucceededWithResponse(formSubmission, fetchResponse) {\n if (formSubmission == this.formSubmission) {\n const responseHTML = await fetchResponse.responseHTML;\n if (responseHTML) {\n if (formSubmission.method != FetchMethod.get) {\n this.view.clearSnapshotCache();\n }\n const { statusCode, redirected } = fetchResponse;\n const action = this.getActionForFormSubmission(formSubmission);\n const visitOptions = { action, response: { statusCode, responseHTML, redirected } };\n this.proposeVisit(fetchResponse.location, visitOptions);\n }\n }\n }\n async formSubmissionFailedWithResponse(formSubmission, fetchResponse) {\n const responseHTML = await fetchResponse.responseHTML;\n if (responseHTML) {\n const snapshot = PageSnapshot.fromHTMLString(responseHTML);\n if (fetchResponse.serverError) {\n await this.view.renderError(snapshot);\n }\n else {\n await this.view.renderPage(snapshot);\n }\n this.view.scrollToTop();\n this.view.clearSnapshotCache();\n }\n }\n formSubmissionErrored(formSubmission, error) {\n console.error(error);\n }\n formSubmissionFinished(formSubmission) {\n if (typeof this.adapter.formSubmissionFinished === 'function') {\n this.adapter.formSubmissionFinished(formSubmission);\n }\n }\n visitStarted(visit) {\n this.delegate.visitStarted(visit);\n }\n visitCompleted(visit) {\n this.delegate.visitCompleted(visit);\n }\n locationWithActionIsSamePage(location, action) {\n const anchor = getAnchor(location);\n const currentAnchor = getAnchor(this.view.lastRenderedLocation);\n const isRestorationToTop = action === 'restore' && typeof anchor === 'undefined';\n return action !== \"replace\" &&\n getRequestURL(location) === getRequestURL(this.view.lastRenderedLocation) &&\n (isRestorationToTop || (anchor != null && anchor !== currentAnchor));\n }\n visitScrolledToSamePageLocation(oldURL, newURL) {\n this.delegate.visitScrolledToSamePageLocation(oldURL, newURL);\n }\n get location() {\n return this.history.location;\n }\n get restorationIdentifier() {\n return this.history.restorationIdentifier;\n }\n getActionForFormSubmission(formSubmission) {\n const { formElement, submitter } = formSubmission;\n const action = getAttribute(\"data-turbo-action\", submitter, formElement);\n return isAction(action) ? action : \"advance\";\n }\n}\n\nvar PageStage;\n(function (PageStage) {\n PageStage[PageStage[\"initial\"] = 0] = \"initial\";\n PageStage[PageStage[\"loading\"] = 1] = \"loading\";\n PageStage[PageStage[\"interactive\"] = 2] = \"interactive\";\n PageStage[PageStage[\"complete\"] = 3] = \"complete\";\n})(PageStage || (PageStage = {}));\nclass PageObserver {\n constructor(delegate) {\n this.stage = PageStage.initial;\n this.started = false;\n this.interpretReadyState = () => {\n const { readyState } = this;\n if (readyState == \"interactive\") {\n this.pageIsInteractive();\n }\n else if (readyState == \"complete\") {\n this.pageIsComplete();\n }\n };\n this.pageWillUnload = () => {\n this.delegate.pageWillUnload();\n };\n this.delegate = delegate;\n }\n start() {\n if (!this.started) {\n if (this.stage == PageStage.initial) {\n this.stage = PageStage.loading;\n }\n document.addEventListener(\"readystatechange\", this.interpretReadyState, false);\n addEventListener(\"pagehide\", this.pageWillUnload, false);\n this.started = true;\n }\n }\n stop() {\n if (this.started) {\n document.removeEventListener(\"readystatechange\", this.interpretReadyState, false);\n removeEventListener(\"pagehide\", this.pageWillUnload, false);\n this.started = false;\n }\n }\n pageIsInteractive() {\n if (this.stage == PageStage.loading) {\n this.stage = PageStage.interactive;\n this.delegate.pageBecameInteractive();\n }\n }\n pageIsComplete() {\n this.pageIsInteractive();\n if (this.stage == PageStage.interactive) {\n this.stage = PageStage.complete;\n this.delegate.pageLoaded();\n }\n }\n get readyState() {\n return document.readyState;\n }\n}\n\nclass ScrollObserver {\n constructor(delegate) {\n this.started = false;\n this.onScroll = () => {\n this.updatePosition({ x: window.pageXOffset, y: window.pageYOffset });\n };\n this.delegate = delegate;\n }\n start() {\n if (!this.started) {\n addEventListener(\"scroll\", this.onScroll, false);\n this.onScroll();\n this.started = true;\n }\n }\n stop() {\n if (this.started) {\n removeEventListener(\"scroll\", this.onScroll, false);\n this.started = false;\n }\n }\n updatePosition(position) {\n this.delegate.scrollPositionChanged(position);\n }\n}\n\nclass StreamObserver {\n constructor(delegate) {\n this.sources = new Set;\n this.started = false;\n this.inspectFetchResponse = ((event) => {\n const response = fetchResponseFromEvent(event);\n if (response && fetchResponseIsStream(response)) {\n event.preventDefault();\n this.receiveMessageResponse(response);\n }\n });\n this.receiveMessageEvent = (event) => {\n if (this.started && typeof event.data == \"string\") {\n this.receiveMessageHTML(event.data);\n }\n };\n this.delegate = delegate;\n }\n start() {\n if (!this.started) {\n this.started = true;\n addEventListener(\"turbo:before-fetch-response\", this.inspectFetchResponse, false);\n }\n }\n stop() {\n if (this.started) {\n this.started = false;\n removeEventListener(\"turbo:before-fetch-response\", this.inspectFetchResponse, false);\n }\n }\n connectStreamSource(source) {\n if (!this.streamSourceIsConnected(source)) {\n this.sources.add(source);\n source.addEventListener(\"message\", this.receiveMessageEvent, false);\n }\n }\n disconnectStreamSource(source) {\n if (this.streamSourceIsConnected(source)) {\n this.sources.delete(source);\n source.removeEventListener(\"message\", this.receiveMessageEvent, false);\n }\n }\n streamSourceIsConnected(source) {\n return this.sources.has(source);\n }\n async receiveMessageResponse(response) {\n const html = await response.responseHTML;\n if (html) {\n this.receiveMessageHTML(html);\n }\n }\n receiveMessageHTML(html) {\n this.delegate.receivedMessageFromStream(new StreamMessage(html));\n }\n}\nfunction fetchResponseFromEvent(event) {\n var _a;\n const fetchResponse = (_a = event.detail) === null || _a === void 0 ? void 0 : _a.fetchResponse;\n if (fetchResponse instanceof FetchResponse) {\n return fetchResponse;\n }\n}\nfunction fetchResponseIsStream(response) {\n var _a;\n const contentType = (_a = response.contentType) !== null && _a !== void 0 ? _a : \"\";\n return contentType.startsWith(StreamMessage.contentType);\n}\n\nclass ErrorRenderer extends Renderer {\n async render() {\n this.replaceHeadAndBody();\n this.activateScriptElements();\n }\n replaceHeadAndBody() {\n const { documentElement, head, body } = document;\n documentElement.replaceChild(this.newHead, head);\n documentElement.replaceChild(this.newElement, body);\n }\n activateScriptElements() {\n for (const replaceableElement of this.scriptElements) {\n const parentNode = replaceableElement.parentNode;\n if (parentNode) {\n const element = this.createScriptElement(replaceableElement);\n parentNode.replaceChild(element, replaceableElement);\n }\n }\n }\n get newHead() {\n return this.newSnapshot.headSnapshot.element;\n }\n get scriptElements() {\n return [...document.documentElement.querySelectorAll(\"script\")];\n }\n}\n\nclass PageRenderer extends Renderer {\n get shouldRender() {\n return this.newSnapshot.isVisitable && this.trackedElementsAreIdentical;\n }\n prepareToRender() {\n this.mergeHead();\n }\n async render() {\n if (this.willRender) {\n this.replaceBody();\n }\n }\n finishRendering() {\n super.finishRendering();\n if (!this.isPreview) {\n this.focusFirstAutofocusableElement();\n }\n }\n get currentHeadSnapshot() {\n return this.currentSnapshot.headSnapshot;\n }\n get newHeadSnapshot() {\n return this.newSnapshot.headSnapshot;\n }\n get newElement() {\n return this.newSnapshot.element;\n }\n mergeHead() {\n this.copyNewHeadStylesheetElements();\n this.copyNewHeadScriptElements();\n this.removeCurrentHeadProvisionalElements();\n this.copyNewHeadProvisionalElements();\n }\n replaceBody() {\n this.preservingPermanentElements(() => {\n this.activateNewBody();\n this.assignNewBody();\n });\n }\n get trackedElementsAreIdentical() {\n return this.currentHeadSnapshot.trackedElementSignature == this.newHeadSnapshot.trackedElementSignature;\n }\n copyNewHeadStylesheetElements() {\n for (const element of this.newHeadStylesheetElements) {\n document.head.appendChild(element);\n }\n }\n copyNewHeadScriptElements() {\n for (const element of this.newHeadScriptElements) {\n document.head.appendChild(this.createScriptElement(element));\n }\n }\n removeCurrentHeadProvisionalElements() {\n for (const element of this.currentHeadProvisionalElements) {\n document.head.removeChild(element);\n }\n }\n copyNewHeadProvisionalElements() {\n for (const element of this.newHeadProvisionalElements) {\n document.head.appendChild(element);\n }\n }\n activateNewBody() {\n document.adoptNode(this.newElement);\n this.activateNewBodyScriptElements();\n }\n activateNewBodyScriptElements() {\n for (const inertScriptElement of this.newBodyScriptElements) {\n const activatedScriptElement = this.createScriptElement(inertScriptElement);\n inertScriptElement.replaceWith(activatedScriptElement);\n }\n }\n assignNewBody() {\n if (document.body && this.newElement instanceof HTMLBodyElement) {\n document.body.replaceWith(this.newElement);\n }\n else {\n document.documentElement.appendChild(this.newElement);\n }\n }\n get newHeadStylesheetElements() {\n return this.newHeadSnapshot.getStylesheetElementsNotInSnapshot(this.currentHeadSnapshot);\n }\n get newHeadScriptElements() {\n return this.newHeadSnapshot.getScriptElementsNotInSnapshot(this.currentHeadSnapshot);\n }\n get currentHeadProvisionalElements() {\n return this.currentHeadSnapshot.provisionalElements;\n }\n get newHeadProvisionalElements() {\n return this.newHeadSnapshot.provisionalElements;\n }\n get newBodyScriptElements() {\n return this.newElement.querySelectorAll(\"script\");\n }\n}\n\nclass SnapshotCache {\n constructor(size) {\n this.keys = [];\n this.snapshots = {};\n this.size = size;\n }\n has(location) {\n return toCacheKey(location) in this.snapshots;\n }\n get(location) {\n if (this.has(location)) {\n const snapshot = this.read(location);\n this.touch(location);\n return snapshot;\n }\n }\n put(location, snapshot) {\n this.write(location, snapshot);\n this.touch(location);\n return snapshot;\n }\n clear() {\n this.snapshots = {};\n }\n read(location) {\n return this.snapshots[toCacheKey(location)];\n }\n write(location, snapshot) {\n this.snapshots[toCacheKey(location)] = snapshot;\n }\n touch(location) {\n const key = toCacheKey(location);\n const index = this.keys.indexOf(key);\n if (index > -1)\n this.keys.splice(index, 1);\n this.keys.unshift(key);\n this.trim();\n }\n trim() {\n for (const key of this.keys.splice(this.size)) {\n delete this.snapshots[key];\n }\n }\n}\n\nclass PageView extends View {\n constructor() {\n super(...arguments);\n this.snapshotCache = new SnapshotCache(10);\n this.lastRenderedLocation = new URL(location.href);\n }\n renderPage(snapshot, isPreview = false, willRender = true) {\n const renderer = new PageRenderer(this.snapshot, snapshot, isPreview, willRender);\n return this.render(renderer);\n }\n renderError(snapshot) {\n const renderer = new ErrorRenderer(this.snapshot, snapshot, false);\n return this.render(renderer);\n }\n clearSnapshotCache() {\n this.snapshotCache.clear();\n }\n async cacheSnapshot() {\n if (this.shouldCacheSnapshot) {\n this.delegate.viewWillCacheSnapshot();\n const { snapshot, lastRenderedLocation: location } = this;\n await nextEventLoopTick();\n const cachedSnapshot = snapshot.clone();\n this.snapshotCache.put(location, cachedSnapshot);\n return cachedSnapshot;\n }\n }\n getCachedSnapshotForLocation(location) {\n return this.snapshotCache.get(location);\n }\n get snapshot() {\n return PageSnapshot.fromElement(this.element);\n }\n get shouldCacheSnapshot() {\n return this.snapshot.isCacheable;\n }\n}\n\nclass Session {\n constructor() {\n this.navigator = new Navigator(this);\n this.history = new History(this);\n this.view = new PageView(this, document.documentElement);\n this.adapter = new BrowserAdapter(this);\n this.pageObserver = new PageObserver(this);\n this.cacheObserver = new CacheObserver();\n this.linkClickObserver = new LinkClickObserver(this);\n this.formSubmitObserver = new FormSubmitObserver(this);\n this.scrollObserver = new ScrollObserver(this);\n this.streamObserver = new StreamObserver(this);\n this.frameRedirector = new FrameRedirector(document.documentElement);\n this.drive = true;\n this.enabled = true;\n this.progressBarDelay = 500;\n this.started = false;\n }\n start() {\n if (!this.started) {\n this.pageObserver.start();\n this.cacheObserver.start();\n this.linkClickObserver.start();\n this.formSubmitObserver.start();\n this.scrollObserver.start();\n this.streamObserver.start();\n this.frameRedirector.start();\n this.history.start();\n this.started = true;\n this.enabled = true;\n }\n }\n disable() {\n this.enabled = false;\n }\n stop() {\n if (this.started) {\n this.pageObserver.stop();\n this.cacheObserver.stop();\n this.linkClickObserver.stop();\n this.formSubmitObserver.stop();\n this.scrollObserver.stop();\n this.streamObserver.stop();\n this.frameRedirector.stop();\n this.history.stop();\n this.started = false;\n }\n }\n registerAdapter(adapter) {\n this.adapter = adapter;\n }\n visit(location, options = {}) {\n this.navigator.proposeVisit(expandURL(location), options);\n }\n connectStreamSource(source) {\n this.streamObserver.connectStreamSource(source);\n }\n disconnectStreamSource(source) {\n this.streamObserver.disconnectStreamSource(source);\n }\n renderStreamMessage(message) {\n document.documentElement.appendChild(StreamMessage.wrap(message).fragment);\n }\n clearCache() {\n this.view.clearSnapshotCache();\n }\n setProgressBarDelay(delay) {\n this.progressBarDelay = delay;\n }\n get location() {\n return this.history.location;\n }\n get restorationIdentifier() {\n return this.history.restorationIdentifier;\n }\n historyPoppedToLocationWithRestorationIdentifier(location, restorationIdentifier) {\n if (this.enabled) {\n this.navigator.startVisit(location, restorationIdentifier, { action: \"restore\", historyChanged: true });\n }\n else {\n this.adapter.pageInvalidated();\n }\n }\n scrollPositionChanged(position) {\n this.history.updateRestorationData({ scrollPosition: position });\n }\n willFollowLinkToLocation(link, location) {\n return this.elementDriveEnabled(link)\n && locationIsVisitable(location, this.snapshot.rootLocation)\n && this.applicationAllowsFollowingLinkToLocation(link, location);\n }\n followedLinkToLocation(link, location) {\n const action = this.getActionForLink(link);\n this.convertLinkWithMethodClickToFormSubmission(link) || this.visit(location.href, { action });\n }\n convertLinkWithMethodClickToFormSubmission(link) {\n const linkMethod = link.getAttribute(\"data-turbo-method\");\n if (linkMethod) {\n const form = document.createElement(\"form\");\n form.method = linkMethod;\n form.action = link.getAttribute(\"href\") || \"undefined\";\n form.hidden = true;\n if (link.hasAttribute(\"data-turbo-confirm\")) {\n form.setAttribute(\"data-turbo-confirm\", link.getAttribute(\"data-turbo-confirm\"));\n }\n const frame = this.getTargetFrameForLink(link);\n if (frame) {\n form.setAttribute(\"data-turbo-frame\", frame);\n form.addEventListener(\"turbo:submit-start\", () => form.remove());\n }\n else {\n form.addEventListener(\"submit\", () => form.remove());\n }\n document.body.appendChild(form);\n return dispatch(\"submit\", { cancelable: true, target: form });\n }\n else {\n return false;\n }\n }\n allowsVisitingLocationWithAction(location, action) {\n return this.locationWithActionIsSamePage(location, action) || this.applicationAllowsVisitingLocation(location);\n }\n visitProposedToLocation(location, options) {\n extendURLWithDeprecatedProperties(location);\n this.adapter.visitProposedToLocation(location, options);\n }\n visitStarted(visit) {\n extendURLWithDeprecatedProperties(visit.location);\n if (!visit.silent) {\n this.notifyApplicationAfterVisitingLocation(visit.location, visit.action);\n }\n }\n visitCompleted(visit) {\n this.notifyApplicationAfterPageLoad(visit.getTimingMetrics());\n }\n locationWithActionIsSamePage(location, action) {\n return this.navigator.locationWithActionIsSamePage(location, action);\n }\n visitScrolledToSamePageLocation(oldURL, newURL) {\n this.notifyApplicationAfterVisitingSamePageLocation(oldURL, newURL);\n }\n willSubmitForm(form, submitter) {\n const action = getAction(form, submitter);\n return this.elementDriveEnabled(form)\n && (!submitter || this.elementDriveEnabled(submitter))\n && locationIsVisitable(expandURL(action), this.snapshot.rootLocation);\n }\n formSubmitted(form, submitter) {\n this.navigator.submitForm(form, submitter);\n }\n pageBecameInteractive() {\n this.view.lastRenderedLocation = this.location;\n this.notifyApplicationAfterPageLoad();\n }\n pageLoaded() {\n this.history.assumeControlOfScrollRestoration();\n }\n pageWillUnload() {\n this.history.relinquishControlOfScrollRestoration();\n }\n receivedMessageFromStream(message) {\n this.renderStreamMessage(message);\n }\n viewWillCacheSnapshot() {\n var _a;\n if (!((_a = this.navigator.currentVisit) === null || _a === void 0 ? void 0 : _a.silent)) {\n this.notifyApplicationBeforeCachingSnapshot();\n }\n }\n allowsImmediateRender({ element }, resume) {\n const event = this.notifyApplicationBeforeRender(element, resume);\n return !event.defaultPrevented;\n }\n viewRenderedSnapshot(snapshot, isPreview) {\n this.view.lastRenderedLocation = this.history.location;\n this.notifyApplicationAfterRender();\n }\n viewInvalidated() {\n this.adapter.pageInvalidated();\n }\n frameLoaded(frame) {\n this.notifyApplicationAfterFrameLoad(frame);\n }\n frameRendered(fetchResponse, frame) {\n this.notifyApplicationAfterFrameRender(fetchResponse, frame);\n }\n applicationAllowsFollowingLinkToLocation(link, location) {\n const event = this.notifyApplicationAfterClickingLinkToLocation(link, location);\n return !event.defaultPrevented;\n }\n applicationAllowsVisitingLocation(location) {\n const event = this.notifyApplicationBeforeVisitingLocation(location);\n return !event.defaultPrevented;\n }\n notifyApplicationAfterClickingLinkToLocation(link, location) {\n return dispatch(\"turbo:click\", { target: link, detail: { url: location.href }, cancelable: true });\n }\n notifyApplicationBeforeVisitingLocation(location) {\n return dispatch(\"turbo:before-visit\", { detail: { url: location.href }, cancelable: true });\n }\n notifyApplicationAfterVisitingLocation(location, action) {\n markAsBusy(document.documentElement);\n return dispatch(\"turbo:visit\", { detail: { url: location.href, action } });\n }\n notifyApplicationBeforeCachingSnapshot() {\n return dispatch(\"turbo:before-cache\");\n }\n notifyApplicationBeforeRender(newBody, resume) {\n return dispatch(\"turbo:before-render\", { detail: { newBody, resume }, cancelable: true });\n }\n notifyApplicationAfterRender() {\n return dispatch(\"turbo:render\");\n }\n notifyApplicationAfterPageLoad(timing = {}) {\n clearBusyState(document.documentElement);\n return dispatch(\"turbo:load\", { detail: { url: this.location.href, timing } });\n }\n notifyApplicationAfterVisitingSamePageLocation(oldURL, newURL) {\n dispatchEvent(new HashChangeEvent(\"hashchange\", { oldURL: oldURL.toString(), newURL: newURL.toString() }));\n }\n notifyApplicationAfterFrameLoad(frame) {\n return dispatch(\"turbo:frame-load\", { target: frame });\n }\n notifyApplicationAfterFrameRender(fetchResponse, frame) {\n return dispatch(\"turbo:frame-render\", { detail: { fetchResponse }, target: frame, cancelable: true });\n }\n elementDriveEnabled(element) {\n const container = element === null || element === void 0 ? void 0 : element.closest(\"[data-turbo]\");\n if (this.drive) {\n if (container) {\n return container.getAttribute(\"data-turbo\") != \"false\";\n }\n else {\n return true;\n }\n }\n else {\n if (container) {\n return container.getAttribute(\"data-turbo\") == \"true\";\n }\n else {\n return false;\n }\n }\n }\n getActionForLink(link) {\n const action = link.getAttribute(\"data-turbo-action\");\n return isAction(action) ? action : \"advance\";\n }\n getTargetFrameForLink(link) {\n const frame = link.getAttribute(\"data-turbo-frame\");\n if (frame) {\n return frame;\n }\n else {\n const container = link.closest(\"turbo-frame\");\n if (container) {\n return container.id;\n }\n }\n }\n get snapshot() {\n return this.view.snapshot;\n }\n}\nfunction extendURLWithDeprecatedProperties(url) {\n Object.defineProperties(url, deprecatedLocationPropertyDescriptors);\n}\nconst deprecatedLocationPropertyDescriptors = {\n absoluteURL: {\n get() {\n return this.toString();\n }\n }\n};\n\nconst session = new Session;\nconst { navigator: navigator$1 } = session;\nfunction start() {\n session.start();\n}\nfunction registerAdapter(adapter) {\n session.registerAdapter(adapter);\n}\nfunction visit(location, options) {\n session.visit(location, options);\n}\nfunction connectStreamSource(source) {\n session.connectStreamSource(source);\n}\nfunction disconnectStreamSource(source) {\n session.disconnectStreamSource(source);\n}\nfunction renderStreamMessage(message) {\n session.renderStreamMessage(message);\n}\nfunction clearCache() {\n session.clearCache();\n}\nfunction setProgressBarDelay(delay) {\n session.setProgressBarDelay(delay);\n}\nfunction setConfirmMethod(confirmMethod) {\n FormSubmission.confirmMethod = confirmMethod;\n}\n\nvar Turbo = /*#__PURE__*/Object.freeze({\n __proto__: null,\n navigator: navigator$1,\n session: session,\n PageRenderer: PageRenderer,\n PageSnapshot: PageSnapshot,\n start: start,\n registerAdapter: registerAdapter,\n visit: visit,\n connectStreamSource: connectStreamSource,\n disconnectStreamSource: disconnectStreamSource,\n renderStreamMessage: renderStreamMessage,\n clearCache: clearCache,\n setProgressBarDelay: setProgressBarDelay,\n setConfirmMethod: setConfirmMethod\n});\n\nclass FrameController {\n constructor(element) {\n this.fetchResponseLoaded = (fetchResponse) => { };\n this.currentFetchRequest = null;\n this.resolveVisitPromise = () => { };\n this.connected = false;\n this.hasBeenLoaded = false;\n this.settingSourceURL = false;\n this.element = element;\n this.view = new FrameView(this, this.element);\n this.appearanceObserver = new AppearanceObserver(this, this.element);\n this.linkInterceptor = new LinkInterceptor(this, this.element);\n this.formInterceptor = new FormInterceptor(this, this.element);\n }\n connect() {\n if (!this.connected) {\n this.connected = true;\n this.reloadable = false;\n if (this.loadingStyle == FrameLoadingStyle.lazy) {\n this.appearanceObserver.start();\n }\n this.linkInterceptor.start();\n this.formInterceptor.start();\n this.sourceURLChanged();\n }\n }\n disconnect() {\n if (this.connected) {\n this.connected = false;\n this.appearanceObserver.stop();\n this.linkInterceptor.stop();\n this.formInterceptor.stop();\n }\n }\n disabledChanged() {\n if (this.loadingStyle == FrameLoadingStyle.eager) {\n this.loadSourceURL();\n }\n }\n sourceURLChanged() {\n if (this.loadingStyle == FrameLoadingStyle.eager || this.hasBeenLoaded) {\n this.loadSourceURL();\n }\n }\n loadingStyleChanged() {\n if (this.loadingStyle == FrameLoadingStyle.lazy) {\n this.appearanceObserver.start();\n }\n else {\n this.appearanceObserver.stop();\n this.loadSourceURL();\n }\n }\n async loadSourceURL() {\n if (!this.settingSourceURL && this.enabled && this.isActive && (this.reloadable || this.sourceURL != this.currentURL)) {\n const previousURL = this.currentURL;\n this.currentURL = this.sourceURL;\n if (this.sourceURL) {\n try {\n this.element.loaded = this.visit(expandURL(this.sourceURL));\n this.appearanceObserver.stop();\n await this.element.loaded;\n this.hasBeenLoaded = true;\n }\n catch (error) {\n this.currentURL = previousURL;\n throw error;\n }\n }\n }\n }\n async loadResponse(fetchResponse) {\n if (fetchResponse.redirected || (fetchResponse.succeeded && fetchResponse.isHTML)) {\n this.sourceURL = fetchResponse.response.url;\n }\n try {\n const html = await fetchResponse.responseHTML;\n if (html) {\n const { body } = parseHTMLDocument(html);\n const snapshot = new Snapshot(await this.extractForeignFrameElement(body));\n const renderer = new FrameRenderer(this.view.snapshot, snapshot, false, false);\n if (this.view.renderPromise)\n await this.view.renderPromise;\n await this.view.render(renderer);\n session.frameRendered(fetchResponse, this.element);\n session.frameLoaded(this.element);\n this.fetchResponseLoaded(fetchResponse);\n }\n }\n catch (error) {\n console.error(error);\n this.view.invalidate();\n }\n finally {\n this.fetchResponseLoaded = () => { };\n }\n }\n elementAppearedInViewport(element) {\n this.loadSourceURL();\n }\n shouldInterceptLinkClick(element, url) {\n if (element.hasAttribute(\"data-turbo-method\")) {\n return false;\n }\n else {\n return this.shouldInterceptNavigation(element);\n }\n }\n linkClickIntercepted(element, url) {\n this.reloadable = true;\n this.navigateFrame(element, url);\n }\n shouldInterceptFormSubmission(element, submitter) {\n return this.shouldInterceptNavigation(element, submitter);\n }\n formSubmissionIntercepted(element, submitter) {\n if (this.formSubmission) {\n this.formSubmission.stop();\n }\n this.reloadable = false;\n this.formSubmission = new FormSubmission(this, element, submitter);\n const { fetchRequest } = this.formSubmission;\n this.prepareHeadersForRequest(fetchRequest.headers, fetchRequest);\n this.formSubmission.start();\n }\n prepareHeadersForRequest(headers, request) {\n headers[\"Turbo-Frame\"] = this.id;\n }\n requestStarted(request) {\n markAsBusy(this.element);\n }\n requestPreventedHandlingResponse(request, response) {\n this.resolveVisitPromise();\n }\n async requestSucceededWithResponse(request, response) {\n await this.loadResponse(response);\n this.resolveVisitPromise();\n }\n requestFailedWithResponse(request, response) {\n console.error(response);\n this.resolveVisitPromise();\n }\n requestErrored(request, error) {\n console.error(error);\n this.resolveVisitPromise();\n }\n requestFinished(request) {\n clearBusyState(this.element);\n }\n formSubmissionStarted({ formElement }) {\n markAsBusy(formElement, this.findFrameElement(formElement));\n }\n formSubmissionSucceededWithResponse(formSubmission, response) {\n const frame = this.findFrameElement(formSubmission.formElement, formSubmission.submitter);\n this.proposeVisitIfNavigatedWithAction(frame, formSubmission.formElement, formSubmission.submitter);\n frame.delegate.loadResponse(response);\n }\n formSubmissionFailedWithResponse(formSubmission, fetchResponse) {\n this.element.delegate.loadResponse(fetchResponse);\n }\n formSubmissionErrored(formSubmission, error) {\n console.error(error);\n }\n formSubmissionFinished({ formElement }) {\n clearBusyState(formElement, this.findFrameElement(formElement));\n }\n allowsImmediateRender(snapshot, resume) {\n return true;\n }\n viewRenderedSnapshot(snapshot, isPreview) {\n }\n viewInvalidated() {\n }\n async visit(url) {\n var _a;\n const request = new FetchRequest(this, FetchMethod.get, url, new URLSearchParams, this.element);\n (_a = this.currentFetchRequest) === null || _a === void 0 ? void 0 : _a.cancel();\n this.currentFetchRequest = request;\n return new Promise(resolve => {\n this.resolveVisitPromise = () => {\n this.resolveVisitPromise = () => { };\n this.currentFetchRequest = null;\n resolve();\n };\n request.perform();\n });\n }\n navigateFrame(element, url, submitter) {\n const frame = this.findFrameElement(element, submitter);\n this.proposeVisitIfNavigatedWithAction(frame, element, submitter);\n frame.setAttribute(\"reloadable\", \"\");\n frame.src = url;\n }\n proposeVisitIfNavigatedWithAction(frame, element, submitter) {\n const action = getAttribute(\"data-turbo-action\", submitter, element, frame);\n if (isAction(action)) {\n const { visitCachedSnapshot } = new SnapshotSubstitution(frame);\n frame.delegate.fetchResponseLoaded = (fetchResponse) => {\n if (frame.src) {\n const { statusCode, redirected } = fetchResponse;\n const responseHTML = frame.ownerDocument.documentElement.outerHTML;\n const response = { statusCode, redirected, responseHTML };\n session.visit(frame.src, { action, response, visitCachedSnapshot, willRender: false });\n }\n };\n }\n }\n findFrameElement(element, submitter) {\n var _a;\n const id = getAttribute(\"data-turbo-frame\", submitter, element) || this.element.getAttribute(\"target\");\n return (_a = getFrameElementById(id)) !== null && _a !== void 0 ? _a : this.element;\n }\n async extractForeignFrameElement(container) {\n let element;\n const id = CSS.escape(this.id);\n try {\n if (element = activateElement(container.querySelector(`turbo-frame#${id}`), this.currentURL)) {\n return element;\n }\n if (element = activateElement(container.querySelector(`turbo-frame[src][recurse~=${id}]`), this.currentURL)) {\n await element.loaded;\n return await this.extractForeignFrameElement(element);\n }\n console.error(`Response has no matching element`);\n }\n catch (error) {\n console.error(error);\n }\n return new FrameElement();\n }\n formActionIsVisitable(form, submitter) {\n const action = getAction(form, submitter);\n return locationIsVisitable(expandURL(action), this.rootLocation);\n }\n shouldInterceptNavigation(element, submitter) {\n const id = getAttribute(\"data-turbo-frame\", submitter, element) || this.element.getAttribute(\"target\");\n if (element instanceof HTMLFormElement && !this.formActionIsVisitable(element, submitter)) {\n return false;\n }\n if (!this.enabled || id == \"_top\") {\n return false;\n }\n if (id) {\n const frameElement = getFrameElementById(id);\n if (frameElement) {\n return !frameElement.disabled;\n }\n }\n if (!session.elementDriveEnabled(element)) {\n return false;\n }\n if (submitter && !session.elementDriveEnabled(submitter)) {\n return false;\n }\n return true;\n }\n get id() {\n return this.element.id;\n }\n get enabled() {\n return !this.element.disabled;\n }\n get sourceURL() {\n if (this.element.src) {\n return this.element.src;\n }\n }\n get reloadable() {\n const frame = this.findFrameElement(this.element);\n return frame.hasAttribute(\"reloadable\");\n }\n set reloadable(value) {\n const frame = this.findFrameElement(this.element);\n if (value) {\n frame.setAttribute(\"reloadable\", \"\");\n }\n else {\n frame.removeAttribute(\"reloadable\");\n }\n }\n set sourceURL(sourceURL) {\n this.settingSourceURL = true;\n this.element.src = sourceURL !== null && sourceURL !== void 0 ? sourceURL : null;\n this.currentURL = this.element.src;\n this.settingSourceURL = false;\n }\n get loadingStyle() {\n return this.element.loading;\n }\n get isLoading() {\n return this.formSubmission !== undefined || this.resolveVisitPromise() !== undefined;\n }\n get isActive() {\n return this.element.isActive && this.connected;\n }\n get rootLocation() {\n var _a;\n const meta = this.element.ownerDocument.querySelector(`meta[name=\"turbo-root\"]`);\n const root = (_a = meta === null || meta === void 0 ? void 0 : meta.content) !== null && _a !== void 0 ? _a : \"/\";\n return expandURL(root);\n }\n}\nclass SnapshotSubstitution {\n constructor(element) {\n this.visitCachedSnapshot = ({ element }) => {\n var _a;\n const { id, clone } = this;\n (_a = element.querySelector(\"#\" + id)) === null || _a === void 0 ? void 0 : _a.replaceWith(clone);\n };\n this.clone = element.cloneNode(true);\n this.id = element.id;\n }\n}\nfunction getFrameElementById(id) {\n if (id != null) {\n const element = document.getElementById(id);\n if (element instanceof FrameElement) {\n return element;\n }\n }\n}\nfunction activateElement(element, currentURL) {\n if (element) {\n const src = element.getAttribute(\"src\");\n if (src != null && currentURL != null && urlsAreEqual(src, currentURL)) {\n throw new Error(`Matching element has a source URL which references itself`);\n }\n if (element.ownerDocument !== document) {\n element = document.importNode(element, true);\n }\n if (element instanceof FrameElement) {\n element.connectedCallback();\n element.disconnectedCallback();\n return element;\n }\n }\n}\n\nconst StreamActions = {\n after() {\n this.targetElements.forEach(e => { var _a; return (_a = e.parentElement) === null || _a === void 0 ? void 0 : _a.insertBefore(this.templateContent, e.nextSibling); });\n },\n append() {\n this.removeDuplicateTargetChildren();\n this.targetElements.forEach(e => e.append(this.templateContent));\n },\n before() {\n this.targetElements.forEach(e => { var _a; return (_a = e.parentElement) === null || _a === void 0 ? void 0 : _a.insertBefore(this.templateContent, e); });\n },\n prepend() {\n this.removeDuplicateTargetChildren();\n this.targetElements.forEach(e => e.prepend(this.templateContent));\n },\n remove() {\n this.targetElements.forEach(e => e.remove());\n },\n replace() {\n this.targetElements.forEach(e => e.replaceWith(this.templateContent));\n },\n update() {\n this.targetElements.forEach(e => {\n e.innerHTML = \"\";\n e.append(this.templateContent);\n });\n }\n};\n\nclass StreamElement extends HTMLElement {\n async connectedCallback() {\n try {\n await this.render();\n }\n catch (error) {\n console.error(error);\n }\n finally {\n this.disconnect();\n }\n }\n async render() {\n var _a;\n return (_a = this.renderPromise) !== null && _a !== void 0 ? _a : (this.renderPromise = (async () => {\n if (this.dispatchEvent(this.beforeRenderEvent)) {\n await nextAnimationFrame();\n this.performAction();\n }\n })());\n }\n disconnect() {\n try {\n this.remove();\n }\n catch (_a) { }\n }\n removeDuplicateTargetChildren() {\n this.duplicateChildren.forEach(c => c.remove());\n }\n get duplicateChildren() {\n var _a;\n const existingChildren = this.targetElements.flatMap(e => [...e.children]).filter(c => !!c.id);\n const newChildrenIds = [...(_a = this.templateContent) === null || _a === void 0 ? void 0 : _a.children].filter(c => !!c.id).map(c => c.id);\n return existingChildren.filter(c => newChildrenIds.includes(c.id));\n }\n get performAction() {\n if (this.action) {\n const actionFunction = StreamActions[this.action];\n if (actionFunction) {\n return actionFunction;\n }\n this.raise(\"unknown action\");\n }\n this.raise(\"action attribute is missing\");\n }\n get targetElements() {\n if (this.target) {\n return this.targetElementsById;\n }\n else if (this.targets) {\n return this.targetElementsByQuery;\n }\n else {\n this.raise(\"target or targets attribute is missing\");\n }\n }\n get templateContent() {\n return this.templateElement.content.cloneNode(true);\n }\n get templateElement() {\n if (this.firstElementChild instanceof HTMLTemplateElement) {\n return this.firstElementChild;\n }\n this.raise(\"first child element must be a