{ "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/velocity-animate/velocity.js", "../../../../../node_modules/moment/moment.js", "../../../../../node_modules/src/js/util/util.js", "../../../../../node_modules/src/js/util/dom-events.js", "../../../../../node_modules/src/js/util/viewport-size.js", "../../../../../node_modules/src/js/slide/pan-bounds.js", "../../../../../node_modules/src/js/slide/zoom-level.js", "../../../../../node_modules/src/js/slide/slide.js", "../../../../../node_modules/src/js/gestures/drag-handler.js", "../../../../../node_modules/src/js/gestures/zoom-handler.js", "../../../../../node_modules/src/js/gestures/tap-handler.js", "../../../../../node_modules/src/js/gestures/gestures.js", "../../../../../node_modules/src/js/main-scroll.js", "../../../../../node_modules/src/js/keyboard.js", "../../../../../node_modules/src/js/util/css-animation.js", "../../../../../node_modules/src/js/util/spring-easer.js", "../../../../../node_modules/src/js/util/spring-animation.js", "../../../../../node_modules/src/js/util/animations.js", "../../../../../node_modules/src/js/scroll-wheel.js", "../../../../../node_modules/src/js/ui/ui-element.js", "../../../../../node_modules/src/js/ui/button-arrow.js", "../../../../../node_modules/src/js/ui/button-close.js", "../../../../../node_modules/src/js/ui/button-zoom.js", "../../../../../node_modules/src/js/ui/loading-indicator.js", "../../../../../node_modules/src/js/ui/counter-indicator.js", "../../../../../node_modules/src/js/ui/ui.js", "../../../../../node_modules/src/js/slide/get-thumb-bounds.js", "../../../../../node_modules/src/js/core/eventable.js", "../../../../../node_modules/src/js/slide/placeholder.js", "../../../../../node_modules/src/js/slide/content.js", "../../../../../node_modules/src/js/slide/loader.js", "../../../../../node_modules/src/js/core/base.js", "../../../../../node_modules/src/js/opener.js", "../../../../../node_modules/src/js/photoswipe.js", "../../../../../node_modules/@rails/ujs/app/assets/javascripts/rails-ujs.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/fetch_requests.js", "../../../../../node_modules/@hotwired/turbo-rails/app/javascript/turbo/index.js", "../../../../../node_modules/@fortawesome/fontawesome-svg-core/index.es.js", "../../../../../node_modules/@fortawesome/free-solid-svg-icons/index.es.js", "../../../../../node_modules/@fortawesome/free-regular-svg-icons/index.es.js", "../../../../../node_modules/@fortawesome/free-brands-svg-icons/index.es.js", "../../../../javascript/src/websites/default/fontawesome.js", "../../../../../node_modules/@hotwired/stimulus/dist/stimulus.js", "../../../../javascript/controllers/application.js", "../../../../javascript/controllers/shared/accordion_controller.js", "../../../../../node_modules/autosize/dist/autosize.esm.js", "../../../../javascript/controllers/shared/autosize_controller.js", "../../../../javascript/controllers/shared/current_popper_controller.js", "../../../../javascript/controllers/shared/expandable_controller.js", "../../../../javascript/controllers/shared/form_controller.js", "../../../../../node_modules/@popperjs/core/lib/dom-utils/getBoundingClientRect.js", "../../../../../node_modules/@popperjs/core/lib/dom-utils/getWindow.js", "../../../../../node_modules/@popperjs/core/lib/dom-utils/getWindowScroll.js", "../../../../../node_modules/@popperjs/core/lib/dom-utils/instanceOf.js", "../../../../../node_modules/@popperjs/core/lib/dom-utils/getHTMLElementScroll.js", "../../../../../node_modules/@popperjs/core/lib/dom-utils/getNodeScroll.js", "../../../../../node_modules/@popperjs/core/lib/dom-utils/getNodeName.js", "../../../../../node_modules/@popperjs/core/lib/dom-utils/getDocumentElement.js", "../../../../../node_modules/@popperjs/core/lib/dom-utils/getWindowScrollBarX.js", "../../../../../node_modules/@popperjs/core/lib/dom-utils/getComputedStyle.js", "../../../../../node_modules/@popperjs/core/lib/dom-utils/isScrollParent.js", "../../../../../node_modules/@popperjs/core/lib/dom-utils/getCompositeRect.js", "../../../../../node_modules/@popperjs/core/lib/dom-utils/getLayoutRect.js", "../../../../../node_modules/@popperjs/core/lib/dom-utils/getParentNode.js", "../../../../../node_modules/@popperjs/core/lib/dom-utils/getScrollParent.js", "../../../../../node_modules/@popperjs/core/lib/dom-utils/listScrollParents.js", "../../../../../node_modules/@popperjs/core/lib/dom-utils/isTableElement.js", "../../../../../node_modules/@popperjs/core/lib/dom-utils/getOffsetParent.js", "../../../../../node_modules/@popperjs/core/lib/enums.js", "../../../../../node_modules/@popperjs/core/lib/utils/orderModifiers.js", "../../../../../node_modules/@popperjs/core/lib/utils/debounce.js", "../../../../../node_modules/@popperjs/core/lib/utils/format.js", "../../../../../node_modules/@popperjs/core/lib/utils/validateModifiers.js", "../../../../../node_modules/@popperjs/core/lib/utils/uniqueBy.js", "../../../../../node_modules/@popperjs/core/lib/utils/getBasePlacement.js", "../../../../../node_modules/@popperjs/core/lib/utils/mergeByName.js", "../../../../../node_modules/@popperjs/core/lib/dom-utils/getViewportRect.js", "../../../../../node_modules/@popperjs/core/lib/dom-utils/getDocumentRect.js", "../../../../../node_modules/@popperjs/core/lib/dom-utils/contains.js", "../../../../../node_modules/@popperjs/core/lib/utils/rectToClientRect.js", "../../../../../node_modules/@popperjs/core/lib/dom-utils/getClippingRect.js", "../../../../../node_modules/@popperjs/core/lib/utils/getVariation.js", "../../../../../node_modules/@popperjs/core/lib/utils/getMainAxisFromPlacement.js", "../../../../../node_modules/@popperjs/core/lib/utils/computeOffsets.js", "../../../../../node_modules/@popperjs/core/lib/utils/getFreshSideObject.js", "../../../../../node_modules/@popperjs/core/lib/utils/mergePaddingObject.js", "../../../../../node_modules/@popperjs/core/lib/utils/expandToHashMap.js", "../../../../../node_modules/@popperjs/core/lib/utils/detectOverflow.js", "../../../../../node_modules/@popperjs/core/lib/index.js", "../../../../../node_modules/@popperjs/core/lib/modifiers/eventListeners.js", "../../../../../node_modules/@popperjs/core/lib/modifiers/popperOffsets.js", "../../../../../node_modules/@popperjs/core/lib/modifiers/computeStyles.js", "../../../../../node_modules/@popperjs/core/lib/modifiers/applyStyles.js", "../../../../../node_modules/@popperjs/core/lib/modifiers/offset.js", "../../../../../node_modules/@popperjs/core/lib/utils/getOppositePlacement.js", "../../../../../node_modules/@popperjs/core/lib/utils/getOppositeVariationPlacement.js", "../../../../../node_modules/@popperjs/core/lib/utils/computeAutoPlacement.js", "../../../../../node_modules/@popperjs/core/lib/modifiers/flip.js", "../../../../../node_modules/@popperjs/core/lib/utils/getAltAxis.js", "../../../../../node_modules/@popperjs/core/lib/utils/within.js", "../../../../../node_modules/@popperjs/core/lib/modifiers/preventOverflow.js", "../../../../../node_modules/@popperjs/core/lib/modifiers/arrow.js", "../../../../../node_modules/@popperjs/core/lib/modifiers/hide.js", "../../../../../node_modules/@popperjs/core/lib/popper.js", "../../../../javascript/controllers/shared/popper_controller.js", "../../../../javascript/controllers/websites/default/fixed_sidebar_controller.js", "../../../../../node_modules/src/js/util/util.js", "../../../../../node_modules/src/js/core/eventable.js", "../../../../../node_modules/src/js/slide/placeholder.js", "../../../../../node_modules/src/js/slide/content.js", "../../../../../node_modules/src/js/util/viewport-size.js", "../../../../../node_modules/src/js/slide/zoom-level.js", "../../../../../node_modules/src/js/slide/loader.js", "../../../../../node_modules/src/js/core/base.js", "../../../../../node_modules/src/js/lightbox/lightbox.js", "../../../../javascript/controllers/websites/default/gallery_controller.js", "../../../../javascript/controllers/websites/default/map_controller.js", "../../../../javascript/controllers/websites/default/navigation_controller.js", "../../../../javascript/controllers/websites/default/index.js", "../../../../javascript/packs/websites/default/application.js"], "sourcesContent": ["export default {\n logger: typeof console !== \"undefined\" ? console : undefined,\n WebSocket: typeof WebSocket !== \"undefined\" ? WebSocket : undefined,\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 recordMessage() {\n this.pingedAt = now()\n }\n\n recordConnect() {\n this.reconnectAttempts = 0\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 \"remote\": \"remote\"\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 const socketProtocols = [...protocols, ...this.consumer.subprotocols || []]\n logger.log(`Opening WebSocket, current state is ${this.getState()}, subprotocols: ${socketProtocols}`)\n if (this.webSocket) { this.uninstallEventHandlers() }\n this.webSocket = new adapters.WebSocket(this.consumer.url, socketProtocols)\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 triedToReconnect() {\n return this.monitor.reconnectAttempts > 0\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 this.monitor.recordMessage()\n switch (type) {\n case message_types.welcome:\n if (this.triedToReconnect()) {\n this.reconnectAttempted = true\n }\n this.monitor.recordConnect()\n return this.subscriptions.reload()\n case message_types.disconnect:\n logger.log(`Disconnecting. Reason: ${reason}`)\n return this.close({allowReconnect: reconnect})\n case message_types.ping:\n return null\n case message_types.confirmation:\n this.subscriptions.confirmSubscription(identifier)\n if (this.reconnectAttempted) {\n this.reconnectAttempted = false\n return this.subscriptions.notify(identifier, \"connected\", {reconnected: true})\n } else {\n return this.subscriptions.notify(identifier, \"connected\", {reconnected: false})\n }\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 this.subprotocols = []\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 addSubProtocol(subprotocol) {\n this.subprotocols = [...this.subprotocols, subprotocol]\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", "/*! VelocityJS.org (1.5.2). (C) 2014 Julian Shapiro. MIT @license: en.wikipedia.org/wiki/MIT_License */\r\n\r\n/*************************\r\n Velocity jQuery Shim\r\n *************************/\r\n\r\n/*! VelocityJS.org jQuery Shim (1.0.1). (C) 2014 The jQuery Foundation. MIT @license: en.wikipedia.org/wiki/MIT_License. */\r\n\r\n/* This file contains the jQuery functions that Velocity relies on, thereby removing Velocity's dependency on a full copy of jQuery, and allowing it to work in any environment. */\r\n/* These shimmed functions are only used if jQuery isn't present. If both this shim and jQuery are loaded, Velocity defaults to jQuery proper. */\r\n/* Browser support: Using this shim instead of jQuery proper removes support for IE8. */\r\n\r\n(function(window) {\r\n\t\"use strict\";\r\n\t/***************\r\n\t Setup\r\n\t ***************/\r\n\r\n\t/* If jQuery is already loaded, there's no point in loading this shim. */\r\n\tif (window.jQuery) {\r\n\t\treturn;\r\n\t}\r\n\r\n\t/* jQuery base. */\r\n\tvar $ = function(selector, context) {\r\n\t\treturn new $.fn.init(selector, context);\r\n\t};\r\n\r\n\t/********************\r\n\t Private Methods\r\n\t ********************/\r\n\r\n\t/* jQuery */\r\n\t$.isWindow = function(obj) {\r\n\t\t/* jshint eqeqeq: false */\r\n\t\treturn obj && obj === obj.window;\r\n\t};\r\n\r\n\t/* jQuery */\r\n\t$.type = function(obj) {\r\n\t\tif (!obj) {\r\n\t\t\treturn obj + \"\";\r\n\t\t}\r\n\r\n\t\treturn typeof obj === \"object\" || typeof obj === \"function\" ?\r\n\t\t\t\tclass2type[toString.call(obj)] || \"object\" :\r\n\t\t\t\ttypeof obj;\r\n\t};\r\n\r\n\t/* jQuery */\r\n\t$.isArray = Array.isArray || function(obj) {\r\n\t\treturn $.type(obj) === \"array\";\r\n\t};\r\n\r\n\t/* jQuery */\r\n\tfunction isArraylike(obj) {\r\n\t\tvar length = obj.length,\r\n\t\t\t\ttype = $.type(obj);\r\n\r\n\t\tif (type === \"function\" || $.isWindow(obj)) {\r\n\t\t\treturn false;\r\n\t\t}\r\n\r\n\t\tif (obj.nodeType === 1 && length) {\r\n\t\t\treturn true;\r\n\t\t}\r\n\r\n\t\treturn type === \"array\" || length === 0 || typeof length === \"number\" && length > 0 && (length - 1) in obj;\r\n\t}\r\n\r\n\t/***************\r\n\t $ Methods\r\n\t ***************/\r\n\r\n\t/* jQuery: Support removed for IE<9. */\r\n\t$.isPlainObject = function(obj) {\r\n\t\tvar key;\r\n\r\n\t\tif (!obj || $.type(obj) !== \"object\" || obj.nodeType || $.isWindow(obj)) {\r\n\t\t\treturn false;\r\n\t\t}\r\n\r\n\t\ttry {\r\n\t\t\tif (obj.constructor &&\r\n\t\t\t\t\t!hasOwn.call(obj, \"constructor\") &&\r\n\t\t\t\t\t!hasOwn.call(obj.constructor.prototype, \"isPrototypeOf\")) {\r\n\t\t\t\treturn false;\r\n\t\t\t}\r\n\t\t} catch (e) {\r\n\t\t\treturn false;\r\n\t\t}\r\n\r\n\t\tfor (key in obj) {\r\n\t\t}\r\n\r\n\t\treturn key === undefined || hasOwn.call(obj, key);\r\n\t};\r\n\r\n\t/* jQuery */\r\n\t$.each = function(obj, callback, args) {\r\n\t\tvar value,\r\n\t\t\t\ti = 0,\r\n\t\t\t\tlength = obj.length,\r\n\t\t\t\tisArray = isArraylike(obj);\r\n\r\n\t\tif (args) {\r\n\t\t\tif (isArray) {\r\n\t\t\t\tfor (; i < length; i++) {\r\n\t\t\t\t\tvalue = callback.apply(obj[i], args);\r\n\r\n\t\t\t\t\tif (value === false) {\r\n\t\t\t\t\t\tbreak;\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t} else {\r\n\t\t\t\tfor (i in obj) {\r\n\t\t\t\t\tif (!obj.hasOwnProperty(i)) {\r\n\t\t\t\t\t\tcontinue;\r\n\t\t\t\t\t}\r\n\t\t\t\t\tvalue = callback.apply(obj[i], args);\r\n\r\n\t\t\t\t\tif (value === false) {\r\n\t\t\t\t\t\tbreak;\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t}\r\n\r\n\t\t} else {\r\n\t\t\tif (isArray) {\r\n\t\t\t\tfor (; i < length; i++) {\r\n\t\t\t\t\tvalue = callback.call(obj[i], i, obj[i]);\r\n\r\n\t\t\t\t\tif (value === false) {\r\n\t\t\t\t\t\tbreak;\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t} else {\r\n\t\t\t\tfor (i in obj) {\r\n\t\t\t\t\tif (!obj.hasOwnProperty(i)) {\r\n\t\t\t\t\t\tcontinue;\r\n\t\t\t\t\t}\r\n\t\t\t\t\tvalue = callback.call(obj[i], i, obj[i]);\r\n\r\n\t\t\t\t\tif (value === false) {\r\n\t\t\t\t\t\tbreak;\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\treturn obj;\r\n\t};\r\n\r\n\t/* Custom */\r\n\t$.data = function(node, key, value) {\r\n\t\t/* $.getData() */\r\n\t\tif (value === undefined) {\r\n\t\t\tvar getId = node[$.expando],\r\n\t\t\t\t\tstore = getId && cache[getId];\r\n\r\n\t\t\tif (key === undefined) {\r\n\t\t\t\treturn store;\r\n\t\t\t} else if (store) {\r\n\t\t\t\tif (key in store) {\r\n\t\t\t\t\treturn store[key];\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\t/* $.setData() */\r\n\t\t} else if (key !== undefined) {\r\n\t\t\tvar setId = node[$.expando] || (node[$.expando] = ++$.uuid);\r\n\r\n\t\t\tcache[setId] = cache[setId] || {};\r\n\t\t\tcache[setId][key] = value;\r\n\r\n\t\t\treturn value;\r\n\t\t}\r\n\t};\r\n\r\n\t/* Custom */\r\n\t$.removeData = function(node, keys) {\r\n\t\tvar id = node[$.expando],\r\n\t\t\t\tstore = id && cache[id];\r\n\r\n\t\tif (store) {\r\n\t\t\t// Cleanup the entire store if no keys are provided.\r\n\t\t\tif (!keys) {\r\n\t\t\t\tdelete cache[id];\r\n\t\t\t} else {\r\n\t\t\t\t$.each(keys, function(_, key) {\r\n\t\t\t\t\tdelete store[key];\r\n\t\t\t\t});\r\n\t\t\t}\r\n\t\t}\r\n\t};\r\n\r\n\t/* jQuery */\r\n\t$.extend = function() {\r\n\t\tvar src, copyIsArray, copy, name, options, clone,\r\n\t\t\t\ttarget = arguments[0] || {},\r\n\t\t\t\ti = 1,\r\n\t\t\t\tlength = arguments.length,\r\n\t\t\t\tdeep = false;\r\n\r\n\t\tif (typeof target === \"boolean\") {\r\n\t\t\tdeep = target;\r\n\r\n\t\t\ttarget = arguments[i] || {};\r\n\t\t\ti++;\r\n\t\t}\r\n\r\n\t\tif (typeof target !== \"object\" && $.type(target) !== \"function\") {\r\n\t\t\ttarget = {};\r\n\t\t}\r\n\r\n\t\tif (i === length) {\r\n\t\t\ttarget = this;\r\n\t\t\ti--;\r\n\t\t}\r\n\r\n\t\tfor (; i < length; i++) {\r\n\t\t\tif ((options = arguments[i])) {\r\n\t\t\t\tfor (name in options) {\r\n\t\t\t\t\tif (!options.hasOwnProperty(name)) {\r\n\t\t\t\t\t\tcontinue;\r\n\t\t\t\t\t}\r\n\t\t\t\t\tsrc = target[name];\r\n\t\t\t\t\tcopy = options[name];\r\n\r\n\t\t\t\t\tif (target === copy) {\r\n\t\t\t\t\t\tcontinue;\r\n\t\t\t\t\t}\r\n\r\n\t\t\t\t\tif (deep && copy && ($.isPlainObject(copy) || (copyIsArray = $.isArray(copy)))) {\r\n\t\t\t\t\t\tif (copyIsArray) {\r\n\t\t\t\t\t\t\tcopyIsArray = false;\r\n\t\t\t\t\t\t\tclone = src && $.isArray(src) ? src : [];\r\n\r\n\t\t\t\t\t\t} else {\r\n\t\t\t\t\t\t\tclone = src && $.isPlainObject(src) ? src : {};\r\n\t\t\t\t\t\t}\r\n\r\n\t\t\t\t\t\ttarget[name] = $.extend(deep, clone, copy);\r\n\r\n\t\t\t\t\t} else if (copy !== undefined) {\r\n\t\t\t\t\t\ttarget[name] = copy;\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\treturn target;\r\n\t};\r\n\r\n\t/* jQuery 1.4.3 */\r\n\t$.queue = function(elem, type, data) {\r\n\t\tfunction $makeArray(arr, results) {\r\n\t\t\tvar ret = results || [];\r\n\r\n\t\t\tif (arr) {\r\n\t\t\t\tif (isArraylike(Object(arr))) {\r\n\t\t\t\t\t/* $.merge */\r\n\t\t\t\t\t(function(first, second) {\r\n\t\t\t\t\t\tvar len = +second.length,\r\n\t\t\t\t\t\t\t\tj = 0,\r\n\t\t\t\t\t\t\t\ti = first.length;\r\n\r\n\t\t\t\t\t\twhile (j < len) {\r\n\t\t\t\t\t\t\tfirst[i++] = second[j++];\r\n\t\t\t\t\t\t}\r\n\r\n\t\t\t\t\t\tif (len !== len) {\r\n\t\t\t\t\t\t\twhile (second[j] !== undefined) {\r\n\t\t\t\t\t\t\t\tfirst[i++] = second[j++];\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t}\r\n\r\n\t\t\t\t\t\tfirst.length = i;\r\n\r\n\t\t\t\t\t\treturn first;\r\n\t\t\t\t\t})(ret, typeof arr === \"string\" ? [arr] : arr);\r\n\t\t\t\t} else {\r\n\t\t\t\t\t[].push.call(ret, arr);\r\n\t\t\t\t}\r\n\t\t\t}\r\n\r\n\t\t\treturn ret;\r\n\t\t}\r\n\r\n\t\tif (!elem) {\r\n\t\t\treturn;\r\n\t\t}\r\n\r\n\t\ttype = (type || \"fx\") + \"queue\";\r\n\r\n\t\tvar q = $.data(elem, type);\r\n\r\n\t\tif (!data) {\r\n\t\t\treturn q || [];\r\n\t\t}\r\n\r\n\t\tif (!q || $.isArray(data)) {\r\n\t\t\tq = $.data(elem, type, $makeArray(data));\r\n\t\t} else {\r\n\t\t\tq.push(data);\r\n\t\t}\r\n\r\n\t\treturn q;\r\n\t};\r\n\r\n\t/* jQuery 1.4.3 */\r\n\t$.dequeue = function(elems, type) {\r\n\t\t/* Custom: Embed element iteration. */\r\n\t\t$.each(elems.nodeType ? [elems] : elems, function(i, elem) {\r\n\t\t\ttype = type || \"fx\";\r\n\r\n\t\t\tvar queue = $.queue(elem, type),\r\n\t\t\t\t\tfn = queue.shift();\r\n\r\n\t\t\tif (fn === \"inprogress\") {\r\n\t\t\t\tfn = queue.shift();\r\n\t\t\t}\r\n\r\n\t\t\tif (fn) {\r\n\t\t\t\tif (type === \"fx\") {\r\n\t\t\t\t\tqueue.unshift(\"inprogress\");\r\n\t\t\t\t}\r\n\r\n\t\t\t\tfn.call(elem, function() {\r\n\t\t\t\t\t$.dequeue(elem, type);\r\n\t\t\t\t});\r\n\t\t\t}\r\n\t\t});\r\n\t};\r\n\r\n\t/******************\r\n\t $.fn Methods\r\n\t ******************/\r\n\r\n\t/* jQuery */\r\n\t$.fn = $.prototype = {\r\n\t\tinit: function(selector) {\r\n\t\t\t/* Just return the element wrapped inside an array; don't proceed with the actual jQuery node wrapping process. */\r\n\t\t\tif (selector.nodeType) {\r\n\t\t\t\tthis[0] = selector;\r\n\r\n\t\t\t\treturn this;\r\n\t\t\t} else {\r\n\t\t\t\tthrow new Error(\"Not a DOM node.\");\r\n\t\t\t}\r\n\t\t},\r\n\t\toffset: function() {\r\n\t\t\t/* jQuery altered code: Dropped disconnected DOM node checking. */\r\n\t\t\tvar box = this[0].getBoundingClientRect ? this[0].getBoundingClientRect() : {top: 0, left: 0};\r\n\r\n\t\t\treturn {\r\n\t\t\t\ttop: box.top + (window.pageYOffset || document.scrollTop || 0) - (document.clientTop || 0),\r\n\t\t\t\tleft: box.left + (window.pageXOffset || document.scrollLeft || 0) - (document.clientLeft || 0)\r\n\t\t\t};\r\n\t\t},\r\n\t\tposition: function() {\r\n\t\t\t/* jQuery */\r\n\t\t\tfunction offsetParentFn(elem) {\r\n\t\t\t\tvar offsetParent = elem.offsetParent;\r\n\r\n\t\t\t\twhile (offsetParent && (offsetParent.nodeName.toLowerCase() !== \"html\" && offsetParent.style && offsetParent.style.position.toLowerCase() === \"static\")) {\r\n\t\t\t\t\toffsetParent = offsetParent.offsetParent;\r\n\t\t\t\t}\r\n\r\n\t\t\t\treturn offsetParent || document;\r\n\t\t\t}\r\n\r\n\t\t\t/* Zepto */\r\n\t\t\tvar elem = this[0],\r\n\t\t\t\t\toffsetParent = offsetParentFn(elem),\r\n\t\t\t\t\toffset = this.offset(),\r\n\t\t\t\t\tparentOffset = /^(?:body|html)$/i.test(offsetParent.nodeName) ? {top: 0, left: 0} : $(offsetParent).offset();\r\n\r\n\t\t\toffset.top -= parseFloat(elem.style.marginTop) || 0;\r\n\t\t\toffset.left -= parseFloat(elem.style.marginLeft) || 0;\r\n\r\n\t\t\tif (offsetParent.style) {\r\n\t\t\t\tparentOffset.top += parseFloat(offsetParent.style.borderTopWidth) || 0;\r\n\t\t\t\tparentOffset.left += parseFloat(offsetParent.style.borderLeftWidth) || 0;\r\n\t\t\t}\r\n\r\n\t\t\treturn {\r\n\t\t\t\ttop: offset.top - parentOffset.top,\r\n\t\t\t\tleft: offset.left - parentOffset.left\r\n\t\t\t};\r\n\t\t}\r\n\t};\r\n\r\n\t/**********************\r\n\t Private Variables\r\n\t **********************/\r\n\r\n\t/* For $.data() */\r\n\tvar cache = {};\r\n\t$.expando = \"velocity\" + (new Date().getTime());\r\n\t$.uuid = 0;\r\n\r\n\t/* For $.queue() */\r\n\tvar class2type = {},\r\n\t\t\thasOwn = class2type.hasOwnProperty,\r\n\t\t\ttoString = class2type.toString;\r\n\r\n\tvar types = \"Boolean Number String Function Array Date RegExp Object Error\".split(\" \");\r\n\tfor (var i = 0; i < types.length; i++) {\r\n\t\tclass2type[\"[object \" + types[i] + \"]\"] = types[i].toLowerCase();\r\n\t}\r\n\r\n\t/* Makes $(node) possible, without having to call init. */\r\n\t$.fn.init.prototype = $.fn;\r\n\r\n\t/* Globalize Velocity onto the window, and assign its Utilities property. */\r\n\twindow.Velocity = {Utilities: $};\r\n})(window);\r\n\r\n/******************\r\n Velocity.js\r\n ******************/\r\n\r\n(function(factory) {\r\n\t\"use strict\";\r\n\t/* CommonJS module. */\r\n\tif (typeof module === \"object\" && typeof module.exports === \"object\") {\r\n\t\tmodule.exports = factory();\r\n\t\t/* AMD module. */\r\n\t} else if (typeof define === \"function\" && define.amd) {\r\n\t\tdefine(factory);\r\n\t\t/* Browser globals. */\r\n\t} else {\r\n\t\tfactory();\r\n\t}\r\n}(function() {\r\n\t\"use strict\";\r\n\treturn function(global, window, document, undefined) {\r\n\r\n\t\t/***************\r\n\t\t Summary\r\n\t\t ***************/\r\n\r\n\t\t/*\r\n\t\t - CSS: CSS stack that works independently from the rest of Velocity.\r\n\t\t - animate(): Core animation method that iterates over the targeted elements and queues the incoming call onto each element individually.\r\n\t\t - Pre-Queueing: Prepare the element for animation by instantiating its data cache and processing the call's options.\r\n\t\t - Queueing: The logic that runs once the call has reached its point of execution in the element's $.queue() stack.\r\n\t\t Most logic is placed here to avoid risking it becoming stale (if the element's properties have changed).\r\n\t\t - Pushing: Consolidation of the tween data followed by its push onto the global in-progress calls container.\r\n\t\t - tick(): The single requestAnimationFrame loop responsible for tweening all in-progress calls.\r\n\t\t - completeCall(): Handles the cleanup process for each Velocity call.\r\n\t\t */\r\n\r\n\t\t/*********************\r\n\t\t Helper Functions\r\n\t\t *********************/\r\n\r\n\t\t/* IE detection. Gist: https://gist.github.com/julianshapiro/9098609 */\r\n\t\tvar IE = (function() {\r\n\t\t\tif (document.documentMode) {\r\n\t\t\t\treturn document.documentMode;\r\n\t\t\t} else {\r\n\t\t\t\tfor (var i = 7; i > 4; i--) {\r\n\t\t\t\t\tvar div = document.createElement(\"div\");\r\n\r\n\t\t\t\t\tdiv.innerHTML = \"\";\r\n\r\n\t\t\t\t\tif (div.getElementsByTagName(\"span\").length) {\r\n\t\t\t\t\t\tdiv = null;\r\n\r\n\t\t\t\t\t\treturn i;\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t}\r\n\r\n\t\t\treturn undefined;\r\n\t\t})();\r\n\r\n\t\t/* rAF shim. Gist: https://gist.github.com/julianshapiro/9497513 */\r\n\t\tvar rAFShim = (function() {\r\n\t\t\tvar timeLast = 0;\r\n\r\n\t\t\treturn window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || function(callback) {\r\n\t\t\t\tvar timeCurrent = (new Date()).getTime(),\r\n\t\t\t\t\t\ttimeDelta;\r\n\r\n\t\t\t\t/* Dynamically set delay on a per-tick basis to match 60fps. */\r\n\t\t\t\t/* Technique by Erik Moller. MIT license: https://gist.github.com/paulirish/1579671 */\r\n\t\t\t\ttimeDelta = Math.max(0, 16 - (timeCurrent - timeLast));\r\n\t\t\t\ttimeLast = timeCurrent + timeDelta;\r\n\r\n\t\t\t\treturn setTimeout(function() {\r\n\t\t\t\t\tcallback(timeCurrent + timeDelta);\r\n\t\t\t\t}, timeDelta);\r\n\t\t\t};\r\n\t\t})();\r\n\r\n\t\tvar performance = (function() {\r\n\t\t\tvar perf = window.performance || {};\r\n\r\n\t\t\tif (typeof perf.now !== \"function\") {\r\n\t\t\t\tvar nowOffset = perf.timing && perf.timing.navigationStart ? perf.timing.navigationStart : (new Date()).getTime();\r\n\r\n\t\t\t\tperf.now = function() {\r\n\t\t\t\t\treturn (new Date()).getTime() - nowOffset;\r\n\t\t\t\t};\r\n\t\t\t}\r\n\t\t\treturn perf;\r\n\t\t})();\r\n\r\n\t\t/* Array compacting. Copyright Lo-Dash. MIT License: https://github.com/lodash/lodash/blob/master/LICENSE.txt */\r\n\t\tfunction compactSparseArray(array) {\r\n\t\t\tvar index = -1,\r\n\t\t\t\t\tlength = array ? array.length : 0,\r\n\t\t\t\t\tresult = [];\r\n\r\n\t\t\twhile (++index < length) {\r\n\t\t\t\tvar value = array[index];\r\n\r\n\t\t\t\tif (value) {\r\n\t\t\t\t\tresult.push(value);\r\n\t\t\t\t}\r\n\t\t\t}\r\n\r\n\t\t\treturn result;\r\n\t\t}\r\n\r\n\t\t/**\r\n\t\t * Shim for \"fixing\" IE's lack of support (IE < 9) for applying slice\r\n\t\t * on host objects like NamedNodeMap, NodeList, and HTMLCollection\r\n\t\t * (technically, since host objects have been implementation-dependent,\r\n\t\t * at least before ES2015, IE hasn't needed to work this way).\r\n\t\t * Also works on strings, fixes IE < 9 to allow an explicit undefined\r\n\t\t * for the 2nd argument (as in Firefox), and prevents errors when\r\n\t\t * called on other DOM objects.\r\n\t\t */\r\n\t\tvar _slice = (function() {\r\n\t\t\tvar slice = Array.prototype.slice;\r\n\r\n\t\t\ttry {\r\n\t\t\t\t// Can't be used with DOM elements in IE < 9\r\n\t\t\t\tslice.call(document.documentElement);\r\n\t\t\t\treturn slice;\r\n\t\t\t} catch (e) { // Fails in IE < 9\r\n\r\n\t\t\t\t// This will work for genuine arrays, array-like objects, \r\n\t\t\t\t// NamedNodeMap (attributes, entities, notations),\r\n\t\t\t\t// NodeList (e.g., getElementsByTagName), HTMLCollection (e.g., childNodes),\r\n\t\t\t\t// and will not fail on other DOM objects (as do DOM elements in IE < 9)\r\n\t\t\t\treturn function(begin, end) {\r\n\t\t\t\t\tvar len = this.length;\r\n\r\n\t\t\t\t\tif (typeof begin !== \"number\") {\r\n\t\t\t\t\t\tbegin = 0;\r\n\t\t\t\t\t}\r\n\t\t\t\t\t// IE < 9 gets unhappy with an undefined end argument\r\n\t\t\t\t\tif (typeof end !== \"number\") {\r\n\t\t\t\t\t\tend = len;\r\n\t\t\t\t\t}\r\n\t\t\t\t\t// For native Array objects, we use the native slice function\r\n\t\t\t\t\tif (this.slice) {\r\n\t\t\t\t\t\treturn slice.call(this, begin, end);\r\n\t\t\t\t\t}\r\n\t\t\t\t\t// For array like object we handle it ourselves.\r\n\t\t\t\t\tvar i,\r\n\t\t\t\t\t\t\tcloned = [],\r\n\t\t\t\t\t\t\t// Handle negative value for \"begin\"\r\n\t\t\t\t\t\t\tstart = (begin >= 0) ? begin : Math.max(0, len + begin),\r\n\t\t\t\t\t\t\t// Handle negative value for \"end\"\r\n\t\t\t\t\t\t\tupTo = end < 0 ? len + end : Math.min(end, len),\r\n\t\t\t\t\t\t\t// Actual expected size of the slice\r\n\t\t\t\t\t\t\tsize = upTo - start;\r\n\r\n\t\t\t\t\tif (size > 0) {\r\n\t\t\t\t\t\tcloned = new Array(size);\r\n\t\t\t\t\t\tif (this.charAt) {\r\n\t\t\t\t\t\t\tfor (i = 0; i < size; i++) {\r\n\t\t\t\t\t\t\t\tcloned[i] = this.charAt(start + i);\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t} else {\r\n\t\t\t\t\t\t\tfor (i = 0; i < size; i++) {\r\n\t\t\t\t\t\t\t\tcloned[i] = this[start + i];\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n\t\t\t\t\treturn cloned;\r\n\t\t\t\t};\r\n\t\t\t}\r\n\t\t})();\r\n\r\n\t\t/* .indexOf doesn't exist in IE<9 */\r\n\t\tvar _inArray = (function() {\r\n\t\t\tif (Array.prototype.includes) {\r\n\t\t\t\treturn function(arr, val) {\r\n\t\t\t\t\treturn arr.includes(val);\r\n\t\t\t\t};\r\n\t\t\t}\r\n\t\t\tif (Array.prototype.indexOf) {\r\n\t\t\t\treturn function(arr, val) {\r\n\t\t\t\t\treturn arr.indexOf(val) >= 0;\r\n\t\t\t\t};\r\n\t\t\t}\r\n\t\t\treturn function(arr, val) {\r\n\t\t\t\tfor (var i = 0; i < arr.length; i++) {\r\n\t\t\t\t\tif (arr[i] === val) {\r\n\t\t\t\t\t\treturn true;\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t\treturn false;\r\n\t\t\t};\r\n\t\t});\r\n\r\n\t\tfunction sanitizeElements(elements) {\r\n\t\t\t/* Unwrap jQuery/Zepto objects. */\r\n\t\t\tif (Type.isWrapped(elements)) {\r\n\t\t\t\telements = _slice.call(elements);\r\n\t\t\t\t/* Wrap a single element in an array so that $.each() can iterate with the element instead of its node's children. */\r\n\t\t\t} else if (Type.isNode(elements)) {\r\n\t\t\t\telements = [elements];\r\n\t\t\t}\r\n\r\n\t\t\treturn elements;\r\n\t\t}\r\n\r\n\t\tvar Type = {\r\n\t\t\tisNumber: function(variable) {\r\n\t\t\t\treturn (typeof variable === \"number\");\r\n\t\t\t},\r\n\t\t\tisString: function(variable) {\r\n\t\t\t\treturn (typeof variable === \"string\");\r\n\t\t\t},\r\n\t\t\tisArray: Array.isArray || function(variable) {\r\n\t\t\t\treturn Object.prototype.toString.call(variable) === \"[object Array]\";\r\n\t\t\t},\r\n\t\t\tisFunction: function(variable) {\r\n\t\t\t\treturn Object.prototype.toString.call(variable) === \"[object Function]\";\r\n\t\t\t},\r\n\t\t\tisNode: function(variable) {\r\n\t\t\t\treturn variable && variable.nodeType;\r\n\t\t\t},\r\n\t\t\t/* Determine if variable is an array-like wrapped jQuery, Zepto or similar element, or even a NodeList etc. */\r\n\t\t\t/* NOTE: HTMLFormElements also have a length. */\r\n\t\t\tisWrapped: function(variable) {\r\n\t\t\t\treturn variable\r\n\t\t\t\t\t\t&& variable !== window\r\n\t\t\t\t\t\t&& Type.isNumber(variable.length)\r\n\t\t\t\t\t\t&& !Type.isString(variable)\r\n\t\t\t\t\t\t&& !Type.isFunction(variable)\r\n\t\t\t\t\t\t&& !Type.isNode(variable)\r\n\t\t\t\t\t\t&& (variable.length === 0 || Type.isNode(variable[0]));\r\n\t\t\t},\r\n\t\t\tisSVG: function(variable) {\r\n\t\t\t\treturn window.SVGElement && (variable instanceof window.SVGElement);\r\n\t\t\t},\r\n\t\t\tisEmptyObject: function(variable) {\r\n\t\t\t\tfor (var name in variable) {\r\n\t\t\t\t\tif (variable.hasOwnProperty(name)) {\r\n\t\t\t\t\t\treturn false;\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\r\n\t\t\t\treturn true;\r\n\t\t\t}\r\n\t\t};\r\n\r\n\t\t/*****************\r\n\t\t Dependencies\r\n\t\t *****************/\r\n\r\n\t\tvar $,\r\n\t\t\t\tisJQuery = false;\r\n\r\n\t\tif (global.fn && global.fn.jquery) {\r\n\t\t\t$ = global;\r\n\t\t\tisJQuery = true;\r\n\t\t} else {\r\n\t\t\t$ = window.Velocity.Utilities;\r\n\t\t}\r\n\r\n\t\tif (IE <= 8 && !isJQuery) {\r\n\t\t\tthrow new Error(\"Velocity: IE8 and below require jQuery to be loaded before Velocity.\");\r\n\t\t} else if (IE <= 7) {\r\n\t\t\t/* Revert to jQuery's $.animate(), and lose Velocity's extra features. */\r\n\t\t\tjQuery.fn.velocity = jQuery.fn.animate;\r\n\r\n\t\t\t/* Now that $.fn.velocity is aliased, abort this Velocity declaration. */\r\n\t\t\treturn;\r\n\t\t}\r\n\r\n\t\t/*****************\r\n\t\t Constants\r\n\t\t *****************/\r\n\r\n\t\tvar DURATION_DEFAULT = 400,\r\n\t\t\t\tEASING_DEFAULT = \"swing\";\r\n\r\n\t\t/*************\r\n\t\t State\r\n\t\t *************/\r\n\r\n\t\tvar Velocity = {\r\n\t\t\t/* Container for page-wide Velocity state data. */\r\n\t\t\tState: {\r\n\t\t\t\t/* Detect mobile devices to determine if mobileHA should be turned on. */\r\n\t\t\t\tisMobile: /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(window.navigator.userAgent),\r\n\t\t\t\t/* The mobileHA option's behavior changes on older Android devices (Gingerbread, versions 2.3.3-2.3.7). */\r\n\t\t\t\tisAndroid: /Android/i.test(window.navigator.userAgent),\r\n\t\t\t\tisGingerbread: /Android 2\\.3\\.[3-7]/i.test(window.navigator.userAgent),\r\n\t\t\t\tisChrome: window.chrome,\r\n\t\t\t\tisFirefox: /Firefox/i.test(window.navigator.userAgent),\r\n\t\t\t\t/* Create a cached element for re-use when checking for CSS property prefixes. */\r\n\t\t\t\tprefixElement: document.createElement(\"div\"),\r\n\t\t\t\t/* Cache every prefix match to avoid repeating lookups. */\r\n\t\t\t\tprefixMatches: {},\r\n\t\t\t\t/* Cache the anchor used for animating window scrolling. */\r\n\t\t\t\tscrollAnchor: null,\r\n\t\t\t\t/* Cache the browser-specific property names associated with the scroll anchor. */\r\n\t\t\t\tscrollPropertyLeft: null,\r\n\t\t\t\tscrollPropertyTop: null,\r\n\t\t\t\t/* Keep track of whether our RAF tick is running. */\r\n\t\t\t\tisTicking: false,\r\n\t\t\t\t/* Container for every in-progress call to Velocity. */\r\n\t\t\t\tcalls: [],\r\n\t\t\t\tdelayedElements: {\r\n\t\t\t\t\tcount: 0\r\n\t\t\t\t}\r\n\t\t\t},\r\n\t\t\t/* Velocity's custom CSS stack. Made global for unit testing. */\r\n\t\t\tCSS: {/* Defined below. */},\r\n\t\t\t/* A shim of the jQuery utility functions used by Velocity -- provided by Velocity's optional jQuery shim. */\r\n\t\t\tUtilities: $,\r\n\t\t\t/* Container for the user's custom animation redirects that are referenced by name in place of the properties map argument. */\r\n\t\t\tRedirects: {/* Manually registered by the user. */},\r\n\t\t\tEasings: {/* Defined below. */},\r\n\t\t\t/* Attempt to use ES6 Promises by default. Users can override this with a third-party promises library. */\r\n\t\t\tPromise: window.Promise,\r\n\t\t\t/* Velocity option defaults, which can be overriden by the user. */\r\n\t\t\tdefaults: {\r\n\t\t\t\tqueue: \"\",\r\n\t\t\t\tduration: DURATION_DEFAULT,\r\n\t\t\t\teasing: EASING_DEFAULT,\r\n\t\t\t\tbegin: undefined,\r\n\t\t\t\tcomplete: undefined,\r\n\t\t\t\tprogress: undefined,\r\n\t\t\t\tdisplay: undefined,\r\n\t\t\t\tvisibility: undefined,\r\n\t\t\t\tloop: false,\r\n\t\t\t\tdelay: false,\r\n\t\t\t\tmobileHA: true,\r\n\t\t\t\t/* Advanced: Set to false to prevent property values from being cached between consecutive Velocity-initiated chain calls. */\r\n\t\t\t\t_cacheValues: true,\r\n\t\t\t\t/* Advanced: Set to false if the promise should always resolve on empty element lists. */\r\n\t\t\t\tpromiseRejectEmpty: true\r\n\t\t\t},\r\n\t\t\t/* A design goal of Velocity is to cache data wherever possible in order to avoid DOM requerying. Accordingly, each element has a data cache. */\r\n\t\t\tinit: function(element) {\r\n\t\t\t\t$.data(element, \"velocity\", {\r\n\t\t\t\t\t/* Store whether this is an SVG element, since its properties are retrieved and updated differently than standard HTML elements. */\r\n\t\t\t\t\tisSVG: Type.isSVG(element),\r\n\t\t\t\t\t/* Keep track of whether the element is currently being animated by Velocity.\r\n\t\t\t\t\t This is used to ensure that property values are not transferred between non-consecutive (stale) calls. */\r\n\t\t\t\t\tisAnimating: false,\r\n\t\t\t\t\t/* A reference to the element's live computedStyle object. Learn more here: https://developer.mozilla.org/en/docs/Web/API/window.getComputedStyle */\r\n\t\t\t\t\tcomputedStyle: null,\r\n\t\t\t\t\t/* Tween data is cached for each animation on the element so that data can be passed across calls --\r\n\t\t\t\t\t in particular, end values are used as subsequent start values in consecutive Velocity calls. */\r\n\t\t\t\t\ttweensContainer: null,\r\n\t\t\t\t\t/* The full root property values of each CSS hook being animated on this element are cached so that:\r\n\t\t\t\t\t 1) Concurrently-animating hooks sharing the same root can have their root values' merged into one while tweening.\r\n\t\t\t\t\t 2) Post-hook-injection root values can be transferred over to consecutively chained Velocity calls as starting root values. */\r\n\t\t\t\t\trootPropertyValueCache: {},\r\n\t\t\t\t\t/* A cache for transform updates, which must be manually flushed via CSS.flushTransformCache(). */\r\n\t\t\t\t\ttransformCache: {}\r\n\t\t\t\t});\r\n\t\t\t},\r\n\t\t\t/* A parallel to jQuery's $.css(), used for getting/setting Velocity's hooked CSS properties. */\r\n\t\t\thook: null, /* Defined below. */\r\n\t\t\t/* Velocity-wide animation time remapping for testing purposes. */\r\n\t\t\tmock: false,\r\n\t\t\tversion: {major: 1, minor: 5, patch: 2},\r\n\t\t\t/* Set to 1 or 2 (most verbose) to output debug info to console. */\r\n\t\t\tdebug: false,\r\n\t\t\t/* Use rAF high resolution timestamp when available */\r\n\t\t\ttimestamp: true,\r\n\t\t\t/* Pause all animations */\r\n\t\t\tpauseAll: function(queueName) {\r\n\t\t\t\tvar currentTime = (new Date()).getTime();\r\n\r\n\t\t\t\t$.each(Velocity.State.calls, function(i, activeCall) {\r\n\r\n\t\t\t\t\tif (activeCall) {\r\n\r\n\t\t\t\t\t\t/* If we have a queueName and this call is not on that queue, skip */\r\n\t\t\t\t\t\tif (queueName !== undefined && ((activeCall[2].queue !== queueName) || (activeCall[2].queue === false))) {\r\n\t\t\t\t\t\t\treturn true;\r\n\t\t\t\t\t\t}\r\n\r\n\t\t\t\t\t\t/* Set call to paused */\r\n\t\t\t\t\t\tactiveCall[5] = {\r\n\t\t\t\t\t\t\tresume: false\r\n\t\t\t\t\t\t};\r\n\t\t\t\t\t}\r\n\t\t\t\t});\r\n\r\n\t\t\t\t/* Pause timers on any currently delayed calls */\r\n\t\t\t\t$.each(Velocity.State.delayedElements, function(k, element) {\r\n\t\t\t\t\tif (!element) {\r\n\t\t\t\t\t\treturn;\r\n\t\t\t\t\t}\r\n\t\t\t\t\tpauseDelayOnElement(element, currentTime);\r\n\t\t\t\t});\r\n\t\t\t},\r\n\t\t\t/* Resume all animations */\r\n\t\t\tresumeAll: function(queueName) {\r\n\t\t\t\tvar currentTime = (new Date()).getTime();\r\n\r\n\t\t\t\t$.each(Velocity.State.calls, function(i, activeCall) {\r\n\r\n\t\t\t\t\tif (activeCall) {\r\n\r\n\t\t\t\t\t\t/* If we have a queueName and this call is not on that queue, skip */\r\n\t\t\t\t\t\tif (queueName !== undefined && ((activeCall[2].queue !== queueName) || (activeCall[2].queue === false))) {\r\n\t\t\t\t\t\t\treturn true;\r\n\t\t\t\t\t\t}\r\n\r\n\t\t\t\t\t\t/* Set call to resumed if it was paused */\r\n\t\t\t\t\t\tif (activeCall[5]) {\r\n\t\t\t\t\t\t\tactiveCall[5].resume = true;\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n\t\t\t\t});\r\n\t\t\t\t/* Resume timers on any currently delayed calls */\r\n\t\t\t\t$.each(Velocity.State.delayedElements, function(k, element) {\r\n\t\t\t\t\tif (!element) {\r\n\t\t\t\t\t\treturn;\r\n\t\t\t\t\t}\r\n\t\t\t\t\tresumeDelayOnElement(element, currentTime);\r\n\t\t\t\t});\r\n\t\t\t}\r\n\t\t};\r\n\r\n\t\t/* Retrieve the appropriate scroll anchor and property name for the browser: https://developer.mozilla.org/en-US/docs/Web/API/Window.scrollY */\r\n\t\tif (window.pageYOffset !== undefined) {\r\n\t\t\tVelocity.State.scrollAnchor = window;\r\n\t\t\tVelocity.State.scrollPropertyLeft = \"pageXOffset\";\r\n\t\t\tVelocity.State.scrollPropertyTop = \"pageYOffset\";\r\n\t\t} else {\r\n\t\t\tVelocity.State.scrollAnchor = document.documentElement || document.body.parentNode || document.body;\r\n\t\t\tVelocity.State.scrollPropertyLeft = \"scrollLeft\";\r\n\t\t\tVelocity.State.scrollPropertyTop = \"scrollTop\";\r\n\t\t}\r\n\r\n\t\t/* Shorthand alias for jQuery's $.data() utility. */\r\n\t\tfunction Data(element) {\r\n\t\t\t/* Hardcode a reference to the plugin name. */\r\n\t\t\tvar response = $.data(element, \"velocity\");\r\n\r\n\t\t\t/* jQuery <=1.4.2 returns null instead of undefined when no match is found. We normalize this behavior. */\r\n\t\t\treturn response === null ? undefined : response;\r\n\t\t}\r\n\r\n\t\t/**************\r\n\t\t Delay Timer\r\n\t\t **************/\r\n\r\n\t\tfunction pauseDelayOnElement(element, currentTime) {\r\n\t\t\t/* Check for any delay timers, and pause the set timeouts (while preserving time data)\r\n\t\t\t to be resumed when the \"resume\" command is issued */\r\n\t\t\tvar data = Data(element);\r\n\t\t\tif (data && data.delayTimer && !data.delayPaused) {\r\n\t\t\t\tdata.delayRemaining = data.delay - currentTime + data.delayBegin;\r\n\t\t\t\tdata.delayPaused = true;\r\n\t\t\t\tclearTimeout(data.delayTimer.setTimeout);\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tfunction resumeDelayOnElement(element, currentTime) {\r\n\t\t\t/* Check for any paused timers and resume */\r\n\t\t\tvar data = Data(element);\r\n\t\t\tif (data && data.delayTimer && data.delayPaused) {\r\n\t\t\t\t/* If the element was mid-delay, re initiate the timeout with the remaining delay */\r\n\t\t\t\tdata.delayPaused = false;\r\n\t\t\t\tdata.delayTimer.setTimeout = setTimeout(data.delayTimer.next, data.delayRemaining);\r\n\t\t\t}\r\n\t\t}\r\n\r\n\r\n\r\n\t\t/**************\r\n\t\t Easing\r\n\t\t **************/\r\n\r\n\t\t/* Step easing generator. */\r\n\t\tfunction generateStep(steps) {\r\n\t\t\treturn function(p) {\r\n\t\t\t\treturn Math.round(p * steps) * (1 / steps);\r\n\t\t\t};\r\n\t\t}\r\n\r\n\t\t/* Bezier curve function generator. Copyright Gaetan Renaudeau. MIT License: http://en.wikipedia.org/wiki/MIT_License */\r\n\t\tfunction generateBezier(mX1, mY1, mX2, mY2) {\r\n\t\t\tvar NEWTON_ITERATIONS = 4,\r\n\t\t\t\t\tNEWTON_MIN_SLOPE = 0.001,\r\n\t\t\t\t\tSUBDIVISION_PRECISION = 0.0000001,\r\n\t\t\t\t\tSUBDIVISION_MAX_ITERATIONS = 10,\r\n\t\t\t\t\tkSplineTableSize = 11,\r\n\t\t\t\t\tkSampleStepSize = 1.0 / (kSplineTableSize - 1.0),\r\n\t\t\t\t\tfloat32ArraySupported = \"Float32Array\" in window;\r\n\r\n\t\t\t/* Must contain four arguments. */\r\n\t\t\tif (arguments.length !== 4) {\r\n\t\t\t\treturn false;\r\n\t\t\t}\r\n\r\n\t\t\t/* Arguments must be numbers. */\r\n\t\t\tfor (var i = 0; i < 4; ++i) {\r\n\t\t\t\tif (typeof arguments[i] !== \"number\" || isNaN(arguments[i]) || !isFinite(arguments[i])) {\r\n\t\t\t\t\treturn false;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\r\n\t\t\t/* X values must be in the [0, 1] range. */\r\n\t\t\tmX1 = Math.min(mX1, 1);\r\n\t\t\tmX2 = Math.min(mX2, 1);\r\n\t\t\tmX1 = Math.max(mX1, 0);\r\n\t\t\tmX2 = Math.max(mX2, 0);\r\n\r\n\t\t\tvar mSampleValues = float32ArraySupported ? new Float32Array(kSplineTableSize) : new Array(kSplineTableSize);\r\n\r\n\t\t\tfunction A(aA1, aA2) {\r\n\t\t\t\treturn 1.0 - 3.0 * aA2 + 3.0 * aA1;\r\n\t\t\t}\r\n\t\t\tfunction B(aA1, aA2) {\r\n\t\t\t\treturn 3.0 * aA2 - 6.0 * aA1;\r\n\t\t\t}\r\n\t\t\tfunction C(aA1) {\r\n\t\t\t\treturn 3.0 * aA1;\r\n\t\t\t}\r\n\r\n\t\t\tfunction calcBezier(aT, aA1, aA2) {\r\n\t\t\t\treturn ((A(aA1, aA2) * aT + B(aA1, aA2)) * aT + C(aA1)) * aT;\r\n\t\t\t}\r\n\r\n\t\t\tfunction getSlope(aT, aA1, aA2) {\r\n\t\t\t\treturn 3.0 * A(aA1, aA2) * aT * aT + 2.0 * B(aA1, aA2) * aT + C(aA1);\r\n\t\t\t}\r\n\r\n\t\t\tfunction newtonRaphsonIterate(aX, aGuessT) {\r\n\t\t\t\tfor (var i = 0; i < NEWTON_ITERATIONS; ++i) {\r\n\t\t\t\t\tvar currentSlope = getSlope(aGuessT, mX1, mX2);\r\n\r\n\t\t\t\t\tif (currentSlope === 0.0) {\r\n\t\t\t\t\t\treturn aGuessT;\r\n\t\t\t\t\t}\r\n\r\n\t\t\t\t\tvar currentX = calcBezier(aGuessT, mX1, mX2) - aX;\r\n\t\t\t\t\taGuessT -= currentX / currentSlope;\r\n\t\t\t\t}\r\n\r\n\t\t\t\treturn aGuessT;\r\n\t\t\t}\r\n\r\n\t\t\tfunction calcSampleValues() {\r\n\t\t\t\tfor (var i = 0; i < kSplineTableSize; ++i) {\r\n\t\t\t\t\tmSampleValues[i] = calcBezier(i * kSampleStepSize, mX1, mX2);\r\n\t\t\t\t}\r\n\t\t\t}\r\n\r\n\t\t\tfunction binarySubdivide(aX, aA, aB) {\r\n\t\t\t\tvar currentX, currentT, i = 0;\r\n\r\n\t\t\t\tdo {\r\n\t\t\t\t\tcurrentT = aA + (aB - aA) / 2.0;\r\n\t\t\t\t\tcurrentX = calcBezier(currentT, mX1, mX2) - aX;\r\n\t\t\t\t\tif (currentX > 0.0) {\r\n\t\t\t\t\t\taB = currentT;\r\n\t\t\t\t\t} else {\r\n\t\t\t\t\t\taA = currentT;\r\n\t\t\t\t\t}\r\n\t\t\t\t} while (Math.abs(currentX) > SUBDIVISION_PRECISION && ++i < SUBDIVISION_MAX_ITERATIONS);\r\n\r\n\t\t\t\treturn currentT;\r\n\t\t\t}\r\n\r\n\t\t\tfunction getTForX(aX) {\r\n\t\t\t\tvar intervalStart = 0.0,\r\n\t\t\t\t\t\tcurrentSample = 1,\r\n\t\t\t\t\t\tlastSample = kSplineTableSize - 1;\r\n\r\n\t\t\t\tfor (; currentSample !== lastSample && mSampleValues[currentSample] <= aX; ++currentSample) {\r\n\t\t\t\t\tintervalStart += kSampleStepSize;\r\n\t\t\t\t}\r\n\r\n\t\t\t\t--currentSample;\r\n\r\n\t\t\t\tvar dist = (aX - mSampleValues[currentSample]) / (mSampleValues[currentSample + 1] - mSampleValues[currentSample]),\r\n\t\t\t\t\t\tguessForT = intervalStart + dist * kSampleStepSize,\r\n\t\t\t\t\t\tinitialSlope = getSlope(guessForT, mX1, mX2);\r\n\r\n\t\t\t\tif (initialSlope >= NEWTON_MIN_SLOPE) {\r\n\t\t\t\t\treturn newtonRaphsonIterate(aX, guessForT);\r\n\t\t\t\t} else if (initialSlope === 0.0) {\r\n\t\t\t\t\treturn guessForT;\r\n\t\t\t\t} else {\r\n\t\t\t\t\treturn binarySubdivide(aX, intervalStart, intervalStart + kSampleStepSize);\r\n\t\t\t\t}\r\n\t\t\t}\r\n\r\n\t\t\tvar _precomputed = false;\r\n\r\n\t\t\tfunction precompute() {\r\n\t\t\t\t_precomputed = true;\r\n\t\t\t\tif (mX1 !== mY1 || mX2 !== mY2) {\r\n\t\t\t\t\tcalcSampleValues();\r\n\t\t\t\t}\r\n\t\t\t}\r\n\r\n\t\t\tvar f = function(aX) {\r\n\t\t\t\tif (!_precomputed) {\r\n\t\t\t\t\tprecompute();\r\n\t\t\t\t}\r\n\t\t\t\tif (mX1 === mY1 && mX2 === mY2) {\r\n\t\t\t\t\treturn aX;\r\n\t\t\t\t}\r\n\t\t\t\tif (aX === 0) {\r\n\t\t\t\t\treturn 0;\r\n\t\t\t\t}\r\n\t\t\t\tif (aX === 1) {\r\n\t\t\t\t\treturn 1;\r\n\t\t\t\t}\r\n\r\n\t\t\t\treturn calcBezier(getTForX(aX), mY1, mY2);\r\n\t\t\t};\r\n\r\n\t\t\tf.getControlPoints = function() {\r\n\t\t\t\treturn [{x: mX1, y: mY1}, {x: mX2, y: mY2}];\r\n\t\t\t};\r\n\r\n\t\t\tvar str = \"generateBezier(\" + [mX1, mY1, mX2, mY2] + \")\";\r\n\t\t\tf.toString = function() {\r\n\t\t\t\treturn str;\r\n\t\t\t};\r\n\r\n\t\t\treturn f;\r\n\t\t}\r\n\r\n\t\t/* Runge-Kutta spring physics function generator. Adapted from Framer.js, copyright Koen Bok. MIT License: http://en.wikipedia.org/wiki/MIT_License */\r\n\t\t/* Given a tension, friction, and duration, a simulation at 60FPS will first run without a defined duration in order to calculate the full path. A second pass\r\n\t\t then adjusts the time delta -- using the relation between actual time and duration -- to calculate the path for the duration-constrained animation. */\r\n\t\tvar generateSpringRK4 = (function() {\r\n\t\t\tfunction springAccelerationForState(state) {\r\n\t\t\t\treturn (-state.tension * state.x) - (state.friction * state.v);\r\n\t\t\t}\r\n\r\n\t\t\tfunction springEvaluateStateWithDerivative(initialState, dt, derivative) {\r\n\t\t\t\tvar state = {\r\n\t\t\t\t\tx: initialState.x + derivative.dx * dt,\r\n\t\t\t\t\tv: initialState.v + derivative.dv * dt,\r\n\t\t\t\t\ttension: initialState.tension,\r\n\t\t\t\t\tfriction: initialState.friction\r\n\t\t\t\t};\r\n\r\n\t\t\t\treturn {dx: state.v, dv: springAccelerationForState(state)};\r\n\t\t\t}\r\n\r\n\t\t\tfunction springIntegrateState(state, dt) {\r\n\t\t\t\tvar a = {\r\n\t\t\t\t\tdx: state.v,\r\n\t\t\t\t\tdv: springAccelerationForState(state)\r\n\t\t\t\t},\r\n\t\t\t\t\t\tb = springEvaluateStateWithDerivative(state, dt * 0.5, a),\r\n\t\t\t\t\t\tc = springEvaluateStateWithDerivative(state, dt * 0.5, b),\r\n\t\t\t\t\t\td = springEvaluateStateWithDerivative(state, dt, c),\r\n\t\t\t\t\t\tdxdt = 1.0 / 6.0 * (a.dx + 2.0 * (b.dx + c.dx) + d.dx),\r\n\t\t\t\t\t\tdvdt = 1.0 / 6.0 * (a.dv + 2.0 * (b.dv + c.dv) + d.dv);\r\n\r\n\t\t\t\tstate.x = state.x + dxdt * dt;\r\n\t\t\t\tstate.v = state.v + dvdt * dt;\r\n\r\n\t\t\t\treturn state;\r\n\t\t\t}\r\n\r\n\t\t\treturn function springRK4Factory(tension, friction, duration) {\r\n\r\n\t\t\t\tvar initState = {\r\n\t\t\t\t\tx: -1,\r\n\t\t\t\t\tv: 0,\r\n\t\t\t\t\ttension: null,\r\n\t\t\t\t\tfriction: null\r\n\t\t\t\t},\r\n\t\t\t\t\t\tpath = [0],\r\n\t\t\t\t\t\ttime_lapsed = 0,\r\n\t\t\t\t\t\ttolerance = 1 / 10000,\r\n\t\t\t\t\t\tDT = 16 / 1000,\r\n\t\t\t\t\t\thave_duration, dt, last_state;\r\n\r\n\t\t\t\ttension = parseFloat(tension) || 500;\r\n\t\t\t\tfriction = parseFloat(friction) || 20;\r\n\t\t\t\tduration = duration || null;\r\n\r\n\t\t\t\tinitState.tension = tension;\r\n\t\t\t\tinitState.friction = friction;\r\n\r\n\t\t\t\thave_duration = duration !== null;\r\n\r\n\t\t\t\t/* Calculate the actual time it takes for this animation to complete with the provided conditions. */\r\n\t\t\t\tif (have_duration) {\r\n\t\t\t\t\t/* Run the simulation without a duration. */\r\n\t\t\t\t\ttime_lapsed = springRK4Factory(tension, friction);\r\n\t\t\t\t\t/* Compute the adjusted time delta. */\r\n\t\t\t\t\tdt = time_lapsed / duration * DT;\r\n\t\t\t\t} else {\r\n\t\t\t\t\tdt = DT;\r\n\t\t\t\t}\r\n\r\n\t\t\t\twhile (true) {\r\n\t\t\t\t\t/* Next/step function .*/\r\n\t\t\t\t\tlast_state = springIntegrateState(last_state || initState, dt);\r\n\t\t\t\t\t/* Store the position. */\r\n\t\t\t\t\tpath.push(1 + last_state.x);\r\n\t\t\t\t\ttime_lapsed += 16;\r\n\t\t\t\t\t/* If the change threshold is reached, break. */\r\n\t\t\t\t\tif (!(Math.abs(last_state.x) > tolerance && Math.abs(last_state.v) > tolerance)) {\r\n\t\t\t\t\t\tbreak;\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\r\n\t\t\t\t/* If duration is not defined, return the actual time required for completing this animation. Otherwise, return a closure that holds the\r\n\t\t\t\t computed path and returns a snapshot of the position according to a given percentComplete. */\r\n\t\t\t\treturn !have_duration ? time_lapsed : function(percentComplete) {\r\n\t\t\t\t\treturn path[ (percentComplete * (path.length - 1)) | 0 ];\r\n\t\t\t\t};\r\n\t\t\t};\r\n\t\t}());\r\n\r\n\t\t/* jQuery easings. */\r\n\t\tVelocity.Easings = {\r\n\t\t\tlinear: function(p) {\r\n\t\t\t\treturn p;\r\n\t\t\t},\r\n\t\t\tswing: function(p) {\r\n\t\t\t\treturn 0.5 - Math.cos(p * Math.PI) / 2;\r\n\t\t\t},\r\n\t\t\t/* Bonus \"spring\" easing, which is a less exaggerated version of easeInOutElastic. */\r\n\t\t\tspring: function(p) {\r\n\t\t\t\treturn 1 - (Math.cos(p * 4.5 * Math.PI) * Math.exp(-p * 6));\r\n\t\t\t}\r\n\t\t};\r\n\r\n\t\t/* CSS3 and Robert Penner easings. */\r\n\t\t$.each(\r\n\t\t\t\t[\r\n\t\t\t\t\t[\"ease\", [0.25, 0.1, 0.25, 1.0]],\r\n\t\t\t\t\t[\"ease-in\", [0.42, 0.0, 1.00, 1.0]],\r\n\t\t\t\t\t[\"ease-out\", [0.00, 0.0, 0.58, 1.0]],\r\n\t\t\t\t\t[\"ease-in-out\", [0.42, 0.0, 0.58, 1.0]],\r\n\t\t\t\t\t[\"easeInSine\", [0.47, 0, 0.745, 0.715]],\r\n\t\t\t\t\t[\"easeOutSine\", [0.39, 0.575, 0.565, 1]],\r\n\t\t\t\t\t[\"easeInOutSine\", [0.445, 0.05, 0.55, 0.95]],\r\n\t\t\t\t\t[\"easeInQuad\", [0.55, 0.085, 0.68, 0.53]],\r\n\t\t\t\t\t[\"easeOutQuad\", [0.25, 0.46, 0.45, 0.94]],\r\n\t\t\t\t\t[\"easeInOutQuad\", [0.455, 0.03, 0.515, 0.955]],\r\n\t\t\t\t\t[\"easeInCubic\", [0.55, 0.055, 0.675, 0.19]],\r\n\t\t\t\t\t[\"easeOutCubic\", [0.215, 0.61, 0.355, 1]],\r\n\t\t\t\t\t[\"easeInOutCubic\", [0.645, 0.045, 0.355, 1]],\r\n\t\t\t\t\t[\"easeInQuart\", [0.895, 0.03, 0.685, 0.22]],\r\n\t\t\t\t\t[\"easeOutQuart\", [0.165, 0.84, 0.44, 1]],\r\n\t\t\t\t\t[\"easeInOutQuart\", [0.77, 0, 0.175, 1]],\r\n\t\t\t\t\t[\"easeInQuint\", [0.755, 0.05, 0.855, 0.06]],\r\n\t\t\t\t\t[\"easeOutQuint\", [0.23, 1, 0.32, 1]],\r\n\t\t\t\t\t[\"easeInOutQuint\", [0.86, 0, 0.07, 1]],\r\n\t\t\t\t\t[\"easeInExpo\", [0.95, 0.05, 0.795, 0.035]],\r\n\t\t\t\t\t[\"easeOutExpo\", [0.19, 1, 0.22, 1]],\r\n\t\t\t\t\t[\"easeInOutExpo\", [1, 0, 0, 1]],\r\n\t\t\t\t\t[\"easeInCirc\", [0.6, 0.04, 0.98, 0.335]],\r\n\t\t\t\t\t[\"easeOutCirc\", [0.075, 0.82, 0.165, 1]],\r\n\t\t\t\t\t[\"easeInOutCirc\", [0.785, 0.135, 0.15, 0.86]]\r\n\t\t\t\t], function(i, easingArray) {\r\n\t\t\tVelocity.Easings[easingArray[0]] = generateBezier.apply(null, easingArray[1]);\r\n\t\t});\r\n\r\n\t\t/* Determine the appropriate easing type given an easing input. */\r\n\t\tfunction getEasing(value, duration) {\r\n\t\t\tvar easing = value;\r\n\r\n\t\t\t/* The easing option can either be a string that references a pre-registered easing,\r\n\t\t\t or it can be a two-/four-item array of integers to be converted into a bezier/spring function. */\r\n\t\t\tif (Type.isString(value)) {\r\n\t\t\t\t/* Ensure that the easing has been assigned to jQuery's Velocity.Easings object. */\r\n\t\t\t\tif (!Velocity.Easings[value]) {\r\n\t\t\t\t\teasing = false;\r\n\t\t\t\t}\r\n\t\t\t} else if (Type.isArray(value) && value.length === 1) {\r\n\t\t\t\teasing = generateStep.apply(null, value);\r\n\t\t\t} else if (Type.isArray(value) && value.length === 2) {\r\n\t\t\t\t/* springRK4 must be passed the animation's duration. */\r\n\t\t\t\t/* Note: If the springRK4 array contains non-numbers, generateSpringRK4() returns an easing\r\n\t\t\t\t function generated with default tension and friction values. */\r\n\t\t\t\teasing = generateSpringRK4.apply(null, value.concat([duration]));\r\n\t\t\t} else if (Type.isArray(value) && value.length === 4) {\r\n\t\t\t\t/* Note: If the bezier array contains non-numbers, generateBezier() returns false. */\r\n\t\t\t\teasing = generateBezier.apply(null, value);\r\n\t\t\t} else {\r\n\t\t\t\teasing = false;\r\n\t\t\t}\r\n\r\n\t\t\t/* Revert to the Velocity-wide default easing type, or fall back to \"swing\" (which is also jQuery's default)\r\n\t\t\t if the Velocity-wide default has been incorrectly modified. */\r\n\t\t\tif (easing === false) {\r\n\t\t\t\tif (Velocity.Easings[Velocity.defaults.easing]) {\r\n\t\t\t\t\teasing = Velocity.defaults.easing;\r\n\t\t\t\t} else {\r\n\t\t\t\t\teasing = EASING_DEFAULT;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\r\n\t\t\treturn easing;\r\n\t\t}\r\n\r\n\t\t/*****************\r\n\t\t CSS Stack\r\n\t\t *****************/\r\n\r\n\t\t/* The CSS object is a highly condensed and performant CSS stack that fully replaces jQuery's.\r\n\t\t It handles the validation, getting, and setting of both standard CSS properties and CSS property hooks. */\r\n\t\t/* Note: A \"CSS\" shorthand is aliased so that our code is easier to read. */\r\n\t\tvar CSS = Velocity.CSS = {\r\n\t\t\t/*************\r\n\t\t\t RegEx\r\n\t\t\t *************/\r\n\r\n\t\t\tRegEx: {\r\n\t\t\t\tisHex: /^#([A-f\\d]{3}){1,2}$/i,\r\n\t\t\t\t/* Unwrap a property value's surrounding text, e.g. \"rgba(4, 3, 2, 1)\" ==> \"4, 3, 2, 1\" and \"rect(4px 3px 2px 1px)\" ==> \"4px 3px 2px 1px\". */\r\n\t\t\t\tvalueUnwrap: /^[A-z]+\\((.*)\\)$/i,\r\n\t\t\t\twrappedValueAlreadyExtracted: /[0-9.]+ [0-9.]+ [0-9.]+( [0-9.]+)?/,\r\n\t\t\t\t/* Split a multi-value property into an array of subvalues, e.g. \"rgba(4, 3, 2, 1) 4px 3px 2px 1px\" ==> [ \"rgba(4, 3, 2, 1)\", \"4px\", \"3px\", \"2px\", \"1px\" ]. */\r\n\t\t\t\tvalueSplit: /([A-z]+\\(.+\\))|(([A-z0-9#-.]+?)(?=\\s|$))/ig\r\n\t\t\t},\r\n\t\t\t/************\r\n\t\t\t Lists\r\n\t\t\t ************/\r\n\r\n\t\t\tLists: {\r\n\t\t\t\tcolors: [\"fill\", \"stroke\", \"stopColor\", \"color\", \"backgroundColor\", \"borderColor\", \"borderTopColor\", \"borderRightColor\", \"borderBottomColor\", \"borderLeftColor\", \"outlineColor\"],\r\n\t\t\t\ttransformsBase: [\"translateX\", \"translateY\", \"scale\", \"scaleX\", \"scaleY\", \"skewX\", \"skewY\", \"rotateZ\"],\r\n\t\t\t\ttransforms3D: [\"transformPerspective\", \"translateZ\", \"scaleZ\", \"rotateX\", \"rotateY\"],\r\n\t\t\t\tunits: [\r\n\t\t\t\t\t\"%\", // relative\r\n\t\t\t\t\t\"em\", \"ex\", \"ch\", \"rem\", // font relative\r\n\t\t\t\t\t\"vw\", \"vh\", \"vmin\", \"vmax\", // viewport relative\r\n\t\t\t\t\t\"cm\", \"mm\", \"Q\", \"in\", \"pc\", \"pt\", \"px\", // absolute lengths\r\n\t\t\t\t\t\"deg\", \"grad\", \"rad\", \"turn\", // angles\r\n\t\t\t\t\t\"s\", \"ms\" // time\r\n\t\t\t\t],\r\n\t\t\t\tcolorNames: {\r\n\t\t\t\t\t\"aliceblue\": \"240,248,255\",\r\n\t\t\t\t\t\"antiquewhite\": \"250,235,215\",\r\n\t\t\t\t\t\"aquamarine\": \"127,255,212\",\r\n\t\t\t\t\t\"aqua\": \"0,255,255\",\r\n\t\t\t\t\t\"azure\": \"240,255,255\",\r\n\t\t\t\t\t\"beige\": \"245,245,220\",\r\n\t\t\t\t\t\"bisque\": \"255,228,196\",\r\n\t\t\t\t\t\"black\": \"0,0,0\",\r\n\t\t\t\t\t\"blanchedalmond\": \"255,235,205\",\r\n\t\t\t\t\t\"blueviolet\": \"138,43,226\",\r\n\t\t\t\t\t\"blue\": \"0,0,255\",\r\n\t\t\t\t\t\"brown\": \"165,42,42\",\r\n\t\t\t\t\t\"burlywood\": \"222,184,135\",\r\n\t\t\t\t\t\"cadetblue\": \"95,158,160\",\r\n\t\t\t\t\t\"chartreuse\": \"127,255,0\",\r\n\t\t\t\t\t\"chocolate\": \"210,105,30\",\r\n\t\t\t\t\t\"coral\": \"255,127,80\",\r\n\t\t\t\t\t\"cornflowerblue\": \"100,149,237\",\r\n\t\t\t\t\t\"cornsilk\": \"255,248,220\",\r\n\t\t\t\t\t\"crimson\": \"220,20,60\",\r\n\t\t\t\t\t\"cyan\": \"0,255,255\",\r\n\t\t\t\t\t\"darkblue\": \"0,0,139\",\r\n\t\t\t\t\t\"darkcyan\": \"0,139,139\",\r\n\t\t\t\t\t\"darkgoldenrod\": \"184,134,11\",\r\n\t\t\t\t\t\"darkgray\": \"169,169,169\",\r\n\t\t\t\t\t\"darkgrey\": \"169,169,169\",\r\n\t\t\t\t\t\"darkgreen\": \"0,100,0\",\r\n\t\t\t\t\t\"darkkhaki\": \"189,183,107\",\r\n\t\t\t\t\t\"darkmagenta\": \"139,0,139\",\r\n\t\t\t\t\t\"darkolivegreen\": \"85,107,47\",\r\n\t\t\t\t\t\"darkorange\": \"255,140,0\",\r\n\t\t\t\t\t\"darkorchid\": \"153,50,204\",\r\n\t\t\t\t\t\"darkred\": \"139,0,0\",\r\n\t\t\t\t\t\"darksalmon\": \"233,150,122\",\r\n\t\t\t\t\t\"darkseagreen\": \"143,188,143\",\r\n\t\t\t\t\t\"darkslateblue\": \"72,61,139\",\r\n\t\t\t\t\t\"darkslategray\": \"47,79,79\",\r\n\t\t\t\t\t\"darkturquoise\": \"0,206,209\",\r\n\t\t\t\t\t\"darkviolet\": \"148,0,211\",\r\n\t\t\t\t\t\"deeppink\": \"255,20,147\",\r\n\t\t\t\t\t\"deepskyblue\": \"0,191,255\",\r\n\t\t\t\t\t\"dimgray\": \"105,105,105\",\r\n\t\t\t\t\t\"dimgrey\": \"105,105,105\",\r\n\t\t\t\t\t\"dodgerblue\": \"30,144,255\",\r\n\t\t\t\t\t\"firebrick\": \"178,34,34\",\r\n\t\t\t\t\t\"floralwhite\": \"255,250,240\",\r\n\t\t\t\t\t\"forestgreen\": \"34,139,34\",\r\n\t\t\t\t\t\"fuchsia\": \"255,0,255\",\r\n\t\t\t\t\t\"gainsboro\": \"220,220,220\",\r\n\t\t\t\t\t\"ghostwhite\": \"248,248,255\",\r\n\t\t\t\t\t\"gold\": \"255,215,0\",\r\n\t\t\t\t\t\"goldenrod\": \"218,165,32\",\r\n\t\t\t\t\t\"gray\": \"128,128,128\",\r\n\t\t\t\t\t\"grey\": \"128,128,128\",\r\n\t\t\t\t\t\"greenyellow\": \"173,255,47\",\r\n\t\t\t\t\t\"green\": \"0,128,0\",\r\n\t\t\t\t\t\"honeydew\": \"240,255,240\",\r\n\t\t\t\t\t\"hotpink\": \"255,105,180\",\r\n\t\t\t\t\t\"indianred\": \"205,92,92\",\r\n\t\t\t\t\t\"indigo\": \"75,0,130\",\r\n\t\t\t\t\t\"ivory\": \"255,255,240\",\r\n\t\t\t\t\t\"khaki\": \"240,230,140\",\r\n\t\t\t\t\t\"lavenderblush\": \"255,240,245\",\r\n\t\t\t\t\t\"lavender\": \"230,230,250\",\r\n\t\t\t\t\t\"lawngreen\": \"124,252,0\",\r\n\t\t\t\t\t\"lemonchiffon\": \"255,250,205\",\r\n\t\t\t\t\t\"lightblue\": \"173,216,230\",\r\n\t\t\t\t\t\"lightcoral\": \"240,128,128\",\r\n\t\t\t\t\t\"lightcyan\": \"224,255,255\",\r\n\t\t\t\t\t\"lightgoldenrodyellow\": \"250,250,210\",\r\n\t\t\t\t\t\"lightgray\": \"211,211,211\",\r\n\t\t\t\t\t\"lightgrey\": \"211,211,211\",\r\n\t\t\t\t\t\"lightgreen\": \"144,238,144\",\r\n\t\t\t\t\t\"lightpink\": \"255,182,193\",\r\n\t\t\t\t\t\"lightsalmon\": \"255,160,122\",\r\n\t\t\t\t\t\"lightseagreen\": \"32,178,170\",\r\n\t\t\t\t\t\"lightskyblue\": \"135,206,250\",\r\n\t\t\t\t\t\"lightslategray\": \"119,136,153\",\r\n\t\t\t\t\t\"lightsteelblue\": \"176,196,222\",\r\n\t\t\t\t\t\"lightyellow\": \"255,255,224\",\r\n\t\t\t\t\t\"limegreen\": \"50,205,50\",\r\n\t\t\t\t\t\"lime\": \"0,255,0\",\r\n\t\t\t\t\t\"linen\": \"250,240,230\",\r\n\t\t\t\t\t\"magenta\": \"255,0,255\",\r\n\t\t\t\t\t\"maroon\": \"128,0,0\",\r\n\t\t\t\t\t\"mediumaquamarine\": \"102,205,170\",\r\n\t\t\t\t\t\"mediumblue\": \"0,0,205\",\r\n\t\t\t\t\t\"mediumorchid\": \"186,85,211\",\r\n\t\t\t\t\t\"mediumpurple\": \"147,112,219\",\r\n\t\t\t\t\t\"mediumseagreen\": \"60,179,113\",\r\n\t\t\t\t\t\"mediumslateblue\": \"123,104,238\",\r\n\t\t\t\t\t\"mediumspringgreen\": \"0,250,154\",\r\n\t\t\t\t\t\"mediumturquoise\": \"72,209,204\",\r\n\t\t\t\t\t\"mediumvioletred\": \"199,21,133\",\r\n\t\t\t\t\t\"midnightblue\": \"25,25,112\",\r\n\t\t\t\t\t\"mintcream\": \"245,255,250\",\r\n\t\t\t\t\t\"mistyrose\": \"255,228,225\",\r\n\t\t\t\t\t\"moccasin\": \"255,228,181\",\r\n\t\t\t\t\t\"navajowhite\": \"255,222,173\",\r\n\t\t\t\t\t\"navy\": \"0,0,128\",\r\n\t\t\t\t\t\"oldlace\": \"253,245,230\",\r\n\t\t\t\t\t\"olivedrab\": \"107,142,35\",\r\n\t\t\t\t\t\"olive\": \"128,128,0\",\r\n\t\t\t\t\t\"orangered\": \"255,69,0\",\r\n\t\t\t\t\t\"orange\": \"255,165,0\",\r\n\t\t\t\t\t\"orchid\": \"218,112,214\",\r\n\t\t\t\t\t\"palegoldenrod\": \"238,232,170\",\r\n\t\t\t\t\t\"palegreen\": \"152,251,152\",\r\n\t\t\t\t\t\"paleturquoise\": \"175,238,238\",\r\n\t\t\t\t\t\"palevioletred\": \"219,112,147\",\r\n\t\t\t\t\t\"papayawhip\": \"255,239,213\",\r\n\t\t\t\t\t\"peachpuff\": \"255,218,185\",\r\n\t\t\t\t\t\"peru\": \"205,133,63\",\r\n\t\t\t\t\t\"pink\": \"255,192,203\",\r\n\t\t\t\t\t\"plum\": \"221,160,221\",\r\n\t\t\t\t\t\"powderblue\": \"176,224,230\",\r\n\t\t\t\t\t\"purple\": \"128,0,128\",\r\n\t\t\t\t\t\"red\": \"255,0,0\",\r\n\t\t\t\t\t\"rosybrown\": \"188,143,143\",\r\n\t\t\t\t\t\"royalblue\": \"65,105,225\",\r\n\t\t\t\t\t\"saddlebrown\": \"139,69,19\",\r\n\t\t\t\t\t\"salmon\": \"250,128,114\",\r\n\t\t\t\t\t\"sandybrown\": \"244,164,96\",\r\n\t\t\t\t\t\"seagreen\": \"46,139,87\",\r\n\t\t\t\t\t\"seashell\": \"255,245,238\",\r\n\t\t\t\t\t\"sienna\": \"160,82,45\",\r\n\t\t\t\t\t\"silver\": \"192,192,192\",\r\n\t\t\t\t\t\"skyblue\": \"135,206,235\",\r\n\t\t\t\t\t\"slateblue\": \"106,90,205\",\r\n\t\t\t\t\t\"slategray\": \"112,128,144\",\r\n\t\t\t\t\t\"snow\": \"255,250,250\",\r\n\t\t\t\t\t\"springgreen\": \"0,255,127\",\r\n\t\t\t\t\t\"steelblue\": \"70,130,180\",\r\n\t\t\t\t\t\"tan\": \"210,180,140\",\r\n\t\t\t\t\t\"teal\": \"0,128,128\",\r\n\t\t\t\t\t\"thistle\": \"216,191,216\",\r\n\t\t\t\t\t\"tomato\": \"255,99,71\",\r\n\t\t\t\t\t\"turquoise\": \"64,224,208\",\r\n\t\t\t\t\t\"violet\": \"238,130,238\",\r\n\t\t\t\t\t\"wheat\": \"245,222,179\",\r\n\t\t\t\t\t\"whitesmoke\": \"245,245,245\",\r\n\t\t\t\t\t\"white\": \"255,255,255\",\r\n\t\t\t\t\t\"yellowgreen\": \"154,205,50\",\r\n\t\t\t\t\t\"yellow\": \"255,255,0\"\r\n\t\t\t\t}\r\n\t\t\t},\r\n\t\t\t/************\r\n\t\t\t Hooks\r\n\t\t\t ************/\r\n\r\n\t\t\t/* Hooks allow a subproperty (e.g. \"boxShadowBlur\") of a compound-value CSS property\r\n\t\t\t (e.g. \"boxShadow: X Y Blur Spread Color\") to be animated as if it were a discrete property. */\r\n\t\t\t/* Note: Beyond enabling fine-grained property animation, hooking is necessary since Velocity only\r\n\t\t\t tweens properties with single numeric values; unlike CSS transitions, Velocity does not interpolate compound-values. */\r\n\t\t\tHooks: {\r\n\t\t\t\t/********************\r\n\t\t\t\t Registration\r\n\t\t\t\t ********************/\r\n\r\n\t\t\t\t/* Templates are a concise way of indicating which subproperties must be individually registered for each compound-value CSS property. */\r\n\t\t\t\t/* Each template consists of the compound-value's base name, its constituent subproperty names, and those subproperties' default values. */\r\n\t\t\t\ttemplates: {\r\n\t\t\t\t\t\"textShadow\": [\"Color X Y Blur\", \"black 0px 0px 0px\"],\r\n\t\t\t\t\t\"boxShadow\": [\"Color X Y Blur Spread\", \"black 0px 0px 0px 0px\"],\r\n\t\t\t\t\t\"clip\": [\"Top Right Bottom Left\", \"0px 0px 0px 0px\"],\r\n\t\t\t\t\t\"backgroundPosition\": [\"X Y\", \"0% 0%\"],\r\n\t\t\t\t\t\"transformOrigin\": [\"X Y Z\", \"50% 50% 0px\"],\r\n\t\t\t\t\t\"perspectiveOrigin\": [\"X Y\", \"50% 50%\"]\r\n\t\t\t\t},\r\n\t\t\t\t/* A \"registered\" hook is one that has been converted from its template form into a live,\r\n\t\t\t\t tweenable property. It contains data to associate it with its root property. */\r\n\t\t\t\tregistered: {\r\n\t\t\t\t\t/* Note: A registered hook looks like this ==> textShadowBlur: [ \"textShadow\", 3 ],\r\n\t\t\t\t\t which consists of the subproperty's name, the associated root property's name,\r\n\t\t\t\t\t and the subproperty's position in the root's value. */\r\n\t\t\t\t},\r\n\t\t\t\t/* Convert the templates into individual hooks then append them to the registered object above. */\r\n\t\t\t\tregister: function() {\r\n\t\t\t\t\t/* Color hooks registration: Colors are defaulted to white -- as opposed to black -- since colors that are\r\n\t\t\t\t\t currently set to \"transparent\" default to their respective template below when color-animated,\r\n\t\t\t\t\t and white is typically a closer match to transparent than black is. An exception is made for text (\"color\"),\r\n\t\t\t\t\t which is almost always set closer to black than white. */\r\n\t\t\t\t\tfor (var i = 0; i < CSS.Lists.colors.length; i++) {\r\n\t\t\t\t\t\tvar rgbComponents = (CSS.Lists.colors[i] === \"color\") ? \"0 0 0 1\" : \"255 255 255 1\";\r\n\t\t\t\t\t\tCSS.Hooks.templates[CSS.Lists.colors[i]] = [\"Red Green Blue Alpha\", rgbComponents];\r\n\t\t\t\t\t}\r\n\r\n\t\t\t\t\tvar rootProperty,\r\n\t\t\t\t\t\t\thookTemplate,\r\n\t\t\t\t\t\t\thookNames;\r\n\r\n\t\t\t\t\t/* In IE, color values inside compound-value properties are positioned at the end the value instead of at the beginning.\r\n\t\t\t\t\t Thus, we re-arrange the templates accordingly. */\r\n\t\t\t\t\tif (IE) {\r\n\t\t\t\t\t\tfor (rootProperty in CSS.Hooks.templates) {\r\n\t\t\t\t\t\t\tif (!CSS.Hooks.templates.hasOwnProperty(rootProperty)) {\r\n\t\t\t\t\t\t\t\tcontinue;\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\thookTemplate = CSS.Hooks.templates[rootProperty];\r\n\t\t\t\t\t\t\thookNames = hookTemplate[0].split(\" \");\r\n\r\n\t\t\t\t\t\t\tvar defaultValues = hookTemplate[1].match(CSS.RegEx.valueSplit);\r\n\r\n\t\t\t\t\t\t\tif (hookNames[0] === \"Color\") {\r\n\t\t\t\t\t\t\t\t/* Reposition both the hook's name and its default value to the end of their respective strings. */\r\n\t\t\t\t\t\t\t\thookNames.push(hookNames.shift());\r\n\t\t\t\t\t\t\t\tdefaultValues.push(defaultValues.shift());\r\n\r\n\t\t\t\t\t\t\t\t/* Replace the existing template for the hook's root property. */\r\n\t\t\t\t\t\t\t\tCSS.Hooks.templates[rootProperty] = [hookNames.join(\" \"), defaultValues.join(\" \")];\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n\r\n\t\t\t\t\t/* Hook registration. */\r\n\t\t\t\t\tfor (rootProperty in CSS.Hooks.templates) {\r\n\t\t\t\t\t\tif (!CSS.Hooks.templates.hasOwnProperty(rootProperty)) {\r\n\t\t\t\t\t\t\tcontinue;\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t\thookTemplate = CSS.Hooks.templates[rootProperty];\r\n\t\t\t\t\t\thookNames = hookTemplate[0].split(\" \");\r\n\r\n\t\t\t\t\t\tfor (var j in hookNames) {\r\n\t\t\t\t\t\t\tif (!hookNames.hasOwnProperty(j)) {\r\n\t\t\t\t\t\t\t\tcontinue;\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\tvar fullHookName = rootProperty + hookNames[j],\r\n\t\t\t\t\t\t\t\t\thookPosition = j;\r\n\r\n\t\t\t\t\t\t\t/* For each hook, register its full name (e.g. textShadowBlur) with its root property (e.g. textShadow)\r\n\t\t\t\t\t\t\t and the hook's position in its template's default value string. */\r\n\t\t\t\t\t\t\tCSS.Hooks.registered[fullHookName] = [rootProperty, hookPosition];\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n\t\t\t\t},\r\n\t\t\t\t/*****************************\r\n\t\t\t\t Injection and Extraction\r\n\t\t\t\t *****************************/\r\n\r\n\t\t\t\t/* Look up the root property associated with the hook (e.g. return \"textShadow\" for \"textShadowBlur\"). */\r\n\t\t\t\t/* Since a hook cannot be set directly (the browser won't recognize it), style updating for hooks is routed through the hook's root property. */\r\n\t\t\t\tgetRoot: function(property) {\r\n\t\t\t\t\tvar hookData = CSS.Hooks.registered[property];\r\n\r\n\t\t\t\t\tif (hookData) {\r\n\t\t\t\t\t\treturn hookData[0];\r\n\t\t\t\t\t} else {\r\n\t\t\t\t\t\t/* If there was no hook match, return the property name untouched. */\r\n\t\t\t\t\t\treturn property;\r\n\t\t\t\t\t}\r\n\t\t\t\t},\r\n\t\t\t\tgetUnit: function(str, start) {\r\n\t\t\t\t\tvar unit = (str.substr(start || 0, 5).match(/^[a-z%]+/) || [])[0] || \"\";\r\n\r\n\t\t\t\t\tif (unit && _inArray(CSS.Lists.units, unit)) {\r\n\t\t\t\t\t\treturn unit;\r\n\t\t\t\t\t}\r\n\t\t\t\t\treturn \"\";\r\n\t\t\t\t},\r\n\t\t\t\tfixColors: function(str) {\r\n\t\t\t\t\treturn str.replace(/(rgba?\\(\\s*)?(\\b[a-z]+\\b)/g, function($0, $1, $2) {\r\n\t\t\t\t\t\tif (CSS.Lists.colorNames.hasOwnProperty($2)) {\r\n\t\t\t\t\t\t\treturn ($1 ? $1 : \"rgba(\") + CSS.Lists.colorNames[$2] + ($1 ? \"\" : \",1)\");\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t\treturn $1 + $2;\r\n\t\t\t\t\t});\r\n\t\t\t\t},\r\n\t\t\t\t/* Convert any rootPropertyValue, null or otherwise, into a space-delimited list of hook values so that\r\n\t\t\t\t the targeted hook can be injected or extracted at its standard position. */\r\n\t\t\t\tcleanRootPropertyValue: function(rootProperty, rootPropertyValue) {\r\n\t\t\t\t\t/* If the rootPropertyValue is wrapped with \"rgb()\", \"clip()\", etc., remove the wrapping to normalize the value before manipulation. */\r\n\t\t\t\t\tif (CSS.RegEx.valueUnwrap.test(rootPropertyValue)) {\r\n\t\t\t\t\t\trootPropertyValue = rootPropertyValue.match(CSS.RegEx.valueUnwrap)[1];\r\n\t\t\t\t\t}\r\n\r\n\t\t\t\t\t/* If rootPropertyValue is a CSS null-value (from which there's inherently no hook value to extract),\r\n\t\t\t\t\t default to the root's default value as defined in CSS.Hooks.templates. */\r\n\t\t\t\t\t/* Note: CSS null-values include \"none\", \"auto\", and \"transparent\". They must be converted into their\r\n\t\t\t\t\t zero-values (e.g. textShadow: \"none\" ==> textShadow: \"0px 0px 0px black\") for hook manipulation to proceed. */\r\n\t\t\t\t\tif (CSS.Values.isCSSNullValue(rootPropertyValue)) {\r\n\t\t\t\t\t\trootPropertyValue = CSS.Hooks.templates[rootProperty][1];\r\n\t\t\t\t\t}\r\n\r\n\t\t\t\t\treturn rootPropertyValue;\r\n\t\t\t\t},\r\n\t\t\t\t/* Extracted the hook's value from its root property's value. This is used to get the starting value of an animating hook. */\r\n\t\t\t\textractValue: function(fullHookName, rootPropertyValue) {\r\n\t\t\t\t\tvar hookData = CSS.Hooks.registered[fullHookName];\r\n\r\n\t\t\t\t\tif (hookData) {\r\n\t\t\t\t\t\tvar hookRoot = hookData[0],\r\n\t\t\t\t\t\t\t\thookPosition = hookData[1];\r\n\r\n\t\t\t\t\t\trootPropertyValue = CSS.Hooks.cleanRootPropertyValue(hookRoot, rootPropertyValue);\r\n\r\n\t\t\t\t\t\t/* Split rootPropertyValue into its constituent hook values then grab the desired hook at its standard position. */\r\n\t\t\t\t\t\treturn rootPropertyValue.toString().match(CSS.RegEx.valueSplit)[hookPosition];\r\n\t\t\t\t\t} else {\r\n\t\t\t\t\t\t/* If the provided fullHookName isn't a registered hook, return the rootPropertyValue that was passed in. */\r\n\t\t\t\t\t\treturn rootPropertyValue;\r\n\t\t\t\t\t}\r\n\t\t\t\t},\r\n\t\t\t\t/* Inject the hook's value into its root property's value. This is used to piece back together the root property\r\n\t\t\t\t once Velocity has updated one of its individually hooked values through tweening. */\r\n\t\t\t\tinjectValue: function(fullHookName, hookValue, rootPropertyValue) {\r\n\t\t\t\t\tvar hookData = CSS.Hooks.registered[fullHookName];\r\n\r\n\t\t\t\t\tif (hookData) {\r\n\t\t\t\t\t\tvar hookRoot = hookData[0],\r\n\t\t\t\t\t\t\t\thookPosition = hookData[1],\r\n\t\t\t\t\t\t\t\trootPropertyValueParts,\r\n\t\t\t\t\t\t\t\trootPropertyValueUpdated;\r\n\r\n\t\t\t\t\t\trootPropertyValue = CSS.Hooks.cleanRootPropertyValue(hookRoot, rootPropertyValue);\r\n\r\n\t\t\t\t\t\t/* Split rootPropertyValue into its individual hook values, replace the targeted value with hookValue,\r\n\t\t\t\t\t\t then reconstruct the rootPropertyValue string. */\r\n\t\t\t\t\t\trootPropertyValueParts = rootPropertyValue.toString().match(CSS.RegEx.valueSplit);\r\n\t\t\t\t\t\trootPropertyValueParts[hookPosition] = hookValue;\r\n\t\t\t\t\t\trootPropertyValueUpdated = rootPropertyValueParts.join(\" \");\r\n\r\n\t\t\t\t\t\treturn rootPropertyValueUpdated;\r\n\t\t\t\t\t} else {\r\n\t\t\t\t\t\t/* If the provided fullHookName isn't a registered hook, return the rootPropertyValue that was passed in. */\r\n\t\t\t\t\t\treturn rootPropertyValue;\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t},\r\n\t\t\t/*******************\r\n\t\t\t Normalizations\r\n\t\t\t *******************/\r\n\r\n\t\t\t/* Normalizations standardize CSS property manipulation by pollyfilling browser-specific implementations (e.g. opacity)\r\n\t\t\t and reformatting special properties (e.g. clip, rgba) to look like standard ones. */\r\n\t\t\tNormalizations: {\r\n\t\t\t\t/* Normalizations are passed a normalization target (either the property's name, its extracted value, or its injected value),\r\n\t\t\t\t the targeted element (which may need to be queried), and the targeted property value. */\r\n\t\t\t\tregistered: {\r\n\t\t\t\t\tclip: function(type, element, propertyValue) {\r\n\t\t\t\t\t\tswitch (type) {\r\n\t\t\t\t\t\t\tcase \"name\":\r\n\t\t\t\t\t\t\t\treturn \"clip\";\r\n\t\t\t\t\t\t\t\t/* Clip needs to be unwrapped and stripped of its commas during extraction. */\r\n\t\t\t\t\t\t\tcase \"extract\":\r\n\t\t\t\t\t\t\t\tvar extracted;\r\n\r\n\t\t\t\t\t\t\t\t/* If Velocity also extracted this value, skip extraction. */\r\n\t\t\t\t\t\t\t\tif (CSS.RegEx.wrappedValueAlreadyExtracted.test(propertyValue)) {\r\n\t\t\t\t\t\t\t\t\textracted = propertyValue;\r\n\t\t\t\t\t\t\t\t} else {\r\n\t\t\t\t\t\t\t\t\t/* Remove the \"rect()\" wrapper. */\r\n\t\t\t\t\t\t\t\t\textracted = propertyValue.toString().match(CSS.RegEx.valueUnwrap);\r\n\r\n\t\t\t\t\t\t\t\t\t/* Strip off commas. */\r\n\t\t\t\t\t\t\t\t\textracted = extracted ? extracted[1].replace(/,(\\s+)?/g, \" \") : propertyValue;\r\n\t\t\t\t\t\t\t\t}\r\n\r\n\t\t\t\t\t\t\t\treturn extracted;\r\n\t\t\t\t\t\t\t\t/* Clip needs to be re-wrapped during injection. */\r\n\t\t\t\t\t\t\tcase \"inject\":\r\n\t\t\t\t\t\t\t\treturn \"rect(\" + propertyValue + \")\";\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t},\r\n\t\t\t\t\tblur: function(type, element, propertyValue) {\r\n\t\t\t\t\t\tswitch (type) {\r\n\t\t\t\t\t\t\tcase \"name\":\r\n\t\t\t\t\t\t\t\treturn Velocity.State.isFirefox ? \"filter\" : \"-webkit-filter\";\r\n\t\t\t\t\t\t\tcase \"extract\":\r\n\t\t\t\t\t\t\t\tvar extracted = parseFloat(propertyValue);\r\n\r\n\t\t\t\t\t\t\t\t/* If extracted is NaN, meaning the value isn't already extracted. */\r\n\t\t\t\t\t\t\t\tif (!(extracted || extracted === 0)) {\r\n\t\t\t\t\t\t\t\t\tvar blurComponent = propertyValue.toString().match(/blur\\(([0-9]+[A-z]+)\\)/i);\r\n\r\n\t\t\t\t\t\t\t\t\t/* If the filter string had a blur component, return just the blur value and unit type. */\r\n\t\t\t\t\t\t\t\t\tif (blurComponent) {\r\n\t\t\t\t\t\t\t\t\t\textracted = blurComponent[1];\r\n\t\t\t\t\t\t\t\t\t\t/* If the component doesn't exist, default blur to 0. */\r\n\t\t\t\t\t\t\t\t\t} else {\r\n\t\t\t\t\t\t\t\t\t\textracted = 0;\r\n\t\t\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\t\t}\r\n\r\n\t\t\t\t\t\t\t\treturn extracted;\r\n\t\t\t\t\t\t\t\t/* Blur needs to be re-wrapped during injection. */\r\n\t\t\t\t\t\t\tcase \"inject\":\r\n\t\t\t\t\t\t\t\t/* For the blur effect to be fully de-applied, it needs to be set to \"none\" instead of 0. */\r\n\t\t\t\t\t\t\t\tif (!parseFloat(propertyValue)) {\r\n\t\t\t\t\t\t\t\t\treturn \"none\";\r\n\t\t\t\t\t\t\t\t} else {\r\n\t\t\t\t\t\t\t\t\treturn \"blur(\" + propertyValue + \")\";\r\n\t\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t},\r\n\t\t\t\t\t/* <=IE8 do not support the standard opacity property. They use filter:alpha(opacity=INT) instead. */\r\n\t\t\t\t\topacity: function(type, element, propertyValue) {\r\n\t\t\t\t\t\tif (IE <= 8) {\r\n\t\t\t\t\t\t\tswitch (type) {\r\n\t\t\t\t\t\t\t\tcase \"name\":\r\n\t\t\t\t\t\t\t\t\treturn \"filter\";\r\n\t\t\t\t\t\t\t\tcase \"extract\":\r\n\t\t\t\t\t\t\t\t\t/* <=IE8 return a \"filter\" value of \"alpha(opacity=\\d{1,3})\".\r\n\t\t\t\t\t\t\t\t\t Extract the value and convert it to a decimal value to match the standard CSS opacity property's formatting. */\r\n\t\t\t\t\t\t\t\t\tvar extracted = propertyValue.toString().match(/alpha\\(opacity=(.*)\\)/i);\r\n\r\n\t\t\t\t\t\t\t\t\tif (extracted) {\r\n\t\t\t\t\t\t\t\t\t\t/* Convert to decimal value. */\r\n\t\t\t\t\t\t\t\t\t\tpropertyValue = extracted[1] / 100;\r\n\t\t\t\t\t\t\t\t\t} else {\r\n\t\t\t\t\t\t\t\t\t\t/* When extracting opacity, default to 1 since a null value means opacity hasn't been set. */\r\n\t\t\t\t\t\t\t\t\t\tpropertyValue = 1;\r\n\t\t\t\t\t\t\t\t\t}\r\n\r\n\t\t\t\t\t\t\t\t\treturn propertyValue;\r\n\t\t\t\t\t\t\t\tcase \"inject\":\r\n\t\t\t\t\t\t\t\t\t/* Opacified elements are required to have their zoom property set to a non-zero value. */\r\n\t\t\t\t\t\t\t\t\telement.style.zoom = 1;\r\n\r\n\t\t\t\t\t\t\t\t\t/* Setting the filter property on elements with certain font property combinations can result in a\r\n\t\t\t\t\t\t\t\t\t highly unappealing ultra-bolding effect. There's no way to remedy this throughout a tween, but dropping the\r\n\t\t\t\t\t\t\t\t\t value altogether (when opacity hits 1) at leasts ensures that the glitch is gone post-tweening. */\r\n\t\t\t\t\t\t\t\t\tif (parseFloat(propertyValue) >= 1) {\r\n\t\t\t\t\t\t\t\t\t\treturn \"\";\r\n\t\t\t\t\t\t\t\t\t} else {\r\n\t\t\t\t\t\t\t\t\t\t/* As per the filter property's spec, convert the decimal value to a whole number and wrap the value. */\r\n\t\t\t\t\t\t\t\t\t\treturn \"alpha(opacity=\" + parseInt(parseFloat(propertyValue) * 100, 10) + \")\";\r\n\t\t\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\t/* With all other browsers, normalization is not required; return the same values that were passed in. */\r\n\t\t\t\t\t\t} else {\r\n\t\t\t\t\t\t\tswitch (type) {\r\n\t\t\t\t\t\t\t\tcase \"name\":\r\n\t\t\t\t\t\t\t\t\treturn \"opacity\";\r\n\t\t\t\t\t\t\t\tcase \"extract\":\r\n\t\t\t\t\t\t\t\t\treturn propertyValue;\r\n\t\t\t\t\t\t\t\tcase \"inject\":\r\n\t\t\t\t\t\t\t\t\treturn propertyValue;\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n\t\t\t\t},\r\n\t\t\t\t/*****************************\r\n\t\t\t\t Batched Registrations\r\n\t\t\t\t *****************************/\r\n\r\n\t\t\t\t/* Note: Batched normalizations extend the CSS.Normalizations.registered object. */\r\n\t\t\t\tregister: function() {\r\n\r\n\t\t\t\t\t/*****************\r\n\t\t\t\t\t Transforms\r\n\t\t\t\t\t *****************/\r\n\r\n\t\t\t\t\t/* Transforms are the subproperties contained by the CSS \"transform\" property. Transforms must undergo normalization\r\n\t\t\t\t\t so that they can be referenced in a properties map by their individual names. */\r\n\t\t\t\t\t/* Note: When transforms are \"set\", they are actually assigned to a per-element transformCache. When all transform\r\n\t\t\t\t\t setting is complete complete, CSS.flushTransformCache() must be manually called to flush the values to the DOM.\r\n\t\t\t\t\t Transform setting is batched in this way to improve performance: the transform style only needs to be updated\r\n\t\t\t\t\t once when multiple transform subproperties are being animated simultaneously. */\r\n\t\t\t\t\t/* Note: IE9 and Android Gingerbread have support for 2D -- but not 3D -- transforms. Since animating unsupported\r\n\t\t\t\t\t transform properties results in the browser ignoring the *entire* transform string, we prevent these 3D values\r\n\t\t\t\t\t from being normalized for these browsers so that tweening skips these properties altogether\r\n\t\t\t\t\t (since it will ignore them as being unsupported by the browser.) */\r\n\t\t\t\t\tif ((!IE || IE > 9) && !Velocity.State.isGingerbread) {\r\n\t\t\t\t\t\t/* Note: Since the standalone CSS \"perspective\" property and the CSS transform \"perspective\" subproperty\r\n\t\t\t\t\t\t share the same name, the latter is given a unique token within Velocity: \"transformPerspective\". */\r\n\t\t\t\t\t\tCSS.Lists.transformsBase = CSS.Lists.transformsBase.concat(CSS.Lists.transforms3D);\r\n\t\t\t\t\t}\r\n\r\n\t\t\t\t\tfor (var i = 0; i < CSS.Lists.transformsBase.length; i++) {\r\n\t\t\t\t\t\t/* Wrap the dynamically generated normalization function in a new scope so that transformName's value is\r\n\t\t\t\t\t\t paired with its respective function. (Otherwise, all functions would take the final for loop's transformName.) */\r\n\t\t\t\t\t\t(function() {\r\n\t\t\t\t\t\t\tvar transformName = CSS.Lists.transformsBase[i];\r\n\r\n\t\t\t\t\t\t\tCSS.Normalizations.registered[transformName] = function(type, element, propertyValue) {\r\n\t\t\t\t\t\t\t\tswitch (type) {\r\n\t\t\t\t\t\t\t\t\t/* The normalized property name is the parent \"transform\" property -- the property that is actually set in CSS. */\r\n\t\t\t\t\t\t\t\t\tcase \"name\":\r\n\t\t\t\t\t\t\t\t\t\treturn \"transform\";\r\n\t\t\t\t\t\t\t\t\t\t/* Transform values are cached onto a per-element transformCache object. */\r\n\t\t\t\t\t\t\t\t\tcase \"extract\":\r\n\t\t\t\t\t\t\t\t\t\t/* If this transform has yet to be assigned a value, return its null value. */\r\n\t\t\t\t\t\t\t\t\t\tif (Data(element) === undefined || Data(element).transformCache[transformName] === undefined) {\r\n\t\t\t\t\t\t\t\t\t\t\t/* Scale CSS.Lists.transformsBase default to 1 whereas all other transform properties default to 0. */\r\n\t\t\t\t\t\t\t\t\t\t\treturn /^scale/i.test(transformName) ? 1 : 0;\r\n\t\t\t\t\t\t\t\t\t\t\t/* When transform values are set, they are wrapped in parentheses as per the CSS spec.\r\n\t\t\t\t\t\t\t\t\t\t\t Thus, when extracting their values (for tween calculations), we strip off the parentheses. */\r\n\t\t\t\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\t\t\t\treturn Data(element).transformCache[transformName].replace(/[()]/g, \"\");\r\n\t\t\t\t\t\t\t\t\tcase \"inject\":\r\n\t\t\t\t\t\t\t\t\t\tvar invalid = false;\r\n\r\n\t\t\t\t\t\t\t\t\t\t/* If an individual transform property contains an unsupported unit type, the browser ignores the *entire* transform property.\r\n\t\t\t\t\t\t\t\t\t\t Thus, protect users from themselves by skipping setting for transform values supplied with invalid unit types. */\r\n\t\t\t\t\t\t\t\t\t\t/* Switch on the base transform type; ignore the axis by removing the last letter from the transform's name. */\r\n\t\t\t\t\t\t\t\t\t\tswitch (transformName.substr(0, transformName.length - 1)) {\r\n\t\t\t\t\t\t\t\t\t\t\t/* Whitelist unit types for each transform. */\r\n\t\t\t\t\t\t\t\t\t\t\tcase \"translate\":\r\n\t\t\t\t\t\t\t\t\t\t\t\tinvalid = !/(%|px|em|rem|vw|vh|\\d)$/i.test(propertyValue);\r\n\t\t\t\t\t\t\t\t\t\t\t\tbreak;\r\n\t\t\t\t\t\t\t\t\t\t\t\t/* Since an axis-free \"scale\" property is supported as well, a little hack is used here to detect it by chopping off its last letter. */\r\n\t\t\t\t\t\t\t\t\t\t\tcase \"scal\":\r\n\t\t\t\t\t\t\t\t\t\t\tcase \"scale\":\r\n\t\t\t\t\t\t\t\t\t\t\t\t/* Chrome on Android has a bug in which scaled elements blur if their initial scale\r\n\t\t\t\t\t\t\t\t\t\t\t\t value is below 1 (which can happen with forcefeeding). Thus, we detect a yet-unset scale property\r\n\t\t\t\t\t\t\t\t\t\t\t\t and ensure that its first value is always 1. More info: http://stackoverflow.com/questions/10417890/css3-animations-with-transform-causes-blurred-elements-on-webkit/10417962#10417962 */\r\n\t\t\t\t\t\t\t\t\t\t\t\tif (Velocity.State.isAndroid && Data(element).transformCache[transformName] === undefined && propertyValue < 1) {\r\n\t\t\t\t\t\t\t\t\t\t\t\t\tpropertyValue = 1;\r\n\t\t\t\t\t\t\t\t\t\t\t\t}\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\tinvalid = !/(\\d)$/i.test(propertyValue);\r\n\t\t\t\t\t\t\t\t\t\t\t\tbreak;\r\n\t\t\t\t\t\t\t\t\t\t\tcase \"skew\":\r\n\t\t\t\t\t\t\t\t\t\t\t\tinvalid = !/(deg|\\d)$/i.test(propertyValue);\r\n\t\t\t\t\t\t\t\t\t\t\t\tbreak;\r\n\t\t\t\t\t\t\t\t\t\t\tcase \"rotate\":\r\n\t\t\t\t\t\t\t\t\t\t\t\tinvalid = !/(deg|\\d)$/i.test(propertyValue);\r\n\t\t\t\t\t\t\t\t\t\t\t\tbreak;\r\n\t\t\t\t\t\t\t\t\t\t}\r\n\r\n\t\t\t\t\t\t\t\t\t\tif (!invalid) {\r\n\t\t\t\t\t\t\t\t\t\t\t/* As per the CSS spec, wrap the value in parentheses. */\r\n\t\t\t\t\t\t\t\t\t\t\tData(element).transformCache[transformName] = \"(\" + propertyValue + \")\";\r\n\t\t\t\t\t\t\t\t\t\t}\r\n\r\n\t\t\t\t\t\t\t\t\t\t/* Although the value is set on the transformCache object, return the newly-updated value for the calling code to process as normal. */\r\n\t\t\t\t\t\t\t\t\t\treturn Data(element).transformCache[transformName];\r\n\t\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\t};\r\n\t\t\t\t\t\t})();\r\n\t\t\t\t\t}\r\n\r\n\t\t\t\t\t/*************\r\n\t\t\t\t\t Colors\r\n\t\t\t\t\t *************/\r\n\r\n\t\t\t\t\t/* Since Velocity only animates a single numeric value per property, color animation is achieved by hooking the individual RGBA components of CSS color properties.\r\n\t\t\t\t\t Accordingly, color values must be normalized (e.g. \"#ff0000\", \"red\", and \"rgb(255, 0, 0)\" ==> \"255 0 0 1\") so that their components can be injected/extracted by CSS.Hooks logic. */\r\n\t\t\t\t\tfor (var j = 0; j < CSS.Lists.colors.length; j++) {\r\n\t\t\t\t\t\t/* Wrap the dynamically generated normalization function in a new scope so that colorName's value is paired with its respective function.\r\n\t\t\t\t\t\t (Otherwise, all functions would take the final for loop's colorName.) */\r\n\t\t\t\t\t\t(function() {\r\n\t\t\t\t\t\t\tvar colorName = CSS.Lists.colors[j];\r\n\r\n\t\t\t\t\t\t\t/* Note: In IE<=8, which support rgb but not rgba, color properties are reverted to rgb by stripping off the alpha component. */\r\n\t\t\t\t\t\t\tCSS.Normalizations.registered[colorName] = function(type, element, propertyValue) {\r\n\t\t\t\t\t\t\t\tswitch (type) {\r\n\t\t\t\t\t\t\t\t\tcase \"name\":\r\n\t\t\t\t\t\t\t\t\t\treturn colorName;\r\n\t\t\t\t\t\t\t\t\t\t/* Convert all color values into the rgb format. (Old IE can return hex values and color names instead of rgb/rgba.) */\r\n\t\t\t\t\t\t\t\t\tcase \"extract\":\r\n\t\t\t\t\t\t\t\t\t\tvar extracted;\r\n\r\n\t\t\t\t\t\t\t\t\t\t/* If the color is already in its hookable form (e.g. \"255 255 255 1\") due to having been previously extracted, skip extraction. */\r\n\t\t\t\t\t\t\t\t\t\tif (CSS.RegEx.wrappedValueAlreadyExtracted.test(propertyValue)) {\r\n\t\t\t\t\t\t\t\t\t\t\textracted = propertyValue;\r\n\t\t\t\t\t\t\t\t\t\t} else {\r\n\t\t\t\t\t\t\t\t\t\t\tvar converted,\r\n\t\t\t\t\t\t\t\t\t\t\t\t\tcolorNames = {\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tblack: \"rgb(0, 0, 0)\",\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tblue: \"rgb(0, 0, 255)\",\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tgray: \"rgb(128, 128, 128)\",\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tgreen: \"rgb(0, 128, 0)\",\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tred: \"rgb(255, 0, 0)\",\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\twhite: \"rgb(255, 255, 255)\"\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t};\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t/* Convert color names to rgb. */\r\n\t\t\t\t\t\t\t\t\t\t\tif (/^[A-z]+$/i.test(propertyValue)) {\r\n\t\t\t\t\t\t\t\t\t\t\t\tif (colorNames[propertyValue] !== undefined) {\r\n\t\t\t\t\t\t\t\t\t\t\t\t\tconverted = colorNames[propertyValue];\r\n\t\t\t\t\t\t\t\t\t\t\t\t} else {\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t/* If an unmatched color name is provided, default to black. */\r\n\t\t\t\t\t\t\t\t\t\t\t\t\tconverted = colorNames.black;\r\n\t\t\t\t\t\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\t\t\t\t\t\t/* Convert hex values to rgb. */\r\n\t\t\t\t\t\t\t\t\t\t\t} else if (CSS.RegEx.isHex.test(propertyValue)) {\r\n\t\t\t\t\t\t\t\t\t\t\t\tconverted = \"rgb(\" + CSS.Values.hexToRgb(propertyValue).join(\" \") + \")\";\r\n\t\t\t\t\t\t\t\t\t\t\t\t/* If the provided color doesn't match any of the accepted color formats, default to black. */\r\n\t\t\t\t\t\t\t\t\t\t\t} else if (!(/^rgba?\\(/i.test(propertyValue))) {\r\n\t\t\t\t\t\t\t\t\t\t\t\tconverted = colorNames.black;\r\n\t\t\t\t\t\t\t\t\t\t\t}\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t/* Remove the surrounding \"rgb/rgba()\" string then replace commas with spaces and strip\r\n\t\t\t\t\t\t\t\t\t\t\t repeated spaces (in case the value included spaces to begin with). */\r\n\t\t\t\t\t\t\t\t\t\t\textracted = (converted || propertyValue).toString().match(CSS.RegEx.valueUnwrap)[1].replace(/,(\\s+)?/g, \" \");\r\n\t\t\t\t\t\t\t\t\t\t}\r\n\r\n\t\t\t\t\t\t\t\t\t\t/* So long as this isn't <=IE8, add a fourth (alpha) component if it's missing and default it to 1 (visible). */\r\n\t\t\t\t\t\t\t\t\t\tif ((!IE || IE > 8) && extracted.split(\" \").length === 3) {\r\n\t\t\t\t\t\t\t\t\t\t\textracted += \" 1\";\r\n\t\t\t\t\t\t\t\t\t\t}\r\n\r\n\t\t\t\t\t\t\t\t\t\treturn extracted;\r\n\t\t\t\t\t\t\t\t\tcase \"inject\":\r\n\t\t\t\t\t\t\t\t\t\t/* If we have a pattern then it might already have the right values */\r\n\t\t\t\t\t\t\t\t\t\tif (/^rgb/.test(propertyValue)) {\r\n\t\t\t\t\t\t\t\t\t\t\treturn propertyValue;\r\n\t\t\t\t\t\t\t\t\t\t}\r\n\r\n\t\t\t\t\t\t\t\t\t\t/* If this is IE<=8 and an alpha component exists, strip it off. */\r\n\t\t\t\t\t\t\t\t\t\tif (IE <= 8) {\r\n\t\t\t\t\t\t\t\t\t\t\tif (propertyValue.split(\" \").length === 4) {\r\n\t\t\t\t\t\t\t\t\t\t\t\tpropertyValue = propertyValue.split(/\\s+/).slice(0, 3).join(\" \");\r\n\t\t\t\t\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\t\t\t\t\t/* Otherwise, add a fourth (alpha) component if it's missing and default it to 1 (visible). */\r\n\t\t\t\t\t\t\t\t\t\t} else if (propertyValue.split(\" \").length === 3) {\r\n\t\t\t\t\t\t\t\t\t\t\tpropertyValue += \" 1\";\r\n\t\t\t\t\t\t\t\t\t\t}\r\n\r\n\t\t\t\t\t\t\t\t\t\t/* Re-insert the browser-appropriate wrapper(\"rgb/rgba()\"), insert commas, and strip off decimal units\r\n\t\t\t\t\t\t\t\t\t\t on all values but the fourth (R, G, and B only accept whole numbers). */\r\n\t\t\t\t\t\t\t\t\t\treturn (IE <= 8 ? \"rgb\" : \"rgba\") + \"(\" + propertyValue.replace(/\\s+/g, \",\").replace(/\\.(\\d)+(?=,)/g, \"\") + \")\";\r\n\t\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\t};\r\n\t\t\t\t\t\t})();\r\n\t\t\t\t\t}\r\n\r\n\t\t\t\t\t/**************\r\n\t\t\t\t\t Dimensions\r\n\t\t\t\t\t **************/\r\n\t\t\t\t\tfunction augmentDimension(name, element, wantInner) {\r\n\t\t\t\t\t\tvar isBorderBox = CSS.getPropertyValue(element, \"boxSizing\").toString().toLowerCase() === \"border-box\";\r\n\r\n\t\t\t\t\t\tif (isBorderBox === (wantInner || false)) {\r\n\t\t\t\t\t\t\t/* in box-sizing mode, the CSS width / height accessors already give the outerWidth / outerHeight. */\r\n\t\t\t\t\t\t\tvar i,\r\n\t\t\t\t\t\t\t\t\tvalue,\r\n\t\t\t\t\t\t\t\t\taugment = 0,\r\n\t\t\t\t\t\t\t\t\tsides = name === \"width\" ? [\"Left\", \"Right\"] : [\"Top\", \"Bottom\"],\r\n\t\t\t\t\t\t\t\t\tfields = [\"padding\" + sides[0], \"padding\" + sides[1], \"border\" + sides[0] + \"Width\", \"border\" + sides[1] + \"Width\"];\r\n\r\n\t\t\t\t\t\t\tfor (i = 0; i < fields.length; i++) {\r\n\t\t\t\t\t\t\t\tvalue = parseFloat(CSS.getPropertyValue(element, fields[i]));\r\n\t\t\t\t\t\t\t\tif (!isNaN(value)) {\r\n\t\t\t\t\t\t\t\t\taugment += value;\r\n\t\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\treturn wantInner ? -augment : augment;\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t\treturn 0;\r\n\t\t\t\t\t}\r\n\t\t\t\t\tfunction getDimension(name, wantInner) {\r\n\t\t\t\t\t\treturn function(type, element, propertyValue) {\r\n\t\t\t\t\t\t\tswitch (type) {\r\n\t\t\t\t\t\t\t\tcase \"name\":\r\n\t\t\t\t\t\t\t\t\treturn name;\r\n\t\t\t\t\t\t\t\tcase \"extract\":\r\n\t\t\t\t\t\t\t\t\treturn parseFloat(propertyValue) + augmentDimension(name, element, wantInner);\r\n\t\t\t\t\t\t\t\tcase \"inject\":\r\n\t\t\t\t\t\t\t\t\treturn (parseFloat(propertyValue) - augmentDimension(name, element, wantInner)) + \"px\";\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t};\r\n\t\t\t\t\t}\r\n\t\t\t\t\tCSS.Normalizations.registered.innerWidth = getDimension(\"width\", true);\r\n\t\t\t\t\tCSS.Normalizations.registered.innerHeight = getDimension(\"height\", true);\r\n\t\t\t\t\tCSS.Normalizations.registered.outerWidth = getDimension(\"width\");\r\n\t\t\t\t\tCSS.Normalizations.registered.outerHeight = getDimension(\"height\");\r\n\t\t\t\t}\r\n\t\t\t},\r\n\t\t\t/************************\r\n\t\t\t CSS Property Names\r\n\t\t\t ************************/\r\n\r\n\t\t\tNames: {\r\n\t\t\t\t/* Camelcase a property name into its JavaScript notation (e.g. \"background-color\" ==> \"backgroundColor\").\r\n\t\t\t\t Camelcasing is used to normalize property names between and across calls. */\r\n\t\t\t\tcamelCase: function(property) {\r\n\t\t\t\t\treturn property.replace(/-(\\w)/g, function(match, subMatch) {\r\n\t\t\t\t\t\treturn subMatch.toUpperCase();\r\n\t\t\t\t\t});\r\n\t\t\t\t},\r\n\t\t\t\t/* For SVG elements, some properties (namely, dimensional ones) are GET/SET via the element's HTML attributes (instead of via CSS styles). */\r\n\t\t\t\tSVGAttribute: function(property) {\r\n\t\t\t\t\tvar SVGAttributes = \"width|height|x|y|cx|cy|r|rx|ry|x1|x2|y1|y2\";\r\n\r\n\t\t\t\t\t/* Certain browsers require an SVG transform to be applied as an attribute. (Otherwise, application via CSS is preferable due to 3D support.) */\r\n\t\t\t\t\tif (IE || (Velocity.State.isAndroid && !Velocity.State.isChrome)) {\r\n\t\t\t\t\t\tSVGAttributes += \"|transform\";\r\n\t\t\t\t\t}\r\n\r\n\t\t\t\t\treturn new RegExp(\"^(\" + SVGAttributes + \")$\", \"i\").test(property);\r\n\t\t\t\t},\r\n\t\t\t\t/* Determine whether a property should be set with a vendor prefix. */\r\n\t\t\t\t/* If a prefixed version of the property exists, return it. Otherwise, return the original property name.\r\n\t\t\t\t If the property is not at all supported by the browser, return a false flag. */\r\n\t\t\t\tprefixCheck: function(property) {\r\n\t\t\t\t\t/* If this property has already been checked, return the cached value. */\r\n\t\t\t\t\tif (Velocity.State.prefixMatches[property]) {\r\n\t\t\t\t\t\treturn [Velocity.State.prefixMatches[property], true];\r\n\t\t\t\t\t} else {\r\n\t\t\t\t\t\tvar vendors = [\"\", \"Webkit\", \"Moz\", \"ms\", \"O\"];\r\n\r\n\t\t\t\t\t\tfor (var i = 0, vendorsLength = vendors.length; i < vendorsLength; i++) {\r\n\t\t\t\t\t\t\tvar propertyPrefixed;\r\n\r\n\t\t\t\t\t\t\tif (i === 0) {\r\n\t\t\t\t\t\t\t\tpropertyPrefixed = property;\r\n\t\t\t\t\t\t\t} else {\r\n\t\t\t\t\t\t\t\t/* Capitalize the first letter of the property to conform to JavaScript vendor prefix notation (e.g. webkitFilter). */\r\n\t\t\t\t\t\t\t\tpropertyPrefixed = vendors[i] + property.replace(/^\\w/, function(match) {\r\n\t\t\t\t\t\t\t\t\treturn match.toUpperCase();\r\n\t\t\t\t\t\t\t\t});\r\n\t\t\t\t\t\t\t}\r\n\r\n\t\t\t\t\t\t\t/* Check if the browser supports this property as prefixed. */\r\n\t\t\t\t\t\t\tif (Type.isString(Velocity.State.prefixElement.style[propertyPrefixed])) {\r\n\t\t\t\t\t\t\t\t/* Cache the match. */\r\n\t\t\t\t\t\t\t\tVelocity.State.prefixMatches[property] = propertyPrefixed;\r\n\r\n\t\t\t\t\t\t\t\treturn [propertyPrefixed, true];\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t}\r\n\r\n\t\t\t\t\t\t/* If the browser doesn't support this property in any form, include a false flag so that the caller can decide how to proceed. */\r\n\t\t\t\t\t\treturn [property, false];\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t},\r\n\t\t\t/************************\r\n\t\t\t CSS Property Values\r\n\t\t\t ************************/\r\n\r\n\t\t\tValues: {\r\n\t\t\t\t/* Hex to RGB conversion. Copyright Tim Down: http://stackoverflow.com/questions/5623838/rgb-to-hex-and-hex-to-rgb */\r\n\t\t\t\thexToRgb: function(hex) {\r\n\t\t\t\t\tvar shortformRegex = /^#?([a-f\\d])([a-f\\d])([a-f\\d])$/i,\r\n\t\t\t\t\t\t\tlongformRegex = /^#?([a-f\\d]{2})([a-f\\d]{2})([a-f\\d]{2})$/i,\r\n\t\t\t\t\t\t\trgbParts;\r\n\r\n\t\t\t\t\thex = hex.replace(shortformRegex, function(m, r, g, b) {\r\n\t\t\t\t\t\treturn r + r + g + g + b + b;\r\n\t\t\t\t\t});\r\n\r\n\t\t\t\t\trgbParts = longformRegex.exec(hex);\r\n\r\n\t\t\t\t\treturn rgbParts ? [parseInt(rgbParts[1], 16), parseInt(rgbParts[2], 16), parseInt(rgbParts[3], 16)] : [0, 0, 0];\r\n\t\t\t\t},\r\n\t\t\t\tisCSSNullValue: function(value) {\r\n\t\t\t\t\t/* The browser defaults CSS values that have not been set to either 0 or one of several possible null-value strings.\r\n\t\t\t\t\t Thus, we check for both falsiness and these special strings. */\r\n\t\t\t\t\t/* Null-value checking is performed to default the special strings to 0 (for the sake of tweening) or their hook\r\n\t\t\t\t\t templates as defined as CSS.Hooks (for the sake of hook injection/extraction). */\r\n\t\t\t\t\t/* Note: Chrome returns \"rgba(0, 0, 0, 0)\" for an undefined color whereas IE returns \"transparent\". */\r\n\t\t\t\t\treturn (!value || /^(none|auto|transparent|(rgba\\(0, ?0, ?0, ?0\\)))$/i.test(value));\r\n\t\t\t\t},\r\n\t\t\t\t/* Retrieve a property's default unit type. Used for assigning a unit type when one is not supplied by the user. */\r\n\t\t\t\tgetUnitType: function(property) {\r\n\t\t\t\t\tif (/^(rotate|skew)/i.test(property)) {\r\n\t\t\t\t\t\treturn \"deg\";\r\n\t\t\t\t\t} else if (/(^(scale|scaleX|scaleY|scaleZ|alpha|flexGrow|flexHeight|zIndex|fontWeight)$)|((opacity|red|green|blue|alpha)$)/i.test(property)) {\r\n\t\t\t\t\t\t/* The above properties are unitless. */\r\n\t\t\t\t\t\treturn \"\";\r\n\t\t\t\t\t} else {\r\n\t\t\t\t\t\t/* Default to px for all other properties. */\r\n\t\t\t\t\t\treturn \"px\";\r\n\t\t\t\t\t}\r\n\t\t\t\t},\r\n\t\t\t\t/* HTML elements default to an associated display type when they're not set to display:none. */\r\n\t\t\t\t/* Note: This function is used for correctly setting the non-\"none\" display value in certain Velocity redirects, such as fadeIn/Out. */\r\n\t\t\t\tgetDisplayType: function(element) {\r\n\t\t\t\t\tvar tagName = element && element.tagName.toString().toLowerCase();\r\n\r\n\t\t\t\t\tif (/^(b|big|i|small|tt|abbr|acronym|cite|code|dfn|em|kbd|strong|samp|var|a|bdo|br|img|map|object|q|script|span|sub|sup|button|input|label|select|textarea)$/i.test(tagName)) {\r\n\t\t\t\t\t\treturn \"inline\";\r\n\t\t\t\t\t} else if (/^(li)$/i.test(tagName)) {\r\n\t\t\t\t\t\treturn \"list-item\";\r\n\t\t\t\t\t} else if (/^(tr)$/i.test(tagName)) {\r\n\t\t\t\t\t\treturn \"table-row\";\r\n\t\t\t\t\t} else if (/^(table)$/i.test(tagName)) {\r\n\t\t\t\t\t\treturn \"table\";\r\n\t\t\t\t\t} else if (/^(tbody)$/i.test(tagName)) {\r\n\t\t\t\t\t\treturn \"table-row-group\";\r\n\t\t\t\t\t\t/* Default to \"block\" when no match is found. */\r\n\t\t\t\t\t} else {\r\n\t\t\t\t\t\treturn \"block\";\r\n\t\t\t\t\t}\r\n\t\t\t\t},\r\n\t\t\t\t/* The class add/remove functions are used to temporarily apply a \"velocity-animating\" class to elements while they're animating. */\r\n\t\t\t\taddClass: function(element, className) {\r\n\t\t\t\t\tif (element) {\r\n\t\t\t\t\t\tif (element.classList) {\r\n\t\t\t\t\t\t\telement.classList.add(className);\r\n\t\t\t\t\t\t} else if (Type.isString(element.className)) {\r\n\t\t\t\t\t\t\t// Element.className is around 15% faster then set/getAttribute\r\n\t\t\t\t\t\t\telement.className += (element.className.length ? \" \" : \"\") + className;\r\n\t\t\t\t\t\t} else {\r\n\t\t\t\t\t\t\t// Work around for IE strict mode animating SVG - and anything else that doesn't behave correctly - the same way jQuery does it\r\n\t\t\t\t\t\t\tvar currentClass = element.getAttribute(IE <= 7 ? \"className\" : \"class\") || \"\";\r\n\r\n\t\t\t\t\t\t\telement.setAttribute(\"class\", currentClass + (currentClass ? \" \" : \"\") + className);\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n\t\t\t\t},\r\n\t\t\t\tremoveClass: function(element, className) {\r\n\t\t\t\t\tif (element) {\r\n\t\t\t\t\t\tif (element.classList) {\r\n\t\t\t\t\t\t\telement.classList.remove(className);\r\n\t\t\t\t\t\t} else if (Type.isString(element.className)) {\r\n\t\t\t\t\t\t\t// Element.className is around 15% faster then set/getAttribute\r\n\t\t\t\t\t\t\t// TODO: Need some jsperf tests on performance - can we get rid of the regex and maybe use split / array manipulation?\r\n\t\t\t\t\t\t\telement.className = element.className.toString().replace(new RegExp(\"(^|\\\\s)\" + className.split(\" \").join(\"|\") + \"(\\\\s|$)\", \"gi\"), \" \");\r\n\t\t\t\t\t\t} else {\r\n\t\t\t\t\t\t\t// Work around for IE strict mode animating SVG - and anything else that doesn't behave correctly - the same way jQuery does it\r\n\t\t\t\t\t\t\tvar currentClass = element.getAttribute(IE <= 7 ? \"className\" : \"class\") || \"\";\r\n\r\n\t\t\t\t\t\t\telement.setAttribute(\"class\", currentClass.replace(new RegExp(\"(^|\\s)\" + className.split(\" \").join(\"|\") + \"(\\s|$)\", \"gi\"), \" \"));\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t},\r\n\t\t\t/****************************\r\n\t\t\t Style Getting & Setting\r\n\t\t\t ****************************/\r\n\r\n\t\t\t/* The singular getPropertyValue, which routes the logic for all normalizations, hooks, and standard CSS properties. */\r\n\t\t\tgetPropertyValue: function(element, property, rootPropertyValue, forceStyleLookup) {\r\n\t\t\t\t/* Get an element's computed property value. */\r\n\t\t\t\t/* Note: Retrieving the value of a CSS property cannot simply be performed by checking an element's\r\n\t\t\t\t style attribute (which only reflects user-defined values). Instead, the browser must be queried for a property's\r\n\t\t\t\t *computed* value. You can read more about getComputedStyle here: https://developer.mozilla.org/en/docs/Web/API/window.getComputedStyle */\r\n\t\t\t\tfunction computePropertyValue(element, property) {\r\n\t\t\t\t\t/* When box-sizing isn't set to border-box, height and width style values are incorrectly computed when an\r\n\t\t\t\t\t element's scrollbars are visible (which expands the element's dimensions). Thus, we defer to the more accurate\r\n\t\t\t\t\t offsetHeight/Width property, which includes the total dimensions for interior, border, padding, and scrollbar.\r\n\t\t\t\t\t We subtract border and padding to get the sum of interior + scrollbar. */\r\n\t\t\t\t\tvar computedValue = 0;\r\n\r\n\t\t\t\t\t/* IE<=8 doesn't support window.getComputedStyle, thus we defer to jQuery, which has an extensive array\r\n\t\t\t\t\t of hacks to accurately retrieve IE8 property values. Re-implementing that logic here is not worth bloating the\r\n\t\t\t\t\t codebase for a dying browser. The performance repercussions of using jQuery here are minimal since\r\n\t\t\t\t\t Velocity is optimized to rarely (and sometimes never) query the DOM. Further, the $.css() codepath isn't that slow. */\r\n\t\t\t\t\tif (IE <= 8) {\r\n\t\t\t\t\t\tcomputedValue = $.css(element, property); /* GET */\r\n\t\t\t\t\t\t/* All other browsers support getComputedStyle. The returned live object reference is cached onto its\r\n\t\t\t\t\t\t associated element so that it does not need to be refetched upon every GET. */\r\n\t\t\t\t\t} else {\r\n\t\t\t\t\t\t/* Browsers do not return height and width values for elements that are set to display:\"none\". Thus, we temporarily\r\n\t\t\t\t\t\t toggle display to the element type's default value. */\r\n\t\t\t\t\t\tvar toggleDisplay = false;\r\n\r\n\t\t\t\t\t\tif (/^(width|height)$/.test(property) && CSS.getPropertyValue(element, \"display\") === 0) {\r\n\t\t\t\t\t\t\ttoggleDisplay = true;\r\n\t\t\t\t\t\t\tCSS.setPropertyValue(element, \"display\", CSS.Values.getDisplayType(element));\r\n\t\t\t\t\t\t}\r\n\r\n\t\t\t\t\t\tvar revertDisplay = function() {\r\n\t\t\t\t\t\t\tif (toggleDisplay) {\r\n\t\t\t\t\t\t\t\tCSS.setPropertyValue(element, \"display\", \"none\");\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t};\r\n\r\n\t\t\t\t\t\tif (!forceStyleLookup) {\r\n\t\t\t\t\t\t\tif (property === \"height\" && CSS.getPropertyValue(element, \"boxSizing\").toString().toLowerCase() !== \"border-box\") {\r\n\t\t\t\t\t\t\t\tvar contentBoxHeight = element.offsetHeight - (parseFloat(CSS.getPropertyValue(element, \"borderTopWidth\")) || 0) - (parseFloat(CSS.getPropertyValue(element, \"borderBottomWidth\")) || 0) - (parseFloat(CSS.getPropertyValue(element, \"paddingTop\")) || 0) - (parseFloat(CSS.getPropertyValue(element, \"paddingBottom\")) || 0);\r\n\t\t\t\t\t\t\t\trevertDisplay();\r\n\r\n\t\t\t\t\t\t\t\treturn contentBoxHeight;\r\n\t\t\t\t\t\t\t} else if (property === \"width\" && CSS.getPropertyValue(element, \"boxSizing\").toString().toLowerCase() !== \"border-box\") {\r\n\t\t\t\t\t\t\t\tvar contentBoxWidth = element.offsetWidth - (parseFloat(CSS.getPropertyValue(element, \"borderLeftWidth\")) || 0) - (parseFloat(CSS.getPropertyValue(element, \"borderRightWidth\")) || 0) - (parseFloat(CSS.getPropertyValue(element, \"paddingLeft\")) || 0) - (parseFloat(CSS.getPropertyValue(element, \"paddingRight\")) || 0);\r\n\t\t\t\t\t\t\t\trevertDisplay();\r\n\r\n\t\t\t\t\t\t\t\treturn contentBoxWidth;\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t}\r\n\r\n\t\t\t\t\t\tvar computedStyle;\r\n\r\n\t\t\t\t\t\t/* For elements that Velocity hasn't been called on directly (e.g. when Velocity queries the DOM on behalf\r\n\t\t\t\t\t\t of a parent of an element its animating), perform a direct getComputedStyle lookup since the object isn't cached. */\r\n\t\t\t\t\t\tif (Data(element) === undefined) {\r\n\t\t\t\t\t\t\tcomputedStyle = window.getComputedStyle(element, null); /* GET */\r\n\t\t\t\t\t\t\t/* If the computedStyle object has yet to be cached, do so now. */\r\n\t\t\t\t\t\t} else if (!Data(element).computedStyle) {\r\n\t\t\t\t\t\t\tcomputedStyle = Data(element).computedStyle = window.getComputedStyle(element, null); /* GET */\r\n\t\t\t\t\t\t\t/* If computedStyle is cached, use it. */\r\n\t\t\t\t\t\t} else {\r\n\t\t\t\t\t\t\tcomputedStyle = Data(element).computedStyle;\r\n\t\t\t\t\t\t}\r\n\r\n\t\t\t\t\t\t/* IE and Firefox do not return a value for the generic borderColor -- they only return individual values for each border side's color.\r\n\t\t\t\t\t\t Also, in all browsers, when border colors aren't all the same, a compound value is returned that Velocity isn't setup to parse.\r\n\t\t\t\t\t\t So, as a polyfill for querying individual border side colors, we just return the top border's color and animate all borders from that value. */\r\n\t\t\t\t\t\tif (property === \"borderColor\") {\r\n\t\t\t\t\t\t\tproperty = \"borderTopColor\";\r\n\t\t\t\t\t\t}\r\n\r\n\t\t\t\t\t\t/* IE9 has a bug in which the \"filter\" property must be accessed from computedStyle using the getPropertyValue method\r\n\t\t\t\t\t\t instead of a direct property lookup. The getPropertyValue method is slower than a direct lookup, which is why we avoid it by default. */\r\n\t\t\t\t\t\tif (IE === 9 && property === \"filter\") {\r\n\t\t\t\t\t\t\tcomputedValue = computedStyle.getPropertyValue(property); /* GET */\r\n\t\t\t\t\t\t} else {\r\n\t\t\t\t\t\t\tcomputedValue = computedStyle[property];\r\n\t\t\t\t\t\t}\r\n\r\n\t\t\t\t\t\t/* Fall back to the property's style value (if defined) when computedValue returns nothing,\r\n\t\t\t\t\t\t which can happen when the element hasn't been painted. */\r\n\t\t\t\t\t\tif (computedValue === \"\" || computedValue === null) {\r\n\t\t\t\t\t\t\tcomputedValue = element.style[property];\r\n\t\t\t\t\t\t}\r\n\r\n\t\t\t\t\t\trevertDisplay();\r\n\t\t\t\t\t}\r\n\r\n\t\t\t\t\t/* For top, right, bottom, and left (TRBL) values that are set to \"auto\" on elements of \"fixed\" or \"absolute\" position,\r\n\t\t\t\t\t defer to jQuery for converting \"auto\" to a numeric value. (For elements with a \"static\" or \"relative\" position, \"auto\" has the same\r\n\t\t\t\t\t effect as being set to 0, so no conversion is necessary.) */\r\n\t\t\t\t\t/* An example of why numeric conversion is necessary: When an element with \"position:absolute\" has an untouched \"left\"\r\n\t\t\t\t\t property, which reverts to \"auto\", left's value is 0 relative to its parent element, but is often non-zero relative\r\n\t\t\t\t\t to its *containing* (not parent) element, which is the nearest \"position:relative\" ancestor or the viewport (and always the viewport in the case of \"position:fixed\"). */\r\n\t\t\t\t\tif (computedValue === \"auto\" && /^(top|right|bottom|left)$/i.test(property)) {\r\n\t\t\t\t\t\tvar position = computePropertyValue(element, \"position\"); /* GET */\r\n\r\n\t\t\t\t\t\t/* For absolute positioning, jQuery's $.position() only returns values for top and left;\r\n\t\t\t\t\t\t right and bottom will have their \"auto\" value reverted to 0. */\r\n\t\t\t\t\t\t/* Note: A jQuery object must be created here since jQuery doesn't have a low-level alias for $.position().\r\n\t\t\t\t\t\t Not a big deal since we're currently in a GET batch anyway. */\r\n\t\t\t\t\t\tif (position === \"fixed\" || (position === \"absolute\" && /top|left/i.test(property))) {\r\n\t\t\t\t\t\t\t/* Note: jQuery strips the pixel unit from its returned values; we re-add it here to conform with computePropertyValue's behavior. */\r\n\t\t\t\t\t\t\tcomputedValue = $(element).position()[property] + \"px\"; /* GET */\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n\r\n\t\t\t\t\treturn computedValue;\r\n\t\t\t\t}\r\n\r\n\t\t\t\tvar propertyValue;\r\n\r\n\t\t\t\t/* If this is a hooked property (e.g. \"clipLeft\" instead of the root property of \"clip\"),\r\n\t\t\t\t extract the hook's value from a normalized rootPropertyValue using CSS.Hooks.extractValue(). */\r\n\t\t\t\tif (CSS.Hooks.registered[property]) {\r\n\t\t\t\t\tvar hook = property,\r\n\t\t\t\t\t\t\thookRoot = CSS.Hooks.getRoot(hook);\r\n\r\n\t\t\t\t\t/* If a cached rootPropertyValue wasn't passed in (which Velocity always attempts to do in order to avoid requerying the DOM),\r\n\t\t\t\t\t query the DOM for the root property's value. */\r\n\t\t\t\t\tif (rootPropertyValue === undefined) {\r\n\t\t\t\t\t\t/* Since the browser is now being directly queried, use the official post-prefixing property name for this lookup. */\r\n\t\t\t\t\t\trootPropertyValue = CSS.getPropertyValue(element, CSS.Names.prefixCheck(hookRoot)[0]); /* GET */\r\n\t\t\t\t\t}\r\n\r\n\t\t\t\t\t/* If this root has a normalization registered, peform the associated normalization extraction. */\r\n\t\t\t\t\tif (CSS.Normalizations.registered[hookRoot]) {\r\n\t\t\t\t\t\trootPropertyValue = CSS.Normalizations.registered[hookRoot](\"extract\", element, rootPropertyValue);\r\n\t\t\t\t\t}\r\n\r\n\t\t\t\t\t/* Extract the hook's value. */\r\n\t\t\t\t\tpropertyValue = CSS.Hooks.extractValue(hook, rootPropertyValue);\r\n\r\n\t\t\t\t\t/* If this is a normalized property (e.g. \"opacity\" becomes \"filter\" in <=IE8) or \"translateX\" becomes \"transform\"),\r\n\t\t\t\t\t normalize the property's name and value, and handle the special case of transforms. */\r\n\t\t\t\t\t/* Note: Normalizing a property is mutually exclusive from hooking a property since hook-extracted values are strictly\r\n\t\t\t\t\t numerical and therefore do not require normalization extraction. */\r\n\t\t\t\t} else if (CSS.Normalizations.registered[property]) {\r\n\t\t\t\t\tvar normalizedPropertyName,\r\n\t\t\t\t\t\t\tnormalizedPropertyValue;\r\n\r\n\t\t\t\t\tnormalizedPropertyName = CSS.Normalizations.registered[property](\"name\", element);\r\n\r\n\t\t\t\t\t/* Transform values are calculated via normalization extraction (see below), which checks against the element's transformCache.\r\n\t\t\t\t\t At no point do transform GETs ever actually query the DOM; initial stylesheet values are never processed.\r\n\t\t\t\t\t This is because parsing 3D transform matrices is not always accurate and would bloat our codebase;\r\n\t\t\t\t\t thus, normalization extraction defaults initial transform values to their zero-values (e.g. 1 for scaleX and 0 for translateX). */\r\n\t\t\t\t\tif (normalizedPropertyName !== \"transform\") {\r\n\t\t\t\t\t\tnormalizedPropertyValue = computePropertyValue(element, CSS.Names.prefixCheck(normalizedPropertyName)[0]); /* GET */\r\n\r\n\t\t\t\t\t\t/* If the value is a CSS null-value and this property has a hook template, use that zero-value template so that hooks can be extracted from it. */\r\n\t\t\t\t\t\tif (CSS.Values.isCSSNullValue(normalizedPropertyValue) && CSS.Hooks.templates[property]) {\r\n\t\t\t\t\t\t\tnormalizedPropertyValue = CSS.Hooks.templates[property][1];\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n\r\n\t\t\t\t\tpropertyValue = CSS.Normalizations.registered[property](\"extract\", element, normalizedPropertyValue);\r\n\t\t\t\t}\r\n\r\n\t\t\t\t/* If a (numeric) value wasn't produced via hook extraction or normalization, query the DOM. */\r\n\t\t\t\tif (!/^[\\d-]/.test(propertyValue)) {\r\n\t\t\t\t\t/* For SVG elements, dimensional properties (which SVGAttribute() detects) are tweened via\r\n\t\t\t\t\t their HTML attribute values instead of their CSS style values. */\r\n\t\t\t\t\tvar data = Data(element);\r\n\r\n\t\t\t\t\tif (data && data.isSVG && CSS.Names.SVGAttribute(property)) {\r\n\t\t\t\t\t\t/* Since the height/width attribute values must be set manually, they don't reflect computed values.\r\n\t\t\t\t\t\t Thus, we use use getBBox() to ensure we always get values for elements with undefined height/width attributes. */\r\n\t\t\t\t\t\tif (/^(height|width)$/i.test(property)) {\r\n\t\t\t\t\t\t\t/* Firefox throws an error if .getBBox() is called on an SVG that isn't attached to the DOM. */\r\n\t\t\t\t\t\t\ttry {\r\n\t\t\t\t\t\t\t\tpropertyValue = element.getBBox()[property];\r\n\t\t\t\t\t\t\t} catch (error) {\r\n\t\t\t\t\t\t\t\tpropertyValue = 0;\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\t/* Otherwise, access the attribute value directly. */\r\n\t\t\t\t\t\t} else {\r\n\t\t\t\t\t\t\tpropertyValue = element.getAttribute(property);\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t} else {\r\n\t\t\t\t\t\tpropertyValue = computePropertyValue(element, CSS.Names.prefixCheck(property)[0]); /* GET */\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\r\n\t\t\t\t/* Since property lookups are for animation purposes (which entails computing the numeric delta between start and end values),\r\n\t\t\t\t convert CSS null-values to an integer of value 0. */\r\n\t\t\t\tif (CSS.Values.isCSSNullValue(propertyValue)) {\r\n\t\t\t\t\tpropertyValue = 0;\r\n\t\t\t\t}\r\n\r\n\t\t\t\tif (Velocity.debug >= 2) {\r\n\t\t\t\t\tconsole.log(\"Get \" + property + \": \" + propertyValue);\r\n\t\t\t\t}\r\n\r\n\t\t\t\treturn propertyValue;\r\n\t\t\t},\r\n\t\t\t/* The singular setPropertyValue, which routes the logic for all normalizations, hooks, and standard CSS properties. */\r\n\t\t\tsetPropertyValue: function(element, property, propertyValue, rootPropertyValue, scrollData) {\r\n\t\t\t\tvar propertyName = property;\r\n\r\n\t\t\t\t/* In order to be subjected to call options and element queueing, scroll animation is routed through Velocity as if it were a standard CSS property. */\r\n\t\t\t\tif (property === \"scroll\") {\r\n\t\t\t\t\t/* If a container option is present, scroll the container instead of the browser window. */\r\n\t\t\t\t\tif (scrollData.container) {\r\n\t\t\t\t\t\tscrollData.container[\"scroll\" + scrollData.direction] = propertyValue;\r\n\t\t\t\t\t\t/* Otherwise, Velocity defaults to scrolling the browser window. */\r\n\t\t\t\t\t} else {\r\n\t\t\t\t\t\tif (scrollData.direction === \"Left\") {\r\n\t\t\t\t\t\t\twindow.scrollTo(propertyValue, scrollData.alternateValue);\r\n\t\t\t\t\t\t} else {\r\n\t\t\t\t\t\t\twindow.scrollTo(scrollData.alternateValue, propertyValue);\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n\t\t\t\t} else {\r\n\t\t\t\t\t/* Transforms (translateX, rotateZ, etc.) are applied to a per-element transformCache object, which is manually flushed via flushTransformCache().\r\n\t\t\t\t\t Thus, for now, we merely cache transforms being SET. */\r\n\t\t\t\t\tif (CSS.Normalizations.registered[property] && CSS.Normalizations.registered[property](\"name\", element) === \"transform\") {\r\n\t\t\t\t\t\t/* Perform a normalization injection. */\r\n\t\t\t\t\t\t/* Note: The normalization logic handles the transformCache updating. */\r\n\t\t\t\t\t\tCSS.Normalizations.registered[property](\"inject\", element, propertyValue);\r\n\r\n\t\t\t\t\t\tpropertyName = \"transform\";\r\n\t\t\t\t\t\tpropertyValue = Data(element).transformCache[property];\r\n\t\t\t\t\t} else {\r\n\t\t\t\t\t\t/* Inject hooks. */\r\n\t\t\t\t\t\tif (CSS.Hooks.registered[property]) {\r\n\t\t\t\t\t\t\tvar hookName = property,\r\n\t\t\t\t\t\t\t\t\thookRoot = CSS.Hooks.getRoot(property);\r\n\r\n\t\t\t\t\t\t\t/* If a cached rootPropertyValue was not provided, query the DOM for the hookRoot's current value. */\r\n\t\t\t\t\t\t\trootPropertyValue = rootPropertyValue || CSS.getPropertyValue(element, hookRoot); /* GET */\r\n\r\n\t\t\t\t\t\t\tpropertyValue = CSS.Hooks.injectValue(hookName, propertyValue, rootPropertyValue);\r\n\t\t\t\t\t\t\tproperty = hookRoot;\r\n\t\t\t\t\t\t}\r\n\r\n\t\t\t\t\t\t/* Normalize names and values. */\r\n\t\t\t\t\t\tif (CSS.Normalizations.registered[property]) {\r\n\t\t\t\t\t\t\tpropertyValue = CSS.Normalizations.registered[property](\"inject\", element, propertyValue);\r\n\t\t\t\t\t\t\tproperty = CSS.Normalizations.registered[property](\"name\", element);\r\n\t\t\t\t\t\t}\r\n\r\n\t\t\t\t\t\t/* Assign the appropriate vendor prefix before performing an official style update. */\r\n\t\t\t\t\t\tpropertyName = CSS.Names.prefixCheck(property)[0];\r\n\r\n\t\t\t\t\t\t/* A try/catch is used for IE<=8, which throws an error when \"invalid\" CSS values are set, e.g. a negative width.\r\n\t\t\t\t\t\t Try/catch is avoided for other browsers since it incurs a performance overhead. */\r\n\t\t\t\t\t\tif (IE <= 8) {\r\n\t\t\t\t\t\t\ttry {\r\n\t\t\t\t\t\t\t\telement.style[propertyName] = propertyValue;\r\n\t\t\t\t\t\t\t} catch (error) {\r\n\t\t\t\t\t\t\t\tif (Velocity.debug) {\r\n\t\t\t\t\t\t\t\t\tconsole.log(\"Browser does not support [\" + propertyValue + \"] for [\" + propertyName + \"]\");\r\n\t\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\t/* SVG elements have their dimensional properties (width, height, x, y, cx, etc.) applied directly as attributes instead of as styles. */\r\n\t\t\t\t\t\t\t/* Note: IE8 does not support SVG elements, so it's okay that we skip it for SVG animation. */\r\n\t\t\t\t\t\t} else {\r\n\t\t\t\t\t\t\tvar data = Data(element);\r\n\r\n\t\t\t\t\t\t\tif (data && data.isSVG && CSS.Names.SVGAttribute(property)) {\r\n\t\t\t\t\t\t\t\t/* Note: For SVG attributes, vendor-prefixed property names are never used. */\r\n\t\t\t\t\t\t\t\t/* Note: Not all CSS properties can be animated via attributes, but the browser won't throw an error for unsupported properties. */\r\n\t\t\t\t\t\t\t\telement.setAttribute(property, propertyValue);\r\n\t\t\t\t\t\t\t} else {\r\n\t\t\t\t\t\t\t\telement.style[propertyName] = propertyValue;\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t}\r\n\r\n\t\t\t\t\t\tif (Velocity.debug >= 2) {\r\n\t\t\t\t\t\t\tconsole.log(\"Set \" + property + \" (\" + propertyName + \"): \" + propertyValue);\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\r\n\t\t\t\t/* Return the normalized property name and value in case the caller wants to know how these values were modified before being applied to the DOM. */\r\n\t\t\t\treturn [propertyName, propertyValue];\r\n\t\t\t},\r\n\t\t\t/* To increase performance by batching transform updates into a single SET, transforms are not directly applied to an element until flushTransformCache() is called. */\r\n\t\t\t/* Note: Velocity applies transform properties in the same order that they are chronogically introduced to the element's CSS styles. */\r\n\t\t\tflushTransformCache: function(element) {\r\n\t\t\t\tvar transformString = \"\",\r\n\t\t\t\t\t\tdata = Data(element);\r\n\r\n\t\t\t\t/* Certain browsers require that SVG transforms be applied as an attribute. However, the SVG transform attribute takes a modified version of CSS's transform string\r\n\t\t\t\t (units are dropped and, except for skewX/Y, subproperties are merged into their master property -- e.g. scaleX and scaleY are merged into scale(X Y). */\r\n\t\t\t\tif ((IE || (Velocity.State.isAndroid && !Velocity.State.isChrome)) && data && data.isSVG) {\r\n\t\t\t\t\t/* Since transform values are stored in their parentheses-wrapped form, we use a helper function to strip out their numeric values.\r\n\t\t\t\t\t Further, SVG transform properties only take unitless (representing pixels) values, so it's okay that parseFloat() strips the unit suffixed to the float value. */\r\n\t\t\t\t\tvar getTransformFloat = function(transformProperty) {\r\n\t\t\t\t\t\treturn parseFloat(CSS.getPropertyValue(element, transformProperty));\r\n\t\t\t\t\t};\r\n\r\n\t\t\t\t\t/* Create an object to organize all the transforms that we'll apply to the SVG element. To keep the logic simple,\r\n\t\t\t\t\t we process *all* transform properties -- even those that may not be explicitly applied (since they default to their zero-values anyway). */\r\n\t\t\t\t\tvar SVGTransforms = {\r\n\t\t\t\t\t\ttranslate: [getTransformFloat(\"translateX\"), getTransformFloat(\"translateY\")],\r\n\t\t\t\t\t\tskewX: [getTransformFloat(\"skewX\")], skewY: [getTransformFloat(\"skewY\")],\r\n\t\t\t\t\t\t/* If the scale property is set (non-1), use that value for the scaleX and scaleY values\r\n\t\t\t\t\t\t (this behavior mimics the result of animating all these properties at once on HTML elements). */\r\n\t\t\t\t\t\tscale: getTransformFloat(\"scale\") !== 1 ? [getTransformFloat(\"scale\"), getTransformFloat(\"scale\")] : [getTransformFloat(\"scaleX\"), getTransformFloat(\"scaleY\")],\r\n\t\t\t\t\t\t/* Note: SVG's rotate transform takes three values: rotation degrees followed by the X and Y values\r\n\t\t\t\t\t\t defining the rotation's origin point. We ignore the origin values (default them to 0). */\r\n\t\t\t\t\t\trotate: [getTransformFloat(\"rotateZ\"), 0, 0]\r\n\t\t\t\t\t};\r\n\r\n\t\t\t\t\t/* Iterate through the transform properties in the user-defined property map order.\r\n\t\t\t\t\t (This mimics the behavior of non-SVG transform animation.) */\r\n\t\t\t\t\t$.each(Data(element).transformCache, function(transformName) {\r\n\t\t\t\t\t\t/* Except for with skewX/Y, revert the axis-specific transform subproperties to their axis-free master\r\n\t\t\t\t\t\t properties so that they match up with SVG's accepted transform properties. */\r\n\t\t\t\t\t\tif (/^translate/i.test(transformName)) {\r\n\t\t\t\t\t\t\ttransformName = \"translate\";\r\n\t\t\t\t\t\t} else if (/^scale/i.test(transformName)) {\r\n\t\t\t\t\t\t\ttransformName = \"scale\";\r\n\t\t\t\t\t\t} else if (/^rotate/i.test(transformName)) {\r\n\t\t\t\t\t\t\ttransformName = \"rotate\";\r\n\t\t\t\t\t\t}\r\n\r\n\t\t\t\t\t\t/* Check that we haven't yet deleted the property from the SVGTransforms container. */\r\n\t\t\t\t\t\tif (SVGTransforms[transformName]) {\r\n\t\t\t\t\t\t\t/* Append the transform property in the SVG-supported transform format. As per the spec, surround the space-delimited values in parentheses. */\r\n\t\t\t\t\t\t\ttransformString += transformName + \"(\" + SVGTransforms[transformName].join(\" \") + \")\" + \" \";\r\n\r\n\t\t\t\t\t\t\t/* After processing an SVG transform property, delete it from the SVGTransforms container so we don't\r\n\t\t\t\t\t\t\t re-insert the same master property if we encounter another one of its axis-specific properties. */\r\n\t\t\t\t\t\t\tdelete SVGTransforms[transformName];\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t});\r\n\t\t\t\t} else {\r\n\t\t\t\t\tvar transformValue,\r\n\t\t\t\t\t\t\tperspective;\r\n\r\n\t\t\t\t\t/* Transform properties are stored as members of the transformCache object. Concatenate all the members into a string. */\r\n\t\t\t\t\t$.each(Data(element).transformCache, function(transformName) {\r\n\t\t\t\t\t\ttransformValue = Data(element).transformCache[transformName];\r\n\r\n\t\t\t\t\t\t/* Transform's perspective subproperty must be set first in order to take effect. Store it temporarily. */\r\n\t\t\t\t\t\tif (transformName === \"transformPerspective\") {\r\n\t\t\t\t\t\t\tperspective = transformValue;\r\n\t\t\t\t\t\t\treturn true;\r\n\t\t\t\t\t\t}\r\n\r\n\t\t\t\t\t\t/* IE9 only supports one rotation type, rotateZ, which it refers to as \"rotate\". */\r\n\t\t\t\t\t\tif (IE === 9 && transformName === \"rotateZ\") {\r\n\t\t\t\t\t\t\ttransformName = \"rotate\";\r\n\t\t\t\t\t\t}\r\n\r\n\t\t\t\t\t\ttransformString += transformName + transformValue + \" \";\r\n\t\t\t\t\t});\r\n\r\n\t\t\t\t\t/* If present, set the perspective subproperty first. */\r\n\t\t\t\t\tif (perspective) {\r\n\t\t\t\t\t\ttransformString = \"perspective\" + perspective + \" \" + transformString;\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\r\n\t\t\t\tCSS.setPropertyValue(element, \"transform\", transformString);\r\n\t\t\t}\r\n\t\t};\r\n\r\n\t\t/* Register hooks and normalizations. */\r\n\t\tCSS.Hooks.register();\r\n\t\tCSS.Normalizations.register();\r\n\r\n\t\t/* Allow hook setting in the same fashion as jQuery's $.css(). */\r\n\t\tVelocity.hook = function(elements, arg2, arg3) {\r\n\t\t\tvar value;\r\n\r\n\t\t\telements = sanitizeElements(elements);\r\n\r\n\t\t\t$.each(elements, function(i, element) {\r\n\t\t\t\t/* Initialize Velocity's per-element data cache if this element hasn't previously been animated. */\r\n\t\t\t\tif (Data(element) === undefined) {\r\n\t\t\t\t\tVelocity.init(element);\r\n\t\t\t\t}\r\n\r\n\t\t\t\t/* Get property value. If an element set was passed in, only return the value for the first element. */\r\n\t\t\t\tif (arg3 === undefined) {\r\n\t\t\t\t\tif (value === undefined) {\r\n\t\t\t\t\t\tvalue = CSS.getPropertyValue(element, arg2);\r\n\t\t\t\t\t}\r\n\t\t\t\t\t/* Set property value. */\r\n\t\t\t\t} else {\r\n\t\t\t\t\t/* sPV returns an array of the normalized propertyName/propertyValue pair used to update the DOM. */\r\n\t\t\t\t\tvar adjustedSet = CSS.setPropertyValue(element, arg2, arg3);\r\n\r\n\t\t\t\t\t/* Transform properties don't automatically set. They have to be flushed to the DOM. */\r\n\t\t\t\t\tif (adjustedSet[0] === \"transform\") {\r\n\t\t\t\t\t\tVelocity.CSS.flushTransformCache(element);\r\n\t\t\t\t\t}\r\n\r\n\t\t\t\t\tvalue = adjustedSet;\r\n\t\t\t\t}\r\n\t\t\t});\r\n\r\n\t\t\treturn value;\r\n\t\t};\r\n\r\n\t\t/*****************\r\n\t\t Animation\r\n\t\t *****************/\r\n\r\n\t\tvar animate = function() {\r\n\t\t\tvar opts;\r\n\r\n\t\t\t/******************\r\n\t\t\t Call Chain\r\n\t\t\t ******************/\r\n\r\n\t\t\t/* Logic for determining what to return to the call stack when exiting out of Velocity. */\r\n\t\t\tfunction getChain() {\r\n\t\t\t\t/* If we are using the utility function, attempt to return this call's promise. If no promise library was detected,\r\n\t\t\t\t default to null instead of returning the targeted elements so that utility function's return value is standardized. */\r\n\t\t\t\tif (isUtility) {\r\n\t\t\t\t\treturn promiseData.promise || null;\r\n\t\t\t\t\t/* Otherwise, if we're using $.fn, return the jQuery-/Zepto-wrapped element set. */\r\n\t\t\t\t} else {\r\n\t\t\t\t\treturn elementsWrapped;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\r\n\t\t\t/*************************\r\n\t\t\t Arguments Assignment\r\n\t\t\t *************************/\r\n\r\n\t\t\t/* To allow for expressive CoffeeScript code, Velocity supports an alternative syntax in which \"elements\" (or \"e\"), \"properties\" (or \"p\"), and \"options\" (or \"o\")\r\n\t\t\t objects are defined on a container object that's passed in as Velocity's sole argument. */\r\n\t\t\t/* Note: Some browsers automatically populate arguments with a \"properties\" object. We detect it by checking for its default \"names\" property. */\r\n\t\t\tvar syntacticSugar = (arguments[0] && (arguments[0].p || (($.isPlainObject(arguments[0].properties) && !arguments[0].properties.names) || Type.isString(arguments[0].properties)))),\r\n\t\t\t\t\t/* Whether Velocity was called via the utility function (as opposed to on a jQuery/Zepto object). */\r\n\t\t\t\t\tisUtility,\r\n\t\t\t\t\t/* When Velocity is called via the utility function ($.Velocity()/Velocity()), elements are explicitly\r\n\t\t\t\t\t passed in as the first parameter. Thus, argument positioning varies. We normalize them here. */\r\n\t\t\t\t\telementsWrapped,\r\n\t\t\t\t\targumentIndex;\r\n\r\n\t\t\tvar elements,\r\n\t\t\t\t\tpropertiesMap,\r\n\t\t\t\t\toptions;\r\n\r\n\t\t\t/* Detect jQuery/Zepto elements being animated via the $.fn method. */\r\n\t\t\tif (Type.isWrapped(this)) {\r\n\t\t\t\tisUtility = false;\r\n\r\n\t\t\t\targumentIndex = 0;\r\n\t\t\t\telements = this;\r\n\t\t\t\telementsWrapped = this;\r\n\t\t\t\t/* Otherwise, raw elements are being animated via the utility function. */\r\n\t\t\t} else {\r\n\t\t\t\tisUtility = true;\r\n\r\n\t\t\t\targumentIndex = 1;\r\n\t\t\t\telements = syntacticSugar ? (arguments[0].elements || arguments[0].e) : arguments[0];\r\n\t\t\t}\r\n\r\n\t\t\t/***************\r\n\t\t\t Promises\r\n\t\t\t ***************/\r\n\r\n\t\t\tvar promiseData = {\r\n\t\t\t\tpromise: null,\r\n\t\t\t\tresolver: null,\r\n\t\t\t\trejecter: null\r\n\t\t\t};\r\n\r\n\t\t\t/* If this call was made via the utility function (which is the default method of invocation when jQuery/Zepto are not being used), and if\r\n\t\t\t promise support was detected, create a promise object for this call and store references to its resolver and rejecter methods. The resolve\r\n\t\t\t method is used when a call completes naturally or is prematurely stopped by the user. In both cases, completeCall() handles the associated\r\n\t\t\t call cleanup and promise resolving logic. The reject method is used when an invalid set of arguments is passed into a Velocity call. */\r\n\t\t\t/* Note: Velocity employs a call-based queueing architecture, which means that stopping an animating element actually stops the full call that\r\n\t\t\t triggered it -- not that one element exclusively. Similarly, there is one promise per call, and all elements targeted by a Velocity call are\r\n\t\t\t grouped together for the purposes of resolving and rejecting a promise. */\r\n\t\t\tif (isUtility && Velocity.Promise) {\r\n\t\t\t\tpromiseData.promise = new Velocity.Promise(function(resolve, reject) {\r\n\t\t\t\t\tpromiseData.resolver = resolve;\r\n\t\t\t\t\tpromiseData.rejecter = reject;\r\n\t\t\t\t});\r\n\t\t\t}\r\n\r\n\t\t\tif (syntacticSugar) {\r\n\t\t\t\tpropertiesMap = arguments[0].properties || arguments[0].p;\r\n\t\t\t\toptions = arguments[0].options || arguments[0].o;\r\n\t\t\t} else {\r\n\t\t\t\tpropertiesMap = arguments[argumentIndex];\r\n\t\t\t\toptions = arguments[argumentIndex + 1];\r\n\t\t\t}\r\n\r\n\t\t\telements = sanitizeElements(elements);\r\n\r\n\t\t\tif (!elements) {\r\n\t\t\t\tif (promiseData.promise) {\r\n\t\t\t\t\tif (!propertiesMap || !options || options.promiseRejectEmpty !== false) {\r\n\t\t\t\t\t\tpromiseData.rejecter();\r\n\t\t\t\t\t} else {\r\n\t\t\t\t\t\tpromiseData.resolver();\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t\treturn;\r\n\t\t\t}\r\n\r\n\t\t\t/* The length of the element set (in the form of a nodeList or an array of elements) is defaulted to 1 in case a\r\n\t\t\t single raw DOM element is passed in (which doesn't contain a length property). */\r\n\t\t\tvar elementsLength = elements.length,\r\n\t\t\t\t\telementsIndex = 0;\r\n\r\n\t\t\t/***************************\r\n\t\t\t Argument Overloading\r\n\t\t\t ***************************/\r\n\r\n\t\t\t/* Support is included for jQuery's argument overloading: $.animate(propertyMap [, duration] [, easing] [, complete]).\r\n\t\t\t Overloading is detected by checking for the absence of an object being passed into options. */\r\n\t\t\t/* Note: The stop/finish/pause/resume actions do not accept animation options, and are therefore excluded from this check. */\r\n\t\t\tif (!/^(stop|finish|finishAll|pause|resume)$/i.test(propertiesMap) && !$.isPlainObject(options)) {\r\n\t\t\t\t/* The utility function shifts all arguments one position to the right, so we adjust for that offset. */\r\n\t\t\t\tvar startingArgumentPosition = argumentIndex + 1;\r\n\r\n\t\t\t\toptions = {};\r\n\r\n\t\t\t\t/* Iterate through all options arguments */\r\n\t\t\t\tfor (var i = startingArgumentPosition; i < arguments.length; i++) {\r\n\t\t\t\t\t/* Treat a number as a duration. Parse it out. */\r\n\t\t\t\t\t/* Note: The following RegEx will return true if passed an array with a number as its first item.\r\n\t\t\t\t\t Thus, arrays are skipped from this check. */\r\n\t\t\t\t\tif (!Type.isArray(arguments[i]) && (/^(fast|normal|slow)$/i.test(arguments[i]) || /^\\d/.test(arguments[i]))) {\r\n\t\t\t\t\t\toptions.duration = arguments[i];\r\n\t\t\t\t\t\t/* Treat strings and arrays as easings. */\r\n\t\t\t\t\t} else if (Type.isString(arguments[i]) || Type.isArray(arguments[i])) {\r\n\t\t\t\t\t\toptions.easing = arguments[i];\r\n\t\t\t\t\t\t/* Treat a function as a complete callback. */\r\n\t\t\t\t\t} else if (Type.isFunction(arguments[i])) {\r\n\t\t\t\t\t\toptions.complete = arguments[i];\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t}\r\n\r\n\t\t\t/*********************\r\n\t\t\t Action Detection\r\n\t\t\t *********************/\r\n\r\n\t\t\t/* Velocity's behavior is categorized into \"actions\": Elements can either be specially scrolled into view,\r\n\t\t\t or they can be started, stopped, paused, resumed, or reversed . If a literal or referenced properties map is passed in as Velocity's\r\n\t\t\t first argument, the associated action is \"start\". Alternatively, \"scroll\", \"reverse\", \"pause\", \"resume\" or \"stop\" can be passed in \r\n\t\t\t instead of a properties map. */\r\n\t\t\tvar action;\r\n\r\n\t\t\tswitch (propertiesMap) {\r\n\t\t\t\tcase \"scroll\":\r\n\t\t\t\t\taction = \"scroll\";\r\n\t\t\t\t\tbreak;\r\n\r\n\t\t\t\tcase \"reverse\":\r\n\t\t\t\t\taction = \"reverse\";\r\n\t\t\t\t\tbreak;\r\n\r\n\t\t\t\tcase \"pause\":\r\n\r\n\t\t\t\t\t/*******************\r\n\t\t\t\t\t Action: Pause\r\n\t\t\t\t\t *******************/\r\n\r\n\t\t\t\t\tvar currentTime = (new Date()).getTime();\r\n\r\n\t\t\t\t\t/* Handle delay timers */\r\n\t\t\t\t\t$.each(elements, function(i, element) {\r\n\t\t\t\t\t\tpauseDelayOnElement(element, currentTime);\r\n\t\t\t\t\t});\r\n\r\n\t\t\t\t\t/* Pause and Resume are call-wide (not on a per element basis). Thus, calling pause or resume on a \r\n\t\t\t\t\t single element will cause any calls that containt tweens for that element to be paused/resumed\r\n\t\t\t\t\t as well. */\r\n\r\n\t\t\t\t\t/* Iterate through all calls and pause any that contain any of our elements */\r\n\t\t\t\t\t$.each(Velocity.State.calls, function(i, activeCall) {\r\n\r\n\t\t\t\t\t\tvar found = false;\r\n\t\t\t\t\t\t/* Inactive calls are set to false by the logic inside completeCall(). Skip them. */\r\n\t\t\t\t\t\tif (activeCall) {\r\n\t\t\t\t\t\t\t/* Iterate through the active call's targeted elements. */\r\n\t\t\t\t\t\t\t$.each(activeCall[1], function(k, activeElement) {\r\n\t\t\t\t\t\t\t\tvar queueName = (options === undefined) ? \"\" : options;\r\n\r\n\t\t\t\t\t\t\t\tif (queueName !== true && (activeCall[2].queue !== queueName) && !(options === undefined && activeCall[2].queue === false)) {\r\n\t\t\t\t\t\t\t\t\treturn true;\r\n\t\t\t\t\t\t\t\t}\r\n\r\n\t\t\t\t\t\t\t\t/* Iterate through the calls targeted by the stop command. */\r\n\t\t\t\t\t\t\t\t$.each(elements, function(l, element) {\r\n\t\t\t\t\t\t\t\t\t/* Check that this call was applied to the target element. */\r\n\t\t\t\t\t\t\t\t\tif (element === activeElement) {\r\n\r\n\t\t\t\t\t\t\t\t\t\t/* Set call to paused */\r\n\t\t\t\t\t\t\t\t\t\tactiveCall[5] = {\r\n\t\t\t\t\t\t\t\t\t\t\tresume: false\r\n\t\t\t\t\t\t\t\t\t\t};\r\n\r\n\t\t\t\t\t\t\t\t\t\t/* Once we match an element, we can bounce out to the next call entirely */\r\n\t\t\t\t\t\t\t\t\t\tfound = true;\r\n\t\t\t\t\t\t\t\t\t\treturn false;\r\n\t\t\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\t\t});\r\n\r\n\t\t\t\t\t\t\t\t/* Proceed to check next call if we have already matched */\r\n\t\t\t\t\t\t\t\tif (found) {\r\n\t\t\t\t\t\t\t\t\treturn false;\r\n\t\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\t});\r\n\t\t\t\t\t\t}\r\n\r\n\t\t\t\t\t});\r\n\r\n\t\t\t\t\t/* Since pause creates no new tweens, exit out of Velocity. */\r\n\t\t\t\t\treturn getChain();\r\n\r\n\t\t\t\tcase \"resume\":\r\n\r\n\t\t\t\t\t/*******************\r\n\t\t\t\t\t Action: Resume\r\n\t\t\t\t\t *******************/\r\n\r\n\t\t\t\t\t/* Handle delay timers */\r\n\t\t\t\t\t$.each(elements, function(i, element) {\r\n\t\t\t\t\t\tresumeDelayOnElement(element, currentTime);\r\n\t\t\t\t\t});\r\n\r\n\t\t\t\t\t/* Pause and Resume are call-wide (not on a per elemnt basis). Thus, calling pause or resume on a \r\n\t\t\t\t\t single element will cause any calls that containt tweens for that element to be paused/resumed\r\n\t\t\t\t\t as well. */\r\n\r\n\t\t\t\t\t/* Iterate through all calls and pause any that contain any of our elements */\r\n\t\t\t\t\t$.each(Velocity.State.calls, function(i, activeCall) {\r\n\t\t\t\t\t\tvar found = false;\r\n\t\t\t\t\t\t/* Inactive calls are set to false by the logic inside completeCall(). Skip them. */\r\n\t\t\t\t\t\tif (activeCall) {\r\n\t\t\t\t\t\t\t/* Iterate through the active call's targeted elements. */\r\n\t\t\t\t\t\t\t$.each(activeCall[1], function(k, activeElement) {\r\n\t\t\t\t\t\t\t\tvar queueName = (options === undefined) ? \"\" : options;\r\n\r\n\t\t\t\t\t\t\t\tif (queueName !== true && (activeCall[2].queue !== queueName) && !(options === undefined && activeCall[2].queue === false)) {\r\n\t\t\t\t\t\t\t\t\treturn true;\r\n\t\t\t\t\t\t\t\t}\r\n\r\n\t\t\t\t\t\t\t\t/* Skip any calls that have never been paused */\r\n\t\t\t\t\t\t\t\tif (!activeCall[5]) {\r\n\t\t\t\t\t\t\t\t\treturn true;\r\n\t\t\t\t\t\t\t\t}\r\n\r\n\t\t\t\t\t\t\t\t/* Iterate through the calls targeted by the stop command. */\r\n\t\t\t\t\t\t\t\t$.each(elements, function(l, element) {\r\n\t\t\t\t\t\t\t\t\t/* Check that this call was applied to the target element. */\r\n\t\t\t\t\t\t\t\t\tif (element === activeElement) {\r\n\r\n\t\t\t\t\t\t\t\t\t\t/* Flag a pause object to be resumed, which will occur during the next tick. In\r\n\t\t\t\t\t\t\t\t\t\t addition, the pause object will at that time be deleted */\r\n\t\t\t\t\t\t\t\t\t\tactiveCall[5].resume = true;\r\n\r\n\t\t\t\t\t\t\t\t\t\t/* Once we match an element, we can bounce out to the next call entirely */\r\n\t\t\t\t\t\t\t\t\t\tfound = true;\r\n\t\t\t\t\t\t\t\t\t\treturn false;\r\n\t\t\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\t\t});\r\n\r\n\t\t\t\t\t\t\t\t/* Proceed to check next call if we have already matched */\r\n\t\t\t\t\t\t\t\tif (found) {\r\n\t\t\t\t\t\t\t\t\treturn false;\r\n\t\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\t});\r\n\t\t\t\t\t\t}\r\n\r\n\t\t\t\t\t});\r\n\r\n\t\t\t\t\t/* Since resume creates no new tweens, exit out of Velocity. */\r\n\t\t\t\t\treturn getChain();\r\n\r\n\t\t\t\tcase \"finish\":\r\n\t\t\t\tcase \"finishAll\":\r\n\t\t\t\tcase \"stop\":\r\n\t\t\t\t\t/*******************\r\n\t\t\t\t\t Action: Stop\r\n\t\t\t\t\t *******************/\r\n\r\n\t\t\t\t\t/* Clear the currently-active delay on each targeted element. */\r\n\t\t\t\t\t$.each(elements, function(i, element) {\r\n\t\t\t\t\t\tif (Data(element) && Data(element).delayTimer) {\r\n\t\t\t\t\t\t\t/* Stop the timer from triggering its cached next() function. */\r\n\t\t\t\t\t\t\tclearTimeout(Data(element).delayTimer.setTimeout);\r\n\r\n\t\t\t\t\t\t\t/* Manually call the next() function so that the subsequent queue items can progress. */\r\n\t\t\t\t\t\t\tif (Data(element).delayTimer.next) {\r\n\t\t\t\t\t\t\t\tData(element).delayTimer.next();\r\n\t\t\t\t\t\t\t}\r\n\r\n\t\t\t\t\t\t\tdelete Data(element).delayTimer;\r\n\t\t\t\t\t\t}\r\n\r\n\t\t\t\t\t\t/* If we want to finish everything in the queue, we have to iterate through it\r\n\t\t\t\t\t\t and call each function. This will make them active calls below, which will\r\n\t\t\t\t\t\t cause them to be applied via the duration setting. */\r\n\t\t\t\t\t\tif (propertiesMap === \"finishAll\" && (options === true || Type.isString(options))) {\r\n\t\t\t\t\t\t\t/* Iterate through the items in the element's queue. */\r\n\t\t\t\t\t\t\t$.each($.queue(element, Type.isString(options) ? options : \"\"), function(_, item) {\r\n\t\t\t\t\t\t\t\t/* The queue array can contain an \"inprogress\" string, which we skip. */\r\n\t\t\t\t\t\t\t\tif (Type.isFunction(item)) {\r\n\t\t\t\t\t\t\t\t\titem();\r\n\t\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\t});\r\n\r\n\t\t\t\t\t\t\t/* Clearing the $.queue() array is achieved by resetting it to []. */\r\n\t\t\t\t\t\t\t$.queue(element, Type.isString(options) ? options : \"\", []);\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t});\r\n\r\n\t\t\t\t\tvar callsToStop = [];\r\n\r\n\t\t\t\t\t/* When the stop action is triggered, the elements' currently active call is immediately stopped. The active call might have\r\n\t\t\t\t\t been applied to multiple elements, in which case all of the call's elements will be stopped. When an element\r\n\t\t\t\t\t is stopped, the next item in its animation queue is immediately triggered. */\r\n\t\t\t\t\t/* An additional argument may be passed in to clear an element's remaining queued calls. Either true (which defaults to the \"fx\" queue)\r\n\t\t\t\t\t or a custom queue string can be passed in. */\r\n\t\t\t\t\t/* Note: The stop command runs prior to Velocity's Queueing phase since its behavior is intended to take effect *immediately*,\r\n\t\t\t\t\t regardless of the element's current queue state. */\r\n\r\n\t\t\t\t\t/* Iterate through every active call. */\r\n\t\t\t\t\t$.each(Velocity.State.calls, function(i, activeCall) {\r\n\t\t\t\t\t\t/* Inactive calls are set to false by the logic inside completeCall(). Skip them. */\r\n\t\t\t\t\t\tif (activeCall) {\r\n\t\t\t\t\t\t\t/* Iterate through the active call's targeted elements. */\r\n\t\t\t\t\t\t\t$.each(activeCall[1], function(k, activeElement) {\r\n\t\t\t\t\t\t\t\t/* If true was passed in as a secondary argument, clear absolutely all calls on this element. Otherwise, only\r\n\t\t\t\t\t\t\t\t clear calls associated with the relevant queue. */\r\n\t\t\t\t\t\t\t\t/* Call stopping logic works as follows:\r\n\t\t\t\t\t\t\t\t - options === true --> stop current default queue calls (and queue:false calls), including remaining queued ones.\r\n\t\t\t\t\t\t\t\t - options === undefined --> stop current queue:\"\" call and all queue:false calls.\r\n\t\t\t\t\t\t\t\t - options === false --> stop only queue:false calls.\r\n\t\t\t\t\t\t\t\t - options === \"custom\" --> stop current queue:\"custom\" call, including remaining queued ones (there is no functionality to only clear the currently-running queue:\"custom\" call). */\r\n\t\t\t\t\t\t\t\tvar queueName = (options === undefined) ? \"\" : options;\r\n\r\n\t\t\t\t\t\t\t\tif (queueName !== true && (activeCall[2].queue !== queueName) && !(options === undefined && activeCall[2].queue === false)) {\r\n\t\t\t\t\t\t\t\t\treturn true;\r\n\t\t\t\t\t\t\t\t}\r\n\r\n\t\t\t\t\t\t\t\t/* Iterate through the calls targeted by the stop command. */\r\n\t\t\t\t\t\t\t\t$.each(elements, function(l, element) {\r\n\t\t\t\t\t\t\t\t\t/* Check that this call was applied to the target element. */\r\n\t\t\t\t\t\t\t\t\tif (element === activeElement) {\r\n\t\t\t\t\t\t\t\t\t\t/* Optionally clear the remaining queued calls. If we're doing \"finishAll\" this won't find anything,\r\n\t\t\t\t\t\t\t\t\t\t due to the queue-clearing above. */\r\n\t\t\t\t\t\t\t\t\t\tif (options === true || Type.isString(options)) {\r\n\t\t\t\t\t\t\t\t\t\t\t/* Iterate through the items in the element's queue. */\r\n\t\t\t\t\t\t\t\t\t\t\t$.each($.queue(element, Type.isString(options) ? options : \"\"), function(_, item) {\r\n\t\t\t\t\t\t\t\t\t\t\t\t/* The queue array can contain an \"inprogress\" string, which we skip. */\r\n\t\t\t\t\t\t\t\t\t\t\t\tif (Type.isFunction(item)) {\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t/* Pass the item's callback a flag indicating that we want to abort from the queue call.\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t (Specifically, the queue will resolve the call's associated promise then abort.) */\r\n\t\t\t\t\t\t\t\t\t\t\t\t\titem(null, true);\r\n\t\t\t\t\t\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\t\t\t\t\t});\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t/* Clearing the $.queue() array is achieved by resetting it to []. */\r\n\t\t\t\t\t\t\t\t\t\t\t$.queue(element, Type.isString(options) ? options : \"\", []);\r\n\t\t\t\t\t\t\t\t\t\t}\r\n\r\n\t\t\t\t\t\t\t\t\t\tif (propertiesMap === \"stop\") {\r\n\t\t\t\t\t\t\t\t\t\t\t/* Since \"reverse\" uses cached start values (the previous call's endValues), these values must be\r\n\t\t\t\t\t\t\t\t\t\t\t changed to reflect the final value that the elements were actually tweened to. */\r\n\t\t\t\t\t\t\t\t\t\t\t/* Note: If only queue:false/queue:\"custom\" animations are currently running on an element, it won't have a tweensContainer\r\n\t\t\t\t\t\t\t\t\t\t\t object. Also, queue:false/queue:\"custom\" animations can't be reversed. */\r\n\t\t\t\t\t\t\t\t\t\t\tvar data = Data(element);\r\n\t\t\t\t\t\t\t\t\t\t\tif (data && data.tweensContainer && (queueName === true || queueName === \"\")) {\r\n\t\t\t\t\t\t\t\t\t\t\t\t$.each(data.tweensContainer, function(m, activeTween) {\r\n\t\t\t\t\t\t\t\t\t\t\t\t\tactiveTween.endValue = activeTween.currentValue;\r\n\t\t\t\t\t\t\t\t\t\t\t\t});\r\n\t\t\t\t\t\t\t\t\t\t\t}\r\n\r\n\t\t\t\t\t\t\t\t\t\t\tcallsToStop.push(i);\r\n\t\t\t\t\t\t\t\t\t\t} else if (propertiesMap === \"finish\" || propertiesMap === \"finishAll\") {\r\n\t\t\t\t\t\t\t\t\t\t\t/* To get active tweens to finish immediately, we forcefully shorten their durations to 1ms so that\r\n\t\t\t\t\t\t\t\t\t\t\t they finish upon the next rAf tick then proceed with normal call completion logic. */\r\n\t\t\t\t\t\t\t\t\t\t\tactiveCall[2].duration = 1;\r\n\t\t\t\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\t\t});\r\n\t\t\t\t\t\t\t});\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t});\r\n\r\n\t\t\t\t\t/* Prematurely call completeCall() on each matched active call. Pass an additional flag for \"stop\" to indicate\r\n\t\t\t\t\t that the complete callback and display:none setting should be skipped since we're completing prematurely. */\r\n\t\t\t\t\tif (propertiesMap === \"stop\") {\r\n\t\t\t\t\t\t$.each(callsToStop, function(i, j) {\r\n\t\t\t\t\t\t\tcompleteCall(j, true);\r\n\t\t\t\t\t\t});\r\n\r\n\t\t\t\t\t\tif (promiseData.promise) {\r\n\t\t\t\t\t\t\t/* Immediately resolve the promise associated with this stop call since stop runs synchronously. */\r\n\t\t\t\t\t\t\tpromiseData.resolver(elements);\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n\r\n\t\t\t\t\t/* Since we're stopping, and not proceeding with queueing, exit out of Velocity. */\r\n\t\t\t\t\treturn getChain();\r\n\r\n\t\t\t\tdefault:\r\n\t\t\t\t\t/* Treat a non-empty plain object as a literal properties map. */\r\n\t\t\t\t\tif ($.isPlainObject(propertiesMap) && !Type.isEmptyObject(propertiesMap)) {\r\n\t\t\t\t\t\taction = \"start\";\r\n\r\n\t\t\t\t\t\t/****************\r\n\t\t\t\t\t\t Redirects\r\n\t\t\t\t\t\t ****************/\r\n\r\n\t\t\t\t\t\t/* Check if a string matches a registered redirect (see Redirects above). */\r\n\t\t\t\t\t} else if (Type.isString(propertiesMap) && Velocity.Redirects[propertiesMap]) {\r\n\t\t\t\t\t\topts = $.extend({}, options);\r\n\r\n\t\t\t\t\t\tvar durationOriginal = opts.duration,\r\n\t\t\t\t\t\t\t\tdelayOriginal = opts.delay || 0;\r\n\r\n\t\t\t\t\t\t/* If the backwards option was passed in, reverse the element set so that elements animate from the last to the first. */\r\n\t\t\t\t\t\tif (opts.backwards === true) {\r\n\t\t\t\t\t\t\telements = $.extend(true, [], elements).reverse();\r\n\t\t\t\t\t\t}\r\n\r\n\t\t\t\t\t\t/* Individually trigger the redirect for each element in the set to prevent users from having to handle iteration logic in their redirect. */\r\n\t\t\t\t\t\t$.each(elements, function(elementIndex, element) {\r\n\t\t\t\t\t\t\t/* If the stagger option was passed in, successively delay each element by the stagger value (in ms). Retain the original delay value. */\r\n\t\t\t\t\t\t\tif (parseFloat(opts.stagger)) {\r\n\t\t\t\t\t\t\t\topts.delay = delayOriginal + (parseFloat(opts.stagger) * elementIndex);\r\n\t\t\t\t\t\t\t} else if (Type.isFunction(opts.stagger)) {\r\n\t\t\t\t\t\t\t\topts.delay = delayOriginal + opts.stagger.call(element, elementIndex, elementsLength);\r\n\t\t\t\t\t\t\t}\r\n\r\n\t\t\t\t\t\t\t/* If the drag option was passed in, successively increase/decrease (depending on the presense of opts.backwards)\r\n\t\t\t\t\t\t\t the duration of each element's animation, using floors to prevent producing very short durations. */\r\n\t\t\t\t\t\t\tif (opts.drag) {\r\n\t\t\t\t\t\t\t\t/* Default the duration of UI pack effects (callouts and transitions) to 1000ms instead of the usual default duration of 400ms. */\r\n\t\t\t\t\t\t\t\topts.duration = parseFloat(durationOriginal) || (/^(callout|transition)/.test(propertiesMap) ? 1000 : DURATION_DEFAULT);\r\n\r\n\t\t\t\t\t\t\t\t/* For each element, take the greater duration of: A) animation completion percentage relative to the original duration,\r\n\t\t\t\t\t\t\t\t B) 75% of the original duration, or C) a 200ms fallback (in case duration is already set to a low value).\r\n\t\t\t\t\t\t\t\t The end result is a baseline of 75% of the redirect's duration that increases/decreases as the end of the element set is approached. */\r\n\t\t\t\t\t\t\t\topts.duration = Math.max(opts.duration * (opts.backwards ? 1 - elementIndex / elementsLength : (elementIndex + 1) / elementsLength), opts.duration * 0.75, 200);\r\n\t\t\t\t\t\t\t}\r\n\r\n\t\t\t\t\t\t\t/* Pass in the call's opts object so that the redirect can optionally extend it. It defaults to an empty object instead of null to\r\n\t\t\t\t\t\t\t reduce the opts checking logic required inside the redirect. */\r\n\t\t\t\t\t\t\tVelocity.Redirects[propertiesMap].call(element, element, opts || {}, elementIndex, elementsLength, elements, promiseData.promise ? promiseData : undefined);\r\n\t\t\t\t\t\t});\r\n\r\n\t\t\t\t\t\t/* Since the animation logic resides within the redirect's own code, abort the remainder of this call.\r\n\t\t\t\t\t\t (The performance overhead up to this point is virtually non-existant.) */\r\n\t\t\t\t\t\t/* Note: The jQuery call chain is kept intact by returning the complete element set. */\r\n\t\t\t\t\t\treturn getChain();\r\n\t\t\t\t\t} else {\r\n\t\t\t\t\t\tvar abortError = \"Velocity: First argument (\" + propertiesMap + \") was not a property map, a known action, or a registered redirect. Aborting.\";\r\n\r\n\t\t\t\t\t\tif (promiseData.promise) {\r\n\t\t\t\t\t\t\tpromiseData.rejecter(new Error(abortError));\r\n\t\t\t\t\t\t} else if (window.console) {\r\n\t\t\t\t\t\t\tconsole.log(abortError);\r\n\t\t\t\t\t\t}\r\n\r\n\t\t\t\t\t\treturn getChain();\r\n\t\t\t\t\t}\r\n\t\t\t}\r\n\r\n\t\t\t/**************************\r\n\t\t\t Call-Wide Variables\r\n\t\t\t **************************/\r\n\r\n\t\t\t/* A container for CSS unit conversion ratios (e.g. %, rem, and em ==> px) that is used to cache ratios across all elements\r\n\t\t\t being animated in a single Velocity call. Calculating unit ratios necessitates DOM querying and updating, and is therefore\r\n\t\t\t avoided (via caching) wherever possible. This container is call-wide instead of page-wide to avoid the risk of using stale\r\n\t\t\t conversion metrics across Velocity animations that are not immediately consecutively chained. */\r\n\t\t\tvar callUnitConversionData = {\r\n\t\t\t\tlastParent: null,\r\n\t\t\t\tlastPosition: null,\r\n\t\t\t\tlastFontSize: null,\r\n\t\t\t\tlastPercentToPxWidth: null,\r\n\t\t\t\tlastPercentToPxHeight: null,\r\n\t\t\t\tlastEmToPx: null,\r\n\t\t\t\tremToPx: null,\r\n\t\t\t\tvwToPx: null,\r\n\t\t\t\tvhToPx: null\r\n\t\t\t};\r\n\r\n\t\t\t/* A container for all the ensuing tween data and metadata associated with this call. This container gets pushed to the page-wide\r\n\t\t\t Velocity.State.calls array that is processed during animation ticking. */\r\n\t\t\tvar call = [];\r\n\r\n\t\t\t/************************\r\n\t\t\t Element Processing\r\n\t\t\t ************************/\r\n\r\n\t\t\t/* Element processing consists of three parts -- data processing that cannot go stale and data processing that *can* go stale (i.e. third-party style modifications):\r\n\t\t\t 1) Pre-Queueing: Element-wide variables, including the element's data storage, are instantiated. Call options are prepared. If triggered, the Stop action is executed.\r\n\t\t\t 2) Queueing: The logic that runs once this call has reached its point of execution in the element's $.queue() stack. Most logic is placed here to avoid risking it becoming stale.\r\n\t\t\t 3) Pushing: Consolidation of the tween data followed by its push onto the global in-progress calls container.\r\n\t\t\t `elementArrayIndex` allows passing index of the element in the original array to value functions.\r\n\t\t\t If `elementsIndex` were used instead the index would be determined by the elements' per-element queue.\r\n\t\t\t */\r\n\t\t\tfunction processElement(element, elementArrayIndex) {\r\n\r\n\t\t\t\t/*************************\r\n\t\t\t\t Part I: Pre-Queueing\r\n\t\t\t\t *************************/\r\n\r\n\t\t\t\t/***************************\r\n\t\t\t\t Element-Wide Variables\r\n\t\t\t\t ***************************/\r\n\r\n\t\t\t\tvar /* The runtime opts object is the extension of the current call's options and Velocity's page-wide option defaults. */\r\n\t\t\t\t\t\topts = $.extend({}, Velocity.defaults, options),\r\n\t\t\t\t\t\t/* A container for the processed data associated with each property in the propertyMap.\r\n\t\t\t\t\t\t (Each property in the map produces its own \"tween\".) */\r\n\t\t\t\t\t\ttweensContainer = {},\r\n\t\t\t\t\t\telementUnitConversionData;\r\n\r\n\t\t\t\t/******************\r\n\t\t\t\t Element Init\r\n\t\t\t\t ******************/\r\n\r\n\t\t\t\tif (Data(element) === undefined) {\r\n\t\t\t\t\tVelocity.init(element);\r\n\t\t\t\t}\r\n\r\n\t\t\t\t/******************\r\n\t\t\t\t Option: Delay\r\n\t\t\t\t ******************/\r\n\r\n\t\t\t\t/* Since queue:false doesn't respect the item's existing queue, we avoid injecting its delay here (it's set later on). */\r\n\t\t\t\t/* Note: Velocity rolls its own delay function since jQuery doesn't have a utility alias for $.fn.delay()\r\n\t\t\t\t (and thus requires jQuery element creation, which we avoid since its overhead includes DOM querying). */\r\n\t\t\t\tif (parseFloat(opts.delay) && opts.queue !== false) {\r\n\t\t\t\t\t$.queue(element, opts.queue, function(next, clearQueue) {\r\n\t\t\t\t\t\tif (clearQueue === true) {\r\n\t\t\t\t\t\t\t/* Do not continue with animation queueing. */\r\n\t\t\t\t\t\t\treturn true;\r\n\t\t\t\t\t\t}\r\n\r\n\t\t\t\t\t\t/* This is a flag used to indicate to the upcoming completeCall() function that this queue entry was initiated by Velocity. See completeCall() for further details. */\r\n\t\t\t\t\t\tVelocity.velocityQueueEntryFlag = true;\r\n\r\n\t\t\t\t\t\t/* The ensuing queue item (which is assigned to the \"next\" argument that $.queue() automatically passes in) will be triggered after a setTimeout delay.\r\n\t\t\t\t\t\t The setTimeout is stored so that it can be subjected to clearTimeout() if this animation is prematurely stopped via Velocity's \"stop\" command, and\r\n\t\t\t\t\t\t delayBegin/delayTime is used to ensure we can \"pause\" and \"resume\" a tween that is still mid-delay. */\r\n\r\n\t\t\t\t\t\t/* Temporarily store delayed elements to facilite access for global pause/resume */\r\n\t\t\t\t\t\tvar callIndex = Velocity.State.delayedElements.count++;\r\n\t\t\t\t\t\tVelocity.State.delayedElements[callIndex] = element;\r\n\r\n\t\t\t\t\t\tvar delayComplete = (function(index) {\r\n\t\t\t\t\t\t\treturn function() {\r\n\t\t\t\t\t\t\t\t/* Clear the temporary element */\r\n\t\t\t\t\t\t\t\tVelocity.State.delayedElements[index] = false;\r\n\r\n\t\t\t\t\t\t\t\t/* Finally, issue the call */\r\n\t\t\t\t\t\t\t\tnext();\r\n\t\t\t\t\t\t\t};\r\n\t\t\t\t\t\t})(callIndex);\r\n\r\n\r\n\t\t\t\t\t\tData(element).delayBegin = (new Date()).getTime();\r\n\t\t\t\t\t\tData(element).delay = parseFloat(opts.delay);\r\n\t\t\t\t\t\tData(element).delayTimer = {\r\n\t\t\t\t\t\t\tsetTimeout: setTimeout(next, parseFloat(opts.delay)),\r\n\t\t\t\t\t\t\tnext: delayComplete\r\n\t\t\t\t\t\t};\r\n\t\t\t\t\t});\r\n\t\t\t\t}\r\n\r\n\t\t\t\t/*********************\r\n\t\t\t\t Option: Duration\r\n\t\t\t\t *********************/\r\n\r\n\t\t\t\t/* Support for jQuery's named durations. */\r\n\t\t\t\tswitch (opts.duration.toString().toLowerCase()) {\r\n\t\t\t\t\tcase \"fast\":\r\n\t\t\t\t\t\topts.duration = 200;\r\n\t\t\t\t\t\tbreak;\r\n\r\n\t\t\t\t\tcase \"normal\":\r\n\t\t\t\t\t\topts.duration = DURATION_DEFAULT;\r\n\t\t\t\t\t\tbreak;\r\n\r\n\t\t\t\t\tcase \"slow\":\r\n\t\t\t\t\t\topts.duration = 600;\r\n\t\t\t\t\t\tbreak;\r\n\r\n\t\t\t\t\tdefault:\r\n\t\t\t\t\t\t/* Remove the potential \"ms\" suffix and default to 1 if the user is attempting to set a duration of 0 (in order to produce an immediate style change). */\r\n\t\t\t\t\t\topts.duration = parseFloat(opts.duration) || 1;\r\n\t\t\t\t}\r\n\r\n\t\t\t\t/************************\r\n\t\t\t\t Global Option: Mock\r\n\t\t\t\t ************************/\r\n\r\n\t\t\t\tif (Velocity.mock !== false) {\r\n\t\t\t\t\t/* In mock mode, all animations are forced to 1ms so that they occur immediately upon the next rAF tick.\r\n\t\t\t\t\t Alternatively, a multiplier can be passed in to time remap all delays and durations. */\r\n\t\t\t\t\tif (Velocity.mock === true) {\r\n\t\t\t\t\t\topts.duration = opts.delay = 1;\r\n\t\t\t\t\t} else {\r\n\t\t\t\t\t\topts.duration *= parseFloat(Velocity.mock) || 1;\r\n\t\t\t\t\t\topts.delay *= parseFloat(Velocity.mock) || 1;\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\r\n\t\t\t\t/*******************\r\n\t\t\t\t Option: Easing\r\n\t\t\t\t *******************/\r\n\r\n\t\t\t\topts.easing = getEasing(opts.easing, opts.duration);\r\n\r\n\t\t\t\t/**********************\r\n\t\t\t\t Option: Callbacks\r\n\t\t\t\t **********************/\r\n\r\n\t\t\t\t/* Callbacks must functions. Otherwise, default to null. */\r\n\t\t\t\tif (opts.begin && !Type.isFunction(opts.begin)) {\r\n\t\t\t\t\topts.begin = null;\r\n\t\t\t\t}\r\n\r\n\t\t\t\tif (opts.progress && !Type.isFunction(opts.progress)) {\r\n\t\t\t\t\topts.progress = null;\r\n\t\t\t\t}\r\n\r\n\t\t\t\tif (opts.complete && !Type.isFunction(opts.complete)) {\r\n\t\t\t\t\topts.complete = null;\r\n\t\t\t\t}\r\n\r\n\t\t\t\t/*********************************\r\n\t\t\t\t Option: Display & Visibility\r\n\t\t\t\t *********************************/\r\n\r\n\t\t\t\t/* Refer to Velocity's documentation (VelocityJS.org/#displayAndVisibility) for a description of the display and visibility options' behavior. */\r\n\t\t\t\t/* Note: We strictly check for undefined instead of falsiness because display accepts an empty string value. */\r\n\t\t\t\tif (opts.display !== undefined && opts.display !== null) {\r\n\t\t\t\t\topts.display = opts.display.toString().toLowerCase();\r\n\r\n\t\t\t\t\t/* Users can pass in a special \"auto\" value to instruct Velocity to set the element to its default display value. */\r\n\t\t\t\t\tif (opts.display === \"auto\") {\r\n\t\t\t\t\t\topts.display = Velocity.CSS.Values.getDisplayType(element);\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\r\n\t\t\t\tif (opts.visibility !== undefined && opts.visibility !== null) {\r\n\t\t\t\t\topts.visibility = opts.visibility.toString().toLowerCase();\r\n\t\t\t\t}\r\n\r\n\t\t\t\t/**********************\r\n\t\t\t\t Option: mobileHA\r\n\t\t\t\t **********************/\r\n\r\n\t\t\t\t/* When set to true, and if this is a mobile device, mobileHA automatically enables hardware acceleration (via a null transform hack)\r\n\t\t\t\t on animating elements. HA is removed from the element at the completion of its animation. */\r\n\t\t\t\t/* Note: Android Gingerbread doesn't support HA. If a null transform hack (mobileHA) is in fact set, it will prevent other tranform subproperties from taking effect. */\r\n\t\t\t\t/* Note: You can read more about the use of mobileHA in Velocity's documentation: VelocityJS.org/#mobileHA. */\r\n\t\t\t\topts.mobileHA = (opts.mobileHA && Velocity.State.isMobile && !Velocity.State.isGingerbread);\r\n\r\n\t\t\t\t/***********************\r\n\t\t\t\t Part II: Queueing\r\n\t\t\t\t ***********************/\r\n\r\n\t\t\t\t/* When a set of elements is targeted by a Velocity call, the set is broken up and each element has the current Velocity call individually queued onto it.\r\n\t\t\t\t In this way, each element's existing queue is respected; some elements may already be animating and accordingly should not have this current Velocity call triggered immediately. */\r\n\t\t\t\t/* In each queue, tween data is processed for each animating property then pushed onto the call-wide calls array. When the last element in the set has had its tweens processed,\r\n\t\t\t\t the call array is pushed to Velocity.State.calls for live processing by the requestAnimationFrame tick. */\r\n\t\t\t\tfunction buildQueue(next) {\r\n\t\t\t\t\tvar data, lastTweensContainer;\r\n\r\n\t\t\t\t\t/*******************\r\n\t\t\t\t\t Option: Begin\r\n\t\t\t\t\t *******************/\r\n\r\n\t\t\t\t\t/* The begin callback is fired once per call -- not once per elemenet -- and is passed the full raw DOM element set as both its context and its first argument. */\r\n\t\t\t\t\tif (opts.begin && elementsIndex === 0) {\r\n\t\t\t\t\t\t/* We throw callbacks in a setTimeout so that thrown errors don't halt the execution of Velocity itself. */\r\n\t\t\t\t\t\ttry {\r\n\t\t\t\t\t\t\topts.begin.call(elements, elements);\r\n\t\t\t\t\t\t} catch (error) {\r\n\t\t\t\t\t\t\tsetTimeout(function() {\r\n\t\t\t\t\t\t\t\tthrow error;\r\n\t\t\t\t\t\t\t}, 1);\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n\r\n\t\t\t\t\t/*****************************************\r\n\t\t\t\t\t Tween Data Construction (for Scroll)\r\n\t\t\t\t\t *****************************************/\r\n\r\n\t\t\t\t\t/* Note: In order to be subjected to chaining and animation options, scroll's tweening is routed through Velocity as if it were a standard CSS property animation. */\r\n\t\t\t\t\tif (action === \"scroll\") {\r\n\t\t\t\t\t\t/* The scroll action uniquely takes an optional \"offset\" option -- specified in pixels -- that offsets the targeted scroll position. */\r\n\t\t\t\t\t\tvar scrollDirection = (/^x$/i.test(opts.axis) ? \"Left\" : \"Top\"),\r\n\t\t\t\t\t\t\t\tscrollOffset = parseFloat(opts.offset) || 0,\r\n\t\t\t\t\t\t\t\tscrollPositionCurrent,\r\n\t\t\t\t\t\t\t\tscrollPositionCurrentAlternate,\r\n\t\t\t\t\t\t\t\tscrollPositionEnd;\r\n\r\n\t\t\t\t\t\t/* Scroll also uniquely takes an optional \"container\" option, which indicates the parent element that should be scrolled --\r\n\t\t\t\t\t\t as opposed to the browser window itself. This is useful for scrolling toward an element that's inside an overflowing parent element. */\r\n\t\t\t\t\t\tif (opts.container) {\r\n\t\t\t\t\t\t\t/* Ensure that either a jQuery object or a raw DOM element was passed in. */\r\n\t\t\t\t\t\t\tif (Type.isWrapped(opts.container) || Type.isNode(opts.container)) {\r\n\t\t\t\t\t\t\t\t/* Extract the raw DOM element from the jQuery wrapper. */\r\n\t\t\t\t\t\t\t\topts.container = opts.container[0] || opts.container;\r\n\t\t\t\t\t\t\t\t/* Note: Unlike other properties in Velocity, the browser's scroll position is never cached since it so frequently changes\r\n\t\t\t\t\t\t\t\t (due to the user's natural interaction with the page). */\r\n\t\t\t\t\t\t\t\tscrollPositionCurrent = opts.container[\"scroll\" + scrollDirection]; /* GET */\r\n\r\n\t\t\t\t\t\t\t\t/* $.position() values are relative to the container's currently viewable area (without taking into account the container's true dimensions\r\n\t\t\t\t\t\t\t\t -- say, for example, if the container was not overflowing). Thus, the scroll end value is the sum of the child element's position *and*\r\n\t\t\t\t\t\t\t\t the scroll container's current scroll position. */\r\n\t\t\t\t\t\t\t\tscrollPositionEnd = (scrollPositionCurrent + $(element).position()[scrollDirection.toLowerCase()]) + scrollOffset; /* GET */\r\n\t\t\t\t\t\t\t\t/* If a value other than a jQuery object or a raw DOM element was passed in, default to null so that this option is ignored. */\r\n\t\t\t\t\t\t\t} else {\r\n\t\t\t\t\t\t\t\topts.container = null;\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t} else {\r\n\t\t\t\t\t\t\t/* If the window itself is being scrolled -- not a containing element -- perform a live scroll position lookup using\r\n\t\t\t\t\t\t\t the appropriate cached property names (which differ based on browser type). */\r\n\t\t\t\t\t\t\tscrollPositionCurrent = Velocity.State.scrollAnchor[Velocity.State[\"scrollProperty\" + scrollDirection]]; /* GET */\r\n\t\t\t\t\t\t\t/* When scrolling the browser window, cache the alternate axis's current value since window.scrollTo() doesn't let us change only one value at a time. */\r\n\t\t\t\t\t\t\tscrollPositionCurrentAlternate = Velocity.State.scrollAnchor[Velocity.State[\"scrollProperty\" + (scrollDirection === \"Left\" ? \"Top\" : \"Left\")]]; /* GET */\r\n\r\n\t\t\t\t\t\t\t/* Unlike $.position(), $.offset() values are relative to the browser window's true dimensions -- not merely its currently viewable area --\r\n\t\t\t\t\t\t\t and therefore end values do not need to be compounded onto current values. */\r\n\t\t\t\t\t\t\tscrollPositionEnd = $(element).offset()[scrollDirection.toLowerCase()] + scrollOffset; /* GET */\r\n\t\t\t\t\t\t}\r\n\r\n\t\t\t\t\t\t/* Since there's only one format that scroll's associated tweensContainer can take, we create it manually. */\r\n\t\t\t\t\t\ttweensContainer = {\r\n\t\t\t\t\t\t\tscroll: {\r\n\t\t\t\t\t\t\t\trootPropertyValue: false,\r\n\t\t\t\t\t\t\t\tstartValue: scrollPositionCurrent,\r\n\t\t\t\t\t\t\t\tcurrentValue: scrollPositionCurrent,\r\n\t\t\t\t\t\t\t\tendValue: scrollPositionEnd,\r\n\t\t\t\t\t\t\t\tunitType: \"\",\r\n\t\t\t\t\t\t\t\teasing: opts.easing,\r\n\t\t\t\t\t\t\t\tscrollData: {\r\n\t\t\t\t\t\t\t\t\tcontainer: opts.container,\r\n\t\t\t\t\t\t\t\t\tdirection: scrollDirection,\r\n\t\t\t\t\t\t\t\t\talternateValue: scrollPositionCurrentAlternate\r\n\t\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\t},\r\n\t\t\t\t\t\t\telement: element\r\n\t\t\t\t\t\t};\r\n\r\n\t\t\t\t\t\tif (Velocity.debug) {\r\n\t\t\t\t\t\t\tconsole.log(\"tweensContainer (scroll): \", tweensContainer.scroll, element);\r\n\t\t\t\t\t\t}\r\n\r\n\t\t\t\t\t\t/******************************************\r\n\t\t\t\t\t\t Tween Data Construction (for Reverse)\r\n\t\t\t\t\t\t ******************************************/\r\n\r\n\t\t\t\t\t\t/* Reverse acts like a \"start\" action in that a property map is animated toward. The only difference is\r\n\t\t\t\t\t\t that the property map used for reverse is the inverse of the map used in the previous call. Thus, we manipulate\r\n\t\t\t\t\t\t the previous call to construct our new map: use the previous map's end values as our new map's start values. Copy over all other data. */\r\n\t\t\t\t\t\t/* Note: Reverse can be directly called via the \"reverse\" parameter, or it can be indirectly triggered via the loop option. (Loops are composed of multiple reverses.) */\r\n\t\t\t\t\t\t/* Note: Reverse calls do not need to be consecutively chained onto a currently-animating element in order to operate on cached values;\r\n\t\t\t\t\t\t there is no harm to reverse being called on a potentially stale data cache since reverse's behavior is simply defined\r\n\t\t\t\t\t\t as reverting to the element's values as they were prior to the previous *Velocity* call. */\r\n\t\t\t\t\t} else if (action === \"reverse\") {\r\n\t\t\t\t\t\tdata = Data(element);\r\n\r\n\t\t\t\t\t\t/* Abort if there is no prior animation data to reverse to. */\r\n\t\t\t\t\t\tif (!data) {\r\n\t\t\t\t\t\t\treturn;\r\n\t\t\t\t\t\t}\r\n\r\n\t\t\t\t\t\tif (!data.tweensContainer) {\r\n\t\t\t\t\t\t\t/* Dequeue the element so that this queue entry releases itself immediately, allowing subsequent queue entries to run. */\r\n\t\t\t\t\t\t\t$.dequeue(element, opts.queue);\r\n\r\n\t\t\t\t\t\t\treturn;\r\n\t\t\t\t\t\t} else {\r\n\t\t\t\t\t\t\t/*********************\r\n\t\t\t\t\t\t\t Options Parsing\r\n\t\t\t\t\t\t\t *********************/\r\n\r\n\t\t\t\t\t\t\t/* If the element was hidden via the display option in the previous call,\r\n\t\t\t\t\t\t\t revert display to \"auto\" prior to reversal so that the element is visible again. */\r\n\t\t\t\t\t\t\tif (data.opts.display === \"none\") {\r\n\t\t\t\t\t\t\t\tdata.opts.display = \"auto\";\r\n\t\t\t\t\t\t\t}\r\n\r\n\t\t\t\t\t\t\tif (data.opts.visibility === \"hidden\") {\r\n\t\t\t\t\t\t\t\tdata.opts.visibility = \"visible\";\r\n\t\t\t\t\t\t\t}\r\n\r\n\t\t\t\t\t\t\t/* If the loop option was set in the previous call, disable it so that \"reverse\" calls aren't recursively generated.\r\n\t\t\t\t\t\t\t Further, remove the previous call's callback options; typically, users do not want these to be refired. */\r\n\t\t\t\t\t\t\tdata.opts.loop = false;\r\n\t\t\t\t\t\t\tdata.opts.begin = null;\r\n\t\t\t\t\t\t\tdata.opts.complete = null;\r\n\r\n\t\t\t\t\t\t\t/* Since we're extending an opts object that has already been extended with the defaults options object,\r\n\t\t\t\t\t\t\t we remove non-explicitly-defined properties that are auto-assigned values. */\r\n\t\t\t\t\t\t\tif (!options.easing) {\r\n\t\t\t\t\t\t\t\tdelete opts.easing;\r\n\t\t\t\t\t\t\t}\r\n\r\n\t\t\t\t\t\t\tif (!options.duration) {\r\n\t\t\t\t\t\t\t\tdelete opts.duration;\r\n\t\t\t\t\t\t\t}\r\n\r\n\t\t\t\t\t\t\t/* The opts object used for reversal is an extension of the options object optionally passed into this\r\n\t\t\t\t\t\t\t reverse call plus the options used in the previous Velocity call. */\r\n\t\t\t\t\t\t\topts = $.extend({}, data.opts, opts);\r\n\r\n\t\t\t\t\t\t\t/*************************************\r\n\t\t\t\t\t\t\t Tweens Container Reconstruction\r\n\t\t\t\t\t\t\t *************************************/\r\n\r\n\t\t\t\t\t\t\t/* Create a deepy copy (indicated via the true flag) of the previous call's tweensContainer. */\r\n\t\t\t\t\t\t\tlastTweensContainer = $.extend(true, {}, data ? data.tweensContainer : null);\r\n\r\n\t\t\t\t\t\t\t/* Manipulate the previous tweensContainer by replacing its end values and currentValues with its start values. */\r\n\t\t\t\t\t\t\tfor (var lastTween in lastTweensContainer) {\r\n\t\t\t\t\t\t\t\t/* In addition to tween data, tweensContainers contain an element property that we ignore here. */\r\n\t\t\t\t\t\t\t\tif (lastTweensContainer.hasOwnProperty(lastTween) && lastTween !== \"element\") {\r\n\t\t\t\t\t\t\t\t\tvar lastStartValue = lastTweensContainer[lastTween].startValue;\r\n\r\n\t\t\t\t\t\t\t\t\tlastTweensContainer[lastTween].startValue = lastTweensContainer[lastTween].currentValue = lastTweensContainer[lastTween].endValue;\r\n\t\t\t\t\t\t\t\t\tlastTweensContainer[lastTween].endValue = lastStartValue;\r\n\r\n\t\t\t\t\t\t\t\t\t/* Easing is the only option that embeds into the individual tween data (since it can be defined on a per-property basis).\r\n\t\t\t\t\t\t\t\t\t Accordingly, every property's easing value must be updated when an options object is passed in with a reverse call.\r\n\t\t\t\t\t\t\t\t\t The side effect of this extensibility is that all per-property easing values are forcefully reset to the new value. */\r\n\t\t\t\t\t\t\t\t\tif (!Type.isEmptyObject(options)) {\r\n\t\t\t\t\t\t\t\t\t\tlastTweensContainer[lastTween].easing = opts.easing;\r\n\t\t\t\t\t\t\t\t\t}\r\n\r\n\t\t\t\t\t\t\t\t\tif (Velocity.debug) {\r\n\t\t\t\t\t\t\t\t\t\tconsole.log(\"reverse tweensContainer (\" + lastTween + \"): \" + JSON.stringify(lastTweensContainer[lastTween]), element);\r\n\t\t\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\t}\r\n\r\n\t\t\t\t\t\t\ttweensContainer = lastTweensContainer;\r\n\t\t\t\t\t\t}\r\n\r\n\t\t\t\t\t\t/*****************************************\r\n\t\t\t\t\t\t Tween Data Construction (for Start)\r\n\t\t\t\t\t\t *****************************************/\r\n\r\n\t\t\t\t\t} else if (action === \"start\") {\r\n\r\n\t\t\t\t\t\t/*************************\r\n\t\t\t\t\t\t Value Transferring\r\n\t\t\t\t\t\t *************************/\r\n\r\n\t\t\t\t\t\t/* If this queue entry follows a previous Velocity-initiated queue entry *and* if this entry was created\r\n\t\t\t\t\t\t while the element was in the process of being animated by Velocity, then this current call is safe to use\r\n\t\t\t\t\t\t the end values from the prior call as its start values. Velocity attempts to perform this value transfer\r\n\t\t\t\t\t\t process whenever possible in order to avoid requerying the DOM. */\r\n\t\t\t\t\t\t/* If values aren't transferred from a prior call and start values were not forcefed by the user (more on this below),\r\n\t\t\t\t\t\t then the DOM is queried for the element's current values as a last resort. */\r\n\t\t\t\t\t\t/* Note: Conversely, animation reversal (and looping) *always* perform inter-call value transfers; they never requery the DOM. */\r\n\r\n\t\t\t\t\t\tdata = Data(element);\r\n\r\n\t\t\t\t\t\t/* The per-element isAnimating flag is used to indicate whether it's safe (i.e. the data isn't stale)\r\n\t\t\t\t\t\t to transfer over end values to use as start values. If it's set to true and there is a previous\r\n\t\t\t\t\t\t Velocity call to pull values from, do so. */\r\n\t\t\t\t\t\tif (data && data.tweensContainer && data.isAnimating === true) {\r\n\t\t\t\t\t\t\tlastTweensContainer = data.tweensContainer;\r\n\t\t\t\t\t\t}\r\n\r\n\t\t\t\t\t\t/***************************\r\n\t\t\t\t\t\t Tween Data Calculation\r\n\t\t\t\t\t\t ***************************/\r\n\r\n\t\t\t\t\t\t/* This function parses property data and defaults endValue, easing, and startValue as appropriate. */\r\n\t\t\t\t\t\t/* Property map values can either take the form of 1) a single value representing the end value,\r\n\t\t\t\t\t\t or 2) an array in the form of [ endValue, [, easing] [, startValue] ].\r\n\t\t\t\t\t\t The optional third parameter is a forcefed startValue to be used instead of querying the DOM for\r\n\t\t\t\t\t\t the element's current value. Read Velocity's docmentation to learn more about forcefeeding: VelocityJS.org/#forcefeeding */\r\n\t\t\t\t\t\tvar parsePropertyValue = function(valueData, skipResolvingEasing) {\r\n\t\t\t\t\t\t\tvar endValue, easing, startValue;\r\n\r\n\t\t\t\t\t\t\t/* If we have a function as the main argument then resolve it first, in case it returns an array that needs to be split */\r\n\t\t\t\t\t\t\tif (Type.isFunction(valueData)) {\r\n\t\t\t\t\t\t\t\tvalueData = valueData.call(element, elementArrayIndex, elementsLength);\r\n\t\t\t\t\t\t\t}\r\n\r\n\t\t\t\t\t\t\t/* Handle the array format, which can be structured as one of three potential overloads:\r\n\t\t\t\t\t\t\t A) [ endValue, easing, startValue ], B) [ endValue, easing ], or C) [ endValue, startValue ] */\r\n\t\t\t\t\t\t\tif (Type.isArray(valueData)) {\r\n\t\t\t\t\t\t\t\t/* endValue is always the first item in the array. Don't bother validating endValue's value now\r\n\t\t\t\t\t\t\t\t since the ensuing property cycling logic does that. */\r\n\t\t\t\t\t\t\t\tendValue = valueData[0];\r\n\r\n\t\t\t\t\t\t\t\t/* Two-item array format: If the second item is a number, function, or hex string, treat it as a\r\n\t\t\t\t\t\t\t\t start value since easings can only be non-hex strings or arrays. */\r\n\t\t\t\t\t\t\t\tif ((!Type.isArray(valueData[1]) && /^[\\d-]/.test(valueData[1])) || Type.isFunction(valueData[1]) || CSS.RegEx.isHex.test(valueData[1])) {\r\n\t\t\t\t\t\t\t\t\tstartValue = valueData[1];\r\n\t\t\t\t\t\t\t\t\t/* Two or three-item array: If the second item is a non-hex string easing name or an array, treat it as an easing. */\r\n\t\t\t\t\t\t\t\t} else if ((Type.isString(valueData[1]) && !CSS.RegEx.isHex.test(valueData[1]) && Velocity.Easings[valueData[1]]) || Type.isArray(valueData[1])) {\r\n\t\t\t\t\t\t\t\t\teasing = skipResolvingEasing ? valueData[1] : getEasing(valueData[1], opts.duration);\r\n\r\n\t\t\t\t\t\t\t\t\t/* Don't bother validating startValue's value now since the ensuing property cycling logic inherently does that. */\r\n\t\t\t\t\t\t\t\t\tstartValue = valueData[2];\r\n\t\t\t\t\t\t\t\t} else {\r\n\t\t\t\t\t\t\t\t\tstartValue = valueData[1] || valueData[2];\r\n\t\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\t\t/* Handle the single-value format. */\r\n\t\t\t\t\t\t\t} else {\r\n\t\t\t\t\t\t\t\tendValue = valueData;\r\n\t\t\t\t\t\t\t}\r\n\r\n\t\t\t\t\t\t\t/* Default to the call's easing if a per-property easing type was not defined. */\r\n\t\t\t\t\t\t\tif (!skipResolvingEasing) {\r\n\t\t\t\t\t\t\t\teasing = easing || opts.easing;\r\n\t\t\t\t\t\t\t}\r\n\r\n\t\t\t\t\t\t\t/* If functions were passed in as values, pass the function the current element as its context,\r\n\t\t\t\t\t\t\t plus the element's index and the element set's size as arguments. Then, assign the returned value. */\r\n\t\t\t\t\t\t\tif (Type.isFunction(endValue)) {\r\n\t\t\t\t\t\t\t\tendValue = endValue.call(element, elementArrayIndex, elementsLength);\r\n\t\t\t\t\t\t\t}\r\n\r\n\t\t\t\t\t\t\tif (Type.isFunction(startValue)) {\r\n\t\t\t\t\t\t\t\tstartValue = startValue.call(element, elementArrayIndex, elementsLength);\r\n\t\t\t\t\t\t\t}\r\n\r\n\t\t\t\t\t\t\t/* Allow startValue to be left as undefined to indicate to the ensuing code that its value was not forcefed. */\r\n\t\t\t\t\t\t\treturn [endValue || 0, easing, startValue];\r\n\t\t\t\t\t\t};\r\n\r\n\t\t\t\t\t\tvar fixPropertyValue = function(property, valueData) {\r\n\t\t\t\t\t\t\t/* In case this property is a hook, there are circumstances where we will intend to work on the hook's root property and not the hooked subproperty. */\r\n\t\t\t\t\t\t\tvar rootProperty = CSS.Hooks.getRoot(property),\r\n\t\t\t\t\t\t\t\t\trootPropertyValue = false,\r\n\t\t\t\t\t\t\t\t\t/* Parse out endValue, easing, and startValue from the property's data. */\r\n\t\t\t\t\t\t\t\t\tendValue = valueData[0],\r\n\t\t\t\t\t\t\t\t\teasing = valueData[1],\r\n\t\t\t\t\t\t\t\t\tstartValue = valueData[2],\r\n\t\t\t\t\t\t\t\t\tpattern;\r\n\r\n\t\t\t\t\t\t\t/**************************\r\n\t\t\t\t\t\t\t Start Value Sourcing\r\n\t\t\t\t\t\t\t **************************/\r\n\r\n\t\t\t\t\t\t\t/* Other than for the dummy tween property, properties that are not supported by the browser (and do not have an associated normalization) will\r\n\t\t\t\t\t\t\t inherently produce no style changes when set, so they are skipped in order to decrease animation tick overhead.\r\n\t\t\t\t\t\t\t Property support is determined via prefixCheck(), which returns a false flag when no supported is detected. */\r\n\t\t\t\t\t\t\t/* Note: Since SVG elements have some of their properties directly applied as HTML attributes,\r\n\t\t\t\t\t\t\t there is no way to check for their explicit browser support, and so we skip skip this check for them. */\r\n\t\t\t\t\t\t\tif ((!data || !data.isSVG) && rootProperty !== \"tween\" && CSS.Names.prefixCheck(rootProperty)[1] === false && CSS.Normalizations.registered[rootProperty] === undefined) {\r\n\t\t\t\t\t\t\t\tif (Velocity.debug) {\r\n\t\t\t\t\t\t\t\t\tconsole.log(\"Skipping [\" + rootProperty + \"] due to a lack of browser support.\");\r\n\t\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\t\treturn;\r\n\t\t\t\t\t\t\t}\r\n\r\n\t\t\t\t\t\t\t/* If the display option is being set to a non-\"none\" (e.g. \"block\") and opacity (filter on IE<=8) is being\r\n\t\t\t\t\t\t\t animated to an endValue of non-zero, the user's intention is to fade in from invisible, thus we forcefeed opacity\r\n\t\t\t\t\t\t\t a startValue of 0 if its startValue hasn't already been sourced by value transferring or prior forcefeeding. */\r\n\t\t\t\t\t\t\tif (((opts.display !== undefined && opts.display !== null && opts.display !== \"none\") || (opts.visibility !== undefined && opts.visibility !== \"hidden\")) && /opacity|filter/.test(property) && !startValue && endValue !== 0) {\r\n\t\t\t\t\t\t\t\tstartValue = 0;\r\n\t\t\t\t\t\t\t}\r\n\r\n\t\t\t\t\t\t\t/* If values have been transferred from the previous Velocity call, extract the endValue and rootPropertyValue\r\n\t\t\t\t\t\t\t for all of the current call's properties that were *also* animated in the previous call. */\r\n\t\t\t\t\t\t\t/* Note: Value transferring can optionally be disabled by the user via the _cacheValues option. */\r\n\t\t\t\t\t\t\tif (opts._cacheValues && lastTweensContainer && lastTweensContainer[property]) {\r\n\t\t\t\t\t\t\t\tif (startValue === undefined) {\r\n\t\t\t\t\t\t\t\t\tstartValue = lastTweensContainer[property].endValue + lastTweensContainer[property].unitType;\r\n\t\t\t\t\t\t\t\t}\r\n\r\n\t\t\t\t\t\t\t\t/* The previous call's rootPropertyValue is extracted from the element's data cache since that's the\r\n\t\t\t\t\t\t\t\t instance of rootPropertyValue that gets freshly updated by the tweening process, whereas the rootPropertyValue\r\n\t\t\t\t\t\t\t\t attached to the incoming lastTweensContainer is equal to the root property's value prior to any tweening. */\r\n\t\t\t\t\t\t\t\trootPropertyValue = data.rootPropertyValueCache[rootProperty];\r\n\t\t\t\t\t\t\t\t/* If values were not transferred from a previous Velocity call, query the DOM as needed. */\r\n\t\t\t\t\t\t\t} else {\r\n\t\t\t\t\t\t\t\t/* Handle hooked properties. */\r\n\t\t\t\t\t\t\t\tif (CSS.Hooks.registered[property]) {\r\n\t\t\t\t\t\t\t\t\tif (startValue === undefined) {\r\n\t\t\t\t\t\t\t\t\t\trootPropertyValue = CSS.getPropertyValue(element, rootProperty); /* GET */\r\n\t\t\t\t\t\t\t\t\t\t/* Note: The following getPropertyValue() call does not actually trigger a DOM query;\r\n\t\t\t\t\t\t\t\t\t\t getPropertyValue() will extract the hook from rootPropertyValue. */\r\n\t\t\t\t\t\t\t\t\t\tstartValue = CSS.getPropertyValue(element, property, rootPropertyValue);\r\n\t\t\t\t\t\t\t\t\t\t/* If startValue is already defined via forcefeeding, do not query the DOM for the root property's value;\r\n\t\t\t\t\t\t\t\t\t\t just grab rootProperty's zero-value template from CSS.Hooks. This overwrites the element's actual\r\n\t\t\t\t\t\t\t\t\t\t root property value (if one is set), but this is acceptable since the primary reason users forcefeed is\r\n\t\t\t\t\t\t\t\t\t\t to avoid DOM queries, and thus we likewise avoid querying the DOM for the root property's value. */\r\n\t\t\t\t\t\t\t\t\t} else {\r\n\t\t\t\t\t\t\t\t\t\t/* Grab this hook's zero-value template, e.g. \"0px 0px 0px black\". */\r\n\t\t\t\t\t\t\t\t\t\trootPropertyValue = CSS.Hooks.templates[rootProperty][1];\r\n\t\t\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\t\t\t/* Handle non-hooked properties that haven't already been defined via forcefeeding. */\r\n\t\t\t\t\t\t\t\t} else if (startValue === undefined) {\r\n\t\t\t\t\t\t\t\t\tstartValue = CSS.getPropertyValue(element, property); /* GET */\r\n\t\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\t}\r\n\r\n\t\t\t\t\t\t\t/**************************\r\n\t\t\t\t\t\t\t Value Data Extraction\r\n\t\t\t\t\t\t\t **************************/\r\n\r\n\t\t\t\t\t\t\tvar separatedValue,\r\n\t\t\t\t\t\t\t\t\tendValueUnitType,\r\n\t\t\t\t\t\t\t\t\tstartValueUnitType,\r\n\t\t\t\t\t\t\t\t\toperator = false;\r\n\r\n\t\t\t\t\t\t\t/* Separates a property value into its numeric value and its unit type. */\r\n\t\t\t\t\t\t\tvar separateValue = function(property, value) {\r\n\t\t\t\t\t\t\t\tvar unitType,\r\n\t\t\t\t\t\t\t\t\t\tnumericValue;\r\n\r\n\t\t\t\t\t\t\t\tnumericValue = (value || \"0\")\r\n\t\t\t\t\t\t\t\t\t\t.toString()\r\n\t\t\t\t\t\t\t\t\t\t.toLowerCase()\r\n\t\t\t\t\t\t\t\t\t\t/* Match the unit type at the end of the value. */\r\n\t\t\t\t\t\t\t\t\t\t.replace(/[%A-z]+$/, function(match) {\r\n\t\t\t\t\t\t\t\t\t\t\t/* Grab the unit type. */\r\n\t\t\t\t\t\t\t\t\t\t\tunitType = match;\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t/* Strip the unit type off of value. */\r\n\t\t\t\t\t\t\t\t\t\t\treturn \"\";\r\n\t\t\t\t\t\t\t\t\t\t});\r\n\r\n\t\t\t\t\t\t\t\t/* If no unit type was supplied, assign one that is appropriate for this property (e.g. \"deg\" for rotateZ or \"px\" for width). */\r\n\t\t\t\t\t\t\t\tif (!unitType) {\r\n\t\t\t\t\t\t\t\t\tunitType = CSS.Values.getUnitType(property);\r\n\t\t\t\t\t\t\t\t}\r\n\r\n\t\t\t\t\t\t\t\treturn [numericValue, unitType];\r\n\t\t\t\t\t\t\t};\r\n\r\n\t\t\t\t\t\t\tif (startValue !== endValue && Type.isString(startValue) && Type.isString(endValue)) {\r\n\t\t\t\t\t\t\t\tpattern = \"\";\r\n\t\t\t\t\t\t\t\tvar iStart = 0, // index in startValue\r\n\t\t\t\t\t\t\t\t\t\tiEnd = 0, // index in endValue\r\n\t\t\t\t\t\t\t\t\t\taStart = [], // array of startValue numbers\r\n\t\t\t\t\t\t\t\t\t\taEnd = [], // array of endValue numbers\r\n\t\t\t\t\t\t\t\t\t\tinCalc = 0, // Keep track of being inside a \"calc()\" so we don't duplicate it\r\n\t\t\t\t\t\t\t\t\t\tinRGB = 0, // Keep track of being inside an RGB as we can't use fractional values\r\n\t\t\t\t\t\t\t\t\t\tinRGBA = 0; // Keep track of being inside an RGBA as we must pass fractional for the alpha channel\r\n\r\n\t\t\t\t\t\t\t\tstartValue = CSS.Hooks.fixColors(startValue);\r\n\t\t\t\t\t\t\t\tendValue = CSS.Hooks.fixColors(endValue);\r\n\t\t\t\t\t\t\t\twhile (iStart < startValue.length && iEnd < endValue.length) {\r\n\t\t\t\t\t\t\t\t\tvar cStart = startValue[iStart],\r\n\t\t\t\t\t\t\t\t\t\t\tcEnd = endValue[iEnd];\r\n\r\n\t\t\t\t\t\t\t\t\tif (/[\\d\\.-]/.test(cStart) && /[\\d\\.-]/.test(cEnd)) {\r\n\t\t\t\t\t\t\t\t\t\tvar tStart = cStart, // temporary character buffer\r\n\t\t\t\t\t\t\t\t\t\t\t\ttEnd = cEnd, // temporary character buffer\r\n\t\t\t\t\t\t\t\t\t\t\t\tdotStart = \".\", // Make sure we can only ever match a single dot in a decimal\r\n\t\t\t\t\t\t\t\t\t\t\t\tdotEnd = \".\"; // Make sure we can only ever match a single dot in a decimal\r\n\r\n\t\t\t\t\t\t\t\t\t\twhile (++iStart < startValue.length) {\r\n\t\t\t\t\t\t\t\t\t\t\tcStart = startValue[iStart];\r\n\t\t\t\t\t\t\t\t\t\t\tif (cStart === dotStart) {\r\n\t\t\t\t\t\t\t\t\t\t\t\tdotStart = \"..\"; // Can never match two characters\r\n\t\t\t\t\t\t\t\t\t\t\t} else if (!/\\d/.test(cStart)) {\r\n\t\t\t\t\t\t\t\t\t\t\t\tbreak;\r\n\t\t\t\t\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\t\t\t\t\ttStart += cStart;\r\n\t\t\t\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\t\t\t\twhile (++iEnd < endValue.length) {\r\n\t\t\t\t\t\t\t\t\t\t\tcEnd = endValue[iEnd];\r\n\t\t\t\t\t\t\t\t\t\t\tif (cEnd === dotEnd) {\r\n\t\t\t\t\t\t\t\t\t\t\t\tdotEnd = \"..\"; // Can never match two characters\r\n\t\t\t\t\t\t\t\t\t\t\t} else if (!/\\d/.test(cEnd)) {\r\n\t\t\t\t\t\t\t\t\t\t\t\tbreak;\r\n\t\t\t\t\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\t\t\t\t\ttEnd += cEnd;\r\n\t\t\t\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\t\t\t\tvar uStart = CSS.Hooks.getUnit(startValue, iStart), // temporary unit type\r\n\t\t\t\t\t\t\t\t\t\t\t\tuEnd = CSS.Hooks.getUnit(endValue, iEnd); // temporary unit type\r\n\r\n\t\t\t\t\t\t\t\t\t\tiStart += uStart.length;\r\n\t\t\t\t\t\t\t\t\t\tiEnd += uEnd.length;\r\n\t\t\t\t\t\t\t\t\t\tif (uStart === uEnd) {\r\n\t\t\t\t\t\t\t\t\t\t\t// Same units\r\n\t\t\t\t\t\t\t\t\t\t\tif (tStart === tEnd) {\r\n\t\t\t\t\t\t\t\t\t\t\t\t// Same numbers, so just copy over\r\n\t\t\t\t\t\t\t\t\t\t\t\tpattern += tStart + uStart;\r\n\t\t\t\t\t\t\t\t\t\t\t} else {\r\n\t\t\t\t\t\t\t\t\t\t\t\t// Different numbers, so store them\r\n\t\t\t\t\t\t\t\t\t\t\t\tpattern += \"{\" + aStart.length + (inRGB ? \"!\" : \"\") + \"}\" + uStart;\r\n\t\t\t\t\t\t\t\t\t\t\t\taStart.push(parseFloat(tStart));\r\n\t\t\t\t\t\t\t\t\t\t\t\taEnd.push(parseFloat(tEnd));\r\n\t\t\t\t\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\t\t\t\t} else {\r\n\t\t\t\t\t\t\t\t\t\t\t// Different units, so put into a \"calc(from + to)\" and animate each side to/from zero\r\n\t\t\t\t\t\t\t\t\t\t\tvar nStart = parseFloat(tStart),\r\n\t\t\t\t\t\t\t\t\t\t\t\t\tnEnd = parseFloat(tEnd);\r\n\r\n\t\t\t\t\t\t\t\t\t\t\tpattern += (inCalc < 5 ? \"calc\" : \"\") + \"(\"\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t+ (nStart ? \"{\" + aStart.length + (inRGB ? \"!\" : \"\") + \"}\" : \"0\") + uStart\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t+ \" + \"\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t+ (nEnd ? \"{\" + (aStart.length + (nStart ? 1 : 0)) + (inRGB ? \"!\" : \"\") + \"}\" : \"0\") + uEnd\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t+ \")\";\r\n\t\t\t\t\t\t\t\t\t\t\tif (nStart) {\r\n\t\t\t\t\t\t\t\t\t\t\t\taStart.push(nStart);\r\n\t\t\t\t\t\t\t\t\t\t\t\taEnd.push(0);\r\n\t\t\t\t\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\t\t\t\t\tif (nEnd) {\r\n\t\t\t\t\t\t\t\t\t\t\t\taStart.push(0);\r\n\t\t\t\t\t\t\t\t\t\t\t\taEnd.push(nEnd);\r\n\t\t\t\t\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\t\t\t} else if (cStart === cEnd) {\r\n\t\t\t\t\t\t\t\t\t\tpattern += cStart;\r\n\t\t\t\t\t\t\t\t\t\tiStart++;\r\n\t\t\t\t\t\t\t\t\t\tiEnd++;\r\n\t\t\t\t\t\t\t\t\t\t// Keep track of being inside a calc()\r\n\t\t\t\t\t\t\t\t\t\tif (inCalc === 0 && cStart === \"c\"\r\n\t\t\t\t\t\t\t\t\t\t\t\t|| inCalc === 1 && cStart === \"a\"\r\n\t\t\t\t\t\t\t\t\t\t\t\t|| inCalc === 2 && cStart === \"l\"\r\n\t\t\t\t\t\t\t\t\t\t\t\t|| inCalc === 3 && cStart === \"c\"\r\n\t\t\t\t\t\t\t\t\t\t\t\t|| inCalc >= 4 && cStart === \"(\"\r\n\t\t\t\t\t\t\t\t\t\t\t\t) {\r\n\t\t\t\t\t\t\t\t\t\t\tinCalc++;\r\n\t\t\t\t\t\t\t\t\t\t} else if ((inCalc && inCalc < 5)\r\n\t\t\t\t\t\t\t\t\t\t\t\t|| inCalc >= 4 && cStart === \")\" && --inCalc < 5) {\r\n\t\t\t\t\t\t\t\t\t\t\tinCalc = 0;\r\n\t\t\t\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\t\t\t\t// Keep track of being inside an rgb() / rgba()\r\n\t\t\t\t\t\t\t\t\t\tif (inRGB === 0 && cStart === \"r\"\r\n\t\t\t\t\t\t\t\t\t\t\t\t|| inRGB === 1 && cStart === \"g\"\r\n\t\t\t\t\t\t\t\t\t\t\t\t|| inRGB === 2 && cStart === \"b\"\r\n\t\t\t\t\t\t\t\t\t\t\t\t|| inRGB === 3 && cStart === \"a\"\r\n\t\t\t\t\t\t\t\t\t\t\t\t|| inRGB >= 3 && cStart === \"(\"\r\n\t\t\t\t\t\t\t\t\t\t\t\t) {\r\n\t\t\t\t\t\t\t\t\t\t\tif (inRGB === 3 && cStart === \"a\") {\r\n\t\t\t\t\t\t\t\t\t\t\t\tinRGBA = 1;\r\n\t\t\t\t\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\t\t\t\t\tinRGB++;\r\n\t\t\t\t\t\t\t\t\t\t} else if (inRGBA && cStart === \",\") {\r\n\t\t\t\t\t\t\t\t\t\t\tif (++inRGBA > 3) {\r\n\t\t\t\t\t\t\t\t\t\t\t\tinRGB = inRGBA = 0;\r\n\t\t\t\t\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\t\t\t\t} else if ((inRGBA && inRGB < (inRGBA ? 5 : 4))\r\n\t\t\t\t\t\t\t\t\t\t\t\t|| inRGB >= (inRGBA ? 4 : 3) && cStart === \")\" && --inRGB < (inRGBA ? 5 : 4)) {\r\n\t\t\t\t\t\t\t\t\t\t\tinRGB = inRGBA = 0;\r\n\t\t\t\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\t\t\t} else {\r\n\t\t\t\t\t\t\t\t\t\tinCalc = 0;\r\n\t\t\t\t\t\t\t\t\t\t// TODO: changing units, fixing colours\r\n\t\t\t\t\t\t\t\t\t\tbreak;\r\n\t\t\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\t\tif (iStart !== startValue.length || iEnd !== endValue.length) {\r\n\t\t\t\t\t\t\t\t\tif (Velocity.debug) {\r\n\t\t\t\t\t\t\t\t\t\tconsole.error(\"Trying to pattern match mis-matched strings [\\\"\" + endValue + \"\\\", \\\"\" + startValue + \"\\\"]\");\r\n\t\t\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\t\t\tpattern = undefined;\r\n\t\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\t\tif (pattern) {\r\n\t\t\t\t\t\t\t\t\tif (aStart.length) {\r\n\t\t\t\t\t\t\t\t\t\tif (Velocity.debug) {\r\n\t\t\t\t\t\t\t\t\t\t\tconsole.log(\"Pattern found \\\"\" + pattern + \"\\\" -> \", aStart, aEnd, \"[\" + startValue + \",\" + endValue + \"]\");\r\n\t\t\t\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\t\t\t\tstartValue = aStart;\r\n\t\t\t\t\t\t\t\t\t\tendValue = aEnd;\r\n\t\t\t\t\t\t\t\t\t\tendValueUnitType = startValueUnitType = \"\";\r\n\t\t\t\t\t\t\t\t\t} else {\r\n\t\t\t\t\t\t\t\t\t\tpattern = undefined;\r\n\t\t\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\t}\r\n\r\n\t\t\t\t\t\t\tif (!pattern) {\r\n\t\t\t\t\t\t\t\t/* Separate startValue. */\r\n\t\t\t\t\t\t\t\tseparatedValue = separateValue(property, startValue);\r\n\t\t\t\t\t\t\t\tstartValue = separatedValue[0];\r\n\t\t\t\t\t\t\t\tstartValueUnitType = separatedValue[1];\r\n\r\n\t\t\t\t\t\t\t\t/* Separate endValue, and extract a value operator (e.g. \"+=\", \"-=\") if one exists. */\r\n\t\t\t\t\t\t\t\tseparatedValue = separateValue(property, endValue);\r\n\t\t\t\t\t\t\t\tendValue = separatedValue[0].replace(/^([+-\\/*])=/, function(match, subMatch) {\r\n\t\t\t\t\t\t\t\t\toperator = subMatch;\r\n\r\n\t\t\t\t\t\t\t\t\t/* Strip the operator off of the value. */\r\n\t\t\t\t\t\t\t\t\treturn \"\";\r\n\t\t\t\t\t\t\t\t});\r\n\t\t\t\t\t\t\t\tendValueUnitType = separatedValue[1];\r\n\r\n\t\t\t\t\t\t\t\t/* Parse float values from endValue and startValue. Default to 0 if NaN is returned. */\r\n\t\t\t\t\t\t\t\tstartValue = parseFloat(startValue) || 0;\r\n\t\t\t\t\t\t\t\tendValue = parseFloat(endValue) || 0;\r\n\r\n\t\t\t\t\t\t\t\t/***************************************\r\n\t\t\t\t\t\t\t\t Property-Specific Value Conversion\r\n\t\t\t\t\t\t\t\t ***************************************/\r\n\r\n\t\t\t\t\t\t\t\t/* Custom support for properties that don't actually accept the % unit type, but where pollyfilling is trivial and relatively foolproof. */\r\n\t\t\t\t\t\t\t\tif (endValueUnitType === \"%\") {\r\n\t\t\t\t\t\t\t\t\t/* A %-value fontSize/lineHeight is relative to the parent's fontSize (as opposed to the parent's dimensions),\r\n\t\t\t\t\t\t\t\t\t which is identical to the em unit's behavior, so we piggyback off of that. */\r\n\t\t\t\t\t\t\t\t\tif (/^(fontSize|lineHeight)$/.test(property)) {\r\n\t\t\t\t\t\t\t\t\t\t/* Convert % into an em decimal value. */\r\n\t\t\t\t\t\t\t\t\t\tendValue = endValue / 100;\r\n\t\t\t\t\t\t\t\t\t\tendValueUnitType = \"em\";\r\n\t\t\t\t\t\t\t\t\t\t/* For scaleX and scaleY, convert the value into its decimal format and strip off the unit type. */\r\n\t\t\t\t\t\t\t\t\t} else if (/^scale/.test(property)) {\r\n\t\t\t\t\t\t\t\t\t\tendValue = endValue / 100;\r\n\t\t\t\t\t\t\t\t\t\tendValueUnitType = \"\";\r\n\t\t\t\t\t\t\t\t\t\t/* For RGB components, take the defined percentage of 255 and strip off the unit type. */\r\n\t\t\t\t\t\t\t\t\t} else if (/(Red|Green|Blue)$/i.test(property)) {\r\n\t\t\t\t\t\t\t\t\t\tendValue = (endValue / 100) * 255;\r\n\t\t\t\t\t\t\t\t\t\tendValueUnitType = \"\";\r\n\t\t\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\t}\r\n\r\n\t\t\t\t\t\t\t/***************************\r\n\t\t\t\t\t\t\t Unit Ratio Calculation\r\n\t\t\t\t\t\t\t ***************************/\r\n\r\n\t\t\t\t\t\t\t/* When queried, the browser returns (most) CSS property values in pixels. Therefore, if an endValue with a unit type of\r\n\t\t\t\t\t\t\t %, em, or rem is animated toward, startValue must be converted from pixels into the same unit type as endValue in order\r\n\t\t\t\t\t\t\t for value manipulation logic (increment/decrement) to proceed. Further, if the startValue was forcefed or transferred\r\n\t\t\t\t\t\t\t from a previous call, startValue may also not be in pixels. Unit conversion logic therefore consists of two steps:\r\n\t\t\t\t\t\t\t 1) Calculating the ratio of %/em/rem/vh/vw relative to pixels\r\n\t\t\t\t\t\t\t 2) Converting startValue into the same unit of measurement as endValue based on these ratios. */\r\n\t\t\t\t\t\t\t/* Unit conversion ratios are calculated by inserting a sibling node next to the target node, copying over its position property,\r\n\t\t\t\t\t\t\t setting values with the target unit type then comparing the returned pixel value. */\r\n\t\t\t\t\t\t\t/* Note: Even if only one of these unit types is being animated, all unit ratios are calculated at once since the overhead\r\n\t\t\t\t\t\t\t of batching the SETs and GETs together upfront outweights the potential overhead\r\n\t\t\t\t\t\t\t of layout thrashing caused by re-querying for uncalculated ratios for subsequently-processed properties. */\r\n\t\t\t\t\t\t\t/* Todo: Shift this logic into the calls' first tick instance so that it's synced with RAF. */\r\n\t\t\t\t\t\t\tvar calculateUnitRatios = function() {\r\n\r\n\t\t\t\t\t\t\t\t/************************\r\n\t\t\t\t\t\t\t\t Same Ratio Checks\r\n\t\t\t\t\t\t\t\t ************************/\r\n\r\n\t\t\t\t\t\t\t\t/* The properties below are used to determine whether the element differs sufficiently from this call's\r\n\t\t\t\t\t\t\t\t previously iterated element to also differ in its unit conversion ratios. If the properties match up with those\r\n\t\t\t\t\t\t\t\t of the prior element, the prior element's conversion ratios are used. Like most optimizations in Velocity,\r\n\t\t\t\t\t\t\t\t this is done to minimize DOM querying. */\r\n\t\t\t\t\t\t\t\tvar sameRatioIndicators = {\r\n\t\t\t\t\t\t\t\t\tmyParent: element.parentNode || document.body, /* GET */\r\n\t\t\t\t\t\t\t\t\tposition: CSS.getPropertyValue(element, \"position\"), /* GET */\r\n\t\t\t\t\t\t\t\t\tfontSize: CSS.getPropertyValue(element, \"fontSize\") /* GET */\r\n\t\t\t\t\t\t\t\t},\r\n\t\t\t\t\t\t\t\t\t\t/* Determine if the same % ratio can be used. % is based on the element's position value and its parent's width and height dimensions. */\r\n\t\t\t\t\t\t\t\t\t\tsamePercentRatio = ((sameRatioIndicators.position === callUnitConversionData.lastPosition) && (sameRatioIndicators.myParent === callUnitConversionData.lastParent)),\r\n\t\t\t\t\t\t\t\t\t\t/* Determine if the same em ratio can be used. em is relative to the element's fontSize. */\r\n\t\t\t\t\t\t\t\t\t\tsameEmRatio = (sameRatioIndicators.fontSize === callUnitConversionData.lastFontSize);\r\n\r\n\t\t\t\t\t\t\t\t/* Store these ratio indicators call-wide for the next element to compare against. */\r\n\t\t\t\t\t\t\t\tcallUnitConversionData.lastParent = sameRatioIndicators.myParent;\r\n\t\t\t\t\t\t\t\tcallUnitConversionData.lastPosition = sameRatioIndicators.position;\r\n\t\t\t\t\t\t\t\tcallUnitConversionData.lastFontSize = sameRatioIndicators.fontSize;\r\n\r\n\t\t\t\t\t\t\t\t/***************************\r\n\t\t\t\t\t\t\t\t Element-Specific Units\r\n\t\t\t\t\t\t\t\t ***************************/\r\n\r\n\t\t\t\t\t\t\t\t/* Note: IE8 rounds to the nearest pixel when returning CSS values, thus we perform conversions using a measurement\r\n\t\t\t\t\t\t\t\t of 100 (instead of 1) to give our ratios a precision of at least 2 decimal values. */\r\n\t\t\t\t\t\t\t\tvar measurement = 100,\r\n\t\t\t\t\t\t\t\t\t\tunitRatios = {};\r\n\r\n\t\t\t\t\t\t\t\tif (!sameEmRatio || !samePercentRatio) {\r\n\t\t\t\t\t\t\t\t\tvar dummy = data && data.isSVG ? document.createElementNS(\"http://www.w3.org/2000/svg\", \"rect\") : document.createElement(\"div\");\r\n\r\n\t\t\t\t\t\t\t\t\tVelocity.init(dummy);\r\n\t\t\t\t\t\t\t\t\tsameRatioIndicators.myParent.appendChild(dummy);\r\n\r\n\t\t\t\t\t\t\t\t\t/* To accurately and consistently calculate conversion ratios, the element's cascaded overflow and box-sizing are stripped.\r\n\t\t\t\t\t\t\t\t\t Similarly, since width/height can be artificially constrained by their min-/max- equivalents, these are controlled for as well. */\r\n\t\t\t\t\t\t\t\t\t/* Note: Overflow must be also be controlled for per-axis since the overflow property overwrites its per-axis values. */\r\n\t\t\t\t\t\t\t\t\t$.each([\"overflow\", \"overflowX\", \"overflowY\"], function(i, property) {\r\n\t\t\t\t\t\t\t\t\t\tVelocity.CSS.setPropertyValue(dummy, property, \"hidden\");\r\n\t\t\t\t\t\t\t\t\t});\r\n\t\t\t\t\t\t\t\t\tVelocity.CSS.setPropertyValue(dummy, \"position\", sameRatioIndicators.position);\r\n\t\t\t\t\t\t\t\t\tVelocity.CSS.setPropertyValue(dummy, \"fontSize\", sameRatioIndicators.fontSize);\r\n\t\t\t\t\t\t\t\t\tVelocity.CSS.setPropertyValue(dummy, \"boxSizing\", \"content-box\");\r\n\r\n\t\t\t\t\t\t\t\t\t/* width and height act as our proxy properties for measuring the horizontal and vertical % ratios. */\r\n\t\t\t\t\t\t\t\t\t$.each([\"minWidth\", \"maxWidth\", \"width\", \"minHeight\", \"maxHeight\", \"height\"], function(i, property) {\r\n\t\t\t\t\t\t\t\t\t\tVelocity.CSS.setPropertyValue(dummy, property, measurement + \"%\");\r\n\t\t\t\t\t\t\t\t\t});\r\n\t\t\t\t\t\t\t\t\t/* paddingLeft arbitrarily acts as our proxy property for the em ratio. */\r\n\t\t\t\t\t\t\t\t\tVelocity.CSS.setPropertyValue(dummy, \"paddingLeft\", measurement + \"em\");\r\n\r\n\t\t\t\t\t\t\t\t\t/* Divide the returned value by the measurement to get the ratio between 1% and 1px. Default to 1 since working with 0 can produce Infinite. */\r\n\t\t\t\t\t\t\t\t\tunitRatios.percentToPxWidth = callUnitConversionData.lastPercentToPxWidth = (parseFloat(CSS.getPropertyValue(dummy, \"width\", null, true)) || 1) / measurement; /* GET */\r\n\t\t\t\t\t\t\t\t\tunitRatios.percentToPxHeight = callUnitConversionData.lastPercentToPxHeight = (parseFloat(CSS.getPropertyValue(dummy, \"height\", null, true)) || 1) / measurement; /* GET */\r\n\t\t\t\t\t\t\t\t\tunitRatios.emToPx = callUnitConversionData.lastEmToPx = (parseFloat(CSS.getPropertyValue(dummy, \"paddingLeft\")) || 1) / measurement; /* GET */\r\n\r\n\t\t\t\t\t\t\t\t\tsameRatioIndicators.myParent.removeChild(dummy);\r\n\t\t\t\t\t\t\t\t} else {\r\n\t\t\t\t\t\t\t\t\tunitRatios.emToPx = callUnitConversionData.lastEmToPx;\r\n\t\t\t\t\t\t\t\t\tunitRatios.percentToPxWidth = callUnitConversionData.lastPercentToPxWidth;\r\n\t\t\t\t\t\t\t\t\tunitRatios.percentToPxHeight = callUnitConversionData.lastPercentToPxHeight;\r\n\t\t\t\t\t\t\t\t}\r\n\r\n\t\t\t\t\t\t\t\t/***************************\r\n\t\t\t\t\t\t\t\t Element-Agnostic Units\r\n\t\t\t\t\t\t\t\t ***************************/\r\n\r\n\t\t\t\t\t\t\t\t/* Whereas % and em ratios are determined on a per-element basis, the rem unit only needs to be checked\r\n\t\t\t\t\t\t\t\t once per call since it's exclusively dependant upon document.body's fontSize. If this is the first time\r\n\t\t\t\t\t\t\t\t that calculateUnitRatios() is being run during this call, remToPx will still be set to its default value of null,\r\n\t\t\t\t\t\t\t\t so we calculate it now. */\r\n\t\t\t\t\t\t\t\tif (callUnitConversionData.remToPx === null) {\r\n\t\t\t\t\t\t\t\t\t/* Default to browsers' default fontSize of 16px in the case of 0. */\r\n\t\t\t\t\t\t\t\t\tcallUnitConversionData.remToPx = parseFloat(CSS.getPropertyValue(document.body, \"fontSize\")) || 16; /* GET */\r\n\t\t\t\t\t\t\t\t}\r\n\r\n\t\t\t\t\t\t\t\t/* Similarly, viewport units are %-relative to the window's inner dimensions. */\r\n\t\t\t\t\t\t\t\tif (callUnitConversionData.vwToPx === null) {\r\n\t\t\t\t\t\t\t\t\tcallUnitConversionData.vwToPx = parseFloat(window.innerWidth) / 100; /* GET */\r\n\t\t\t\t\t\t\t\t\tcallUnitConversionData.vhToPx = parseFloat(window.innerHeight) / 100; /* GET */\r\n\t\t\t\t\t\t\t\t}\r\n\r\n\t\t\t\t\t\t\t\tunitRatios.remToPx = callUnitConversionData.remToPx;\r\n\t\t\t\t\t\t\t\tunitRatios.vwToPx = callUnitConversionData.vwToPx;\r\n\t\t\t\t\t\t\t\tunitRatios.vhToPx = callUnitConversionData.vhToPx;\r\n\r\n\t\t\t\t\t\t\t\tif (Velocity.debug >= 1) {\r\n\t\t\t\t\t\t\t\t\tconsole.log(\"Unit ratios: \" + JSON.stringify(unitRatios), element);\r\n\t\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\t\treturn unitRatios;\r\n\t\t\t\t\t\t\t};\r\n\r\n\t\t\t\t\t\t\t/********************\r\n\t\t\t\t\t\t\t Unit Conversion\r\n\t\t\t\t\t\t\t ********************/\r\n\r\n\t\t\t\t\t\t\t/* The * and / operators, which are not passed in with an associated unit, inherently use startValue's unit. Skip value and unit conversion. */\r\n\t\t\t\t\t\t\tif (/[\\/*]/.test(operator)) {\r\n\t\t\t\t\t\t\t\tendValueUnitType = startValueUnitType;\r\n\t\t\t\t\t\t\t\t/* If startValue and endValue differ in unit type, convert startValue into the same unit type as endValue so that if endValueUnitType\r\n\t\t\t\t\t\t\t\t is a relative unit (%, em, rem), the values set during tweening will continue to be accurately relative even if the metrics they depend\r\n\t\t\t\t\t\t\t\t on are dynamically changing during the course of the animation. Conversely, if we always normalized into px and used px for setting values, the px ratio\r\n\t\t\t\t\t\t\t\t would become stale if the original unit being animated toward was relative and the underlying metrics change during the animation. */\r\n\t\t\t\t\t\t\t\t/* Since 0 is 0 in any unit type, no conversion is necessary when startValue is 0 -- we just start at 0 with endValueUnitType. */\r\n\t\t\t\t\t\t\t} else if ((startValueUnitType !== endValueUnitType) && startValue !== 0) {\r\n\t\t\t\t\t\t\t\t/* Unit conversion is also skipped when endValue is 0, but *startValueUnitType* must be used for tween values to remain accurate. */\r\n\t\t\t\t\t\t\t\t/* Note: Skipping unit conversion here means that if endValueUnitType was originally a relative unit, the animation won't relatively\r\n\t\t\t\t\t\t\t\t match the underlying metrics if they change, but this is acceptable since we're animating toward invisibility instead of toward visibility,\r\n\t\t\t\t\t\t\t\t which remains past the point of the animation's completion. */\r\n\t\t\t\t\t\t\t\tif (endValue === 0) {\r\n\t\t\t\t\t\t\t\t\tendValueUnitType = startValueUnitType;\r\n\t\t\t\t\t\t\t\t} else {\r\n\t\t\t\t\t\t\t\t\t/* By this point, we cannot avoid unit conversion (it's undesirable since it causes layout thrashing).\r\n\t\t\t\t\t\t\t\t\t If we haven't already, we trigger calculateUnitRatios(), which runs once per element per call. */\r\n\t\t\t\t\t\t\t\t\telementUnitConversionData = elementUnitConversionData || calculateUnitRatios();\r\n\r\n\t\t\t\t\t\t\t\t\t/* The following RegEx matches CSS properties that have their % values measured relative to the x-axis. */\r\n\t\t\t\t\t\t\t\t\t/* Note: W3C spec mandates that all of margin and padding's properties (even top and bottom) are %-relative to the *width* of the parent element. */\r\n\t\t\t\t\t\t\t\t\tvar axis = (/margin|padding|left|right|width|text|word|letter/i.test(property) || /X$/.test(property) || property === \"x\") ? \"x\" : \"y\";\r\n\r\n\t\t\t\t\t\t\t\t\t/* In order to avoid generating n^2 bespoke conversion functions, unit conversion is a two-step process:\r\n\t\t\t\t\t\t\t\t\t 1) Convert startValue into pixels. 2) Convert this new pixel value into endValue's unit type. */\r\n\t\t\t\t\t\t\t\t\tswitch (startValueUnitType) {\r\n\t\t\t\t\t\t\t\t\t\tcase \"%\":\r\n\t\t\t\t\t\t\t\t\t\t\t/* Note: translateX and translateY are the only properties that are %-relative to an element's own dimensions -- not its parent's dimensions.\r\n\t\t\t\t\t\t\t\t\t\t\t Velocity does not include a special conversion process to account for this behavior. Therefore, animating translateX/Y from a % value\r\n\t\t\t\t\t\t\t\t\t\t\t to a non-% value will produce an incorrect start value. Fortunately, this sort of cross-unit conversion is rarely done by users in practice. */\r\n\t\t\t\t\t\t\t\t\t\t\tstartValue *= (axis === \"x\" ? elementUnitConversionData.percentToPxWidth : elementUnitConversionData.percentToPxHeight);\r\n\t\t\t\t\t\t\t\t\t\t\tbreak;\r\n\r\n\t\t\t\t\t\t\t\t\t\tcase \"px\":\r\n\t\t\t\t\t\t\t\t\t\t\t/* px acts as our midpoint in the unit conversion process; do nothing. */\r\n\t\t\t\t\t\t\t\t\t\t\tbreak;\r\n\r\n\t\t\t\t\t\t\t\t\t\tdefault:\r\n\t\t\t\t\t\t\t\t\t\t\tstartValue *= elementUnitConversionData[startValueUnitType + \"ToPx\"];\r\n\t\t\t\t\t\t\t\t\t}\r\n\r\n\t\t\t\t\t\t\t\t\t/* Invert the px ratios to convert into to the target unit. */\r\n\t\t\t\t\t\t\t\t\tswitch (endValueUnitType) {\r\n\t\t\t\t\t\t\t\t\t\tcase \"%\":\r\n\t\t\t\t\t\t\t\t\t\t\tstartValue *= 1 / (axis === \"x\" ? elementUnitConversionData.percentToPxWidth : elementUnitConversionData.percentToPxHeight);\r\n\t\t\t\t\t\t\t\t\t\t\tbreak;\r\n\r\n\t\t\t\t\t\t\t\t\t\tcase \"px\":\r\n\t\t\t\t\t\t\t\t\t\t\t/* startValue is already in px, do nothing; we're done. */\r\n\t\t\t\t\t\t\t\t\t\t\tbreak;\r\n\r\n\t\t\t\t\t\t\t\t\t\tdefault:\r\n\t\t\t\t\t\t\t\t\t\t\tstartValue *= 1 / elementUnitConversionData[endValueUnitType + \"ToPx\"];\r\n\t\t\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\t}\r\n\r\n\t\t\t\t\t\t\t/*********************\r\n\t\t\t\t\t\t\t Relative Values\r\n\t\t\t\t\t\t\t *********************/\r\n\r\n\t\t\t\t\t\t\t/* Operator logic must be performed last since it requires unit-normalized start and end values. */\r\n\t\t\t\t\t\t\t/* Note: Relative *percent values* do not behave how most people think; while one would expect \"+=50%\"\r\n\t\t\t\t\t\t\t to increase the property 1.5x its current value, it in fact increases the percent units in absolute terms:\r\n\t\t\t\t\t\t\t 50 points is added on top of the current % value. */\r\n\t\t\t\t\t\t\tswitch (operator) {\r\n\t\t\t\t\t\t\t\tcase \"+\":\r\n\t\t\t\t\t\t\t\t\tendValue = startValue + endValue;\r\n\t\t\t\t\t\t\t\t\tbreak;\r\n\r\n\t\t\t\t\t\t\t\tcase \"-\":\r\n\t\t\t\t\t\t\t\t\tendValue = startValue - endValue;\r\n\t\t\t\t\t\t\t\t\tbreak;\r\n\r\n\t\t\t\t\t\t\t\tcase \"*\":\r\n\t\t\t\t\t\t\t\t\tendValue = startValue * endValue;\r\n\t\t\t\t\t\t\t\t\tbreak;\r\n\r\n\t\t\t\t\t\t\t\tcase \"/\":\r\n\t\t\t\t\t\t\t\t\tendValue = startValue / endValue;\r\n\t\t\t\t\t\t\t\t\tbreak;\r\n\t\t\t\t\t\t\t}\r\n\r\n\t\t\t\t\t\t\t/**************************\r\n\t\t\t\t\t\t\t tweensContainer Push\r\n\t\t\t\t\t\t\t **************************/\r\n\r\n\t\t\t\t\t\t\t/* Construct the per-property tween object, and push it to the element's tweensContainer. */\r\n\t\t\t\t\t\t\ttweensContainer[property] = {\r\n\t\t\t\t\t\t\t\trootPropertyValue: rootPropertyValue,\r\n\t\t\t\t\t\t\t\tstartValue: startValue,\r\n\t\t\t\t\t\t\t\tcurrentValue: startValue,\r\n\t\t\t\t\t\t\t\tendValue: endValue,\r\n\t\t\t\t\t\t\t\tunitType: endValueUnitType,\r\n\t\t\t\t\t\t\t\teasing: easing\r\n\t\t\t\t\t\t\t};\r\n\t\t\t\t\t\t\tif (pattern) {\r\n\t\t\t\t\t\t\t\ttweensContainer[property].pattern = pattern;\r\n\t\t\t\t\t\t\t}\r\n\r\n\t\t\t\t\t\t\tif (Velocity.debug) {\r\n\t\t\t\t\t\t\t\tconsole.log(\"tweensContainer (\" + property + \"): \" + JSON.stringify(tweensContainer[property]), element);\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t};\r\n\r\n\t\t\t\t\t\t/* Create a tween out of each property, and append its associated data to tweensContainer. */\r\n\t\t\t\t\t\tfor (var property in propertiesMap) {\r\n\r\n\t\t\t\t\t\t\tif (!propertiesMap.hasOwnProperty(property)) {\r\n\t\t\t\t\t\t\t\tcontinue;\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\t/* The original property name's format must be used for the parsePropertyValue() lookup,\r\n\t\t\t\t\t\t\t but we then use its camelCase styling to normalize it for manipulation. */\r\n\t\t\t\t\t\t\tvar propertyName = CSS.Names.camelCase(property),\r\n\t\t\t\t\t\t\t\t\tvalueData = parsePropertyValue(propertiesMap[property]);\r\n\r\n\t\t\t\t\t\t\t/* Find shorthand color properties that have been passed a hex string. */\r\n\t\t\t\t\t\t\t/* Would be quicker to use CSS.Lists.colors.includes() if possible */\r\n\t\t\t\t\t\t\tif (_inArray(CSS.Lists.colors, propertyName)) {\r\n\t\t\t\t\t\t\t\t/* Parse the value data for each shorthand. */\r\n\t\t\t\t\t\t\t\tvar endValue = valueData[0],\r\n\t\t\t\t\t\t\t\t\t\teasing = valueData[1],\r\n\t\t\t\t\t\t\t\t\t\tstartValue = valueData[2];\r\n\r\n\t\t\t\t\t\t\t\tif (CSS.RegEx.isHex.test(endValue)) {\r\n\t\t\t\t\t\t\t\t\t/* Convert the hex strings into their RGB component arrays. */\r\n\t\t\t\t\t\t\t\t\tvar colorComponents = [\"Red\", \"Green\", \"Blue\"],\r\n\t\t\t\t\t\t\t\t\t\t\tendValueRGB = CSS.Values.hexToRgb(endValue),\r\n\t\t\t\t\t\t\t\t\t\t\tstartValueRGB = startValue ? CSS.Values.hexToRgb(startValue) : undefined;\r\n\r\n\t\t\t\t\t\t\t\t\t/* Inject the RGB component tweens into propertiesMap. */\r\n\t\t\t\t\t\t\t\t\tfor (var i = 0; i < colorComponents.length; i++) {\r\n\t\t\t\t\t\t\t\t\t\tvar dataArray = [endValueRGB[i]];\r\n\r\n\t\t\t\t\t\t\t\t\t\tif (easing) {\r\n\t\t\t\t\t\t\t\t\t\t\tdataArray.push(easing);\r\n\t\t\t\t\t\t\t\t\t\t}\r\n\r\n\t\t\t\t\t\t\t\t\t\tif (startValueRGB !== undefined) {\r\n\t\t\t\t\t\t\t\t\t\t\tdataArray.push(startValueRGB[i]);\r\n\t\t\t\t\t\t\t\t\t\t}\r\n\r\n\t\t\t\t\t\t\t\t\t\tfixPropertyValue(propertyName + colorComponents[i], dataArray);\r\n\t\t\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\t\t\t/* If we have replaced a shortcut color value then don't update the standard property name */\r\n\t\t\t\t\t\t\t\t\tcontinue;\r\n\t\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\tfixPropertyValue(propertyName, valueData);\r\n\t\t\t\t\t\t}\r\n\r\n\t\t\t\t\t\t/* Along with its property data, store a reference to the element itself onto tweensContainer. */\r\n\t\t\t\t\t\ttweensContainer.element = element;\r\n\t\t\t\t\t}\r\n\r\n\t\t\t\t\t/*****************\r\n\t\t\t\t\t Call Push\r\n\t\t\t\t\t *****************/\r\n\r\n\t\t\t\t\t/* Note: tweensContainer can be empty if all of the properties in this call's property map were skipped due to not\r\n\t\t\t\t\t being supported by the browser. The element property is used for checking that the tweensContainer has been appended to. */\r\n\t\t\t\t\tif (tweensContainer.element) {\r\n\t\t\t\t\t\t/* Apply the \"velocity-animating\" indicator class. */\r\n\t\t\t\t\t\tCSS.Values.addClass(element, \"velocity-animating\");\r\n\r\n\t\t\t\t\t\t/* The call array houses the tweensContainers for each element being animated in the current call. */\r\n\t\t\t\t\t\tcall.push(tweensContainer);\r\n\r\n\t\t\t\t\t\tdata = Data(element);\r\n\r\n\t\t\t\t\t\tif (data) {\r\n\t\t\t\t\t\t\t/* Store the tweensContainer and options if we're working on the default effects queue, so that they can be used by the reverse command. */\r\n\t\t\t\t\t\t\tif (opts.queue === \"\") {\r\n\r\n\t\t\t\t\t\t\t\tdata.tweensContainer = tweensContainer;\r\n\t\t\t\t\t\t\t\tdata.opts = opts;\r\n\t\t\t\t\t\t\t}\r\n\r\n\t\t\t\t\t\t\t/* Switch on the element's animating flag. */\r\n\t\t\t\t\t\t\tdata.isAnimating = true;\r\n\t\t\t\t\t\t}\r\n\r\n\t\t\t\t\t\t/* Once the final element in this call's element set has been processed, push the call array onto\r\n\t\t\t\t\t\t Velocity.State.calls for the animation tick to immediately begin processing. */\r\n\t\t\t\t\t\tif (elementsIndex === elementsLength - 1) {\r\n\t\t\t\t\t\t\t/* Add the current call plus its associated metadata (the element set and the call's options) onto the global call container.\r\n\t\t\t\t\t\t\t Anything on this call container is subjected to tick() processing. */\r\n\t\t\t\t\t\t\tVelocity.State.calls.push([call, elements, opts, null, promiseData.resolver, null, 0]);\r\n\r\n\t\t\t\t\t\t\t/* If the animation tick isn't running, start it. (Velocity shuts it off when there are no active calls to process.) */\r\n\t\t\t\t\t\t\tif (Velocity.State.isTicking === false) {\r\n\t\t\t\t\t\t\t\tVelocity.State.isTicking = true;\r\n\r\n\t\t\t\t\t\t\t\t/* Start the tick loop. */\r\n\t\t\t\t\t\t\t\ttick();\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t} else {\r\n\t\t\t\t\t\t\telementsIndex++;\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\r\n\t\t\t\t/* When the queue option is set to false, the call skips the element's queue and fires immediately. */\r\n\t\t\t\tif (opts.queue === false) {\r\n\t\t\t\t\t/* Since this buildQueue call doesn't respect the element's existing queue (which is where a delay option would have been appended),\r\n\t\t\t\t\t we manually inject the delay property here with an explicit setTimeout. */\r\n\t\t\t\t\tif (opts.delay) {\r\n\r\n\t\t\t\t\t\t/* Temporarily store delayed elements to facilitate access for global pause/resume */\r\n\t\t\t\t\t\tvar callIndex = Velocity.State.delayedElements.count++;\r\n\t\t\t\t\t\tVelocity.State.delayedElements[callIndex] = element;\r\n\r\n\t\t\t\t\t\tvar delayComplete = (function(index) {\r\n\t\t\t\t\t\t\treturn function() {\r\n\t\t\t\t\t\t\t\t/* Clear the temporary element */\r\n\t\t\t\t\t\t\t\tVelocity.State.delayedElements[index] = false;\r\n\r\n\t\t\t\t\t\t\t\t/* Finally, issue the call */\r\n\t\t\t\t\t\t\t\tbuildQueue();\r\n\t\t\t\t\t\t\t};\r\n\t\t\t\t\t\t})(callIndex);\r\n\r\n\t\t\t\t\t\tData(element).delayBegin = (new Date()).getTime();\r\n\t\t\t\t\t\tData(element).delay = parseFloat(opts.delay);\r\n\t\t\t\t\t\tData(element).delayTimer = {\r\n\t\t\t\t\t\t\tsetTimeout: setTimeout(buildQueue, parseFloat(opts.delay)),\r\n\t\t\t\t\t\t\tnext: delayComplete\r\n\t\t\t\t\t\t};\r\n\t\t\t\t\t} else {\r\n\t\t\t\t\t\tbuildQueue();\r\n\t\t\t\t\t}\r\n\t\t\t\t\t/* Otherwise, the call undergoes element queueing as normal. */\r\n\t\t\t\t\t/* Note: To interoperate with jQuery, Velocity uses jQuery's own $.queue() stack for queuing logic. */\r\n\t\t\t\t} else {\r\n\t\t\t\t\t$.queue(element, opts.queue, function(next, clearQueue) {\r\n\t\t\t\t\t\t/* If the clearQueue flag was passed in by the stop command, resolve this call's promise. (Promises can only be resolved once,\r\n\t\t\t\t\t\t so it's fine if this is repeatedly triggered for each element in the associated call.) */\r\n\t\t\t\t\t\tif (clearQueue === true) {\r\n\t\t\t\t\t\t\tif (promiseData.promise) {\r\n\t\t\t\t\t\t\t\tpromiseData.resolver(elements);\r\n\t\t\t\t\t\t\t}\r\n\r\n\t\t\t\t\t\t\t/* Do not continue with animation queueing. */\r\n\t\t\t\t\t\t\treturn true;\r\n\t\t\t\t\t\t}\r\n\r\n\t\t\t\t\t\t/* This flag indicates to the upcoming completeCall() function that this queue entry was initiated by Velocity.\r\n\t\t\t\t\t\t See completeCall() for further details. */\r\n\t\t\t\t\t\tVelocity.velocityQueueEntryFlag = true;\r\n\r\n\t\t\t\t\t\tbuildQueue(next);\r\n\t\t\t\t\t});\r\n\t\t\t\t}\r\n\r\n\t\t\t\t/*********************\r\n\t\t\t\t Auto-Dequeuing\r\n\t\t\t\t *********************/\r\n\r\n\t\t\t\t/* As per jQuery's $.queue() behavior, to fire the first non-custom-queue entry on an element, the element\r\n\t\t\t\t must be dequeued if its queue stack consists *solely* of the current call. (This can be determined by checking\r\n\t\t\t\t for the \"inprogress\" item that jQuery prepends to active queue stack arrays.) Regardless, whenever the element's\r\n\t\t\t\t queue is further appended with additional items -- including $.delay()'s or even $.animate() calls, the queue's\r\n\t\t\t\t first entry is automatically fired. This behavior contrasts that of custom queues, which never auto-fire. */\r\n\t\t\t\t/* Note: When an element set is being subjected to a non-parallel Velocity call, the animation will not begin until\r\n\t\t\t\t each one of the elements in the set has reached the end of its individually pre-existing queue chain. */\r\n\t\t\t\t/* Note: Unfortunately, most people don't fully grasp jQuery's powerful, yet quirky, $.queue() function.\r\n\t\t\t\t Lean more here: http://stackoverflow.com/questions/1058158/can-somebody-explain-jquery-queue-to-me */\r\n\t\t\t\tif ((opts.queue === \"\" || opts.queue === \"fx\") && $.queue(element)[0] !== \"inprogress\") {\r\n\t\t\t\t\t$.dequeue(element);\r\n\t\t\t\t}\r\n\t\t\t}\r\n\r\n\t\t\t/**************************\r\n\t\t\t Element Set Iteration\r\n\t\t\t **************************/\r\n\r\n\t\t\t/* If the \"nodeType\" property exists on the elements variable, we're animating a single element.\r\n\t\t\t Place it in an array so that $.each() can iterate over it. */\r\n\t\t\t$.each(elements, function(i, element) {\r\n\t\t\t\t/* Ensure each element in a set has a nodeType (is a real element) to avoid throwing errors. */\r\n\t\t\t\tif (Type.isNode(element)) {\r\n\t\t\t\t\tprocessElement(element, i);\r\n\t\t\t\t}\r\n\t\t\t});\r\n\r\n\t\t\t/******************\r\n\t\t\t Option: Loop\r\n\t\t\t ******************/\r\n\r\n\t\t\t/* The loop option accepts an integer indicating how many times the element should loop between the values in the\r\n\t\t\t current call's properties map and the element's property values prior to this call. */\r\n\t\t\t/* Note: The loop option's logic is performed here -- after element processing -- because the current call needs\r\n\t\t\t to undergo its queue insertion prior to the loop option generating its series of constituent \"reverse\" calls,\r\n\t\t\t which chain after the current call. Two reverse calls (two \"alternations\") constitute one loop. */\r\n\t\t\topts = $.extend({}, Velocity.defaults, options);\r\n\t\t\topts.loop = parseInt(opts.loop, 10);\r\n\t\t\tvar reverseCallsCount = (opts.loop * 2) - 1;\r\n\r\n\t\t\tif (opts.loop) {\r\n\t\t\t\t/* Double the loop count to convert it into its appropriate number of \"reverse\" calls.\r\n\t\t\t\t Subtract 1 from the resulting value since the current call is included in the total alternation count. */\r\n\t\t\t\tfor (var x = 0; x < reverseCallsCount; x++) {\r\n\t\t\t\t\t/* Since the logic for the reverse action occurs inside Queueing and therefore this call's options object\r\n\t\t\t\t\t isn't parsed until then as well, the current call's delay option must be explicitly passed into the reverse\r\n\t\t\t\t\t call so that the delay logic that occurs inside *Pre-Queueing* can process it. */\r\n\t\t\t\t\tvar reverseOptions = {\r\n\t\t\t\t\t\tdelay: opts.delay,\r\n\t\t\t\t\t\tprogress: opts.progress\r\n\t\t\t\t\t};\r\n\r\n\t\t\t\t\t/* If a complete callback was passed into this call, transfer it to the loop redirect's final \"reverse\" call\r\n\t\t\t\t\t so that it's triggered when the entire redirect is complete (and not when the very first animation is complete). */\r\n\t\t\t\t\tif (x === reverseCallsCount - 1) {\r\n\t\t\t\t\t\treverseOptions.display = opts.display;\r\n\t\t\t\t\t\treverseOptions.visibility = opts.visibility;\r\n\t\t\t\t\t\treverseOptions.complete = opts.complete;\r\n\t\t\t\t\t}\r\n\r\n\t\t\t\t\tanimate(elements, \"reverse\", reverseOptions);\r\n\t\t\t\t}\r\n\t\t\t}\r\n\r\n\t\t\t/***************\r\n\t\t\t Chaining\r\n\t\t\t ***************/\r\n\r\n\t\t\t/* Return the elements back to the call chain, with wrapped elements taking precedence in case Velocity was called via the $.fn. extension. */\r\n\t\t\treturn getChain();\r\n\t\t};\r\n\r\n\t\t/* Turn Velocity into the animation function, extended with the pre-existing Velocity object. */\r\n\t\tVelocity = $.extend(animate, Velocity);\r\n\t\t/* For legacy support, also expose the literal animate method. */\r\n\t\tVelocity.animate = animate;\r\n\r\n\t\t/**************\r\n\t\t Timing\r\n\t\t **************/\r\n\r\n\t\t/* Ticker function. */\r\n\t\tvar ticker = window.requestAnimationFrame || rAFShim;\r\n\r\n\t\t/* Inactive browser tabs pause rAF, which results in all active animations immediately sprinting to their completion states when the tab refocuses.\r\n\t\t To get around this, we dynamically switch rAF to setTimeout (which the browser *doesn't* pause) when the tab loses focus. We skip this for mobile\r\n\t\t devices to avoid wasting battery power on inactive tabs. */\r\n\t\t/* Note: Tab focus detection doesn't work on older versions of IE, but that's okay since they don't support rAF to begin with. */\r\n\t\tif (!Velocity.State.isMobile && document.hidden !== undefined) {\r\n\t\t\tvar updateTicker = function() {\r\n\t\t\t\t/* Reassign the rAF function (which the global tick() function uses) based on the tab's focus state. */\r\n\t\t\t\tif (document.hidden) {\r\n\t\t\t\t\tticker = function(callback) {\r\n\t\t\t\t\t\t/* The tick function needs a truthy first argument in order to pass its internal timestamp check. */\r\n\t\t\t\t\t\treturn setTimeout(function() {\r\n\t\t\t\t\t\t\tcallback(true);\r\n\t\t\t\t\t\t}, 16);\r\n\t\t\t\t\t};\r\n\r\n\t\t\t\t\t/* The rAF loop has been paused by the browser, so we manually restart the tick. */\r\n\t\t\t\t\ttick();\r\n\t\t\t\t} else {\r\n\t\t\t\t\tticker = window.requestAnimationFrame || rAFShim;\r\n\t\t\t\t}\r\n\t\t\t};\r\n\r\n\t\t\t/* Page could be sitting in the background at this time (i.e. opened as new tab) so making sure we use correct ticker from the start */\r\n\t\t\tupdateTicker();\r\n\r\n\t\t\t/* And then run check again every time visibility changes */\r\n\t\t\tdocument.addEventListener(\"visibilitychange\", updateTicker);\r\n\t\t}\r\n\r\n\t\t/************\r\n\t\t Tick\r\n\t\t ************/\r\n\r\n\t\t/* Note: All calls to Velocity are pushed to the Velocity.State.calls array, which is fully iterated through upon each tick. */\r\n\t\tfunction tick(timestamp) {\r\n\t\t\t/* An empty timestamp argument indicates that this is the first tick occurence since ticking was turned on.\r\n\t\t\t We leverage this metadata to fully ignore the first tick pass since RAF's initial pass is fired whenever\r\n\t\t\t the browser's next tick sync time occurs, which results in the first elements subjected to Velocity\r\n\t\t\t calls being animated out of sync with any elements animated immediately thereafter. In short, we ignore\r\n\t\t\t the first RAF tick pass so that elements being immediately consecutively animated -- instead of simultaneously animated\r\n\t\t\t by the same Velocity call -- are properly batched into the same initial RAF tick and consequently remain in sync thereafter. */\r\n\t\t\tif (timestamp) {\r\n\t\t\t\t/* We normally use RAF's high resolution timestamp but as it can be significantly offset when the browser is\r\n\t\t\t\t under high stress we give the option for choppiness over allowing the browser to drop huge chunks of frames.\r\n\t\t\t\t We use performance.now() and shim it if it doesn't exist for when the tab is hidden. */\r\n\t\t\t\tvar timeCurrent = Velocity.timestamp && timestamp !== true ? timestamp : performance.now();\r\n\r\n\t\t\t\t/********************\r\n\t\t\t\t Call Iteration\r\n\t\t\t\t ********************/\r\n\r\n\t\t\t\tvar callsLength = Velocity.State.calls.length;\r\n\r\n\t\t\t\t/* To speed up iterating over this array, it is compacted (falsey items -- calls that have completed -- are removed)\r\n\t\t\t\t when its length has ballooned to a point that can impact tick performance. This only becomes necessary when animation\r\n\t\t\t\t has been continuous with many elements over a long period of time; whenever all active calls are completed, completeCall() clears Velocity.State.calls. */\r\n\t\t\t\tif (callsLength > 10000) {\r\n\t\t\t\t\tVelocity.State.calls = compactSparseArray(Velocity.State.calls);\r\n\t\t\t\t\tcallsLength = Velocity.State.calls.length;\r\n\t\t\t\t}\r\n\r\n\t\t\t\t/* Iterate through each active call. */\r\n\t\t\t\tfor (var i = 0; i < callsLength; i++) {\r\n\t\t\t\t\t/* When a Velocity call is completed, its Velocity.State.calls entry is set to false. Continue on to the next call. */\r\n\t\t\t\t\tif (!Velocity.State.calls[i]) {\r\n\t\t\t\t\t\tcontinue;\r\n\t\t\t\t\t}\r\n\r\n\t\t\t\t\t/************************\r\n\t\t\t\t\t Call-Wide Variables\r\n\t\t\t\t\t ************************/\r\n\r\n\t\t\t\t\tvar callContainer = Velocity.State.calls[i],\r\n\t\t\t\t\t\t\tcall = callContainer[0],\r\n\t\t\t\t\t\t\topts = callContainer[2],\r\n\t\t\t\t\t\t\ttimeStart = callContainer[3],\r\n\t\t\t\t\t\t\tfirstTick = !timeStart,\r\n\t\t\t\t\t\t\ttweenDummyValue = null,\r\n\t\t\t\t\t\t\tpauseObject = callContainer[5],\r\n\t\t\t\t\t\t\tmillisecondsEllapsed = callContainer[6];\r\n\r\n\r\n\r\n\t\t\t\t\t/* If timeStart is undefined, then this is the first time that this call has been processed by tick().\r\n\t\t\t\t\t We assign timeStart now so that its value is as close to the real animation start time as possible.\r\n\t\t\t\t\t (Conversely, had timeStart been defined when this call was added to Velocity.State.calls, the delay\r\n\t\t\t\t\t between that time and now would cause the first few frames of the tween to be skipped since\r\n\t\t\t\t\t percentComplete is calculated relative to timeStart.) */\r\n\t\t\t\t\t/* Further, subtract 16ms (the approximate resolution of RAF) from the current time value so that the\r\n\t\t\t\t\t first tick iteration isn't wasted by animating at 0% tween completion, which would produce the\r\n\t\t\t\t\t same style value as the element's current value. */\r\n\t\t\t\t\tif (!timeStart) {\r\n\t\t\t\t\t\ttimeStart = Velocity.State.calls[i][3] = timeCurrent - 16;\r\n\t\t\t\t\t}\r\n\r\n\t\t\t\t\t/* If a pause object is present, skip processing unless it has been set to resume */\r\n\t\t\t\t\tif (pauseObject) {\r\n\t\t\t\t\t\tif (pauseObject.resume === true) {\r\n\t\t\t\t\t\t\t/* Update the time start to accomodate the paused completion amount */\r\n\t\t\t\t\t\t\ttimeStart = callContainer[3] = Math.round(timeCurrent - millisecondsEllapsed - 16);\r\n\r\n\t\t\t\t\t\t\t/* Remove pause object after processing */\r\n\t\t\t\t\t\t\tcallContainer[5] = null;\r\n\t\t\t\t\t\t} else {\r\n\t\t\t\t\t\t\tcontinue;\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n\r\n\t\t\t\t\tmillisecondsEllapsed = callContainer[6] = timeCurrent - timeStart;\r\n\r\n\t\t\t\t\t/* The tween's completion percentage is relative to the tween's start time, not the tween's start value\r\n\t\t\t\t\t (which would result in unpredictable tween durations since JavaScript's timers are not particularly accurate).\r\n\t\t\t\t\t Accordingly, we ensure that percentComplete does not exceed 1. */\r\n\t\t\t\t\tvar percentComplete = Math.min((millisecondsEllapsed) / opts.duration, 1);\r\n\r\n\t\t\t\t\t/**********************\r\n\t\t\t\t\t Element Iteration\r\n\t\t\t\t\t **********************/\r\n\r\n\t\t\t\t\t/* For every call, iterate through each of the elements in its set. */\r\n\t\t\t\t\tfor (var j = 0, callLength = call.length; j < callLength; j++) {\r\n\t\t\t\t\t\tvar tweensContainer = call[j],\r\n\t\t\t\t\t\t\t\telement = tweensContainer.element;\r\n\r\n\t\t\t\t\t\t/* Check to see if this element has been deleted midway through the animation by checking for the\r\n\t\t\t\t\t\t continued existence of its data cache. If it's gone, or the element is currently paused, skip animating this element. */\r\n\t\t\t\t\t\tif (!Data(element)) {\r\n\t\t\t\t\t\t\tcontinue;\r\n\t\t\t\t\t\t}\r\n\r\n\t\t\t\t\t\tvar transformPropertyExists = false;\r\n\r\n\t\t\t\t\t\t/**********************************\r\n\t\t\t\t\t\t Display & Visibility Toggling\r\n\t\t\t\t\t\t **********************************/\r\n\r\n\t\t\t\t\t\t/* If the display option is set to non-\"none\", set it upfront so that the element can become visible before tweening begins.\r\n\t\t\t\t\t\t (Otherwise, display's \"none\" value is set in completeCall() once the animation has completed.) */\r\n\t\t\t\t\t\tif (opts.display !== undefined && opts.display !== null && opts.display !== \"none\") {\r\n\t\t\t\t\t\t\tif (opts.display === \"flex\") {\r\n\t\t\t\t\t\t\t\tvar flexValues = [\"-webkit-box\", \"-moz-box\", \"-ms-flexbox\", \"-webkit-flex\"];\r\n\r\n\t\t\t\t\t\t\t\t$.each(flexValues, function(i, flexValue) {\r\n\t\t\t\t\t\t\t\t\tCSS.setPropertyValue(element, \"display\", flexValue);\r\n\t\t\t\t\t\t\t\t});\r\n\t\t\t\t\t\t\t}\r\n\r\n\t\t\t\t\t\t\tCSS.setPropertyValue(element, \"display\", opts.display);\r\n\t\t\t\t\t\t}\r\n\r\n\t\t\t\t\t\t/* Same goes with the visibility option, but its \"none\" equivalent is \"hidden\". */\r\n\t\t\t\t\t\tif (opts.visibility !== undefined && opts.visibility !== \"hidden\") {\r\n\t\t\t\t\t\t\tCSS.setPropertyValue(element, \"visibility\", opts.visibility);\r\n\t\t\t\t\t\t}\r\n\r\n\t\t\t\t\t\t/************************\r\n\t\t\t\t\t\t Property Iteration\r\n\t\t\t\t\t\t ************************/\r\n\r\n\t\t\t\t\t\t/* For every element, iterate through each property. */\r\n\t\t\t\t\t\tfor (var property in tweensContainer) {\r\n\t\t\t\t\t\t\t/* Note: In addition to property tween data, tweensContainer contains a reference to its associated element. */\r\n\t\t\t\t\t\t\tif (tweensContainer.hasOwnProperty(property) && property !== \"element\") {\r\n\t\t\t\t\t\t\t\tvar tween = tweensContainer[property],\r\n\t\t\t\t\t\t\t\t\t\tcurrentValue,\r\n\t\t\t\t\t\t\t\t\t\t/* Easing can either be a pre-genereated function or a string that references a pre-registered easing\r\n\t\t\t\t\t\t\t\t\t\t on the Velocity.Easings object. In either case, return the appropriate easing *function*. */\r\n\t\t\t\t\t\t\t\t\t\teasing = Type.isString(tween.easing) ? Velocity.Easings[tween.easing] : tween.easing;\r\n\r\n\t\t\t\t\t\t\t\t/******************************\r\n\t\t\t\t\t\t\t\t Current Value Calculation\r\n\t\t\t\t\t\t\t\t ******************************/\r\n\r\n\t\t\t\t\t\t\t\tif (Type.isString(tween.pattern)) {\r\n\t\t\t\t\t\t\t\t\tvar patternReplace = percentComplete === 1 ?\r\n\t\t\t\t\t\t\t\t\t\t\tfunction($0, index, round) {\r\n\t\t\t\t\t\t\t\t\t\t\t\tvar result = tween.endValue[index];\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\treturn round ? Math.round(result) : result;\r\n\t\t\t\t\t\t\t\t\t\t\t} :\r\n\t\t\t\t\t\t\t\t\t\t\tfunction($0, index, round) {\r\n\t\t\t\t\t\t\t\t\t\t\t\tvar startValue = tween.startValue[index],\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\ttweenDelta = tween.endValue[index] - startValue,\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tresult = startValue + (tweenDelta * easing(percentComplete, opts, tweenDelta));\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\treturn round ? Math.round(result) : result;\r\n\t\t\t\t\t\t\t\t\t\t\t};\r\n\r\n\t\t\t\t\t\t\t\t\tcurrentValue = tween.pattern.replace(/{(\\d+)(!)?}/g, patternReplace);\r\n\t\t\t\t\t\t\t\t} else if (percentComplete === 1) {\r\n\t\t\t\t\t\t\t\t\t/* If this is the last tick pass (if we've reached 100% completion for this tween),\r\n\t\t\t\t\t\t\t\t\t ensure that currentValue is explicitly set to its target endValue so that it's not subjected to any rounding. */\r\n\t\t\t\t\t\t\t\t\tcurrentValue = tween.endValue;\r\n\t\t\t\t\t\t\t\t} else {\r\n\t\t\t\t\t\t\t\t\t/* Otherwise, calculate currentValue based on the current delta from startValue. */\r\n\t\t\t\t\t\t\t\t\tvar tweenDelta = tween.endValue - tween.startValue;\r\n\r\n\t\t\t\t\t\t\t\t\tcurrentValue = tween.startValue + (tweenDelta * easing(percentComplete, opts, tweenDelta));\r\n\t\t\t\t\t\t\t\t\t/* If no value change is occurring, don't proceed with DOM updating. */\r\n\t\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\t\tif (!firstTick && (currentValue === tween.currentValue)) {\r\n\t\t\t\t\t\t\t\t\tcontinue;\r\n\t\t\t\t\t\t\t\t}\r\n\r\n\t\t\t\t\t\t\t\ttween.currentValue = currentValue;\r\n\r\n\t\t\t\t\t\t\t\t/* If we're tweening a fake 'tween' property in order to log transition values, update the one-per-call variable so that\r\n\t\t\t\t\t\t\t\t it can be passed into the progress callback. */\r\n\t\t\t\t\t\t\t\tif (property === \"tween\") {\r\n\t\t\t\t\t\t\t\t\ttweenDummyValue = currentValue;\r\n\t\t\t\t\t\t\t\t} else {\r\n\t\t\t\t\t\t\t\t\t/******************\r\n\t\t\t\t\t\t\t\t\t Hooks: Part I\r\n\t\t\t\t\t\t\t\t\t ******************/\r\n\t\t\t\t\t\t\t\t\tvar hookRoot;\r\n\r\n\t\t\t\t\t\t\t\t\t/* For hooked properties, the newly-updated rootPropertyValueCache is cached onto the element so that it can be used\r\n\t\t\t\t\t\t\t\t\t for subsequent hooks in this call that are associated with the same root property. If we didn't cache the updated\r\n\t\t\t\t\t\t\t\t\t rootPropertyValue, each subsequent update to the root property in this tick pass would reset the previous hook's\r\n\t\t\t\t\t\t\t\t\t updates to rootPropertyValue prior to injection. A nice performance byproduct of rootPropertyValue caching is that\r\n\t\t\t\t\t\t\t\t\t subsequently chained animations using the same hookRoot but a different hook can use this cached rootPropertyValue. */\r\n\t\t\t\t\t\t\t\t\tif (CSS.Hooks.registered[property]) {\r\n\t\t\t\t\t\t\t\t\t\thookRoot = CSS.Hooks.getRoot(property);\r\n\r\n\t\t\t\t\t\t\t\t\t\tvar rootPropertyValueCache = Data(element).rootPropertyValueCache[hookRoot];\r\n\r\n\t\t\t\t\t\t\t\t\t\tif (rootPropertyValueCache) {\r\n\t\t\t\t\t\t\t\t\t\t\ttween.rootPropertyValue = rootPropertyValueCache;\r\n\t\t\t\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\t\t\t}\r\n\r\n\t\t\t\t\t\t\t\t\t/*****************\r\n\t\t\t\t\t\t\t\t\t DOM Update\r\n\t\t\t\t\t\t\t\t\t *****************/\r\n\r\n\t\t\t\t\t\t\t\t\t/* setPropertyValue() returns an array of the property name and property value post any normalization that may have been performed. */\r\n\t\t\t\t\t\t\t\t\t/* Note: To solve an IE<=8 positioning bug, the unit type is dropped when setting a property value of 0. */\r\n\t\t\t\t\t\t\t\t\tvar adjustedSetData = CSS.setPropertyValue(element, /* SET */\r\n\t\t\t\t\t\t\t\t\t\t\tproperty,\r\n\t\t\t\t\t\t\t\t\t\t\ttween.currentValue + (IE < 9 && parseFloat(currentValue) === 0 ? \"\" : tween.unitType),\r\n\t\t\t\t\t\t\t\t\t\t\ttween.rootPropertyValue,\r\n\t\t\t\t\t\t\t\t\t\t\ttween.scrollData);\r\n\r\n\t\t\t\t\t\t\t\t\t/*******************\r\n\t\t\t\t\t\t\t\t\t Hooks: Part II\r\n\t\t\t\t\t\t\t\t\t *******************/\r\n\r\n\t\t\t\t\t\t\t\t\t/* Now that we have the hook's updated rootPropertyValue (the post-processed value provided by adjustedSetData), cache it onto the element. */\r\n\t\t\t\t\t\t\t\t\tif (CSS.Hooks.registered[property]) {\r\n\t\t\t\t\t\t\t\t\t\t/* Since adjustedSetData contains normalized data ready for DOM updating, the rootPropertyValue needs to be re-extracted from its normalized form. ?? */\r\n\t\t\t\t\t\t\t\t\t\tif (CSS.Normalizations.registered[hookRoot]) {\r\n\t\t\t\t\t\t\t\t\t\t\tData(element).rootPropertyValueCache[hookRoot] = CSS.Normalizations.registered[hookRoot](\"extract\", null, adjustedSetData[1]);\r\n\t\t\t\t\t\t\t\t\t\t} else {\r\n\t\t\t\t\t\t\t\t\t\t\tData(element).rootPropertyValueCache[hookRoot] = adjustedSetData[1];\r\n\t\t\t\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\t\t\t}\r\n\r\n\t\t\t\t\t\t\t\t\t/***************\r\n\t\t\t\t\t\t\t\t\t Transforms\r\n\t\t\t\t\t\t\t\t\t ***************/\r\n\r\n\t\t\t\t\t\t\t\t\t/* Flag whether a transform property is being animated so that flushTransformCache() can be triggered once this tick pass is complete. */\r\n\t\t\t\t\t\t\t\t\tif (adjustedSetData[0] === \"transform\") {\r\n\t\t\t\t\t\t\t\t\t\ttransformPropertyExists = true;\r\n\t\t\t\t\t\t\t\t\t}\r\n\r\n\t\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t}\r\n\r\n\t\t\t\t\t\t/****************\r\n\t\t\t\t\t\t mobileHA\r\n\t\t\t\t\t\t ****************/\r\n\r\n\t\t\t\t\t\t/* If mobileHA is enabled, set the translate3d transform to null to force hardware acceleration.\r\n\t\t\t\t\t\t It's safe to override this property since Velocity doesn't actually support its animation (hooks are used in its place). */\r\n\t\t\t\t\t\tif (opts.mobileHA) {\r\n\t\t\t\t\t\t\t/* Don't set the null transform hack if we've already done so. */\r\n\t\t\t\t\t\t\tif (Data(element).transformCache.translate3d === undefined) {\r\n\t\t\t\t\t\t\t\t/* All entries on the transformCache object are later concatenated into a single transform string via flushTransformCache(). */\r\n\t\t\t\t\t\t\t\tData(element).transformCache.translate3d = \"(0px, 0px, 0px)\";\r\n\r\n\t\t\t\t\t\t\t\ttransformPropertyExists = true;\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t}\r\n\r\n\t\t\t\t\t\tif (transformPropertyExists) {\r\n\t\t\t\t\t\t\tCSS.flushTransformCache(element);\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n\r\n\t\t\t\t\t/* The non-\"none\" display value is only applied to an element once -- when its associated call is first ticked through.\r\n\t\t\t\t\t Accordingly, it's set to false so that it isn't re-processed by this call in the next tick. */\r\n\t\t\t\t\tif (opts.display !== undefined && opts.display !== \"none\") {\r\n\t\t\t\t\t\tVelocity.State.calls[i][2].display = false;\r\n\t\t\t\t\t}\r\n\t\t\t\t\tif (opts.visibility !== undefined && opts.visibility !== \"hidden\") {\r\n\t\t\t\t\t\tVelocity.State.calls[i][2].visibility = false;\r\n\t\t\t\t\t}\r\n\r\n\t\t\t\t\t/* Pass the elements and the timing data (percentComplete, msRemaining, timeStart, tweenDummyValue) into the progress callback. */\r\n\t\t\t\t\tif (opts.progress) {\r\n\t\t\t\t\t\topts.progress.call(callContainer[1],\r\n\t\t\t\t\t\t\t\tcallContainer[1],\r\n\t\t\t\t\t\t\t\tpercentComplete,\r\n\t\t\t\t\t\t\t\tMath.max(0, (timeStart + opts.duration) - timeCurrent),\r\n\t\t\t\t\t\t\t\ttimeStart,\r\n\t\t\t\t\t\t\t\ttweenDummyValue);\r\n\t\t\t\t\t}\r\n\r\n\t\t\t\t\t/* If this call has finished tweening, pass its index to completeCall() to handle call cleanup. */\r\n\t\t\t\t\tif (percentComplete === 1) {\r\n\t\t\t\t\t\tcompleteCall(i);\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t}\r\n\r\n\t\t\t/* Note: completeCall() sets the isTicking flag to false when the last call on Velocity.State.calls has completed. */\r\n\t\t\tif (Velocity.State.isTicking) {\r\n\t\t\t\tticker(tick);\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\t/**********************\r\n\t\t Call Completion\r\n\t\t **********************/\r\n\r\n\t\t/* Note: Unlike tick(), which processes all active calls at once, call completion is handled on a per-call basis. */\r\n\t\tfunction completeCall(callIndex, isStopped) {\r\n\t\t\t/* Ensure the call exists. */\r\n\t\t\tif (!Velocity.State.calls[callIndex]) {\r\n\t\t\t\treturn false;\r\n\t\t\t}\r\n\r\n\t\t\t/* Pull the metadata from the call. */\r\n\t\t\tvar call = Velocity.State.calls[callIndex][0],\r\n\t\t\t\t\telements = Velocity.State.calls[callIndex][1],\r\n\t\t\t\t\topts = Velocity.State.calls[callIndex][2],\r\n\t\t\t\t\tresolver = Velocity.State.calls[callIndex][4];\r\n\r\n\t\t\tvar remainingCallsExist = false;\r\n\r\n\t\t\t/*************************\r\n\t\t\t Element Finalization\r\n\t\t\t *************************/\r\n\r\n\t\t\tfor (var i = 0, callLength = call.length; i < callLength; i++) {\r\n\t\t\t\tvar element = call[i].element;\r\n\r\n\t\t\t\t/* If the user set display to \"none\" (intending to hide the element), set it now that the animation has completed. */\r\n\t\t\t\t/* Note: display:none isn't set when calls are manually stopped (via Velocity(\"stop\"). */\r\n\t\t\t\t/* Note: Display gets ignored with \"reverse\" calls and infinite loops, since this behavior would be undesirable. */\r\n\t\t\t\tif (!isStopped && !opts.loop) {\r\n\t\t\t\t\tif (opts.display === \"none\") {\r\n\t\t\t\t\t\tCSS.setPropertyValue(element, \"display\", opts.display);\r\n\t\t\t\t\t}\r\n\r\n\t\t\t\t\tif (opts.visibility === \"hidden\") {\r\n\t\t\t\t\t\tCSS.setPropertyValue(element, \"visibility\", opts.visibility);\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\r\n\t\t\t\t/* If the element's queue is empty (if only the \"inprogress\" item is left at position 0) or if its queue is about to run\r\n\t\t\t\t a non-Velocity-initiated entry, turn off the isAnimating flag. A non-Velocity-initiatied queue entry's logic might alter\r\n\t\t\t\t an element's CSS values and thereby cause Velocity's cached value data to go stale. To detect if a queue entry was initiated by Velocity,\r\n\t\t\t\t we check for the existence of our special Velocity.queueEntryFlag declaration, which minifiers won't rename since the flag\r\n\t\t\t\t is assigned to jQuery's global $ object and thus exists out of Velocity's own scope. */\r\n\t\t\t\tvar data = Data(element);\r\n\r\n\t\t\t\tif (opts.loop !== true && ($.queue(element)[1] === undefined || !/\\.velocityQueueEntryFlag/i.test($.queue(element)[1]))) {\r\n\t\t\t\t\t/* The element may have been deleted. Ensure that its data cache still exists before acting on it. */\r\n\t\t\t\t\tif (data) {\r\n\t\t\t\t\t\tdata.isAnimating = false;\r\n\t\t\t\t\t\t/* Clear the element's rootPropertyValueCache, which will become stale. */\r\n\t\t\t\t\t\tdata.rootPropertyValueCache = {};\r\n\r\n\t\t\t\t\t\tvar transformHAPropertyExists = false;\r\n\t\t\t\t\t\t/* If any 3D transform subproperty is at its default value (regardless of unit type), remove it. */\r\n\t\t\t\t\t\t$.each(CSS.Lists.transforms3D, function(i, transformName) {\r\n\t\t\t\t\t\t\tvar defaultValue = /^scale/.test(transformName) ? 1 : 0,\r\n\t\t\t\t\t\t\t\t\tcurrentValue = data.transformCache[transformName];\r\n\r\n\t\t\t\t\t\t\tif (data.transformCache[transformName] !== undefined && new RegExp(\"^\\\\(\" + defaultValue + \"[^.]\").test(currentValue)) {\r\n\t\t\t\t\t\t\t\ttransformHAPropertyExists = true;\r\n\r\n\t\t\t\t\t\t\t\tdelete data.transformCache[transformName];\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t});\r\n\r\n\t\t\t\t\t\t/* Mobile devices have hardware acceleration removed at the end of the animation in order to avoid hogging the GPU's memory. */\r\n\t\t\t\t\t\tif (opts.mobileHA) {\r\n\t\t\t\t\t\t\ttransformHAPropertyExists = true;\r\n\t\t\t\t\t\t\tdelete data.transformCache.translate3d;\r\n\t\t\t\t\t\t}\r\n\r\n\t\t\t\t\t\t/* Flush the subproperty removals to the DOM. */\r\n\t\t\t\t\t\tif (transformHAPropertyExists) {\r\n\t\t\t\t\t\t\tCSS.flushTransformCache(element);\r\n\t\t\t\t\t\t}\r\n\r\n\t\t\t\t\t\t/* Remove the \"velocity-animating\" indicator class. */\r\n\t\t\t\t\t\tCSS.Values.removeClass(element, \"velocity-animating\");\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\r\n\t\t\t\t/*********************\r\n\t\t\t\t Option: Complete\r\n\t\t\t\t *********************/\r\n\r\n\t\t\t\t/* Complete is fired once per call (not once per element) and is passed the full raw DOM element set as both its context and its first argument. */\r\n\t\t\t\t/* Note: Callbacks aren't fired when calls are manually stopped (via Velocity(\"stop\"). */\r\n\t\t\t\tif (!isStopped && opts.complete && !opts.loop && (i === callLength - 1)) {\r\n\t\t\t\t\t/* We throw callbacks in a setTimeout so that thrown errors don't halt the execution of Velocity itself. */\r\n\t\t\t\t\ttry {\r\n\t\t\t\t\t\topts.complete.call(elements, elements);\r\n\t\t\t\t\t} catch (error) {\r\n\t\t\t\t\t\tsetTimeout(function() {\r\n\t\t\t\t\t\t\tthrow error;\r\n\t\t\t\t\t\t}, 1);\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\r\n\t\t\t\t/**********************\r\n\t\t\t\t Promise Resolving\r\n\t\t\t\t **********************/\r\n\r\n\t\t\t\t/* Note: Infinite loops don't return promises. */\r\n\t\t\t\tif (resolver && opts.loop !== true) {\r\n\t\t\t\t\tresolver(elements);\r\n\t\t\t\t}\r\n\r\n\t\t\t\t/****************************\r\n\t\t\t\t Option: Loop (Infinite)\r\n\t\t\t\t ****************************/\r\n\r\n\t\t\t\tif (data && opts.loop === true && !isStopped) {\r\n\t\t\t\t\t/* If a rotateX/Y/Z property is being animated by 360 deg with loop:true, swap tween start/end values to enable\r\n\t\t\t\t\t continuous iterative rotation looping. (Otherise, the element would just rotate back and forth.) */\r\n\t\t\t\t\t$.each(data.tweensContainer, function(propertyName, tweenContainer) {\r\n\t\t\t\t\t\tif (/^rotate/.test(propertyName) && ((parseFloat(tweenContainer.startValue) - parseFloat(tweenContainer.endValue)) % 360 === 0)) {\r\n\t\t\t\t\t\t\tvar oldStartValue = tweenContainer.startValue;\r\n\r\n\t\t\t\t\t\t\ttweenContainer.startValue = tweenContainer.endValue;\r\n\t\t\t\t\t\t\ttweenContainer.endValue = oldStartValue;\r\n\t\t\t\t\t\t}\r\n\r\n\t\t\t\t\t\tif (/^backgroundPosition/.test(propertyName) && parseFloat(tweenContainer.endValue) === 100 && tweenContainer.unitType === \"%\") {\r\n\t\t\t\t\t\t\ttweenContainer.endValue = 0;\r\n\t\t\t\t\t\t\ttweenContainer.startValue = 100;\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t});\r\n\r\n\t\t\t\t\tVelocity(element, \"reverse\", {loop: true, delay: opts.delay});\r\n\t\t\t\t}\r\n\r\n\t\t\t\t/***************\r\n\t\t\t\t Dequeueing\r\n\t\t\t\t ***************/\r\n\r\n\t\t\t\t/* Fire the next call in the queue so long as this call's queue wasn't set to false (to trigger a parallel animation),\r\n\t\t\t\t which would have already caused the next call to fire. Note: Even if the end of the animation queue has been reached,\r\n\t\t\t\t $.dequeue() must still be called in order to completely clear jQuery's animation queue. */\r\n\t\t\t\tif (opts.queue !== false) {\r\n\t\t\t\t\t$.dequeue(element, opts.queue);\r\n\t\t\t\t}\r\n\t\t\t}\r\n\r\n\t\t\t/************************\r\n\t\t\t Calls Array Cleanup\r\n\t\t\t ************************/\r\n\r\n\t\t\t/* Since this call is complete, set it to false so that the rAF tick skips it. This array is later compacted via compactSparseArray().\r\n\t\t\t (For performance reasons, the call is set to false instead of being deleted from the array: http://www.html5rocks.com/en/tutorials/speed/v8/) */\r\n\t\t\tVelocity.State.calls[callIndex] = false;\r\n\r\n\t\t\t/* Iterate through the calls array to determine if this was the final in-progress animation.\r\n\t\t\t If so, set a flag to end ticking and clear the calls array. */\r\n\t\t\tfor (var j = 0, callsLength = Velocity.State.calls.length; j < callsLength; j++) {\r\n\t\t\t\tif (Velocity.State.calls[j] !== false) {\r\n\t\t\t\t\tremainingCallsExist = true;\r\n\r\n\t\t\t\t\tbreak;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\r\n\t\t\tif (remainingCallsExist === false) {\r\n\t\t\t\t/* tick() will detect this flag upon its next iteration and subsequently turn itself off. */\r\n\t\t\t\tVelocity.State.isTicking = false;\r\n\r\n\t\t\t\t/* Clear the calls array so that its length is reset. */\r\n\t\t\t\tdelete Velocity.State.calls;\r\n\t\t\t\tVelocity.State.calls = [];\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\t/******************\r\n\t\t Frameworks\r\n\t\t ******************/\r\n\r\n\t\t/* Both jQuery and Zepto allow their $.fn object to be extended to allow wrapped elements to be subjected to plugin calls.\r\n\t\t If either framework is loaded, register a \"velocity\" extension pointing to Velocity's core animate() method. Velocity\r\n\t\t also registers itself onto a global container (window.jQuery || window.Zepto || window) so that certain features are\r\n\t\t accessible beyond just a per-element scope. This master object contains an .animate() method, which is later assigned to $.fn\r\n\t\t (if jQuery or Zepto are present). Accordingly, Velocity can both act on wrapped DOM elements and stand alone for targeting raw DOM elements. */\r\n\t\tglobal.Velocity = Velocity;\r\n\r\n\t\tif (global !== window) {\r\n\t\t\t/* Assign the element function to Velocity's core animate() method. */\r\n\t\t\tglobal.fn.velocity = animate;\r\n\t\t\t/* Assign the object function's defaults to Velocity's global defaults object. */\r\n\t\t\tglobal.fn.velocity.defaults = Velocity.defaults;\r\n\t\t}\r\n\r\n\t\t/***********************\r\n\t\t Packaged Redirects\r\n\t\t ***********************/\r\n\r\n\t\t/* slideUp, slideDown */\r\n\t\t$.each([\"Down\", \"Up\"], function(i, direction) {\r\n\t\t\tVelocity.Redirects[\"slide\" + direction] = function(element, options, elementsIndex, elementsSize, elements, promiseData) {\r\n\t\t\t\tvar opts = $.extend({}, options),\r\n\t\t\t\t\t\tbegin = opts.begin,\r\n\t\t\t\t\t\tcomplete = opts.complete,\r\n\t\t\t\t\t\tinlineValues = {},\r\n\t\t\t\t\t\tcomputedValues = {height: \"\", marginTop: \"\", marginBottom: \"\", paddingTop: \"\", paddingBottom: \"\"};\r\n\r\n\t\t\t\tif (opts.display === undefined) {\r\n\t\t\t\t\t/* Show the element before slideDown begins and hide the element after slideUp completes. */\r\n\t\t\t\t\t/* Note: Inline elements cannot have dimensions animated, so they're reverted to inline-block. */\r\n\t\t\t\t\topts.display = (direction === \"Down\" ? (Velocity.CSS.Values.getDisplayType(element) === \"inline\" ? \"inline-block\" : \"block\") : \"none\");\r\n\t\t\t\t}\r\n\r\n\t\t\t\topts.begin = function() {\r\n\t\t\t\t\t/* If the user passed in a begin callback, fire it now. */\r\n\t\t\t\t\tif (elementsIndex === 0 && begin) {\r\n\t\t\t\t\t\tbegin.call(elements, elements);\r\n\t\t\t\t\t}\r\n\r\n\t\t\t\t\t/* Cache the elements' original vertical dimensional property values so that we can animate back to them. */\r\n\t\t\t\t\tfor (var property in computedValues) {\r\n\t\t\t\t\t\tif (!computedValues.hasOwnProperty(property)) {\r\n\t\t\t\t\t\t\tcontinue;\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t\tinlineValues[property] = element.style[property];\r\n\r\n\t\t\t\t\t\t/* For slideDown, use forcefeeding to animate all vertical properties from 0. For slideUp,\r\n\t\t\t\t\t\t use forcefeeding to start from computed values and animate down to 0. */\r\n\t\t\t\t\t\tvar propertyValue = CSS.getPropertyValue(element, property);\r\n\t\t\t\t\t\tcomputedValues[property] = (direction === \"Down\") ? [propertyValue, 0] : [0, propertyValue];\r\n\t\t\t\t\t}\r\n\r\n\t\t\t\t\t/* Force vertical overflow content to clip so that sliding works as expected. */\r\n\t\t\t\t\tinlineValues.overflow = element.style.overflow;\r\n\t\t\t\t\telement.style.overflow = \"hidden\";\r\n\t\t\t\t};\r\n\r\n\t\t\t\topts.complete = function() {\r\n\t\t\t\t\t/* Reset element to its pre-slide inline values once its slide animation is complete. */\r\n\t\t\t\t\tfor (var property in inlineValues) {\r\n\t\t\t\t\t\tif (inlineValues.hasOwnProperty(property)) {\r\n\t\t\t\t\t\t\telement.style[property] = inlineValues[property];\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n\r\n\t\t\t\t\t/* If the user passed in a complete callback, fire it now. */\r\n\t\t\t\t\tif (elementsIndex === elementsSize - 1) {\r\n\t\t\t\t\t\tif (complete) {\r\n\t\t\t\t\t\t\tcomplete.call(elements, elements);\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t\tif (promiseData) {\r\n\t\t\t\t\t\t\tpromiseData.resolver(elements);\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n\t\t\t\t};\r\n\r\n\t\t\t\tVelocity(element, computedValues, opts);\r\n\t\t\t};\r\n\t\t});\r\n\r\n\t\t/* fadeIn, fadeOut */\r\n\t\t$.each([\"In\", \"Out\"], function(i, direction) {\r\n\t\t\tVelocity.Redirects[\"fade\" + direction] = function(element, options, elementsIndex, elementsSize, elements, promiseData) {\r\n\t\t\t\tvar opts = $.extend({}, options),\r\n\t\t\t\t\t\tcomplete = opts.complete,\r\n\t\t\t\t\t\tpropertiesMap = {opacity: (direction === \"In\") ? 1 : 0};\r\n\r\n\t\t\t\t/* Since redirects are triggered individually for each element in the animated set, avoid repeatedly triggering\r\n\t\t\t\t callbacks by firing them only when the final element has been reached. */\r\n\t\t\t\tif (elementsIndex !== 0) {\r\n\t\t\t\t\topts.begin = null;\r\n\t\t\t\t}\r\n\t\t\t\tif (elementsIndex !== elementsSize - 1) {\r\n\t\t\t\t\topts.complete = null;\r\n\t\t\t\t} else {\r\n\t\t\t\t\topts.complete = function() {\r\n\t\t\t\t\t\tif (complete) {\r\n\t\t\t\t\t\t\tcomplete.call(elements, elements);\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t\tif (promiseData) {\r\n\t\t\t\t\t\t\tpromiseData.resolver(elements);\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t};\r\n\t\t\t\t}\r\n\r\n\t\t\t\t/* If a display was passed in, use it. Otherwise, default to \"none\" for fadeOut or the element-specific default for fadeIn. */\r\n\t\t\t\t/* Note: We allow users to pass in \"null\" to skip display setting altogether. */\r\n\t\t\t\tif (opts.display === undefined) {\r\n\t\t\t\t\topts.display = (direction === \"In\" ? \"auto\" : \"none\");\r\n\t\t\t\t}\r\n\r\n\t\t\t\tVelocity(this, propertiesMap, opts);\r\n\t\t\t};\r\n\t\t});\r\n\r\n\t\treturn Velocity;\r\n\t}((window.jQuery || window.Zepto || window), window, (window ? window.document : undefined));\r\n}));\r\n\r\n/******************\r\n Known Issues\r\n ******************/\r\n\r\n/* The CSS spec mandates that the translateX/Y/Z transforms are %-relative to the element itself -- not its parent.\r\n Velocity, however, doesn't make this distinction. Thus, converting to or from the % unit with these subproperties\r\n will produce an inaccurate conversion value. The same issue exists with the cx/cy attributes of SVG circles and ellipses. */\r\n", "//! moment.js\n//! version : 2.29.0\n//! authors : Tim Wood, Iskren Chernev, Moment.js contributors\n//! license : MIT\n//! momentjs.com\n\n;(function (global, factory) {\n typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :\n typeof define === 'function' && define.amd ? define(factory) :\n global.moment = factory()\n}(this, (function () { 'use strict';\n\n var hookCallback;\n\n function hooks() {\n return hookCallback.apply(null, arguments);\n }\n\n // This is done to register the method called with moment()\n // without creating circular dependencies.\n function setHookCallback(callback) {\n hookCallback = callback;\n }\n\n function isArray(input) {\n return (\n input instanceof Array ||\n Object.prototype.toString.call(input) === '[object Array]'\n );\n }\n\n function isObject(input) {\n // IE8 will treat undefined and null as object if it wasn't for\n // input != null\n return (\n input != null &&\n Object.prototype.toString.call(input) === '[object Object]'\n );\n }\n\n function hasOwnProp(a, b) {\n return Object.prototype.hasOwnProperty.call(a, b);\n }\n\n function isObjectEmpty(obj) {\n if (Object.getOwnPropertyNames) {\n return Object.getOwnPropertyNames(obj).length === 0;\n } else {\n var k;\n for (k in obj) {\n if (hasOwnProp(obj, k)) {\n return false;\n }\n }\n return true;\n }\n }\n\n function isUndefined(input) {\n return input === void 0;\n }\n\n function isNumber(input) {\n return (\n typeof input === 'number' ||\n Object.prototype.toString.call(input) === '[object Number]'\n );\n }\n\n function isDate(input) {\n return (\n input instanceof Date ||\n Object.prototype.toString.call(input) === '[object Date]'\n );\n }\n\n function map(arr, fn) {\n var res = [],\n i;\n for (i = 0; i < arr.length; ++i) {\n res.push(fn(arr[i], i));\n }\n return res;\n }\n\n function extend(a, b) {\n for (var i in b) {\n if (hasOwnProp(b, i)) {\n a[i] = b[i];\n }\n }\n\n if (hasOwnProp(b, 'toString')) {\n a.toString = b.toString;\n }\n\n if (hasOwnProp(b, 'valueOf')) {\n a.valueOf = b.valueOf;\n }\n\n return a;\n }\n\n function createUTC(input, format, locale, strict) {\n return createLocalOrUTC(input, format, locale, strict, true).utc();\n }\n\n function defaultParsingFlags() {\n // We need to deep clone this object.\n return {\n empty: false,\n unusedTokens: [],\n unusedInput: [],\n overflow: -2,\n charsLeftOver: 0,\n nullInput: false,\n invalidEra: null,\n invalidMonth: null,\n invalidFormat: false,\n userInvalidated: false,\n iso: false,\n parsedDateParts: [],\n era: null,\n meridiem: null,\n rfc2822: false,\n weekdayMismatch: false,\n };\n }\n\n function getParsingFlags(m) {\n if (m._pf == null) {\n m._pf = defaultParsingFlags();\n }\n return m._pf;\n }\n\n var some;\n if (Array.prototype.some) {\n some = Array.prototype.some;\n } else {\n some = function (fun) {\n var t = Object(this),\n len = t.length >>> 0,\n i;\n\n for (i = 0; i < len; i++) {\n if (i in t && fun.call(this, t[i], i, t)) {\n return true;\n }\n }\n\n return false;\n };\n }\n\n function isValid(m) {\n if (m._isValid == null) {\n var flags = getParsingFlags(m),\n parsedParts = some.call(flags.parsedDateParts, function (i) {\n return i != null;\n }),\n isNowValid =\n !isNaN(m._d.getTime()) &&\n flags.overflow < 0 &&\n !flags.empty &&\n !flags.invalidEra &&\n !flags.invalidMonth &&\n !flags.invalidWeekday &&\n !flags.weekdayMismatch &&\n !flags.nullInput &&\n !flags.invalidFormat &&\n !flags.userInvalidated &&\n (!flags.meridiem || (flags.meridiem && parsedParts));\n\n if (m._strict) {\n isNowValid =\n isNowValid &&\n flags.charsLeftOver === 0 &&\n flags.unusedTokens.length === 0 &&\n flags.bigHour === undefined;\n }\n\n if (Object.isFrozen == null || !Object.isFrozen(m)) {\n m._isValid = isNowValid;\n } else {\n return isNowValid;\n }\n }\n return m._isValid;\n }\n\n function createInvalid(flags) {\n var m = createUTC(NaN);\n if (flags != null) {\n extend(getParsingFlags(m), flags);\n } else {\n getParsingFlags(m).userInvalidated = true;\n }\n\n return m;\n }\n\n // Plugins that add properties should also add the key here (null value),\n // so we can properly clone ourselves.\n var momentProperties = (hooks.momentProperties = []),\n updateInProgress = false;\n\n function copyConfig(to, from) {\n var i, prop, val;\n\n if (!isUndefined(from._isAMomentObject)) {\n to._isAMomentObject = from._isAMomentObject;\n }\n if (!isUndefined(from._i)) {\n to._i = from._i;\n }\n if (!isUndefined(from._f)) {\n to._f = from._f;\n }\n if (!isUndefined(from._l)) {\n to._l = from._l;\n }\n if (!isUndefined(from._strict)) {\n to._strict = from._strict;\n }\n if (!isUndefined(from._tzm)) {\n to._tzm = from._tzm;\n }\n if (!isUndefined(from._isUTC)) {\n to._isUTC = from._isUTC;\n }\n if (!isUndefined(from._offset)) {\n to._offset = from._offset;\n }\n if (!isUndefined(from._pf)) {\n to._pf = getParsingFlags(from);\n }\n if (!isUndefined(from._locale)) {\n to._locale = from._locale;\n }\n\n if (momentProperties.length > 0) {\n for (i = 0; i < momentProperties.length; i++) {\n prop = momentProperties[i];\n val = from[prop];\n if (!isUndefined(val)) {\n to[prop] = val;\n }\n }\n }\n\n return to;\n }\n\n // Moment prototype object\n function Moment(config) {\n copyConfig(this, config);\n this._d = new Date(config._d != null ? config._d.getTime() : NaN);\n if (!this.isValid()) {\n this._d = new Date(NaN);\n }\n // Prevent infinite loop in case updateOffset creates new moment\n // objects.\n if (updateInProgress === false) {\n updateInProgress = true;\n hooks.updateOffset(this);\n updateInProgress = false;\n }\n }\n\n function isMoment(obj) {\n return (\n obj instanceof Moment || (obj != null && obj._isAMomentObject != null)\n );\n }\n\n function warn(msg) {\n if (\n hooks.suppressDeprecationWarnings === false &&\n typeof console !== 'undefined' &&\n console.warn\n ) {\n console.warn('Deprecation warning: ' + msg);\n }\n }\n\n function deprecate(msg, fn) {\n var firstTime = true;\n\n return extend(function () {\n if (hooks.deprecationHandler != null) {\n hooks.deprecationHandler(null, msg);\n }\n if (firstTime) {\n var args = [],\n arg,\n i,\n key;\n for (i = 0; i < arguments.length; i++) {\n arg = '';\n if (typeof arguments[i] === 'object') {\n arg += '\\n[' + i + '] ';\n for (key in arguments[0]) {\n if (hasOwnProp(arguments[0], key)) {\n arg += key + ': ' + arguments[0][key] + ', ';\n }\n }\n arg = arg.slice(0, -2); // Remove trailing comma and space\n } else {\n arg = arguments[i];\n }\n args.push(arg);\n }\n warn(\n msg +\n '\\nArguments: ' +\n Array.prototype.slice.call(args).join('') +\n '\\n' +\n new Error().stack\n );\n firstTime = false;\n }\n return fn.apply(this, arguments);\n }, fn);\n }\n\n var deprecations = {};\n\n function deprecateSimple(name, msg) {\n if (hooks.deprecationHandler != null) {\n hooks.deprecationHandler(name, msg);\n }\n if (!deprecations[name]) {\n warn(msg);\n deprecations[name] = true;\n }\n }\n\n hooks.suppressDeprecationWarnings = false;\n hooks.deprecationHandler = null;\n\n function isFunction(input) {\n return (\n (typeof Function !== 'undefined' && input instanceof Function) ||\n Object.prototype.toString.call(input) === '[object Function]'\n );\n }\n\n function set(config) {\n var prop, i;\n for (i in config) {\n if (hasOwnProp(config, i)) {\n prop = config[i];\n if (isFunction(prop)) {\n this[i] = prop;\n } else {\n this['_' + i] = prop;\n }\n }\n }\n this._config = config;\n // Lenient ordinal parsing accepts just a number in addition to\n // number + (possibly) stuff coming from _dayOfMonthOrdinalParse.\n // TODO: Remove \"ordinalParse\" fallback in next major release.\n this._dayOfMonthOrdinalParseLenient = new RegExp(\n (this._dayOfMonthOrdinalParse.source || this._ordinalParse.source) +\n '|' +\n /\\d{1,2}/.source\n );\n }\n\n function mergeConfigs(parentConfig, childConfig) {\n var res = extend({}, parentConfig),\n prop;\n for (prop in childConfig) {\n if (hasOwnProp(childConfig, prop)) {\n if (isObject(parentConfig[prop]) && isObject(childConfig[prop])) {\n res[prop] = {};\n extend(res[prop], parentConfig[prop]);\n extend(res[prop], childConfig[prop]);\n } else if (childConfig[prop] != null) {\n res[prop] = childConfig[prop];\n } else {\n delete res[prop];\n }\n }\n }\n for (prop in parentConfig) {\n if (\n hasOwnProp(parentConfig, prop) &&\n !hasOwnProp(childConfig, prop) &&\n isObject(parentConfig[prop])\n ) {\n // make sure changes to properties don't modify parent config\n res[prop] = extend({}, res[prop]);\n }\n }\n return res;\n }\n\n function Locale(config) {\n if (config != null) {\n this.set(config);\n }\n }\n\n var keys;\n\n if (Object.keys) {\n keys = Object.keys;\n } else {\n keys = function (obj) {\n var i,\n res = [];\n for (i in obj) {\n if (hasOwnProp(obj, i)) {\n res.push(i);\n }\n }\n return res;\n };\n }\n\n var defaultCalendar = {\n sameDay: '[Today at] LT',\n nextDay: '[Tomorrow at] LT',\n nextWeek: 'dddd [at] LT',\n lastDay: '[Yesterday at] LT',\n lastWeek: '[Last] dddd [at] LT',\n sameElse: 'L',\n };\n\n function calendar(key, mom, now) {\n var output = this._calendar[key] || this._calendar['sameElse'];\n return isFunction(output) ? output.call(mom, now) : output;\n }\n\n function zeroFill(number, targetLength, forceSign) {\n var absNumber = '' + Math.abs(number),\n zerosToFill = targetLength - absNumber.length,\n sign = number >= 0;\n return (\n (sign ? (forceSign ? '+' : '') : '-') +\n Math.pow(10, Math.max(0, zerosToFill)).toString().substr(1) +\n absNumber\n );\n }\n\n var formattingTokens = /(\\[[^\\[]*\\])|(\\\\)?([Hh]mm(ss)?|Mo|MM?M?M?|Do|DDDo|DD?D?D?|ddd?d?|do?|w[o|w]?|W[o|W]?|Qo?|N{1,5}|YYYYYY|YYYYY|YYYY|YY|y{2,4}|yo?|gg(ggg?)?|GG(GGG?)?|e|E|a|A|hh?|HH?|kk?|mm?|ss?|S{1,9}|x|X|zz?|ZZ?|.)/g,\n localFormattingTokens = /(\\[[^\\[]*\\])|(\\\\)?(LTS|LT|LL?L?L?|l{1,4})/g,\n formatFunctions = {},\n formatTokenFunctions = {};\n\n // token: 'M'\n // padded: ['MM', 2]\n // ordinal: 'Mo'\n // callback: function () { this.month() + 1 }\n function addFormatToken(token, padded, ordinal, callback) {\n var func = callback;\n if (typeof callback === 'string') {\n func = function () {\n return this[callback]();\n };\n }\n if (token) {\n formatTokenFunctions[token] = func;\n }\n if (padded) {\n formatTokenFunctions[padded[0]] = function () {\n return zeroFill(func.apply(this, arguments), padded[1], padded[2]);\n };\n }\n if (ordinal) {\n formatTokenFunctions[ordinal] = function () {\n return this.localeData().ordinal(\n func.apply(this, arguments),\n token\n );\n };\n }\n }\n\n function removeFormattingTokens(input) {\n if (input.match(/\\[[\\s\\S]/)) {\n return input.replace(/^\\[|\\]$/g, '');\n }\n return input.replace(/\\\\/g, '');\n }\n\n function makeFormatFunction(format) {\n var array = format.match(formattingTokens),\n i,\n length;\n\n for (i = 0, length = array.length; i < length; i++) {\n if (formatTokenFunctions[array[i]]) {\n array[i] = formatTokenFunctions[array[i]];\n } else {\n array[i] = removeFormattingTokens(array[i]);\n }\n }\n\n return function (mom) {\n var output = '',\n i;\n for (i = 0; i < length; i++) {\n output += isFunction(array[i])\n ? array[i].call(mom, format)\n : array[i];\n }\n return output;\n };\n }\n\n // format date using native date object\n function formatMoment(m, format) {\n if (!m.isValid()) {\n return m.localeData().invalidDate();\n }\n\n format = expandFormat(format, m.localeData());\n formatFunctions[format] =\n formatFunctions[format] || makeFormatFunction(format);\n\n return formatFunctions[format](m);\n }\n\n function expandFormat(format, locale) {\n var i = 5;\n\n function replaceLongDateFormatTokens(input) {\n return locale.longDateFormat(input) || input;\n }\n\n localFormattingTokens.lastIndex = 0;\n while (i >= 0 && localFormattingTokens.test(format)) {\n format = format.replace(\n localFormattingTokens,\n replaceLongDateFormatTokens\n );\n localFormattingTokens.lastIndex = 0;\n i -= 1;\n }\n\n return format;\n }\n\n var defaultLongDateFormat = {\n LTS: 'h:mm:ss A',\n LT: 'h:mm A',\n L: 'MM/DD/YYYY',\n LL: 'MMMM D, YYYY',\n LLL: 'MMMM D, YYYY h:mm A',\n LLLL: 'dddd, MMMM D, YYYY h:mm A',\n };\n\n function longDateFormat(key) {\n var format = this._longDateFormat[key],\n formatUpper = this._longDateFormat[key.toUpperCase()];\n\n if (format || !formatUpper) {\n return format;\n }\n\n this._longDateFormat[key] = formatUpper\n .match(formattingTokens)\n .map(function (tok) {\n if (\n tok === 'MMMM' ||\n tok === 'MM' ||\n tok === 'DD' ||\n tok === 'dddd'\n ) {\n return tok.slice(1);\n }\n return tok;\n })\n .join('');\n\n return this._longDateFormat[key];\n }\n\n var defaultInvalidDate = 'Invalid date';\n\n function invalidDate() {\n return this._invalidDate;\n }\n\n var defaultOrdinal = '%d',\n defaultDayOfMonthOrdinalParse = /\\d{1,2}/;\n\n function ordinal(number) {\n return this._ordinal.replace('%d', number);\n }\n\n var defaultRelativeTime = {\n future: 'in %s',\n past: '%s ago',\n s: 'a few seconds',\n ss: '%d seconds',\n m: 'a minute',\n mm: '%d minutes',\n h: 'an hour',\n hh: '%d hours',\n d: 'a day',\n dd: '%d days',\n w: 'a week',\n ww: '%d weeks',\n M: 'a month',\n MM: '%d months',\n y: 'a year',\n yy: '%d years',\n };\n\n function relativeTime(number, withoutSuffix, string, isFuture) {\n var output = this._relativeTime[string];\n return isFunction(output)\n ? output(number, withoutSuffix, string, isFuture)\n : output.replace(/%d/i, number);\n }\n\n function pastFuture(diff, output) {\n var format = this._relativeTime[diff > 0 ? 'future' : 'past'];\n return isFunction(format) ? format(output) : format.replace(/%s/i, output);\n }\n\n var aliases = {};\n\n function addUnitAlias(unit, shorthand) {\n var lowerCase = unit.toLowerCase();\n aliases[lowerCase] = aliases[lowerCase + 's'] = aliases[shorthand] = unit;\n }\n\n function normalizeUnits(units) {\n return typeof units === 'string'\n ? aliases[units] || aliases[units.toLowerCase()]\n : undefined;\n }\n\n function normalizeObjectUnits(inputObject) {\n var normalizedInput = {},\n normalizedProp,\n prop;\n\n for (prop in inputObject) {\n if (hasOwnProp(inputObject, prop)) {\n normalizedProp = normalizeUnits(prop);\n if (normalizedProp) {\n normalizedInput[normalizedProp] = inputObject[prop];\n }\n }\n }\n\n return normalizedInput;\n }\n\n var priorities = {};\n\n function addUnitPriority(unit, priority) {\n priorities[unit] = priority;\n }\n\n function getPrioritizedUnits(unitsObj) {\n var units = [],\n u;\n for (u in unitsObj) {\n if (hasOwnProp(unitsObj, u)) {\n units.push({ unit: u, priority: priorities[u] });\n }\n }\n units.sort(function (a, b) {\n return a.priority - b.priority;\n });\n return units;\n }\n\n function isLeapYear(year) {\n return (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0;\n }\n\n function absFloor(number) {\n if (number < 0) {\n // -0 -> 0\n return Math.ceil(number) || 0;\n } else {\n return Math.floor(number);\n }\n }\n\n function toInt(argumentForCoercion) {\n var coercedNumber = +argumentForCoercion,\n value = 0;\n\n if (coercedNumber !== 0 && isFinite(coercedNumber)) {\n value = absFloor(coercedNumber);\n }\n\n return value;\n }\n\n function makeGetSet(unit, keepTime) {\n return function (value) {\n if (value != null) {\n set$1(this, unit, value);\n hooks.updateOffset(this, keepTime);\n return this;\n } else {\n return get(this, unit);\n }\n };\n }\n\n function get(mom, unit) {\n return mom.isValid()\n ? mom._d['get' + (mom._isUTC ? 'UTC' : '') + unit]()\n : NaN;\n }\n\n function set$1(mom, unit, value) {\n if (mom.isValid() && !isNaN(value)) {\n if (\n unit === 'FullYear' &&\n isLeapYear(mom.year()) &&\n mom.month() === 1 &&\n mom.date() === 29\n ) {\n value = toInt(value);\n mom._d['set' + (mom._isUTC ? 'UTC' : '') + unit](\n value,\n mom.month(),\n daysInMonth(value, mom.month())\n );\n } else {\n mom._d['set' + (mom._isUTC ? 'UTC' : '') + unit](value);\n }\n }\n }\n\n // MOMENTS\n\n function stringGet(units) {\n units = normalizeUnits(units);\n if (isFunction(this[units])) {\n return this[units]();\n }\n return this;\n }\n\n function stringSet(units, value) {\n if (typeof units === 'object') {\n units = normalizeObjectUnits(units);\n var prioritized = getPrioritizedUnits(units),\n i;\n for (i = 0; i < prioritized.length; i++) {\n this[prioritized[i].unit](units[prioritized[i].unit]);\n }\n } else {\n units = normalizeUnits(units);\n if (isFunction(this[units])) {\n return this[units](value);\n }\n }\n return this;\n }\n\n var match1 = /\\d/, // 0 - 9\n match2 = /\\d\\d/, // 00 - 99\n match3 = /\\d{3}/, // 000 - 999\n match4 = /\\d{4}/, // 0000 - 9999\n match6 = /[+-]?\\d{6}/, // -999999 - 999999\n match1to2 = /\\d\\d?/, // 0 - 99\n match3to4 = /\\d\\d\\d\\d?/, // 999 - 9999\n match5to6 = /\\d\\d\\d\\d\\d\\d?/, // 99999 - 999999\n match1to3 = /\\d{1,3}/, // 0 - 999\n match1to4 = /\\d{1,4}/, // 0 - 9999\n match1to6 = /[+-]?\\d{1,6}/, // -999999 - 999999\n matchUnsigned = /\\d+/, // 0 - inf\n matchSigned = /[+-]?\\d+/, // -inf - inf\n matchOffset = /Z|[+-]\\d\\d:?\\d\\d/gi, // +00:00 -00:00 +0000 -0000 or Z\n matchShortOffset = /Z|[+-]\\d\\d(?::?\\d\\d)?/gi, // +00 -00 +00:00 -00:00 +0000 -0000 or Z\n matchTimestamp = /[+-]?\\d+(\\.\\d{1,3})?/, // 123456789 123456789.123\n // any word (or two) characters or numbers including two/three word month in arabic.\n // includes scottish gaelic two word and hyphenated months\n matchWord = /[0-9]{0,256}['a-z\\u00A0-\\u05FF\\u0700-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFF07\\uFF10-\\uFFEF]{1,256}|[\\u0600-\\u06FF\\/]{1,256}(\\s*?[\\u0600-\\u06FF]{1,256}){1,2}/i,\n regexes;\n\n regexes = {};\n\n function addRegexToken(token, regex, strictRegex) {\n regexes[token] = isFunction(regex)\n ? regex\n : function (isStrict, localeData) {\n return isStrict && strictRegex ? strictRegex : regex;\n };\n }\n\n function getParseRegexForToken(token, config) {\n if (!hasOwnProp(regexes, token)) {\n return new RegExp(unescapeFormat(token));\n }\n\n return regexes[token](config._strict, config._locale);\n }\n\n // Code from http://stackoverflow.com/questions/3561493/is-there-a-regexp-escape-function-in-javascript\n function unescapeFormat(s) {\n return regexEscape(\n s\n .replace('\\\\', '')\n .replace(/\\\\(\\[)|\\\\(\\])|\\[([^\\]\\[]*)\\]|\\\\(.)/g, function (\n matched,\n p1,\n p2,\n p3,\n p4\n ) {\n return p1 || p2 || p3 || p4;\n })\n );\n }\n\n function regexEscape(s) {\n return s.replace(/[-\\/\\\\^$*+?.()|[\\]{}]/g, '\\\\$&');\n }\n\n var tokens = {};\n\n function addParseToken(token, callback) {\n var i,\n func = callback;\n if (typeof token === 'string') {\n token = [token];\n }\n if (isNumber(callback)) {\n func = function (input, array) {\n array[callback] = toInt(input);\n };\n }\n for (i = 0; i < token.length; i++) {\n tokens[token[i]] = func;\n }\n }\n\n function addWeekParseToken(token, callback) {\n addParseToken(token, function (input, array, config, token) {\n config._w = config._w || {};\n callback(input, config._w, config, token);\n });\n }\n\n function addTimeToArrayFromToken(token, input, config) {\n if (input != null && hasOwnProp(tokens, token)) {\n tokens[token](input, config._a, config, token);\n }\n }\n\n var YEAR = 0,\n MONTH = 1,\n DATE = 2,\n HOUR = 3,\n MINUTE = 4,\n SECOND = 5,\n MILLISECOND = 6,\n WEEK = 7,\n WEEKDAY = 8;\n\n function mod(n, x) {\n return ((n % x) + x) % x;\n }\n\n var indexOf;\n\n if (Array.prototype.indexOf) {\n indexOf = Array.prototype.indexOf;\n } else {\n indexOf = function (o) {\n // I know\n var i;\n for (i = 0; i < this.length; ++i) {\n if (this[i] === o) {\n return i;\n }\n }\n return -1;\n };\n }\n\n function daysInMonth(year, month) {\n if (isNaN(year) || isNaN(month)) {\n return NaN;\n }\n var modMonth = mod(month, 12);\n year += (month - modMonth) / 12;\n return modMonth === 1\n ? isLeapYear(year)\n ? 29\n : 28\n : 31 - ((modMonth % 7) % 2);\n }\n\n // FORMATTING\n\n addFormatToken('M', ['MM', 2], 'Mo', function () {\n return this.month() + 1;\n });\n\n addFormatToken('MMM', 0, 0, function (format) {\n return this.localeData().monthsShort(this, format);\n });\n\n addFormatToken('MMMM', 0, 0, function (format) {\n return this.localeData().months(this, format);\n });\n\n // ALIASES\n\n addUnitAlias('month', 'M');\n\n // PRIORITY\n\n addUnitPriority('month', 8);\n\n // PARSING\n\n addRegexToken('M', match1to2);\n addRegexToken('MM', match1to2, match2);\n addRegexToken('MMM', function (isStrict, locale) {\n return locale.monthsShortRegex(isStrict);\n });\n addRegexToken('MMMM', function (isStrict, locale) {\n return locale.monthsRegex(isStrict);\n });\n\n addParseToken(['M', 'MM'], function (input, array) {\n array[MONTH] = toInt(input) - 1;\n });\n\n addParseToken(['MMM', 'MMMM'], function (input, array, config, token) {\n var month = config._locale.monthsParse(input, token, config._strict);\n // if we didn't find a month name, mark the date as invalid.\n if (month != null) {\n array[MONTH] = month;\n } else {\n getParsingFlags(config).invalidMonth = input;\n }\n });\n\n // LOCALES\n\n var defaultLocaleMonths = 'January_February_March_April_May_June_July_August_September_October_November_December'.split(\n '_'\n ),\n defaultLocaleMonthsShort = 'Jan_Feb_Mar_Apr_May_Jun_Jul_Aug_Sep_Oct_Nov_Dec'.split(\n '_'\n ),\n MONTHS_IN_FORMAT = /D[oD]?(\\[[^\\[\\]]*\\]|\\s)+MMMM?/,\n defaultMonthsShortRegex = matchWord,\n defaultMonthsRegex = matchWord;\n\n function localeMonths(m, format) {\n if (!m) {\n return isArray(this._months)\n ? this._months\n : this._months['standalone'];\n }\n return isArray(this._months)\n ? this._months[m.month()]\n : this._months[\n (this._months.isFormat || MONTHS_IN_FORMAT).test(format)\n ? 'format'\n : 'standalone'\n ][m.month()];\n }\n\n function localeMonthsShort(m, format) {\n if (!m) {\n return isArray(this._monthsShort)\n ? this._monthsShort\n : this._monthsShort['standalone'];\n }\n return isArray(this._monthsShort)\n ? this._monthsShort[m.month()]\n : this._monthsShort[\n MONTHS_IN_FORMAT.test(format) ? 'format' : 'standalone'\n ][m.month()];\n }\n\n function handleStrictParse(monthName, format, strict) {\n var i,\n ii,\n mom,\n llc = monthName.toLocaleLowerCase();\n if (!this._monthsParse) {\n // this is not used\n this._monthsParse = [];\n this._longMonthsParse = [];\n this._shortMonthsParse = [];\n for (i = 0; i < 12; ++i) {\n mom = createUTC([2000, i]);\n this._shortMonthsParse[i] = this.monthsShort(\n mom,\n ''\n ).toLocaleLowerCase();\n this._longMonthsParse[i] = this.months(mom, '').toLocaleLowerCase();\n }\n }\n\n if (strict) {\n if (format === 'MMM') {\n ii = indexOf.call(this._shortMonthsParse, llc);\n return ii !== -1 ? ii : null;\n } else {\n ii = indexOf.call(this._longMonthsParse, llc);\n return ii !== -1 ? ii : null;\n }\n } else {\n if (format === 'MMM') {\n ii = indexOf.call(this._shortMonthsParse, llc);\n if (ii !== -1) {\n return ii;\n }\n ii = indexOf.call(this._longMonthsParse, llc);\n return ii !== -1 ? ii : null;\n } else {\n ii = indexOf.call(this._longMonthsParse, llc);\n if (ii !== -1) {\n return ii;\n }\n ii = indexOf.call(this._shortMonthsParse, llc);\n return ii !== -1 ? ii : null;\n }\n }\n }\n\n function localeMonthsParse(monthName, format, strict) {\n var i, mom, regex;\n\n if (this._monthsParseExact) {\n return handleStrictParse.call(this, monthName, format, strict);\n }\n\n if (!this._monthsParse) {\n this._monthsParse = [];\n this._longMonthsParse = [];\n this._shortMonthsParse = [];\n }\n\n // TODO: add sorting\n // Sorting makes sure if one month (or abbr) is a prefix of another\n // see sorting in computeMonthsParse\n for (i = 0; i < 12; i++) {\n // make the regex if we don't have it already\n mom = createUTC([2000, i]);\n if (strict && !this._longMonthsParse[i]) {\n this._longMonthsParse[i] = new RegExp(\n '^' + this.months(mom, '').replace('.', '') + '$',\n 'i'\n );\n this._shortMonthsParse[i] = new RegExp(\n '^' + this.monthsShort(mom, '').replace('.', '') + '$',\n 'i'\n );\n }\n if (!strict && !this._monthsParse[i]) {\n regex =\n '^' + this.months(mom, '') + '|^' + this.monthsShort(mom, '');\n this._monthsParse[i] = new RegExp(regex.replace('.', ''), 'i');\n }\n // test the regex\n if (\n strict &&\n format === 'MMMM' &&\n this._longMonthsParse[i].test(monthName)\n ) {\n return i;\n } else if (\n strict &&\n format === 'MMM' &&\n this._shortMonthsParse[i].test(monthName)\n ) {\n return i;\n } else if (!strict && this._monthsParse[i].test(monthName)) {\n return i;\n }\n }\n }\n\n // MOMENTS\n\n function setMonth(mom, value) {\n var dayOfMonth;\n\n if (!mom.isValid()) {\n // No op\n return mom;\n }\n\n if (typeof value === 'string') {\n if (/^\\d+$/.test(value)) {\n value = toInt(value);\n } else {\n value = mom.localeData().monthsParse(value);\n // TODO: Another silent failure?\n if (!isNumber(value)) {\n return mom;\n }\n }\n }\n\n dayOfMonth = Math.min(mom.date(), daysInMonth(mom.year(), value));\n mom._d['set' + (mom._isUTC ? 'UTC' : '') + 'Month'](value, dayOfMonth);\n return mom;\n }\n\n function getSetMonth(value) {\n if (value != null) {\n setMonth(this, value);\n hooks.updateOffset(this, true);\n return this;\n } else {\n return get(this, 'Month');\n }\n }\n\n function getDaysInMonth() {\n return daysInMonth(this.year(), this.month());\n }\n\n function monthsShortRegex(isStrict) {\n if (this._monthsParseExact) {\n if (!hasOwnProp(this, '_monthsRegex')) {\n computeMonthsParse.call(this);\n }\n if (isStrict) {\n return this._monthsShortStrictRegex;\n } else {\n return this._monthsShortRegex;\n }\n } else {\n if (!hasOwnProp(this, '_monthsShortRegex')) {\n this._monthsShortRegex = defaultMonthsShortRegex;\n }\n return this._monthsShortStrictRegex && isStrict\n ? this._monthsShortStrictRegex\n : this._monthsShortRegex;\n }\n }\n\n function monthsRegex(isStrict) {\n if (this._monthsParseExact) {\n if (!hasOwnProp(this, '_monthsRegex')) {\n computeMonthsParse.call(this);\n }\n if (isStrict) {\n return this._monthsStrictRegex;\n } else {\n return this._monthsRegex;\n }\n } else {\n if (!hasOwnProp(this, '_monthsRegex')) {\n this._monthsRegex = defaultMonthsRegex;\n }\n return this._monthsStrictRegex && isStrict\n ? this._monthsStrictRegex\n : this._monthsRegex;\n }\n }\n\n function computeMonthsParse() {\n function cmpLenRev(a, b) {\n return b.length - a.length;\n }\n\n var shortPieces = [],\n longPieces = [],\n mixedPieces = [],\n i,\n mom;\n for (i = 0; i < 12; i++) {\n // make the regex if we don't have it already\n mom = createUTC([2000, i]);\n shortPieces.push(this.monthsShort(mom, ''));\n longPieces.push(this.months(mom, ''));\n mixedPieces.push(this.months(mom, ''));\n mixedPieces.push(this.monthsShort(mom, ''));\n }\n // Sorting makes sure if one month (or abbr) is a prefix of another it\n // will match the longer piece.\n shortPieces.sort(cmpLenRev);\n longPieces.sort(cmpLenRev);\n mixedPieces.sort(cmpLenRev);\n for (i = 0; i < 12; i++) {\n shortPieces[i] = regexEscape(shortPieces[i]);\n longPieces[i] = regexEscape(longPieces[i]);\n }\n for (i = 0; i < 24; i++) {\n mixedPieces[i] = regexEscape(mixedPieces[i]);\n }\n\n this._monthsRegex = new RegExp('^(' + mixedPieces.join('|') + ')', 'i');\n this._monthsShortRegex = this._monthsRegex;\n this._monthsStrictRegex = new RegExp(\n '^(' + longPieces.join('|') + ')',\n 'i'\n );\n this._monthsShortStrictRegex = new RegExp(\n '^(' + shortPieces.join('|') + ')',\n 'i'\n );\n }\n\n // FORMATTING\n\n addFormatToken('Y', 0, 0, function () {\n var y = this.year();\n return y <= 9999 ? zeroFill(y, 4) : '+' + y;\n });\n\n addFormatToken(0, ['YY', 2], 0, function () {\n return this.year() % 100;\n });\n\n addFormatToken(0, ['YYYY', 4], 0, 'year');\n addFormatToken(0, ['YYYYY', 5], 0, 'year');\n addFormatToken(0, ['YYYYYY', 6, true], 0, 'year');\n\n // ALIASES\n\n addUnitAlias('year', 'y');\n\n // PRIORITIES\n\n addUnitPriority('year', 1);\n\n // PARSING\n\n addRegexToken('Y', matchSigned);\n addRegexToken('YY', match1to2, match2);\n addRegexToken('YYYY', match1to4, match4);\n addRegexToken('YYYYY', match1to6, match6);\n addRegexToken('YYYYYY', match1to6, match6);\n\n addParseToken(['YYYYY', 'YYYYYY'], YEAR);\n addParseToken('YYYY', function (input, array) {\n array[YEAR] =\n input.length === 2 ? hooks.parseTwoDigitYear(input) : toInt(input);\n });\n addParseToken('YY', function (input, array) {\n array[YEAR] = hooks.parseTwoDigitYear(input);\n });\n addParseToken('Y', function (input, array) {\n array[YEAR] = parseInt(input, 10);\n });\n\n // HELPERS\n\n function daysInYear(year) {\n return isLeapYear(year) ? 366 : 365;\n }\n\n // HOOKS\n\n hooks.parseTwoDigitYear = function (input) {\n return toInt(input) + (toInt(input) > 68 ? 1900 : 2000);\n };\n\n // MOMENTS\n\n var getSetYear = makeGetSet('FullYear', true);\n\n function getIsLeapYear() {\n return isLeapYear(this.year());\n }\n\n function createDate(y, m, d, h, M, s, ms) {\n // can't just apply() to create a date:\n // https://stackoverflow.com/q/181348\n var date;\n // the date constructor remaps years 0-99 to 1900-1999\n if (y < 100 && y >= 0) {\n // preserve leap years using a full 400 year cycle, then reset\n date = new Date(y + 400, m, d, h, M, s, ms);\n if (isFinite(date.getFullYear())) {\n date.setFullYear(y);\n }\n } else {\n date = new Date(y, m, d, h, M, s, ms);\n }\n\n return date;\n }\n\n function createUTCDate(y) {\n var date, args;\n // the Date.UTC function remaps years 0-99 to 1900-1999\n if (y < 100 && y >= 0) {\n args = Array.prototype.slice.call(arguments);\n // preserve leap years using a full 400 year cycle, then reset\n args[0] = y + 400;\n date = new Date(Date.UTC.apply(null, args));\n if (isFinite(date.getUTCFullYear())) {\n date.setUTCFullYear(y);\n }\n } else {\n date = new Date(Date.UTC.apply(null, arguments));\n }\n\n return date;\n }\n\n // start-of-first-week - start-of-year\n function firstWeekOffset(year, dow, doy) {\n var // first-week day -- which january is always in the first week (4 for iso, 1 for other)\n fwd = 7 + dow - doy,\n // first-week day local weekday -- which local weekday is fwd\n fwdlw = (7 + createUTCDate(year, 0, fwd).getUTCDay() - dow) % 7;\n\n return -fwdlw + fwd - 1;\n }\n\n // https://en.wikipedia.org/wiki/ISO_week_date#Calculating_a_date_given_the_year.2C_week_number_and_weekday\n function dayOfYearFromWeeks(year, week, weekday, dow, doy) {\n var localWeekday = (7 + weekday - dow) % 7,\n weekOffset = firstWeekOffset(year, dow, doy),\n dayOfYear = 1 + 7 * (week - 1) + localWeekday + weekOffset,\n resYear,\n resDayOfYear;\n\n if (dayOfYear <= 0) {\n resYear = year - 1;\n resDayOfYear = daysInYear(resYear) + dayOfYear;\n } else if (dayOfYear > daysInYear(year)) {\n resYear = year + 1;\n resDayOfYear = dayOfYear - daysInYear(year);\n } else {\n resYear = year;\n resDayOfYear = dayOfYear;\n }\n\n return {\n year: resYear,\n dayOfYear: resDayOfYear,\n };\n }\n\n function weekOfYear(mom, dow, doy) {\n var weekOffset = firstWeekOffset(mom.year(), dow, doy),\n week = Math.floor((mom.dayOfYear() - weekOffset - 1) / 7) + 1,\n resWeek,\n resYear;\n\n if (week < 1) {\n resYear = mom.year() - 1;\n resWeek = week + weeksInYear(resYear, dow, doy);\n } else if (week > weeksInYear(mom.year(), dow, doy)) {\n resWeek = week - weeksInYear(mom.year(), dow, doy);\n resYear = mom.year() + 1;\n } else {\n resYear = mom.year();\n resWeek = week;\n }\n\n return {\n week: resWeek,\n year: resYear,\n };\n }\n\n function weeksInYear(year, dow, doy) {\n var weekOffset = firstWeekOffset(year, dow, doy),\n weekOffsetNext = firstWeekOffset(year + 1, dow, doy);\n return (daysInYear(year) - weekOffset + weekOffsetNext) / 7;\n }\n\n // FORMATTING\n\n addFormatToken('w', ['ww', 2], 'wo', 'week');\n addFormatToken('W', ['WW', 2], 'Wo', 'isoWeek');\n\n // ALIASES\n\n addUnitAlias('week', 'w');\n addUnitAlias('isoWeek', 'W');\n\n // PRIORITIES\n\n addUnitPriority('week', 5);\n addUnitPriority('isoWeek', 5);\n\n // PARSING\n\n addRegexToken('w', match1to2);\n addRegexToken('ww', match1to2, match2);\n addRegexToken('W', match1to2);\n addRegexToken('WW', match1to2, match2);\n\n addWeekParseToken(['w', 'ww', 'W', 'WW'], function (\n input,\n week,\n config,\n token\n ) {\n week[token.substr(0, 1)] = toInt(input);\n });\n\n // HELPERS\n\n // LOCALES\n\n function localeWeek(mom) {\n return weekOfYear(mom, this._week.dow, this._week.doy).week;\n }\n\n var defaultLocaleWeek = {\n dow: 0, // Sunday is the first day of the week.\n doy: 6, // The week that contains Jan 6th is the first week of the year.\n };\n\n function localeFirstDayOfWeek() {\n return this._week.dow;\n }\n\n function localeFirstDayOfYear() {\n return this._week.doy;\n }\n\n // MOMENTS\n\n function getSetWeek(input) {\n var week = this.localeData().week(this);\n return input == null ? week : this.add((input - week) * 7, 'd');\n }\n\n function getSetISOWeek(input) {\n var week = weekOfYear(this, 1, 4).week;\n return input == null ? week : this.add((input - week) * 7, 'd');\n }\n\n // FORMATTING\n\n addFormatToken('d', 0, 'do', 'day');\n\n addFormatToken('dd', 0, 0, function (format) {\n return this.localeData().weekdaysMin(this, format);\n });\n\n addFormatToken('ddd', 0, 0, function (format) {\n return this.localeData().weekdaysShort(this, format);\n });\n\n addFormatToken('dddd', 0, 0, function (format) {\n return this.localeData().weekdays(this, format);\n });\n\n addFormatToken('e', 0, 0, 'weekday');\n addFormatToken('E', 0, 0, 'isoWeekday');\n\n // ALIASES\n\n addUnitAlias('day', 'd');\n addUnitAlias('weekday', 'e');\n addUnitAlias('isoWeekday', 'E');\n\n // PRIORITY\n addUnitPriority('day', 11);\n addUnitPriority('weekday', 11);\n addUnitPriority('isoWeekday', 11);\n\n // PARSING\n\n addRegexToken('d', match1to2);\n addRegexToken('e', match1to2);\n addRegexToken('E', match1to2);\n addRegexToken('dd', function (isStrict, locale) {\n return locale.weekdaysMinRegex(isStrict);\n });\n addRegexToken('ddd', function (isStrict, locale) {\n return locale.weekdaysShortRegex(isStrict);\n });\n addRegexToken('dddd', function (isStrict, locale) {\n return locale.weekdaysRegex(isStrict);\n });\n\n addWeekParseToken(['dd', 'ddd', 'dddd'], function (input, week, config, token) {\n var weekday = config._locale.weekdaysParse(input, token, config._strict);\n // if we didn't get a weekday name, mark the date as invalid\n if (weekday != null) {\n week.d = weekday;\n } else {\n getParsingFlags(config).invalidWeekday = input;\n }\n });\n\n addWeekParseToken(['d', 'e', 'E'], function (input, week, config, token) {\n week[token] = toInt(input);\n });\n\n // HELPERS\n\n function parseWeekday(input, locale) {\n if (typeof input !== 'string') {\n return input;\n }\n\n if (!isNaN(input)) {\n return parseInt(input, 10);\n }\n\n input = locale.weekdaysParse(input);\n if (typeof input === 'number') {\n return input;\n }\n\n return null;\n }\n\n function parseIsoWeekday(input, locale) {\n if (typeof input === 'string') {\n return locale.weekdaysParse(input) % 7 || 7;\n }\n return isNaN(input) ? null : input;\n }\n\n // LOCALES\n function shiftWeekdays(ws, n) {\n return ws.slice(n, 7).concat(ws.slice(0, n));\n }\n\n var defaultLocaleWeekdays = 'Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday'.split(\n '_'\n ),\n defaultLocaleWeekdaysShort = 'Sun_Mon_Tue_Wed_Thu_Fri_Sat'.split('_'),\n defaultLocaleWeekdaysMin = 'Su_Mo_Tu_We_Th_Fr_Sa'.split('_'),\n defaultWeekdaysRegex = matchWord,\n defaultWeekdaysShortRegex = matchWord,\n defaultWeekdaysMinRegex = matchWord;\n\n function localeWeekdays(m, format) {\n var weekdays = isArray(this._weekdays)\n ? this._weekdays\n : this._weekdays[\n m && m !== true && this._weekdays.isFormat.test(format)\n ? 'format'\n : 'standalone'\n ];\n return m === true\n ? shiftWeekdays(weekdays, this._week.dow)\n : m\n ? weekdays[m.day()]\n : weekdays;\n }\n\n function localeWeekdaysShort(m) {\n return m === true\n ? shiftWeekdays(this._weekdaysShort, this._week.dow)\n : m\n ? this._weekdaysShort[m.day()]\n : this._weekdaysShort;\n }\n\n function localeWeekdaysMin(m) {\n return m === true\n ? shiftWeekdays(this._weekdaysMin, this._week.dow)\n : m\n ? this._weekdaysMin[m.day()]\n : this._weekdaysMin;\n }\n\n function handleStrictParse$1(weekdayName, format, strict) {\n var i,\n ii,\n mom,\n llc = weekdayName.toLocaleLowerCase();\n if (!this._weekdaysParse) {\n this._weekdaysParse = [];\n this._shortWeekdaysParse = [];\n this._minWeekdaysParse = [];\n\n for (i = 0; i < 7; ++i) {\n mom = createUTC([2000, 1]).day(i);\n this._minWeekdaysParse[i] = this.weekdaysMin(\n mom,\n ''\n ).toLocaleLowerCase();\n this._shortWeekdaysParse[i] = this.weekdaysShort(\n mom,\n ''\n ).toLocaleLowerCase();\n this._weekdaysParse[i] = this.weekdays(mom, '').toLocaleLowerCase();\n }\n }\n\n if (strict) {\n if (format === 'dddd') {\n ii = indexOf.call(this._weekdaysParse, llc);\n return ii !== -1 ? ii : null;\n } else if (format === 'ddd') {\n ii = indexOf.call(this._shortWeekdaysParse, llc);\n return ii !== -1 ? ii : null;\n } else {\n ii = indexOf.call(this._minWeekdaysParse, llc);\n return ii !== -1 ? ii : null;\n }\n } else {\n if (format === 'dddd') {\n ii = indexOf.call(this._weekdaysParse, llc);\n if (ii !== -1) {\n return ii;\n }\n ii = indexOf.call(this._shortWeekdaysParse, llc);\n if (ii !== -1) {\n return ii;\n }\n ii = indexOf.call(this._minWeekdaysParse, llc);\n return ii !== -1 ? ii : null;\n } else if (format === 'ddd') {\n ii = indexOf.call(this._shortWeekdaysParse, llc);\n if (ii !== -1) {\n return ii;\n }\n ii = indexOf.call(this._weekdaysParse, llc);\n if (ii !== -1) {\n return ii;\n }\n ii = indexOf.call(this._minWeekdaysParse, llc);\n return ii !== -1 ? ii : null;\n } else {\n ii = indexOf.call(this._minWeekdaysParse, llc);\n if (ii !== -1) {\n return ii;\n }\n ii = indexOf.call(this._weekdaysParse, llc);\n if (ii !== -1) {\n return ii;\n }\n ii = indexOf.call(this._shortWeekdaysParse, llc);\n return ii !== -1 ? ii : null;\n }\n }\n }\n\n function localeWeekdaysParse(weekdayName, format, strict) {\n var i, mom, regex;\n\n if (this._weekdaysParseExact) {\n return handleStrictParse$1.call(this, weekdayName, format, strict);\n }\n\n if (!this._weekdaysParse) {\n this._weekdaysParse = [];\n this._minWeekdaysParse = [];\n this._shortWeekdaysParse = [];\n this._fullWeekdaysParse = [];\n }\n\n for (i = 0; i < 7; i++) {\n // make the regex if we don't have it already\n\n mom = createUTC([2000, 1]).day(i);\n if (strict && !this._fullWeekdaysParse[i]) {\n this._fullWeekdaysParse[i] = new RegExp(\n '^' + this.weekdays(mom, '').replace('.', '\\\\.?') + '$',\n 'i'\n );\n this._shortWeekdaysParse[i] = new RegExp(\n '^' + this.weekdaysShort(mom, '').replace('.', '\\\\.?') + '$',\n 'i'\n );\n this._minWeekdaysParse[i] = new RegExp(\n '^' + this.weekdaysMin(mom, '').replace('.', '\\\\.?') + '$',\n 'i'\n );\n }\n if (!this._weekdaysParse[i]) {\n regex =\n '^' +\n this.weekdays(mom, '') +\n '|^' +\n this.weekdaysShort(mom, '') +\n '|^' +\n this.weekdaysMin(mom, '');\n this._weekdaysParse[i] = new RegExp(regex.replace('.', ''), 'i');\n }\n // test the regex\n if (\n strict &&\n format === 'dddd' &&\n this._fullWeekdaysParse[i].test(weekdayName)\n ) {\n return i;\n } else if (\n strict &&\n format === 'ddd' &&\n this._shortWeekdaysParse[i].test(weekdayName)\n ) {\n return i;\n } else if (\n strict &&\n format === 'dd' &&\n this._minWeekdaysParse[i].test(weekdayName)\n ) {\n return i;\n } else if (!strict && this._weekdaysParse[i].test(weekdayName)) {\n return i;\n }\n }\n }\n\n // MOMENTS\n\n function getSetDayOfWeek(input) {\n if (!this.isValid()) {\n return input != null ? this : NaN;\n }\n var day = this._isUTC ? this._d.getUTCDay() : this._d.getDay();\n if (input != null) {\n input = parseWeekday(input, this.localeData());\n return this.add(input - day, 'd');\n } else {\n return day;\n }\n }\n\n function getSetLocaleDayOfWeek(input) {\n if (!this.isValid()) {\n return input != null ? this : NaN;\n }\n var weekday = (this.day() + 7 - this.localeData()._week.dow) % 7;\n return input == null ? weekday : this.add(input - weekday, 'd');\n }\n\n function getSetISODayOfWeek(input) {\n if (!this.isValid()) {\n return input != null ? this : NaN;\n }\n\n // behaves the same as moment#day except\n // as a getter, returns 7 instead of 0 (1-7 range instead of 0-6)\n // as a setter, sunday should belong to the previous week.\n\n if (input != null) {\n var weekday = parseIsoWeekday(input, this.localeData());\n return this.day(this.day() % 7 ? weekday : weekday - 7);\n } else {\n return this.day() || 7;\n }\n }\n\n function weekdaysRegex(isStrict) {\n if (this._weekdaysParseExact) {\n if (!hasOwnProp(this, '_weekdaysRegex')) {\n computeWeekdaysParse.call(this);\n }\n if (isStrict) {\n return this._weekdaysStrictRegex;\n } else {\n return this._weekdaysRegex;\n }\n } else {\n if (!hasOwnProp(this, '_weekdaysRegex')) {\n this._weekdaysRegex = defaultWeekdaysRegex;\n }\n return this._weekdaysStrictRegex && isStrict\n ? this._weekdaysStrictRegex\n : this._weekdaysRegex;\n }\n }\n\n function weekdaysShortRegex(isStrict) {\n if (this._weekdaysParseExact) {\n if (!hasOwnProp(this, '_weekdaysRegex')) {\n computeWeekdaysParse.call(this);\n }\n if (isStrict) {\n return this._weekdaysShortStrictRegex;\n } else {\n return this._weekdaysShortRegex;\n }\n } else {\n if (!hasOwnProp(this, '_weekdaysShortRegex')) {\n this._weekdaysShortRegex = defaultWeekdaysShortRegex;\n }\n return this._weekdaysShortStrictRegex && isStrict\n ? this._weekdaysShortStrictRegex\n : this._weekdaysShortRegex;\n }\n }\n\n function weekdaysMinRegex(isStrict) {\n if (this._weekdaysParseExact) {\n if (!hasOwnProp(this, '_weekdaysRegex')) {\n computeWeekdaysParse.call(this);\n }\n if (isStrict) {\n return this._weekdaysMinStrictRegex;\n } else {\n return this._weekdaysMinRegex;\n }\n } else {\n if (!hasOwnProp(this, '_weekdaysMinRegex')) {\n this._weekdaysMinRegex = defaultWeekdaysMinRegex;\n }\n return this._weekdaysMinStrictRegex && isStrict\n ? this._weekdaysMinStrictRegex\n : this._weekdaysMinRegex;\n }\n }\n\n function computeWeekdaysParse() {\n function cmpLenRev(a, b) {\n return b.length - a.length;\n }\n\n var minPieces = [],\n shortPieces = [],\n longPieces = [],\n mixedPieces = [],\n i,\n mom,\n minp,\n shortp,\n longp;\n for (i = 0; i < 7; i++) {\n // make the regex if we don't have it already\n mom = createUTC([2000, 1]).day(i);\n minp = regexEscape(this.weekdaysMin(mom, ''));\n shortp = regexEscape(this.weekdaysShort(mom, ''));\n longp = regexEscape(this.weekdays(mom, ''));\n minPieces.push(minp);\n shortPieces.push(shortp);\n longPieces.push(longp);\n mixedPieces.push(minp);\n mixedPieces.push(shortp);\n mixedPieces.push(longp);\n }\n // Sorting makes sure if one weekday (or abbr) is a prefix of another it\n // will match the longer piece.\n minPieces.sort(cmpLenRev);\n shortPieces.sort(cmpLenRev);\n longPieces.sort(cmpLenRev);\n mixedPieces.sort(cmpLenRev);\n\n this._weekdaysRegex = new RegExp('^(' + mixedPieces.join('|') + ')', 'i');\n this._weekdaysShortRegex = this._weekdaysRegex;\n this._weekdaysMinRegex = this._weekdaysRegex;\n\n this._weekdaysStrictRegex = new RegExp(\n '^(' + longPieces.join('|') + ')',\n 'i'\n );\n this._weekdaysShortStrictRegex = new RegExp(\n '^(' + shortPieces.join('|') + ')',\n 'i'\n );\n this._weekdaysMinStrictRegex = new RegExp(\n '^(' + minPieces.join('|') + ')',\n 'i'\n );\n }\n\n // FORMATTING\n\n function hFormat() {\n return this.hours() % 12 || 12;\n }\n\n function kFormat() {\n return this.hours() || 24;\n }\n\n addFormatToken('H', ['HH', 2], 0, 'hour');\n addFormatToken('h', ['hh', 2], 0, hFormat);\n addFormatToken('k', ['kk', 2], 0, kFormat);\n\n addFormatToken('hmm', 0, 0, function () {\n return '' + hFormat.apply(this) + zeroFill(this.minutes(), 2);\n });\n\n addFormatToken('hmmss', 0, 0, function () {\n return (\n '' +\n hFormat.apply(this) +\n zeroFill(this.minutes(), 2) +\n zeroFill(this.seconds(), 2)\n );\n });\n\n addFormatToken('Hmm', 0, 0, function () {\n return '' + this.hours() + zeroFill(this.minutes(), 2);\n });\n\n addFormatToken('Hmmss', 0, 0, function () {\n return (\n '' +\n this.hours() +\n zeroFill(this.minutes(), 2) +\n zeroFill(this.seconds(), 2)\n );\n });\n\n function meridiem(token, lowercase) {\n addFormatToken(token, 0, 0, function () {\n return this.localeData().meridiem(\n this.hours(),\n this.minutes(),\n lowercase\n );\n });\n }\n\n meridiem('a', true);\n meridiem('A', false);\n\n // ALIASES\n\n addUnitAlias('hour', 'h');\n\n // PRIORITY\n addUnitPriority('hour', 13);\n\n // PARSING\n\n function matchMeridiem(isStrict, locale) {\n return locale._meridiemParse;\n }\n\n addRegexToken('a', matchMeridiem);\n addRegexToken('A', matchMeridiem);\n addRegexToken('H', match1to2);\n addRegexToken('h', match1to2);\n addRegexToken('k', match1to2);\n addRegexToken('HH', match1to2, match2);\n addRegexToken('hh', match1to2, match2);\n addRegexToken('kk', match1to2, match2);\n\n addRegexToken('hmm', match3to4);\n addRegexToken('hmmss', match5to6);\n addRegexToken('Hmm', match3to4);\n addRegexToken('Hmmss', match5to6);\n\n addParseToken(['H', 'HH'], HOUR);\n addParseToken(['k', 'kk'], function (input, array, config) {\n var kInput = toInt(input);\n array[HOUR] = kInput === 24 ? 0 : kInput;\n });\n addParseToken(['a', 'A'], function (input, array, config) {\n config._isPm = config._locale.isPM(input);\n config._meridiem = input;\n });\n addParseToken(['h', 'hh'], function (input, array, config) {\n array[HOUR] = toInt(input);\n getParsingFlags(config).bigHour = true;\n });\n addParseToken('hmm', function (input, array, config) {\n var pos = input.length - 2;\n array[HOUR] = toInt(input.substr(0, pos));\n array[MINUTE] = toInt(input.substr(pos));\n getParsingFlags(config).bigHour = true;\n });\n addParseToken('hmmss', function (input, array, config) {\n var pos1 = input.length - 4,\n pos2 = input.length - 2;\n array[HOUR] = toInt(input.substr(0, pos1));\n array[MINUTE] = toInt(input.substr(pos1, 2));\n array[SECOND] = toInt(input.substr(pos2));\n getParsingFlags(config).bigHour = true;\n });\n addParseToken('Hmm', function (input, array, config) {\n var pos = input.length - 2;\n array[HOUR] = toInt(input.substr(0, pos));\n array[MINUTE] = toInt(input.substr(pos));\n });\n addParseToken('Hmmss', function (input, array, config) {\n var pos1 = input.length - 4,\n pos2 = input.length - 2;\n array[HOUR] = toInt(input.substr(0, pos1));\n array[MINUTE] = toInt(input.substr(pos1, 2));\n array[SECOND] = toInt(input.substr(pos2));\n });\n\n // LOCALES\n\n function localeIsPM(input) {\n // IE8 Quirks Mode & IE7 Standards Mode do not allow accessing strings like arrays\n // Using charAt should be more compatible.\n return (input + '').toLowerCase().charAt(0) === 'p';\n }\n\n var defaultLocaleMeridiemParse = /[ap]\\.?m?\\.?/i,\n // Setting the hour should keep the time, because the user explicitly\n // specified which hour they want. So trying to maintain the same hour (in\n // a new timezone) makes sense. Adding/subtracting hours does not follow\n // this rule.\n getSetHour = makeGetSet('Hours', true);\n\n function localeMeridiem(hours, minutes, isLower) {\n if (hours > 11) {\n return isLower ? 'pm' : 'PM';\n } else {\n return isLower ? 'am' : 'AM';\n }\n }\n\n var baseConfig = {\n calendar: defaultCalendar,\n longDateFormat: defaultLongDateFormat,\n invalidDate: defaultInvalidDate,\n ordinal: defaultOrdinal,\n dayOfMonthOrdinalParse: defaultDayOfMonthOrdinalParse,\n relativeTime: defaultRelativeTime,\n\n months: defaultLocaleMonths,\n monthsShort: defaultLocaleMonthsShort,\n\n week: defaultLocaleWeek,\n\n weekdays: defaultLocaleWeekdays,\n weekdaysMin: defaultLocaleWeekdaysMin,\n weekdaysShort: defaultLocaleWeekdaysShort,\n\n meridiemParse: defaultLocaleMeridiemParse,\n };\n\n // internal storage for locale config files\n var locales = {},\n localeFamilies = {},\n globalLocale;\n\n function commonPrefix(arr1, arr2) {\n var i,\n minl = Math.min(arr1.length, arr2.length);\n for (i = 0; i < minl; i += 1) {\n if (arr1[i] !== arr2[i]) {\n return i;\n }\n }\n return minl;\n }\n\n function normalizeLocale(key) {\n return key ? key.toLowerCase().replace('_', '-') : key;\n }\n\n // pick the locale from the array\n // try ['en-au', 'en-gb'] as 'en-au', 'en-gb', 'en', as in move through the list trying each\n // substring from most specific to least, but move to the next array item if it's a more specific variant than the current root\n function chooseLocale(names) {\n var i = 0,\n j,\n next,\n locale,\n split;\n\n while (i < names.length) {\n split = normalizeLocale(names[i]).split('-');\n j = split.length;\n next = normalizeLocale(names[i + 1]);\n next = next ? next.split('-') : null;\n while (j > 0) {\n locale = loadLocale(split.slice(0, j).join('-'));\n if (locale) {\n return locale;\n }\n if (\n next &&\n next.length >= j &&\n commonPrefix(split, next) >= j - 1\n ) {\n //the next array item is better than a shallower substring of this one\n break;\n }\n j--;\n }\n i++;\n }\n return globalLocale;\n }\n\n function loadLocale(name) {\n var oldLocale = null,\n aliasedRequire;\n // TODO: Find a better way to register and load all the locales in Node\n if (\n locales[name] === undefined &&\n typeof module !== 'undefined' &&\n module &&\n module.exports\n ) {\n try {\n oldLocale = globalLocale._abbr;\n aliasedRequire = require;\n aliasedRequire('./locale/' + name);\n getSetGlobalLocale(oldLocale);\n } catch (e) {\n // mark as not found to avoid repeating expensive file require call causing high CPU\n // when trying to find en-US, en_US, en-us for every format call\n locales[name] = null; // null means not found\n }\n }\n return locales[name];\n }\n\n // This function will load locale and then set the global locale. If\n // no arguments are passed in, it will simply return the current global\n // locale key.\n function getSetGlobalLocale(key, values) {\n var data;\n if (key) {\n if (isUndefined(values)) {\n data = getLocale(key);\n } else {\n data = defineLocale(key, values);\n }\n\n if (data) {\n // moment.duration._locale = moment._locale = data;\n globalLocale = data;\n } else {\n if (typeof console !== 'undefined' && console.warn) {\n //warn user if arguments are passed but the locale could not be set\n console.warn(\n 'Locale ' + key + ' not found. Did you forget to load it?'\n );\n }\n }\n }\n\n return globalLocale._abbr;\n }\n\n function defineLocale(name, config) {\n if (config !== null) {\n var locale,\n parentConfig = baseConfig;\n config.abbr = name;\n if (locales[name] != null) {\n deprecateSimple(\n 'defineLocaleOverride',\n 'use moment.updateLocale(localeName, config) to change ' +\n 'an existing locale. moment.defineLocale(localeName, ' +\n 'config) should only be used for creating a new locale ' +\n 'See http://momentjs.com/guides/#/warnings/define-locale/ for more info.'\n );\n parentConfig = locales[name]._config;\n } else if (config.parentLocale != null) {\n if (locales[config.parentLocale] != null) {\n parentConfig = locales[config.parentLocale]._config;\n } else {\n locale = loadLocale(config.parentLocale);\n if (locale != null) {\n parentConfig = locale._config;\n } else {\n if (!localeFamilies[config.parentLocale]) {\n localeFamilies[config.parentLocale] = [];\n }\n localeFamilies[config.parentLocale].push({\n name: name,\n config: config,\n });\n return null;\n }\n }\n }\n locales[name] = new Locale(mergeConfigs(parentConfig, config));\n\n if (localeFamilies[name]) {\n localeFamilies[name].forEach(function (x) {\n defineLocale(x.name, x.config);\n });\n }\n\n // backwards compat for now: also set the locale\n // make sure we set the locale AFTER all child locales have been\n // created, so we won't end up with the child locale set.\n getSetGlobalLocale(name);\n\n return locales[name];\n } else {\n // useful for testing\n delete locales[name];\n return null;\n }\n }\n\n function updateLocale(name, config) {\n if (config != null) {\n var locale,\n tmpLocale,\n parentConfig = baseConfig;\n\n if (locales[name] != null && locales[name].parentLocale != null) {\n // Update existing child locale in-place to avoid memory-leaks\n locales[name].set(mergeConfigs(locales[name]._config, config));\n } else {\n // MERGE\n tmpLocale = loadLocale(name);\n if (tmpLocale != null) {\n parentConfig = tmpLocale._config;\n }\n config = mergeConfigs(parentConfig, config);\n if (tmpLocale == null) {\n // updateLocale is called for creating a new locale\n // Set abbr so it will have a name (getters return\n // undefined otherwise).\n config.abbr = name;\n }\n locale = new Locale(config);\n locale.parentLocale = locales[name];\n locales[name] = locale;\n }\n\n // backwards compat for now: also set the locale\n getSetGlobalLocale(name);\n } else {\n // pass null for config to unupdate, useful for tests\n if (locales[name] != null) {\n if (locales[name].parentLocale != null) {\n locales[name] = locales[name].parentLocale;\n if (name === getSetGlobalLocale()) {\n getSetGlobalLocale(name);\n }\n } else if (locales[name] != null) {\n delete locales[name];\n }\n }\n }\n return locales[name];\n }\n\n // returns locale data\n function getLocale(key) {\n var locale;\n\n if (key && key._locale && key._locale._abbr) {\n key = key._locale._abbr;\n }\n\n if (!key) {\n return globalLocale;\n }\n\n if (!isArray(key)) {\n //short-circuit everything else\n locale = loadLocale(key);\n if (locale) {\n return locale;\n }\n key = [key];\n }\n\n return chooseLocale(key);\n }\n\n function listLocales() {\n return keys(locales);\n }\n\n function checkOverflow(m) {\n var overflow,\n a = m._a;\n\n if (a && getParsingFlags(m).overflow === -2) {\n overflow =\n a[MONTH] < 0 || a[MONTH] > 11\n ? MONTH\n : a[DATE] < 1 || a[DATE] > daysInMonth(a[YEAR], a[MONTH])\n ? DATE\n : a[HOUR] < 0 ||\n a[HOUR] > 24 ||\n (a[HOUR] === 24 &&\n (a[MINUTE] !== 0 ||\n a[SECOND] !== 0 ||\n a[MILLISECOND] !== 0))\n ? HOUR\n : a[MINUTE] < 0 || a[MINUTE] > 59\n ? MINUTE\n : a[SECOND] < 0 || a[SECOND] > 59\n ? SECOND\n : a[MILLISECOND] < 0 || a[MILLISECOND] > 999\n ? MILLISECOND\n : -1;\n\n if (\n getParsingFlags(m)._overflowDayOfYear &&\n (overflow < YEAR || overflow > DATE)\n ) {\n overflow = DATE;\n }\n if (getParsingFlags(m)._overflowWeeks && overflow === -1) {\n overflow = WEEK;\n }\n if (getParsingFlags(m)._overflowWeekday && overflow === -1) {\n overflow = WEEKDAY;\n }\n\n getParsingFlags(m).overflow = overflow;\n }\n\n return m;\n }\n\n // iso 8601 regex\n // 0000-00-00 0000-W00 or 0000-W00-0 + T + 00 or 00:00 or 00:00:00 or 00:00:00.000 + +00:00 or +0000 or +00)\n var extendedIsoRegex = /^\\s*((?:[+-]\\d{6}|\\d{4})-(?:\\d\\d-\\d\\d|W\\d\\d-\\d|W\\d\\d|\\d\\d\\d|\\d\\d))(?:(T| )(\\d\\d(?::\\d\\d(?::\\d\\d(?:[.,]\\d+)?)?)?)([+-]\\d\\d(?::?\\d\\d)?|\\s*Z)?)?$/,\n basicIsoRegex = /^\\s*((?:[+-]\\d{6}|\\d{4})(?:\\d\\d\\d\\d|W\\d\\d\\d|W\\d\\d|\\d\\d\\d|\\d\\d|))(?:(T| )(\\d\\d(?:\\d\\d(?:\\d\\d(?:[.,]\\d+)?)?)?)([+-]\\d\\d(?::?\\d\\d)?|\\s*Z)?)?$/,\n tzRegex = /Z|[+-]\\d\\d(?::?\\d\\d)?/,\n isoDates = [\n ['YYYYYY-MM-DD', /[+-]\\d{6}-\\d\\d-\\d\\d/],\n ['YYYY-MM-DD', /\\d{4}-\\d\\d-\\d\\d/],\n ['GGGG-[W]WW-E', /\\d{4}-W\\d\\d-\\d/],\n ['GGGG-[W]WW', /\\d{4}-W\\d\\d/, false],\n ['YYYY-DDD', /\\d{4}-\\d{3}/],\n ['YYYY-MM', /\\d{4}-\\d\\d/, false],\n ['YYYYYYMMDD', /[+-]\\d{10}/],\n ['YYYYMMDD', /\\d{8}/],\n ['GGGG[W]WWE', /\\d{4}W\\d{3}/],\n ['GGGG[W]WW', /\\d{4}W\\d{2}/, false],\n ['YYYYDDD', /\\d{7}/],\n ['YYYYMM', /\\d{6}/, false],\n ['YYYY', /\\d{4}/, false],\n ],\n // iso time formats and regexes\n isoTimes = [\n ['HH:mm:ss.SSSS', /\\d\\d:\\d\\d:\\d\\d\\.\\d+/],\n ['HH:mm:ss,SSSS', /\\d\\d:\\d\\d:\\d\\d,\\d+/],\n ['HH:mm:ss', /\\d\\d:\\d\\d:\\d\\d/],\n ['HH:mm', /\\d\\d:\\d\\d/],\n ['HHmmss.SSSS', /\\d\\d\\d\\d\\d\\d\\.\\d+/],\n ['HHmmss,SSSS', /\\d\\d\\d\\d\\d\\d,\\d+/],\n ['HHmmss', /\\d\\d\\d\\d\\d\\d/],\n ['HHmm', /\\d\\d\\d\\d/],\n ['HH', /\\d\\d/],\n ],\n aspNetJsonRegex = /^\\/?Date\\((-?\\d+)/i,\n // RFC 2822 regex: For details see https://tools.ietf.org/html/rfc2822#section-3.3\n rfc2822 = /^(?:(Mon|Tue|Wed|Thu|Fri|Sat|Sun),?\\s)?(\\d{1,2})\\s(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\\s(\\d{2,4})\\s(\\d\\d):(\\d\\d)(?::(\\d\\d))?\\s(?:(UT|GMT|[ECMP][SD]T)|([Zz])|([+-]\\d{4}))$/,\n obsOffsets = {\n UT: 0,\n GMT: 0,\n EDT: -4 * 60,\n EST: -5 * 60,\n CDT: -5 * 60,\n CST: -6 * 60,\n MDT: -6 * 60,\n MST: -7 * 60,\n PDT: -7 * 60,\n PST: -8 * 60,\n };\n\n // date from iso format\n function configFromISO(config) {\n var i,\n l,\n string = config._i,\n match = extendedIsoRegex.exec(string) || basicIsoRegex.exec(string),\n allowTime,\n dateFormat,\n timeFormat,\n tzFormat;\n\n if (match) {\n getParsingFlags(config).iso = true;\n\n for (i = 0, l = isoDates.length; i < l; i++) {\n if (isoDates[i][1].exec(match[1])) {\n dateFormat = isoDates[i][0];\n allowTime = isoDates[i][2] !== false;\n break;\n }\n }\n if (dateFormat == null) {\n config._isValid = false;\n return;\n }\n if (match[3]) {\n for (i = 0, l = isoTimes.length; i < l; i++) {\n if (isoTimes[i][1].exec(match[3])) {\n // match[2] should be 'T' or space\n timeFormat = (match[2] || ' ') + isoTimes[i][0];\n break;\n }\n }\n if (timeFormat == null) {\n config._isValid = false;\n return;\n }\n }\n if (!allowTime && timeFormat != null) {\n config._isValid = false;\n return;\n }\n if (match[4]) {\n if (tzRegex.exec(match[4])) {\n tzFormat = 'Z';\n } else {\n config._isValid = false;\n return;\n }\n }\n config._f = dateFormat + (timeFormat || '') + (tzFormat || '');\n configFromStringAndFormat(config);\n } else {\n config._isValid = false;\n }\n }\n\n function extractFromRFC2822Strings(\n yearStr,\n monthStr,\n dayStr,\n hourStr,\n minuteStr,\n secondStr\n ) {\n var result = [\n untruncateYear(yearStr),\n defaultLocaleMonthsShort.indexOf(monthStr),\n parseInt(dayStr, 10),\n parseInt(hourStr, 10),\n parseInt(minuteStr, 10),\n ];\n\n if (secondStr) {\n result.push(parseInt(secondStr, 10));\n }\n\n return result;\n }\n\n function untruncateYear(yearStr) {\n var year = parseInt(yearStr, 10);\n if (year <= 49) {\n return 2000 + year;\n } else if (year <= 999) {\n return 1900 + year;\n }\n return year;\n }\n\n function preprocessRFC2822(s) {\n // Remove comments and folding whitespace and replace multiple-spaces with a single space\n return s\n .replace(/\\([^)]*\\)|[\\n\\t]/g, ' ')\n .replace(/(\\s\\s+)/g, ' ')\n .replace(/^\\s\\s*/, '')\n .replace(/\\s\\s*$/, '');\n }\n\n function checkWeekday(weekdayStr, parsedInput, config) {\n if (weekdayStr) {\n // TODO: Replace the vanilla JS Date object with an independent day-of-week check.\n var weekdayProvided = defaultLocaleWeekdaysShort.indexOf(weekdayStr),\n weekdayActual = new Date(\n parsedInput[0],\n parsedInput[1],\n parsedInput[2]\n ).getDay();\n if (weekdayProvided !== weekdayActual) {\n getParsingFlags(config).weekdayMismatch = true;\n config._isValid = false;\n return false;\n }\n }\n return true;\n }\n\n function calculateOffset(obsOffset, militaryOffset, numOffset) {\n if (obsOffset) {\n return obsOffsets[obsOffset];\n } else if (militaryOffset) {\n // the only allowed military tz is Z\n return 0;\n } else {\n var hm = parseInt(numOffset, 10),\n m = hm % 100,\n h = (hm - m) / 100;\n return h * 60 + m;\n }\n }\n\n // date and time from ref 2822 format\n function configFromRFC2822(config) {\n var match = rfc2822.exec(preprocessRFC2822(config._i)),\n parsedArray;\n if (match) {\n parsedArray = extractFromRFC2822Strings(\n match[4],\n match[3],\n match[2],\n match[5],\n match[6],\n match[7]\n );\n if (!checkWeekday(match[1], parsedArray, config)) {\n return;\n }\n\n config._a = parsedArray;\n config._tzm = calculateOffset(match[8], match[9], match[10]);\n\n config._d = createUTCDate.apply(null, config._a);\n config._d.setUTCMinutes(config._d.getUTCMinutes() - config._tzm);\n\n getParsingFlags(config).rfc2822 = true;\n } else {\n config._isValid = false;\n }\n }\n\n // date from 1) ASP.NET, 2) ISO, 3) RFC 2822 formats, or 4) optional fallback if parsing isn't strict\n function configFromString(config) {\n var matched = aspNetJsonRegex.exec(config._i);\n if (matched !== null) {\n config._d = new Date(+matched[1]);\n return;\n }\n\n configFromISO(config);\n if (config._isValid === false) {\n delete config._isValid;\n } else {\n return;\n }\n\n configFromRFC2822(config);\n if (config._isValid === false) {\n delete config._isValid;\n } else {\n return;\n }\n\n if (config._strict) {\n config._isValid = false;\n } else {\n // Final attempt, use Input Fallback\n hooks.createFromInputFallback(config);\n }\n }\n\n hooks.createFromInputFallback = deprecate(\n 'value provided is not in a recognized RFC2822 or ISO format. moment construction falls back to js Date(), ' +\n 'which is not reliable across all browsers and versions. Non RFC2822/ISO date formats are ' +\n 'discouraged and will be removed in an upcoming major release. Please refer to ' +\n 'http://momentjs.com/guides/#/warnings/js-date/ for more info.',\n function (config) {\n config._d = new Date(config._i + (config._useUTC ? ' UTC' : ''));\n }\n );\n\n // Pick the first defined of two or three arguments.\n function defaults(a, b, c) {\n if (a != null) {\n return a;\n }\n if (b != null) {\n return b;\n }\n return c;\n }\n\n function currentDateArray(config) {\n // hooks is actually the exported moment object\n var nowValue = new Date(hooks.now());\n if (config._useUTC) {\n return [\n nowValue.getUTCFullYear(),\n nowValue.getUTCMonth(),\n nowValue.getUTCDate(),\n ];\n }\n return [nowValue.getFullYear(), nowValue.getMonth(), nowValue.getDate()];\n }\n\n // convert an array to a date.\n // the array should mirror the parameters below\n // note: all values past the year are optional and will default to the lowest possible value.\n // [year, month, day , hour, minute, second, millisecond]\n function configFromArray(config) {\n var i,\n date,\n input = [],\n currentDate,\n expectedWeekday,\n yearToUse;\n\n if (config._d) {\n return;\n }\n\n currentDate = currentDateArray(config);\n\n //compute day of the year from weeks and weekdays\n if (config._w && config._a[DATE] == null && config._a[MONTH] == null) {\n dayOfYearFromWeekInfo(config);\n }\n\n //if the day of the year is set, figure out what it is\n if (config._dayOfYear != null) {\n yearToUse = defaults(config._a[YEAR], currentDate[YEAR]);\n\n if (\n config._dayOfYear > daysInYear(yearToUse) ||\n config._dayOfYear === 0\n ) {\n getParsingFlags(config)._overflowDayOfYear = true;\n }\n\n date = createUTCDate(yearToUse, 0, config._dayOfYear);\n config._a[MONTH] = date.getUTCMonth();\n config._a[DATE] = date.getUTCDate();\n }\n\n // Default to current date.\n // * if no year, month, day of month are given, default to today\n // * if day of month is given, default month and year\n // * if month is given, default only year\n // * if year is given, don't default anything\n for (i = 0; i < 3 && config._a[i] == null; ++i) {\n config._a[i] = input[i] = currentDate[i];\n }\n\n // Zero out whatever was not defaulted, including time\n for (; i < 7; i++) {\n config._a[i] = input[i] =\n config._a[i] == null ? (i === 2 ? 1 : 0) : config._a[i];\n }\n\n // Check for 24:00:00.000\n if (\n config._a[HOUR] === 24 &&\n config._a[MINUTE] === 0 &&\n config._a[SECOND] === 0 &&\n config._a[MILLISECOND] === 0\n ) {\n config._nextDay = true;\n config._a[HOUR] = 0;\n }\n\n config._d = (config._useUTC ? createUTCDate : createDate).apply(\n null,\n input\n );\n expectedWeekday = config._useUTC\n ? config._d.getUTCDay()\n : config._d.getDay();\n\n // Apply timezone offset from input. The actual utcOffset can be changed\n // with parseZone.\n if (config._tzm != null) {\n config._d.setUTCMinutes(config._d.getUTCMinutes() - config._tzm);\n }\n\n if (config._nextDay) {\n config._a[HOUR] = 24;\n }\n\n // check for mismatching day of week\n if (\n config._w &&\n typeof config._w.d !== 'undefined' &&\n config._w.d !== expectedWeekday\n ) {\n getParsingFlags(config).weekdayMismatch = true;\n }\n }\n\n function dayOfYearFromWeekInfo(config) {\n var w, weekYear, week, weekday, dow, doy, temp, weekdayOverflow, curWeek;\n\n w = config._w;\n if (w.GG != null || w.W != null || w.E != null) {\n dow = 1;\n doy = 4;\n\n // TODO: We need to take the current isoWeekYear, but that depends on\n // how we interpret now (local, utc, fixed offset). So create\n // a now version of current config (take local/utc/offset flags, and\n // create now).\n weekYear = defaults(\n w.GG,\n config._a[YEAR],\n weekOfYear(createLocal(), 1, 4).year\n );\n week = defaults(w.W, 1);\n weekday = defaults(w.E, 1);\n if (weekday < 1 || weekday > 7) {\n weekdayOverflow = true;\n }\n } else {\n dow = config._locale._week.dow;\n doy = config._locale._week.doy;\n\n curWeek = weekOfYear(createLocal(), dow, doy);\n\n weekYear = defaults(w.gg, config._a[YEAR], curWeek.year);\n\n // Default to current week.\n week = defaults(w.w, curWeek.week);\n\n if (w.d != null) {\n // weekday -- low day numbers are considered next week\n weekday = w.d;\n if (weekday < 0 || weekday > 6) {\n weekdayOverflow = true;\n }\n } else if (w.e != null) {\n // local weekday -- counting starts from beginning of week\n weekday = w.e + dow;\n if (w.e < 0 || w.e > 6) {\n weekdayOverflow = true;\n }\n } else {\n // default to beginning of week\n weekday = dow;\n }\n }\n if (week < 1 || week > weeksInYear(weekYear, dow, doy)) {\n getParsingFlags(config)._overflowWeeks = true;\n } else if (weekdayOverflow != null) {\n getParsingFlags(config)._overflowWeekday = true;\n } else {\n temp = dayOfYearFromWeeks(weekYear, week, weekday, dow, doy);\n config._a[YEAR] = temp.year;\n config._dayOfYear = temp.dayOfYear;\n }\n }\n\n // constant that refers to the ISO standard\n hooks.ISO_8601 = function () {};\n\n // constant that refers to the RFC 2822 form\n hooks.RFC_2822 = function () {};\n\n // date from string and format string\n function configFromStringAndFormat(config) {\n // TODO: Move this to another part of the creation flow to prevent circular deps\n if (config._f === hooks.ISO_8601) {\n configFromISO(config);\n return;\n }\n if (config._f === hooks.RFC_2822) {\n configFromRFC2822(config);\n return;\n }\n config._a = [];\n getParsingFlags(config).empty = true;\n\n // This array is used to make a Date, either with `new Date` or `Date.UTC`\n var string = '' + config._i,\n i,\n parsedInput,\n tokens,\n token,\n skipped,\n stringLength = string.length,\n totalParsedInputLength = 0,\n era;\n\n tokens =\n expandFormat(config._f, config._locale).match(formattingTokens) || [];\n\n for (i = 0; i < tokens.length; i++) {\n token = tokens[i];\n parsedInput = (string.match(getParseRegexForToken(token, config)) ||\n [])[0];\n if (parsedInput) {\n skipped = string.substr(0, string.indexOf(parsedInput));\n if (skipped.length > 0) {\n getParsingFlags(config).unusedInput.push(skipped);\n }\n string = string.slice(\n string.indexOf(parsedInput) + parsedInput.length\n );\n totalParsedInputLength += parsedInput.length;\n }\n // don't parse if it's not a known token\n if (formatTokenFunctions[token]) {\n if (parsedInput) {\n getParsingFlags(config).empty = false;\n } else {\n getParsingFlags(config).unusedTokens.push(token);\n }\n addTimeToArrayFromToken(token, parsedInput, config);\n } else if (config._strict && !parsedInput) {\n getParsingFlags(config).unusedTokens.push(token);\n }\n }\n\n // add remaining unparsed input length to the string\n getParsingFlags(config).charsLeftOver =\n stringLength - totalParsedInputLength;\n if (string.length > 0) {\n getParsingFlags(config).unusedInput.push(string);\n }\n\n // clear _12h flag if hour is <= 12\n if (\n config._a[HOUR] <= 12 &&\n getParsingFlags(config).bigHour === true &&\n config._a[HOUR] > 0\n ) {\n getParsingFlags(config).bigHour = undefined;\n }\n\n getParsingFlags(config).parsedDateParts = config._a.slice(0);\n getParsingFlags(config).meridiem = config._meridiem;\n // handle meridiem\n config._a[HOUR] = meridiemFixWrap(\n config._locale,\n config._a[HOUR],\n config._meridiem\n );\n\n // handle era\n era = getParsingFlags(config).era;\n if (era !== null) {\n config._a[YEAR] = config._locale.erasConvertYear(era, config._a[YEAR]);\n }\n\n configFromArray(config);\n checkOverflow(config);\n }\n\n function meridiemFixWrap(locale, hour, meridiem) {\n var isPm;\n\n if (meridiem == null) {\n // nothing to do\n return hour;\n }\n if (locale.meridiemHour != null) {\n return locale.meridiemHour(hour, meridiem);\n } else if (locale.isPM != null) {\n // Fallback\n isPm = locale.isPM(meridiem);\n if (isPm && hour < 12) {\n hour += 12;\n }\n if (!isPm && hour === 12) {\n hour = 0;\n }\n return hour;\n } else {\n // this is not supposed to happen\n return hour;\n }\n }\n\n // date from string and array of format strings\n function configFromStringAndArray(config) {\n var tempConfig,\n bestMoment,\n scoreToBeat,\n i,\n currentScore,\n validFormatFound,\n bestFormatIsValid = false;\n\n if (config._f.length === 0) {\n getParsingFlags(config).invalidFormat = true;\n config._d = new Date(NaN);\n return;\n }\n\n for (i = 0; i < config._f.length; i++) {\n currentScore = 0;\n validFormatFound = false;\n tempConfig = copyConfig({}, config);\n if (config._useUTC != null) {\n tempConfig._useUTC = config._useUTC;\n }\n tempConfig._f = config._f[i];\n configFromStringAndFormat(tempConfig);\n\n if (isValid(tempConfig)) {\n validFormatFound = true;\n }\n\n // if there is any input that was not parsed add a penalty for that format\n currentScore += getParsingFlags(tempConfig).charsLeftOver;\n\n //or tokens\n currentScore += getParsingFlags(tempConfig).unusedTokens.length * 10;\n\n getParsingFlags(tempConfig).score = currentScore;\n\n if (!bestFormatIsValid) {\n if (\n scoreToBeat == null ||\n currentScore < scoreToBeat ||\n validFormatFound\n ) {\n scoreToBeat = currentScore;\n bestMoment = tempConfig;\n if (validFormatFound) {\n bestFormatIsValid = true;\n }\n }\n } else {\n if (currentScore < scoreToBeat) {\n scoreToBeat = currentScore;\n bestMoment = tempConfig;\n }\n }\n }\n\n extend(config, bestMoment || tempConfig);\n }\n\n function configFromObject(config) {\n if (config._d) {\n return;\n }\n\n var i = normalizeObjectUnits(config._i),\n dayOrDate = i.day === undefined ? i.date : i.day;\n config._a = map(\n [i.year, i.month, dayOrDate, i.hour, i.minute, i.second, i.millisecond],\n function (obj) {\n return obj && parseInt(obj, 10);\n }\n );\n\n configFromArray(config);\n }\n\n function createFromConfig(config) {\n var res = new Moment(checkOverflow(prepareConfig(config)));\n if (res._nextDay) {\n // Adding is smart enough around DST\n res.add(1, 'd');\n res._nextDay = undefined;\n }\n\n return res;\n }\n\n function prepareConfig(config) {\n var input = config._i,\n format = config._f;\n\n config._locale = config._locale || getLocale(config._l);\n\n if (input === null || (format === undefined && input === '')) {\n return createInvalid({ nullInput: true });\n }\n\n if (typeof input === 'string') {\n config._i = input = config._locale.preparse(input);\n }\n\n if (isMoment(input)) {\n return new Moment(checkOverflow(input));\n } else if (isDate(input)) {\n config._d = input;\n } else if (isArray(format)) {\n configFromStringAndArray(config);\n } else if (format) {\n configFromStringAndFormat(config);\n } else {\n configFromInput(config);\n }\n\n if (!isValid(config)) {\n config._d = null;\n }\n\n return config;\n }\n\n function configFromInput(config) {\n var input = config._i;\n if (isUndefined(input)) {\n config._d = new Date(hooks.now());\n } else if (isDate(input)) {\n config._d = new Date(input.valueOf());\n } else if (typeof input === 'string') {\n configFromString(config);\n } else if (isArray(input)) {\n config._a = map(input.slice(0), function (obj) {\n return parseInt(obj, 10);\n });\n configFromArray(config);\n } else if (isObject(input)) {\n configFromObject(config);\n } else if (isNumber(input)) {\n // from milliseconds\n config._d = new Date(input);\n } else {\n hooks.createFromInputFallback(config);\n }\n }\n\n function createLocalOrUTC(input, format, locale, strict, isUTC) {\n var c = {};\n\n if (format === true || format === false) {\n strict = format;\n format = undefined;\n }\n\n if (locale === true || locale === false) {\n strict = locale;\n locale = undefined;\n }\n\n if (\n (isObject(input) && isObjectEmpty(input)) ||\n (isArray(input) && input.length === 0)\n ) {\n input = undefined;\n }\n // object construction must be done this way.\n // https://github.com/moment/moment/issues/1423\n c._isAMomentObject = true;\n c._useUTC = c._isUTC = isUTC;\n c._l = locale;\n c._i = input;\n c._f = format;\n c._strict = strict;\n\n return createFromConfig(c);\n }\n\n function createLocal(input, format, locale, strict) {\n return createLocalOrUTC(input, format, locale, strict, false);\n }\n\n var prototypeMin = deprecate(\n 'moment().min is deprecated, use moment.max instead. http://momentjs.com/guides/#/warnings/min-max/',\n function () {\n var other = createLocal.apply(null, arguments);\n if (this.isValid() && other.isValid()) {\n return other < this ? this : other;\n } else {\n return createInvalid();\n }\n }\n ),\n prototypeMax = deprecate(\n 'moment().max is deprecated, use moment.min instead. http://momentjs.com/guides/#/warnings/min-max/',\n function () {\n var other = createLocal.apply(null, arguments);\n if (this.isValid() && other.isValid()) {\n return other > this ? this : other;\n } else {\n return createInvalid();\n }\n }\n );\n\n // Pick a moment m from moments so that m[fn](other) is true for all\n // other. This relies on the function fn to be transitive.\n //\n // moments should either be an array of moment objects or an array, whose\n // first element is an array of moment objects.\n function pickBy(fn, moments) {\n var res, i;\n if (moments.length === 1 && isArray(moments[0])) {\n moments = moments[0];\n }\n if (!moments.length) {\n return createLocal();\n }\n res = moments[0];\n for (i = 1; i < moments.length; ++i) {\n if (!moments[i].isValid() || moments[i][fn](res)) {\n res = moments[i];\n }\n }\n return res;\n }\n\n // TODO: Use [].sort instead?\n function min() {\n var args = [].slice.call(arguments, 0);\n\n return pickBy('isBefore', args);\n }\n\n function max() {\n var args = [].slice.call(arguments, 0);\n\n return pickBy('isAfter', args);\n }\n\n var now = function () {\n return Date.now ? Date.now() : +new Date();\n };\n\n var ordering = [\n 'year',\n 'quarter',\n 'month',\n 'week',\n 'day',\n 'hour',\n 'minute',\n 'second',\n 'millisecond',\n ];\n\n function isDurationValid(m) {\n var key,\n unitHasDecimal = false,\n i;\n for (key in m) {\n if (\n hasOwnProp(m, key) &&\n !(\n indexOf.call(ordering, key) !== -1 &&\n (m[key] == null || !isNaN(m[key]))\n )\n ) {\n return false;\n }\n }\n\n for (i = 0; i < ordering.length; ++i) {\n if (m[ordering[i]]) {\n if (unitHasDecimal) {\n return false; // only allow non-integers for smallest unit\n }\n if (parseFloat(m[ordering[i]]) !== toInt(m[ordering[i]])) {\n unitHasDecimal = true;\n }\n }\n }\n\n return true;\n }\n\n function isValid$1() {\n return this._isValid;\n }\n\n function createInvalid$1() {\n return createDuration(NaN);\n }\n\n function Duration(duration) {\n var normalizedInput = normalizeObjectUnits(duration),\n years = normalizedInput.year || 0,\n quarters = normalizedInput.quarter || 0,\n months = normalizedInput.month || 0,\n weeks = normalizedInput.week || normalizedInput.isoWeek || 0,\n days = normalizedInput.day || 0,\n hours = normalizedInput.hour || 0,\n minutes = normalizedInput.minute || 0,\n seconds = normalizedInput.second || 0,\n milliseconds = normalizedInput.millisecond || 0;\n\n this._isValid = isDurationValid(normalizedInput);\n\n // representation for dateAddRemove\n this._milliseconds =\n +milliseconds +\n seconds * 1e3 + // 1000\n minutes * 6e4 + // 1000 * 60\n hours * 1000 * 60 * 60; //using 1000 * 60 * 60 instead of 36e5 to avoid floating point rounding errors https://github.com/moment/moment/issues/2978\n // Because of dateAddRemove treats 24 hours as different from a\n // day when working around DST, we need to store them separately\n this._days = +days + weeks * 7;\n // It is impossible to translate months into days without knowing\n // which months you are are talking about, so we have to store\n // it separately.\n this._months = +months + quarters * 3 + years * 12;\n\n this._data = {};\n\n this._locale = getLocale();\n\n this._bubble();\n }\n\n function isDuration(obj) {\n return obj instanceof Duration;\n }\n\n function absRound(number) {\n if (number < 0) {\n return Math.round(-1 * number) * -1;\n } else {\n return Math.round(number);\n }\n }\n\n // compare two arrays, return the number of differences\n function compareArrays(array1, array2, dontConvert) {\n var len = Math.min(array1.length, array2.length),\n lengthDiff = Math.abs(array1.length - array2.length),\n diffs = 0,\n i;\n for (i = 0; i < len; i++) {\n if (\n (dontConvert && array1[i] !== array2[i]) ||\n (!dontConvert && toInt(array1[i]) !== toInt(array2[i]))\n ) {\n diffs++;\n }\n }\n return diffs + lengthDiff;\n }\n\n // FORMATTING\n\n function offset(token, separator) {\n addFormatToken(token, 0, 0, function () {\n var offset = this.utcOffset(),\n sign = '+';\n if (offset < 0) {\n offset = -offset;\n sign = '-';\n }\n return (\n sign +\n zeroFill(~~(offset / 60), 2) +\n separator +\n zeroFill(~~offset % 60, 2)\n );\n });\n }\n\n offset('Z', ':');\n offset('ZZ', '');\n\n // PARSING\n\n addRegexToken('Z', matchShortOffset);\n addRegexToken('ZZ', matchShortOffset);\n addParseToken(['Z', 'ZZ'], function (input, array, config) {\n config._useUTC = true;\n config._tzm = offsetFromString(matchShortOffset, input);\n });\n\n // HELPERS\n\n // timezone chunker\n // '+10:00' > ['10', '00']\n // '-1530' > ['-15', '30']\n var chunkOffset = /([\\+\\-]|\\d\\d)/gi;\n\n function offsetFromString(matcher, string) {\n var matches = (string || '').match(matcher),\n chunk,\n parts,\n minutes;\n\n if (matches === null) {\n return null;\n }\n\n chunk = matches[matches.length - 1] || [];\n parts = (chunk + '').match(chunkOffset) || ['-', 0, 0];\n minutes = +(parts[1] * 60) + toInt(parts[2]);\n\n return minutes === 0 ? 0 : parts[0] === '+' ? minutes : -minutes;\n }\n\n // Return a moment from input, that is local/utc/zone equivalent to model.\n function cloneWithOffset(input, model) {\n var res, diff;\n if (model._isUTC) {\n res = model.clone();\n diff =\n (isMoment(input) || isDate(input)\n ? input.valueOf()\n : createLocal(input).valueOf()) - res.valueOf();\n // Use low-level api, because this fn is low-level api.\n res._d.setTime(res._d.valueOf() + diff);\n hooks.updateOffset(res, false);\n return res;\n } else {\n return createLocal(input).local();\n }\n }\n\n function getDateOffset(m) {\n // On Firefox.24 Date#getTimezoneOffset returns a floating point.\n // https://github.com/moment/moment/pull/1871\n return -Math.round(m._d.getTimezoneOffset());\n }\n\n // HOOKS\n\n // This function will be called whenever a moment is mutated.\n // It is intended to keep the offset in sync with the timezone.\n hooks.updateOffset = function () {};\n\n // MOMENTS\n\n // keepLocalTime = true means only change the timezone, without\n // affecting the local hour. So 5:31:26 +0300 --[utcOffset(2, true)]-->\n // 5:31:26 +0200 It is possible that 5:31:26 doesn't exist with offset\n // +0200, so we adjust the time as needed, to be valid.\n //\n // Keeping the time actually adds/subtracts (one hour)\n // from the actual represented time. That is why we call updateOffset\n // a second time. In case it wants us to change the offset again\n // _changeInProgress == true case, then we have to adjust, because\n // there is no such time in the given timezone.\n function getSetOffset(input, keepLocalTime, keepMinutes) {\n var offset = this._offset || 0,\n localAdjust;\n if (!this.isValid()) {\n return input != null ? this : NaN;\n }\n if (input != null) {\n if (typeof input === 'string') {\n input = offsetFromString(matchShortOffset, input);\n if (input === null) {\n return this;\n }\n } else if (Math.abs(input) < 16 && !keepMinutes) {\n input = input * 60;\n }\n if (!this._isUTC && keepLocalTime) {\n localAdjust = getDateOffset(this);\n }\n this._offset = input;\n this._isUTC = true;\n if (localAdjust != null) {\n this.add(localAdjust, 'm');\n }\n if (offset !== input) {\n if (!keepLocalTime || this._changeInProgress) {\n addSubtract(\n this,\n createDuration(input - offset, 'm'),\n 1,\n false\n );\n } else if (!this._changeInProgress) {\n this._changeInProgress = true;\n hooks.updateOffset(this, true);\n this._changeInProgress = null;\n }\n }\n return this;\n } else {\n return this._isUTC ? offset : getDateOffset(this);\n }\n }\n\n function getSetZone(input, keepLocalTime) {\n if (input != null) {\n if (typeof input !== 'string') {\n input = -input;\n }\n\n this.utcOffset(input, keepLocalTime);\n\n return this;\n } else {\n return -this.utcOffset();\n }\n }\n\n function setOffsetToUTC(keepLocalTime) {\n return this.utcOffset(0, keepLocalTime);\n }\n\n function setOffsetToLocal(keepLocalTime) {\n if (this._isUTC) {\n this.utcOffset(0, keepLocalTime);\n this._isUTC = false;\n\n if (keepLocalTime) {\n this.subtract(getDateOffset(this), 'm');\n }\n }\n return this;\n }\n\n function setOffsetToParsedOffset() {\n if (this._tzm != null) {\n this.utcOffset(this._tzm, false, true);\n } else if (typeof this._i === 'string') {\n var tZone = offsetFromString(matchOffset, this._i);\n if (tZone != null) {\n this.utcOffset(tZone);\n } else {\n this.utcOffset(0, true);\n }\n }\n return this;\n }\n\n function hasAlignedHourOffset(input) {\n if (!this.isValid()) {\n return false;\n }\n input = input ? createLocal(input).utcOffset() : 0;\n\n return (this.utcOffset() - input) % 60 === 0;\n }\n\n function isDaylightSavingTime() {\n return (\n this.utcOffset() > this.clone().month(0).utcOffset() ||\n this.utcOffset() > this.clone().month(5).utcOffset()\n );\n }\n\n function isDaylightSavingTimeShifted() {\n if (!isUndefined(this._isDSTShifted)) {\n return this._isDSTShifted;\n }\n\n var c = {},\n other;\n\n copyConfig(c, this);\n c = prepareConfig(c);\n\n if (c._a) {\n other = c._isUTC ? createUTC(c._a) : createLocal(c._a);\n this._isDSTShifted =\n this.isValid() && compareArrays(c._a, other.toArray()) > 0;\n } else {\n this._isDSTShifted = false;\n }\n\n return this._isDSTShifted;\n }\n\n function isLocal() {\n return this.isValid() ? !this._isUTC : false;\n }\n\n function isUtcOffset() {\n return this.isValid() ? this._isUTC : false;\n }\n\n function isUtc() {\n return this.isValid() ? this._isUTC && this._offset === 0 : false;\n }\n\n // ASP.NET json date format regex\n var aspNetRegex = /^(-|\\+)?(?:(\\d*)[. ])?(\\d+):(\\d+)(?::(\\d+)(\\.\\d*)?)?$/,\n // from http://docs.closure-library.googlecode.com/git/closure_goog_date_date.js.source.html\n // somewhat more in line with 4.4.3.2 2004 spec, but allows decimal anywhere\n // and further modified to allow for strings containing both week and day\n isoRegex = /^(-|\\+)?P(?:([-+]?[0-9,.]*)Y)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)W)?(?:([-+]?[0-9,.]*)D)?(?:T(?:([-+]?[0-9,.]*)H)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)S)?)?$/;\n\n function createDuration(input, key) {\n var duration = input,\n // matching against regexp is expensive, do it on demand\n match = null,\n sign,\n ret,\n diffRes;\n\n if (isDuration(input)) {\n duration = {\n ms: input._milliseconds,\n d: input._days,\n M: input._months,\n };\n } else if (isNumber(input) || !isNaN(+input)) {\n duration = {};\n if (key) {\n duration[key] = +input;\n } else {\n duration.milliseconds = +input;\n }\n } else if ((match = aspNetRegex.exec(input))) {\n sign = match[1] === '-' ? -1 : 1;\n duration = {\n y: 0,\n d: toInt(match[DATE]) * sign,\n h: toInt(match[HOUR]) * sign,\n m: toInt(match[MINUTE]) * sign,\n s: toInt(match[SECOND]) * sign,\n ms: toInt(absRound(match[MILLISECOND] * 1000)) * sign, // the millisecond decimal point is included in the match\n };\n } else if ((match = isoRegex.exec(input))) {\n sign = match[1] === '-' ? -1 : 1;\n duration = {\n y: parseIso(match[2], sign),\n M: parseIso(match[3], sign),\n w: parseIso(match[4], sign),\n d: parseIso(match[5], sign),\n h: parseIso(match[6], sign),\n m: parseIso(match[7], sign),\n s: parseIso(match[8], sign),\n };\n } else if (duration == null) {\n // checks for null or undefined\n duration = {};\n } else if (\n typeof duration === 'object' &&\n ('from' in duration || 'to' in duration)\n ) {\n diffRes = momentsDifference(\n createLocal(duration.from),\n createLocal(duration.to)\n );\n\n duration = {};\n duration.ms = diffRes.milliseconds;\n duration.M = diffRes.months;\n }\n\n ret = new Duration(duration);\n\n if (isDuration(input) && hasOwnProp(input, '_locale')) {\n ret._locale = input._locale;\n }\n\n if (isDuration(input) && hasOwnProp(input, '_isValid')) {\n ret._isValid = input._isValid;\n }\n\n return ret;\n }\n\n createDuration.fn = Duration.prototype;\n createDuration.invalid = createInvalid$1;\n\n function parseIso(inp, sign) {\n // We'd normally use ~~inp for this, but unfortunately it also\n // converts floats to ints.\n // inp may be undefined, so careful calling replace on it.\n var res = inp && parseFloat(inp.replace(',', '.'));\n // apply sign while we're at it\n return (isNaN(res) ? 0 : res) * sign;\n }\n\n function positiveMomentsDifference(base, other) {\n var res = {};\n\n res.months =\n other.month() - base.month() + (other.year() - base.year()) * 12;\n if (base.clone().add(res.months, 'M').isAfter(other)) {\n --res.months;\n }\n\n res.milliseconds = +other - +base.clone().add(res.months, 'M');\n\n return res;\n }\n\n function momentsDifference(base, other) {\n var res;\n if (!(base.isValid() && other.isValid())) {\n return { milliseconds: 0, months: 0 };\n }\n\n other = cloneWithOffset(other, base);\n if (base.isBefore(other)) {\n res = positiveMomentsDifference(base, other);\n } else {\n res = positiveMomentsDifference(other, base);\n res.milliseconds = -res.milliseconds;\n res.months = -res.months;\n }\n\n return res;\n }\n\n // TODO: remove 'name' arg after deprecation is removed\n function createAdder(direction, name) {\n return function (val, period) {\n var dur, tmp;\n //invert the arguments, but complain about it\n if (period !== null && !isNaN(+period)) {\n deprecateSimple(\n name,\n 'moment().' +\n name +\n '(period, number) is deprecated. Please use moment().' +\n name +\n '(number, period). ' +\n 'See http://momentjs.com/guides/#/warnings/add-inverted-param/ for more info.'\n );\n tmp = val;\n val = period;\n period = tmp;\n }\n\n dur = createDuration(val, period);\n addSubtract(this, dur, direction);\n return this;\n };\n }\n\n function addSubtract(mom, duration, isAdding, updateOffset) {\n var milliseconds = duration._milliseconds,\n days = absRound(duration._days),\n months = absRound(duration._months);\n\n if (!mom.isValid()) {\n // No op\n return;\n }\n\n updateOffset = updateOffset == null ? true : updateOffset;\n\n if (months) {\n setMonth(mom, get(mom, 'Month') + months * isAdding);\n }\n if (days) {\n set$1(mom, 'Date', get(mom, 'Date') + days * isAdding);\n }\n if (milliseconds) {\n mom._d.setTime(mom._d.valueOf() + milliseconds * isAdding);\n }\n if (updateOffset) {\n hooks.updateOffset(mom, days || months);\n }\n }\n\n var add = createAdder(1, 'add'),\n subtract = createAdder(-1, 'subtract');\n\n function isString(input) {\n return typeof input === 'string' || input instanceof String;\n }\n\n // type MomentInput = Moment | Date | string | number | (number | string)[] | MomentInputObject | void; // null | undefined\n function isMomentInput(input) {\n return (\n isMoment(input) ||\n isDate(input) ||\n isString(input) ||\n isNumber(input) ||\n isNumberOrStringArray(input) ||\n isMomentInputObject(input) ||\n input === null ||\n input === undefined\n );\n }\n\n function isMomentInputObject(input) {\n var objectTest = isObject(input) && !isObjectEmpty(input),\n propertyTest = false,\n properties = [\n 'years',\n 'year',\n 'y',\n 'months',\n 'month',\n 'M',\n 'days',\n 'day',\n 'd',\n 'dates',\n 'date',\n 'D',\n 'hours',\n 'hour',\n 'h',\n 'minutes',\n 'minute',\n 'm',\n 'seconds',\n 'second',\n 's',\n 'milliseconds',\n 'millisecond',\n 'ms',\n ],\n i,\n property;\n\n for (i = 0; i < properties.length; i += 1) {\n property = properties[i];\n propertyTest = propertyTest || hasOwnProp(input, property);\n }\n\n return objectTest && propertyTest;\n }\n\n function isNumberOrStringArray(input) {\n var arrayTest = isArray(input),\n dataTypeTest = false;\n if (arrayTest) {\n dataTypeTest =\n input.filter(function (item) {\n return !isNumber(item) && isString(input);\n }).length === 0;\n }\n return arrayTest && dataTypeTest;\n }\n\n function isCalendarSpec(input) {\n var objectTest = isObject(input) && !isObjectEmpty(input),\n propertyTest = false,\n properties = [\n 'sameDay',\n 'nextDay',\n 'lastDay',\n 'nextWeek',\n 'lastWeek',\n 'sameElse',\n ],\n i,\n property;\n\n for (i = 0; i < properties.length; i += 1) {\n property = properties[i];\n propertyTest = propertyTest || hasOwnProp(input, property);\n }\n\n return objectTest && propertyTest;\n }\n\n function getCalendarFormat(myMoment, now) {\n var diff = myMoment.diff(now, 'days', true);\n return diff < -6\n ? 'sameElse'\n : diff < -1\n ? 'lastWeek'\n : diff < 0\n ? 'lastDay'\n : diff < 1\n ? 'sameDay'\n : diff < 2\n ? 'nextDay'\n : diff < 7\n ? 'nextWeek'\n : 'sameElse';\n }\n\n function calendar$1(time, formats) {\n // Support for single parameter, formats only overload to the calendar function\n if (arguments.length === 1) {\n if (!arguments[0]) {\n time = undefined;\n formats = undefined;\n } else if (isMomentInput(arguments[0])) {\n time = arguments[0];\n formats = undefined;\n } else if (isCalendarSpec(arguments[0])) {\n formats = arguments[0];\n time = undefined;\n }\n }\n // We want to compare the start of today, vs this.\n // Getting start-of-today depends on whether we're local/utc/offset or not.\n var now = time || createLocal(),\n sod = cloneWithOffset(now, this).startOf('day'),\n format = hooks.calendarFormat(this, sod) || 'sameElse',\n output =\n formats &&\n (isFunction(formats[format])\n ? formats[format].call(this, now)\n : formats[format]);\n\n return this.format(\n output || this.localeData().calendar(format, this, createLocal(now))\n );\n }\n\n function clone() {\n return new Moment(this);\n }\n\n function isAfter(input, units) {\n var localInput = isMoment(input) ? input : createLocal(input);\n if (!(this.isValid() && localInput.isValid())) {\n return false;\n }\n units = normalizeUnits(units) || 'millisecond';\n if (units === 'millisecond') {\n return this.valueOf() > localInput.valueOf();\n } else {\n return localInput.valueOf() < this.clone().startOf(units).valueOf();\n }\n }\n\n function isBefore(input, units) {\n var localInput = isMoment(input) ? input : createLocal(input);\n if (!(this.isValid() && localInput.isValid())) {\n return false;\n }\n units = normalizeUnits(units) || 'millisecond';\n if (units === 'millisecond') {\n return this.valueOf() < localInput.valueOf();\n } else {\n return this.clone().endOf(units).valueOf() < localInput.valueOf();\n }\n }\n\n function isBetween(from, to, units, inclusivity) {\n var localFrom = isMoment(from) ? from : createLocal(from),\n localTo = isMoment(to) ? to : createLocal(to);\n if (!(this.isValid() && localFrom.isValid() && localTo.isValid())) {\n return false;\n }\n inclusivity = inclusivity || '()';\n return (\n (inclusivity[0] === '('\n ? this.isAfter(localFrom, units)\n : !this.isBefore(localFrom, units)) &&\n (inclusivity[1] === ')'\n ? this.isBefore(localTo, units)\n : !this.isAfter(localTo, units))\n );\n }\n\n function isSame(input, units) {\n var localInput = isMoment(input) ? input : createLocal(input),\n inputMs;\n if (!(this.isValid() && localInput.isValid())) {\n return false;\n }\n units = normalizeUnits(units) || 'millisecond';\n if (units === 'millisecond') {\n return this.valueOf() === localInput.valueOf();\n } else {\n inputMs = localInput.valueOf();\n return (\n this.clone().startOf(units).valueOf() <= inputMs &&\n inputMs <= this.clone().endOf(units).valueOf()\n );\n }\n }\n\n function isSameOrAfter(input, units) {\n return this.isSame(input, units) || this.isAfter(input, units);\n }\n\n function isSameOrBefore(input, units) {\n return this.isSame(input, units) || this.isBefore(input, units);\n }\n\n function diff(input, units, asFloat) {\n var that, zoneDelta, output;\n\n if (!this.isValid()) {\n return NaN;\n }\n\n that = cloneWithOffset(input, this);\n\n if (!that.isValid()) {\n return NaN;\n }\n\n zoneDelta = (that.utcOffset() - this.utcOffset()) * 6e4;\n\n units = normalizeUnits(units);\n\n switch (units) {\n case 'year':\n output = monthDiff(this, that) / 12;\n break;\n case 'month':\n output = monthDiff(this, that);\n break;\n case 'quarter':\n output = monthDiff(this, that) / 3;\n break;\n case 'second':\n output = (this - that) / 1e3;\n break; // 1000\n case 'minute':\n output = (this - that) / 6e4;\n break; // 1000 * 60\n case 'hour':\n output = (this - that) / 36e5;\n break; // 1000 * 60 * 60\n case 'day':\n output = (this - that - zoneDelta) / 864e5;\n break; // 1000 * 60 * 60 * 24, negate dst\n case 'week':\n output = (this - that - zoneDelta) / 6048e5;\n break; // 1000 * 60 * 60 * 24 * 7, negate dst\n default:\n output = this - that;\n }\n\n return asFloat ? output : absFloor(output);\n }\n\n function monthDiff(a, b) {\n if (a.date() < b.date()) {\n // end-of-month calculations work correct when the start month has more\n // days than the end month.\n return -monthDiff(b, a);\n }\n // difference in months\n var wholeMonthDiff = (b.year() - a.year()) * 12 + (b.month() - a.month()),\n // b is in (anchor - 1 month, anchor + 1 month)\n anchor = a.clone().add(wholeMonthDiff, 'months'),\n anchor2,\n adjust;\n\n if (b - anchor < 0) {\n anchor2 = a.clone().add(wholeMonthDiff - 1, 'months');\n // linear across the month\n adjust = (b - anchor) / (anchor - anchor2);\n } else {\n anchor2 = a.clone().add(wholeMonthDiff + 1, 'months');\n // linear across the month\n adjust = (b - anchor) / (anchor2 - anchor);\n }\n\n //check for negative zero, return zero if negative zero\n return -(wholeMonthDiff + adjust) || 0;\n }\n\n hooks.defaultFormat = 'YYYY-MM-DDTHH:mm:ssZ';\n hooks.defaultFormatUtc = 'YYYY-MM-DDTHH:mm:ss[Z]';\n\n function toString() {\n return this.clone().locale('en').format('ddd MMM DD YYYY HH:mm:ss [GMT]ZZ');\n }\n\n function toISOString(keepOffset) {\n if (!this.isValid()) {\n return null;\n }\n var utc = keepOffset !== true,\n m = utc ? this.clone().utc() : this;\n if (m.year() < 0 || m.year() > 9999) {\n return formatMoment(\n m,\n utc\n ? 'YYYYYY-MM-DD[T]HH:mm:ss.SSS[Z]'\n : 'YYYYYY-MM-DD[T]HH:mm:ss.SSSZ'\n );\n }\n if (isFunction(Date.prototype.toISOString)) {\n // native implementation is ~50x faster, use it when we can\n if (utc) {\n return this.toDate().toISOString();\n } else {\n return new Date(this.valueOf() + this.utcOffset() * 60 * 1000)\n .toISOString()\n .replace('Z', formatMoment(m, 'Z'));\n }\n }\n return formatMoment(\n m,\n utc ? 'YYYY-MM-DD[T]HH:mm:ss.SSS[Z]' : 'YYYY-MM-DD[T]HH:mm:ss.SSSZ'\n );\n }\n\n /**\n * Return a human readable representation of a moment that can\n * also be evaluated to get a new moment which is the same\n *\n * @link https://nodejs.org/dist/latest/docs/api/util.html#util_custom_inspect_function_on_objects\n */\n function inspect() {\n if (!this.isValid()) {\n return 'moment.invalid(/* ' + this._i + ' */)';\n }\n var func = 'moment',\n zone = '',\n prefix,\n year,\n datetime,\n suffix;\n if (!this.isLocal()) {\n func = this.utcOffset() === 0 ? 'moment.utc' : 'moment.parseZone';\n zone = 'Z';\n }\n prefix = '[' + func + '(\"]';\n year = 0 <= this.year() && this.year() <= 9999 ? 'YYYY' : 'YYYYYY';\n datetime = '-MM-DD[T]HH:mm:ss.SSS';\n suffix = zone + '[\")]';\n\n return this.format(prefix + year + datetime + suffix);\n }\n\n function format(inputString) {\n if (!inputString) {\n inputString = this.isUtc()\n ? hooks.defaultFormatUtc\n : hooks.defaultFormat;\n }\n var output = formatMoment(this, inputString);\n return this.localeData().postformat(output);\n }\n\n function from(time, withoutSuffix) {\n if (\n this.isValid() &&\n ((isMoment(time) && time.isValid()) || createLocal(time).isValid())\n ) {\n return createDuration({ to: this, from: time })\n .locale(this.locale())\n .humanize(!withoutSuffix);\n } else {\n return this.localeData().invalidDate();\n }\n }\n\n function fromNow(withoutSuffix) {\n return this.from(createLocal(), withoutSuffix);\n }\n\n function to(time, withoutSuffix) {\n if (\n this.isValid() &&\n ((isMoment(time) && time.isValid()) || createLocal(time).isValid())\n ) {\n return createDuration({ from: this, to: time })\n .locale(this.locale())\n .humanize(!withoutSuffix);\n } else {\n return this.localeData().invalidDate();\n }\n }\n\n function toNow(withoutSuffix) {\n return this.to(createLocal(), withoutSuffix);\n }\n\n // If passed a locale key, it will set the locale for this\n // instance. Otherwise, it will return the locale configuration\n // variables for this instance.\n function locale(key) {\n var newLocaleData;\n\n if (key === undefined) {\n return this._locale._abbr;\n } else {\n newLocaleData = getLocale(key);\n if (newLocaleData != null) {\n this._locale = newLocaleData;\n }\n return this;\n }\n }\n\n var lang = deprecate(\n 'moment().lang() is deprecated. Instead, use moment().localeData() to get the language configuration. Use moment().locale() to change languages.',\n function (key) {\n if (key === undefined) {\n return this.localeData();\n } else {\n return this.locale(key);\n }\n }\n );\n\n function localeData() {\n return this._locale;\n }\n\n var MS_PER_SECOND = 1000,\n MS_PER_MINUTE = 60 * MS_PER_SECOND,\n MS_PER_HOUR = 60 * MS_PER_MINUTE,\n MS_PER_400_YEARS = (365 * 400 + 97) * 24 * MS_PER_HOUR;\n\n // actual modulo - handles negative numbers (for dates before 1970):\n function mod$1(dividend, divisor) {\n return ((dividend % divisor) + divisor) % divisor;\n }\n\n function localStartOfDate(y, m, d) {\n // the date constructor remaps years 0-99 to 1900-1999\n if (y < 100 && y >= 0) {\n // preserve leap years using a full 400 year cycle, then reset\n return new Date(y + 400, m, d) - MS_PER_400_YEARS;\n } else {\n return new Date(y, m, d).valueOf();\n }\n }\n\n function utcStartOfDate(y, m, d) {\n // Date.UTC remaps years 0-99 to 1900-1999\n if (y < 100 && y >= 0) {\n // preserve leap years using a full 400 year cycle, then reset\n return Date.UTC(y + 400, m, d) - MS_PER_400_YEARS;\n } else {\n return Date.UTC(y, m, d);\n }\n }\n\n function startOf(units) {\n var time, startOfDate;\n units = normalizeUnits(units);\n if (units === undefined || units === 'millisecond' || !this.isValid()) {\n return this;\n }\n\n startOfDate = this._isUTC ? utcStartOfDate : localStartOfDate;\n\n switch (units) {\n case 'year':\n time = startOfDate(this.year(), 0, 1);\n break;\n case 'quarter':\n time = startOfDate(\n this.year(),\n this.month() - (this.month() % 3),\n 1\n );\n break;\n case 'month':\n time = startOfDate(this.year(), this.month(), 1);\n break;\n case 'week':\n time = startOfDate(\n this.year(),\n this.month(),\n this.date() - this.weekday()\n );\n break;\n case 'isoWeek':\n time = startOfDate(\n this.year(),\n this.month(),\n this.date() - (this.isoWeekday() - 1)\n );\n break;\n case 'day':\n case 'date':\n time = startOfDate(this.year(), this.month(), this.date());\n break;\n case 'hour':\n time = this._d.valueOf();\n time -= mod$1(\n time + (this._isUTC ? 0 : this.utcOffset() * MS_PER_MINUTE),\n MS_PER_HOUR\n );\n break;\n case 'minute':\n time = this._d.valueOf();\n time -= mod$1(time, MS_PER_MINUTE);\n break;\n case 'second':\n time = this._d.valueOf();\n time -= mod$1(time, MS_PER_SECOND);\n break;\n }\n\n this._d.setTime(time);\n hooks.updateOffset(this, true);\n return this;\n }\n\n function endOf(units) {\n var time, startOfDate;\n units = normalizeUnits(units);\n if (units === undefined || units === 'millisecond' || !this.isValid()) {\n return this;\n }\n\n startOfDate = this._isUTC ? utcStartOfDate : localStartOfDate;\n\n switch (units) {\n case 'year':\n time = startOfDate(this.year() + 1, 0, 1) - 1;\n break;\n case 'quarter':\n time =\n startOfDate(\n this.year(),\n this.month() - (this.month() % 3) + 3,\n 1\n ) - 1;\n break;\n case 'month':\n time = startOfDate(this.year(), this.month() + 1, 1) - 1;\n break;\n case 'week':\n time =\n startOfDate(\n this.year(),\n this.month(),\n this.date() - this.weekday() + 7\n ) - 1;\n break;\n case 'isoWeek':\n time =\n startOfDate(\n this.year(),\n this.month(),\n this.date() - (this.isoWeekday() - 1) + 7\n ) - 1;\n break;\n case 'day':\n case 'date':\n time = startOfDate(this.year(), this.month(), this.date() + 1) - 1;\n break;\n case 'hour':\n time = this._d.valueOf();\n time +=\n MS_PER_HOUR -\n mod$1(\n time + (this._isUTC ? 0 : this.utcOffset() * MS_PER_MINUTE),\n MS_PER_HOUR\n ) -\n 1;\n break;\n case 'minute':\n time = this._d.valueOf();\n time += MS_PER_MINUTE - mod$1(time, MS_PER_MINUTE) - 1;\n break;\n case 'second':\n time = this._d.valueOf();\n time += MS_PER_SECOND - mod$1(time, MS_PER_SECOND) - 1;\n break;\n }\n\n this._d.setTime(time);\n hooks.updateOffset(this, true);\n return this;\n }\n\n function valueOf() {\n return this._d.valueOf() - (this._offset || 0) * 60000;\n }\n\n function unix() {\n return Math.floor(this.valueOf() / 1000);\n }\n\n function toDate() {\n return new Date(this.valueOf());\n }\n\n function toArray() {\n var m = this;\n return [\n m.year(),\n m.month(),\n m.date(),\n m.hour(),\n m.minute(),\n m.second(),\n m.millisecond(),\n ];\n }\n\n function toObject() {\n var m = this;\n return {\n years: m.year(),\n months: m.month(),\n date: m.date(),\n hours: m.hours(),\n minutes: m.minutes(),\n seconds: m.seconds(),\n milliseconds: m.milliseconds(),\n };\n }\n\n function toJSON() {\n // new Date(NaN).toJSON() === null\n return this.isValid() ? this.toISOString() : null;\n }\n\n function isValid$2() {\n return isValid(this);\n }\n\n function parsingFlags() {\n return extend({}, getParsingFlags(this));\n }\n\n function invalidAt() {\n return getParsingFlags(this).overflow;\n }\n\n function creationData() {\n return {\n input: this._i,\n format: this._f,\n locale: this._locale,\n isUTC: this._isUTC,\n strict: this._strict,\n };\n }\n\n addFormatToken('N', 0, 0, 'eraAbbr');\n addFormatToken('NN', 0, 0, 'eraAbbr');\n addFormatToken('NNN', 0, 0, 'eraAbbr');\n addFormatToken('NNNN', 0, 0, 'eraName');\n addFormatToken('NNNNN', 0, 0, 'eraNarrow');\n\n addFormatToken('y', ['y', 1], 'yo', 'eraYear');\n addFormatToken('y', ['yy', 2], 0, 'eraYear');\n addFormatToken('y', ['yyy', 3], 0, 'eraYear');\n addFormatToken('y', ['yyyy', 4], 0, 'eraYear');\n\n addRegexToken('N', matchEraAbbr);\n addRegexToken('NN', matchEraAbbr);\n addRegexToken('NNN', matchEraAbbr);\n addRegexToken('NNNN', matchEraName);\n addRegexToken('NNNNN', matchEraNarrow);\n\n addParseToken(['N', 'NN', 'NNN', 'NNNN', 'NNNNN'], function (\n input,\n array,\n config,\n token\n ) {\n var era = config._locale.erasParse(input, token, config._strict);\n if (era) {\n getParsingFlags(config).era = era;\n } else {\n getParsingFlags(config).invalidEra = input;\n }\n });\n\n addRegexToken('y', matchUnsigned);\n addRegexToken('yy', matchUnsigned);\n addRegexToken('yyy', matchUnsigned);\n addRegexToken('yyyy', matchUnsigned);\n addRegexToken('yo', matchEraYearOrdinal);\n\n addParseToken(['y', 'yy', 'yyy', 'yyyy'], YEAR);\n addParseToken(['yo'], function (input, array, config, token) {\n var match;\n if (config._locale._eraYearOrdinalRegex) {\n match = input.match(config._locale._eraYearOrdinalRegex);\n }\n\n if (config._locale.eraYearOrdinalParse) {\n array[YEAR] = config._locale.eraYearOrdinalParse(input, match);\n } else {\n array[YEAR] = parseInt(input, 10);\n }\n });\n\n function localeEras(m, format) {\n var i,\n l,\n date,\n eras = this._eras || getLocale('en')._eras;\n for (i = 0, l = eras.length; i < l; ++i) {\n switch (typeof eras[i].since) {\n case 'string':\n // truncate time\n date = hooks(eras[i].since).startOf('day');\n eras[i].since = date.valueOf();\n break;\n }\n\n switch (typeof eras[i].until) {\n case 'undefined':\n eras[i].until = +Infinity;\n break;\n case 'string':\n // truncate time\n date = hooks(eras[i].until).startOf('day').valueOf();\n eras[i].until = date.valueOf();\n break;\n }\n }\n return eras;\n }\n\n function localeErasParse(eraName, format, strict) {\n var i,\n l,\n eras = this.eras(),\n name,\n abbr,\n narrow;\n eraName = eraName.toUpperCase();\n\n for (i = 0, l = eras.length; i < l; ++i) {\n name = eras[i].name.toUpperCase();\n abbr = eras[i].abbr.toUpperCase();\n narrow = eras[i].narrow.toUpperCase();\n\n if (strict) {\n switch (format) {\n case 'N':\n case 'NN':\n case 'NNN':\n if (abbr === eraName) {\n return eras[i];\n }\n break;\n\n case 'NNNN':\n if (name === eraName) {\n return eras[i];\n }\n break;\n\n case 'NNNNN':\n if (narrow === eraName) {\n return eras[i];\n }\n break;\n }\n } else if ([name, abbr, narrow].indexOf(eraName) >= 0) {\n return eras[i];\n }\n }\n }\n\n function localeErasConvertYear(era, year) {\n var dir = era.since <= era.until ? +1 : -1;\n if (year === undefined) {\n return hooks(era.since).year();\n } else {\n return hooks(era.since).year() + (year - era.offset) * dir;\n }\n }\n\n function getEraName() {\n var i,\n l,\n val,\n eras = this.localeData().eras();\n for (i = 0, l = eras.length; i < l; ++i) {\n // truncate time\n val = this.clone().startOf('day').valueOf();\n\n if (eras[i].since <= val && val <= eras[i].until) {\n return eras[i].name;\n }\n if (eras[i].until <= val && val <= eras[i].since) {\n return eras[i].name;\n }\n }\n\n return '';\n }\n\n function getEraNarrow() {\n var i,\n l,\n val,\n eras = this.localeData().eras();\n for (i = 0, l = eras.length; i < l; ++i) {\n // truncate time\n val = this.clone().startOf('day').valueOf();\n\n if (eras[i].since <= val && val <= eras[i].until) {\n return eras[i].narrow;\n }\n if (eras[i].until <= val && val <= eras[i].since) {\n return eras[i].narrow;\n }\n }\n\n return '';\n }\n\n function getEraAbbr() {\n var i,\n l,\n val,\n eras = this.localeData().eras();\n for (i = 0, l = eras.length; i < l; ++i) {\n // truncate time\n val = this.clone().startOf('day').valueOf();\n\n if (eras[i].since <= val && val <= eras[i].until) {\n return eras[i].abbr;\n }\n if (eras[i].until <= val && val <= eras[i].since) {\n return eras[i].abbr;\n }\n }\n\n return '';\n }\n\n function getEraYear() {\n var i,\n l,\n dir,\n val,\n eras = this.localeData().eras();\n for (i = 0, l = eras.length; i < l; ++i) {\n dir = eras[i].since <= eras[i].until ? +1 : -1;\n\n // truncate time\n val = this.clone().startOf('day').valueOf();\n\n if (\n (eras[i].since <= val && val <= eras[i].until) ||\n (eras[i].until <= val && val <= eras[i].since)\n ) {\n return (\n (this.year() - hooks(eras[i].since).year()) * dir +\n eras[i].offset\n );\n }\n }\n\n return this.year();\n }\n\n function erasNameRegex(isStrict) {\n if (!hasOwnProp(this, '_erasNameRegex')) {\n computeErasParse.call(this);\n }\n return isStrict ? this._erasNameRegex : this._erasRegex;\n }\n\n function erasAbbrRegex(isStrict) {\n if (!hasOwnProp(this, '_erasAbbrRegex')) {\n computeErasParse.call(this);\n }\n return isStrict ? this._erasAbbrRegex : this._erasRegex;\n }\n\n function erasNarrowRegex(isStrict) {\n if (!hasOwnProp(this, '_erasNarrowRegex')) {\n computeErasParse.call(this);\n }\n return isStrict ? this._erasNarrowRegex : this._erasRegex;\n }\n\n function matchEraAbbr(isStrict, locale) {\n return locale.erasAbbrRegex(isStrict);\n }\n\n function matchEraName(isStrict, locale) {\n return locale.erasNameRegex(isStrict);\n }\n\n function matchEraNarrow(isStrict, locale) {\n return locale.erasNarrowRegex(isStrict);\n }\n\n function matchEraYearOrdinal(isStrict, locale) {\n return locale._eraYearOrdinalRegex || matchUnsigned;\n }\n\n function computeErasParse() {\n var abbrPieces = [],\n namePieces = [],\n narrowPieces = [],\n mixedPieces = [],\n i,\n l,\n eras = this.eras();\n\n for (i = 0, l = eras.length; i < l; ++i) {\n namePieces.push(regexEscape(eras[i].name));\n abbrPieces.push(regexEscape(eras[i].abbr));\n narrowPieces.push(regexEscape(eras[i].narrow));\n\n mixedPieces.push(regexEscape(eras[i].name));\n mixedPieces.push(regexEscape(eras[i].abbr));\n mixedPieces.push(regexEscape(eras[i].narrow));\n }\n\n this._erasRegex = new RegExp('^(' + mixedPieces.join('|') + ')', 'i');\n this._erasNameRegex = new RegExp('^(' + namePieces.join('|') + ')', 'i');\n this._erasAbbrRegex = new RegExp('^(' + abbrPieces.join('|') + ')', 'i');\n this._erasNarrowRegex = new RegExp(\n '^(' + narrowPieces.join('|') + ')',\n 'i'\n );\n }\n\n // FORMATTING\n\n addFormatToken(0, ['gg', 2], 0, function () {\n return this.weekYear() % 100;\n });\n\n addFormatToken(0, ['GG', 2], 0, function () {\n return this.isoWeekYear() % 100;\n });\n\n function addWeekYearFormatToken(token, getter) {\n addFormatToken(0, [token, token.length], 0, getter);\n }\n\n addWeekYearFormatToken('gggg', 'weekYear');\n addWeekYearFormatToken('ggggg', 'weekYear');\n addWeekYearFormatToken('GGGG', 'isoWeekYear');\n addWeekYearFormatToken('GGGGG', 'isoWeekYear');\n\n // ALIASES\n\n addUnitAlias('weekYear', 'gg');\n addUnitAlias('isoWeekYear', 'GG');\n\n // PRIORITY\n\n addUnitPriority('weekYear', 1);\n addUnitPriority('isoWeekYear', 1);\n\n // PARSING\n\n addRegexToken('G', matchSigned);\n addRegexToken('g', matchSigned);\n addRegexToken('GG', match1to2, match2);\n addRegexToken('gg', match1to2, match2);\n addRegexToken('GGGG', match1to4, match4);\n addRegexToken('gggg', match1to4, match4);\n addRegexToken('GGGGG', match1to6, match6);\n addRegexToken('ggggg', match1to6, match6);\n\n addWeekParseToken(['gggg', 'ggggg', 'GGGG', 'GGGGG'], function (\n input,\n week,\n config,\n token\n ) {\n week[token.substr(0, 2)] = toInt(input);\n });\n\n addWeekParseToken(['gg', 'GG'], function (input, week, config, token) {\n week[token] = hooks.parseTwoDigitYear(input);\n });\n\n // MOMENTS\n\n function getSetWeekYear(input) {\n return getSetWeekYearHelper.call(\n this,\n input,\n this.week(),\n this.weekday(),\n this.localeData()._week.dow,\n this.localeData()._week.doy\n );\n }\n\n function getSetISOWeekYear(input) {\n return getSetWeekYearHelper.call(\n this,\n input,\n this.isoWeek(),\n this.isoWeekday(),\n 1,\n 4\n );\n }\n\n function getISOWeeksInYear() {\n return weeksInYear(this.year(), 1, 4);\n }\n\n function getISOWeeksInISOWeekYear() {\n return weeksInYear(this.isoWeekYear(), 1, 4);\n }\n\n function getWeeksInYear() {\n var weekInfo = this.localeData()._week;\n return weeksInYear(this.year(), weekInfo.dow, weekInfo.doy);\n }\n\n function getWeeksInWeekYear() {\n var weekInfo = this.localeData()._week;\n return weeksInYear(this.weekYear(), weekInfo.dow, weekInfo.doy);\n }\n\n function getSetWeekYearHelper(input, week, weekday, dow, doy) {\n var weeksTarget;\n if (input == null) {\n return weekOfYear(this, dow, doy).year;\n } else {\n weeksTarget = weeksInYear(input, dow, doy);\n if (week > weeksTarget) {\n week = weeksTarget;\n }\n return setWeekAll.call(this, input, week, weekday, dow, doy);\n }\n }\n\n function setWeekAll(weekYear, week, weekday, dow, doy) {\n var dayOfYearData = dayOfYearFromWeeks(weekYear, week, weekday, dow, doy),\n date = createUTCDate(dayOfYearData.year, 0, dayOfYearData.dayOfYear);\n\n this.year(date.getUTCFullYear());\n this.month(date.getUTCMonth());\n this.date(date.getUTCDate());\n return this;\n }\n\n // FORMATTING\n\n addFormatToken('Q', 0, 'Qo', 'quarter');\n\n // ALIASES\n\n addUnitAlias('quarter', 'Q');\n\n // PRIORITY\n\n addUnitPriority('quarter', 7);\n\n // PARSING\n\n addRegexToken('Q', match1);\n addParseToken('Q', function (input, array) {\n array[MONTH] = (toInt(input) - 1) * 3;\n });\n\n // MOMENTS\n\n function getSetQuarter(input) {\n return input == null\n ? Math.ceil((this.month() + 1) / 3)\n : this.month((input - 1) * 3 + (this.month() % 3));\n }\n\n // FORMATTING\n\n addFormatToken('D', ['DD', 2], 'Do', 'date');\n\n // ALIASES\n\n addUnitAlias('date', 'D');\n\n // PRIORITY\n addUnitPriority('date', 9);\n\n // PARSING\n\n addRegexToken('D', match1to2);\n addRegexToken('DD', match1to2, match2);\n addRegexToken('Do', function (isStrict, locale) {\n // TODO: Remove \"ordinalParse\" fallback in next major release.\n return isStrict\n ? locale._dayOfMonthOrdinalParse || locale._ordinalParse\n : locale._dayOfMonthOrdinalParseLenient;\n });\n\n addParseToken(['D', 'DD'], DATE);\n addParseToken('Do', function (input, array) {\n array[DATE] = toInt(input.match(match1to2)[0]);\n });\n\n // MOMENTS\n\n var getSetDayOfMonth = makeGetSet('Date', true);\n\n // FORMATTING\n\n addFormatToken('DDD', ['DDDD', 3], 'DDDo', 'dayOfYear');\n\n // ALIASES\n\n addUnitAlias('dayOfYear', 'DDD');\n\n // PRIORITY\n addUnitPriority('dayOfYear', 4);\n\n // PARSING\n\n addRegexToken('DDD', match1to3);\n addRegexToken('DDDD', match3);\n addParseToken(['DDD', 'DDDD'], function (input, array, config) {\n config._dayOfYear = toInt(input);\n });\n\n // HELPERS\n\n // MOMENTS\n\n function getSetDayOfYear(input) {\n var dayOfYear =\n Math.round(\n (this.clone().startOf('day') - this.clone().startOf('year')) / 864e5\n ) + 1;\n return input == null ? dayOfYear : this.add(input - dayOfYear, 'd');\n }\n\n // FORMATTING\n\n addFormatToken('m', ['mm', 2], 0, 'minute');\n\n // ALIASES\n\n addUnitAlias('minute', 'm');\n\n // PRIORITY\n\n addUnitPriority('minute', 14);\n\n // PARSING\n\n addRegexToken('m', match1to2);\n addRegexToken('mm', match1to2, match2);\n addParseToken(['m', 'mm'], MINUTE);\n\n // MOMENTS\n\n var getSetMinute = makeGetSet('Minutes', false);\n\n // FORMATTING\n\n addFormatToken('s', ['ss', 2], 0, 'second');\n\n // ALIASES\n\n addUnitAlias('second', 's');\n\n // PRIORITY\n\n addUnitPriority('second', 15);\n\n // PARSING\n\n addRegexToken('s', match1to2);\n addRegexToken('ss', match1to2, match2);\n addParseToken(['s', 'ss'], SECOND);\n\n // MOMENTS\n\n var getSetSecond = makeGetSet('Seconds', false);\n\n // FORMATTING\n\n addFormatToken('S', 0, 0, function () {\n return ~~(this.millisecond() / 100);\n });\n\n addFormatToken(0, ['SS', 2], 0, function () {\n return ~~(this.millisecond() / 10);\n });\n\n addFormatToken(0, ['SSS', 3], 0, 'millisecond');\n addFormatToken(0, ['SSSS', 4], 0, function () {\n return this.millisecond() * 10;\n });\n addFormatToken(0, ['SSSSS', 5], 0, function () {\n return this.millisecond() * 100;\n });\n addFormatToken(0, ['SSSSSS', 6], 0, function () {\n return this.millisecond() * 1000;\n });\n addFormatToken(0, ['SSSSSSS', 7], 0, function () {\n return this.millisecond() * 10000;\n });\n addFormatToken(0, ['SSSSSSSS', 8], 0, function () {\n return this.millisecond() * 100000;\n });\n addFormatToken(0, ['SSSSSSSSS', 9], 0, function () {\n return this.millisecond() * 1000000;\n });\n\n // ALIASES\n\n addUnitAlias('millisecond', 'ms');\n\n // PRIORITY\n\n addUnitPriority('millisecond', 16);\n\n // PARSING\n\n addRegexToken('S', match1to3, match1);\n addRegexToken('SS', match1to3, match2);\n addRegexToken('SSS', match1to3, match3);\n\n var token, getSetMillisecond;\n for (token = 'SSSS'; token.length <= 9; token += 'S') {\n addRegexToken(token, matchUnsigned);\n }\n\n function parseMs(input, array) {\n array[MILLISECOND] = toInt(('0.' + input) * 1000);\n }\n\n for (token = 'S'; token.length <= 9; token += 'S') {\n addParseToken(token, parseMs);\n }\n\n getSetMillisecond = makeGetSet('Milliseconds', false);\n\n // FORMATTING\n\n addFormatToken('z', 0, 0, 'zoneAbbr');\n addFormatToken('zz', 0, 0, 'zoneName');\n\n // MOMENTS\n\n function getZoneAbbr() {\n return this._isUTC ? 'UTC' : '';\n }\n\n function getZoneName() {\n return this._isUTC ? 'Coordinated Universal Time' : '';\n }\n\n var proto = Moment.prototype;\n\n proto.add = add;\n proto.calendar = calendar$1;\n proto.clone = clone;\n proto.diff = diff;\n proto.endOf = endOf;\n proto.format = format;\n proto.from = from;\n proto.fromNow = fromNow;\n proto.to = to;\n proto.toNow = toNow;\n proto.get = stringGet;\n proto.invalidAt = invalidAt;\n proto.isAfter = isAfter;\n proto.isBefore = isBefore;\n proto.isBetween = isBetween;\n proto.isSame = isSame;\n proto.isSameOrAfter = isSameOrAfter;\n proto.isSameOrBefore = isSameOrBefore;\n proto.isValid = isValid$2;\n proto.lang = lang;\n proto.locale = locale;\n proto.localeData = localeData;\n proto.max = prototypeMax;\n proto.min = prototypeMin;\n proto.parsingFlags = parsingFlags;\n proto.set = stringSet;\n proto.startOf = startOf;\n proto.subtract = subtract;\n proto.toArray = toArray;\n proto.toObject = toObject;\n proto.toDate = toDate;\n proto.toISOString = toISOString;\n proto.inspect = inspect;\n if (typeof Symbol !== 'undefined' && Symbol.for != null) {\n proto[Symbol.for('nodejs.util.inspect.custom')] = function () {\n return 'Moment<' + this.format() + '>';\n };\n }\n proto.toJSON = toJSON;\n proto.toString = toString;\n proto.unix = unix;\n proto.valueOf = valueOf;\n proto.creationData = creationData;\n proto.eraName = getEraName;\n proto.eraNarrow = getEraNarrow;\n proto.eraAbbr = getEraAbbr;\n proto.eraYear = getEraYear;\n proto.year = getSetYear;\n proto.isLeapYear = getIsLeapYear;\n proto.weekYear = getSetWeekYear;\n proto.isoWeekYear = getSetISOWeekYear;\n proto.quarter = proto.quarters = getSetQuarter;\n proto.month = getSetMonth;\n proto.daysInMonth = getDaysInMonth;\n proto.week = proto.weeks = getSetWeek;\n proto.isoWeek = proto.isoWeeks = getSetISOWeek;\n proto.weeksInYear = getWeeksInYear;\n proto.weeksInWeekYear = getWeeksInWeekYear;\n proto.isoWeeksInYear = getISOWeeksInYear;\n proto.isoWeeksInISOWeekYear = getISOWeeksInISOWeekYear;\n proto.date = getSetDayOfMonth;\n proto.day = proto.days = getSetDayOfWeek;\n proto.weekday = getSetLocaleDayOfWeek;\n proto.isoWeekday = getSetISODayOfWeek;\n proto.dayOfYear = getSetDayOfYear;\n proto.hour = proto.hours = getSetHour;\n proto.minute = proto.minutes = getSetMinute;\n proto.second = proto.seconds = getSetSecond;\n proto.millisecond = proto.milliseconds = getSetMillisecond;\n proto.utcOffset = getSetOffset;\n proto.utc = setOffsetToUTC;\n proto.local = setOffsetToLocal;\n proto.parseZone = setOffsetToParsedOffset;\n proto.hasAlignedHourOffset = hasAlignedHourOffset;\n proto.isDST = isDaylightSavingTime;\n proto.isLocal = isLocal;\n proto.isUtcOffset = isUtcOffset;\n proto.isUtc = isUtc;\n proto.isUTC = isUtc;\n proto.zoneAbbr = getZoneAbbr;\n proto.zoneName = getZoneName;\n proto.dates = deprecate(\n 'dates accessor is deprecated. Use date instead.',\n getSetDayOfMonth\n );\n proto.months = deprecate(\n 'months accessor is deprecated. Use month instead',\n getSetMonth\n );\n proto.years = deprecate(\n 'years accessor is deprecated. Use year instead',\n getSetYear\n );\n proto.zone = deprecate(\n 'moment().zone is deprecated, use moment().utcOffset instead. http://momentjs.com/guides/#/warnings/zone/',\n getSetZone\n );\n proto.isDSTShifted = deprecate(\n 'isDSTShifted is deprecated. See http://momentjs.com/guides/#/warnings/dst-shifted/ for more information',\n isDaylightSavingTimeShifted\n );\n\n function createUnix(input) {\n return createLocal(input * 1000);\n }\n\n function createInZone() {\n return createLocal.apply(null, arguments).parseZone();\n }\n\n function preParsePostFormat(string) {\n return string;\n }\n\n var proto$1 = Locale.prototype;\n\n proto$1.calendar = calendar;\n proto$1.longDateFormat = longDateFormat;\n proto$1.invalidDate = invalidDate;\n proto$1.ordinal = ordinal;\n proto$1.preparse = preParsePostFormat;\n proto$1.postformat = preParsePostFormat;\n proto$1.relativeTime = relativeTime;\n proto$1.pastFuture = pastFuture;\n proto$1.set = set;\n proto$1.eras = localeEras;\n proto$1.erasParse = localeErasParse;\n proto$1.erasConvertYear = localeErasConvertYear;\n proto$1.erasAbbrRegex = erasAbbrRegex;\n proto$1.erasNameRegex = erasNameRegex;\n proto$1.erasNarrowRegex = erasNarrowRegex;\n\n proto$1.months = localeMonths;\n proto$1.monthsShort = localeMonthsShort;\n proto$1.monthsParse = localeMonthsParse;\n proto$1.monthsRegex = monthsRegex;\n proto$1.monthsShortRegex = monthsShortRegex;\n proto$1.week = localeWeek;\n proto$1.firstDayOfYear = localeFirstDayOfYear;\n proto$1.firstDayOfWeek = localeFirstDayOfWeek;\n\n proto$1.weekdays = localeWeekdays;\n proto$1.weekdaysMin = localeWeekdaysMin;\n proto$1.weekdaysShort = localeWeekdaysShort;\n proto$1.weekdaysParse = localeWeekdaysParse;\n\n proto$1.weekdaysRegex = weekdaysRegex;\n proto$1.weekdaysShortRegex = weekdaysShortRegex;\n proto$1.weekdaysMinRegex = weekdaysMinRegex;\n\n proto$1.isPM = localeIsPM;\n proto$1.meridiem = localeMeridiem;\n\n function get$1(format, index, field, setter) {\n var locale = getLocale(),\n utc = createUTC().set(setter, index);\n return locale[field](utc, format);\n }\n\n function listMonthsImpl(format, index, field) {\n if (isNumber(format)) {\n index = format;\n format = undefined;\n }\n\n format = format || '';\n\n if (index != null) {\n return get$1(format, index, field, 'month');\n }\n\n var i,\n out = [];\n for (i = 0; i < 12; i++) {\n out[i] = get$1(format, i, field, 'month');\n }\n return out;\n }\n\n // ()\n // (5)\n // (fmt, 5)\n // (fmt)\n // (true)\n // (true, 5)\n // (true, fmt, 5)\n // (true, fmt)\n function listWeekdaysImpl(localeSorted, format, index, field) {\n if (typeof localeSorted === 'boolean') {\n if (isNumber(format)) {\n index = format;\n format = undefined;\n }\n\n format = format || '';\n } else {\n format = localeSorted;\n index = format;\n localeSorted = false;\n\n if (isNumber(format)) {\n index = format;\n format = undefined;\n }\n\n format = format || '';\n }\n\n var locale = getLocale(),\n shift = localeSorted ? locale._week.dow : 0,\n i,\n out = [];\n\n if (index != null) {\n return get$1(format, (index + shift) % 7, field, 'day');\n }\n\n for (i = 0; i < 7; i++) {\n out[i] = get$1(format, (i + shift) % 7, field, 'day');\n }\n return out;\n }\n\n function listMonths(format, index) {\n return listMonthsImpl(format, index, 'months');\n }\n\n function listMonthsShort(format, index) {\n return listMonthsImpl(format, index, 'monthsShort');\n }\n\n function listWeekdays(localeSorted, format, index) {\n return listWeekdaysImpl(localeSorted, format, index, 'weekdays');\n }\n\n function listWeekdaysShort(localeSorted, format, index) {\n return listWeekdaysImpl(localeSorted, format, index, 'weekdaysShort');\n }\n\n function listWeekdaysMin(localeSorted, format, index) {\n return listWeekdaysImpl(localeSorted, format, index, 'weekdaysMin');\n }\n\n getSetGlobalLocale('en', {\n eras: [\n {\n since: '0001-01-01',\n until: +Infinity,\n offset: 1,\n name: 'Anno Domini',\n narrow: 'AD',\n abbr: 'AD',\n },\n {\n since: '0000-12-31',\n until: -Infinity,\n offset: 1,\n name: 'Before Christ',\n narrow: 'BC',\n abbr: 'BC',\n },\n ],\n dayOfMonthOrdinalParse: /\\d{1,2}(th|st|nd|rd)/,\n ordinal: function (number) {\n var b = number % 10,\n output =\n toInt((number % 100) / 10) === 1\n ? 'th'\n : b === 1\n ? 'st'\n : b === 2\n ? 'nd'\n : b === 3\n ? 'rd'\n : 'th';\n return number + output;\n },\n });\n\n // Side effect imports\n\n hooks.lang = deprecate(\n 'moment.lang is deprecated. Use moment.locale instead.',\n getSetGlobalLocale\n );\n hooks.langData = deprecate(\n 'moment.langData is deprecated. Use moment.localeData instead.',\n getLocale\n );\n\n var mathAbs = Math.abs;\n\n function abs() {\n var data = this._data;\n\n this._milliseconds = mathAbs(this._milliseconds);\n this._days = mathAbs(this._days);\n this._months = mathAbs(this._months);\n\n data.milliseconds = mathAbs(data.milliseconds);\n data.seconds = mathAbs(data.seconds);\n data.minutes = mathAbs(data.minutes);\n data.hours = mathAbs(data.hours);\n data.months = mathAbs(data.months);\n data.years = mathAbs(data.years);\n\n return this;\n }\n\n function addSubtract$1(duration, input, value, direction) {\n var other = createDuration(input, value);\n\n duration._milliseconds += direction * other._milliseconds;\n duration._days += direction * other._days;\n duration._months += direction * other._months;\n\n return duration._bubble();\n }\n\n // supports only 2.0-style add(1, 's') or add(duration)\n function add$1(input, value) {\n return addSubtract$1(this, input, value, 1);\n }\n\n // supports only 2.0-style subtract(1, 's') or subtract(duration)\n function subtract$1(input, value) {\n return addSubtract$1(this, input, value, -1);\n }\n\n function absCeil(number) {\n if (number < 0) {\n return Math.floor(number);\n } else {\n return Math.ceil(number);\n }\n }\n\n function bubble() {\n var milliseconds = this._milliseconds,\n days = this._days,\n months = this._months,\n data = this._data,\n seconds,\n minutes,\n hours,\n years,\n monthsFromDays;\n\n // if we have a mix of positive and negative values, bubble down first\n // check: https://github.com/moment/moment/issues/2166\n if (\n !(\n (milliseconds >= 0 && days >= 0 && months >= 0) ||\n (milliseconds <= 0 && days <= 0 && months <= 0)\n )\n ) {\n milliseconds += absCeil(monthsToDays(months) + days) * 864e5;\n days = 0;\n months = 0;\n }\n\n // The following code bubbles up values, see the tests for\n // examples of what that means.\n data.milliseconds = milliseconds % 1000;\n\n seconds = absFloor(milliseconds / 1000);\n data.seconds = seconds % 60;\n\n minutes = absFloor(seconds / 60);\n data.minutes = minutes % 60;\n\n hours = absFloor(minutes / 60);\n data.hours = hours % 24;\n\n days += absFloor(hours / 24);\n\n // convert days to months\n monthsFromDays = absFloor(daysToMonths(days));\n months += monthsFromDays;\n days -= absCeil(monthsToDays(monthsFromDays));\n\n // 12 months -> 1 year\n years = absFloor(months / 12);\n months %= 12;\n\n data.days = days;\n data.months = months;\n data.years = years;\n\n return this;\n }\n\n function daysToMonths(days) {\n // 400 years have 146097 days (taking into account leap year rules)\n // 400 years have 12 months === 4800\n return (days * 4800) / 146097;\n }\n\n function monthsToDays(months) {\n // the reverse of daysToMonths\n return (months * 146097) / 4800;\n }\n\n function as(units) {\n if (!this.isValid()) {\n return NaN;\n }\n var days,\n months,\n milliseconds = this._milliseconds;\n\n units = normalizeUnits(units);\n\n if (units === 'month' || units === 'quarter' || units === 'year') {\n days = this._days + milliseconds / 864e5;\n months = this._months + daysToMonths(days);\n switch (units) {\n case 'month':\n return months;\n case 'quarter':\n return months / 3;\n case 'year':\n return months / 12;\n }\n } else {\n // handle milliseconds separately because of floating point math errors (issue #1867)\n days = this._days + Math.round(monthsToDays(this._months));\n switch (units) {\n case 'week':\n return days / 7 + milliseconds / 6048e5;\n case 'day':\n return days + milliseconds / 864e5;\n case 'hour':\n return days * 24 + milliseconds / 36e5;\n case 'minute':\n return days * 1440 + milliseconds / 6e4;\n case 'second':\n return days * 86400 + milliseconds / 1000;\n // Math.floor prevents floating point math errors here\n case 'millisecond':\n return Math.floor(days * 864e5) + milliseconds;\n default:\n throw new Error('Unknown unit ' + units);\n }\n }\n }\n\n // TODO: Use this.as('ms')?\n function valueOf$1() {\n if (!this.isValid()) {\n return NaN;\n }\n return (\n this._milliseconds +\n this._days * 864e5 +\n (this._months % 12) * 2592e6 +\n toInt(this._months / 12) * 31536e6\n );\n }\n\n function makeAs(alias) {\n return function () {\n return this.as(alias);\n };\n }\n\n var asMilliseconds = makeAs('ms'),\n asSeconds = makeAs('s'),\n asMinutes = makeAs('m'),\n asHours = makeAs('h'),\n asDays = makeAs('d'),\n asWeeks = makeAs('w'),\n asMonths = makeAs('M'),\n asQuarters = makeAs('Q'),\n asYears = makeAs('y');\n\n function clone$1() {\n return createDuration(this);\n }\n\n function get$2(units) {\n units = normalizeUnits(units);\n return this.isValid() ? this[units + 's']() : NaN;\n }\n\n function makeGetter(name) {\n return function () {\n return this.isValid() ? this._data[name] : NaN;\n };\n }\n\n var milliseconds = makeGetter('milliseconds'),\n seconds = makeGetter('seconds'),\n minutes = makeGetter('minutes'),\n hours = makeGetter('hours'),\n days = makeGetter('days'),\n months = makeGetter('months'),\n years = makeGetter('years');\n\n function weeks() {\n return absFloor(this.days() / 7);\n }\n\n var round = Math.round,\n thresholds = {\n ss: 44, // a few seconds to seconds\n s: 45, // seconds to minute\n m: 45, // minutes to hour\n h: 22, // hours to day\n d: 26, // days to month/week\n w: null, // weeks to month\n M: 11, // months to year\n };\n\n // helper function for moment.fn.from, moment.fn.fromNow, and moment.duration.fn.humanize\n function substituteTimeAgo(string, number, withoutSuffix, isFuture, locale) {\n return locale.relativeTime(number || 1, !!withoutSuffix, string, isFuture);\n }\n\n function relativeTime$1(posNegDuration, withoutSuffix, thresholds, locale) {\n var duration = createDuration(posNegDuration).abs(),\n seconds = round(duration.as('s')),\n minutes = round(duration.as('m')),\n hours = round(duration.as('h')),\n days = round(duration.as('d')),\n months = round(duration.as('M')),\n weeks = round(duration.as('w')),\n years = round(duration.as('y')),\n a =\n (seconds <= thresholds.ss && ['s', seconds]) ||\n (seconds < thresholds.s && ['ss', seconds]) ||\n (minutes <= 1 && ['m']) ||\n (minutes < thresholds.m && ['mm', minutes]) ||\n (hours <= 1 && ['h']) ||\n (hours < thresholds.h && ['hh', hours]) ||\n (days <= 1 && ['d']) ||\n (days < thresholds.d && ['dd', days]);\n\n if (thresholds.w != null) {\n a =\n a ||\n (weeks <= 1 && ['w']) ||\n (weeks < thresholds.w && ['ww', weeks]);\n }\n a = a ||\n (months <= 1 && ['M']) ||\n (months < thresholds.M && ['MM', months]) ||\n (years <= 1 && ['y']) || ['yy', years];\n\n a[2] = withoutSuffix;\n a[3] = +posNegDuration > 0;\n a[4] = locale;\n return substituteTimeAgo.apply(null, a);\n }\n\n // This function allows you to set the rounding function for relative time strings\n function getSetRelativeTimeRounding(roundingFunction) {\n if (roundingFunction === undefined) {\n return round;\n }\n if (typeof roundingFunction === 'function') {\n round = roundingFunction;\n return true;\n }\n return false;\n }\n\n // This function allows you to set a threshold for relative time strings\n function getSetRelativeTimeThreshold(threshold, limit) {\n if (thresholds[threshold] === undefined) {\n return false;\n }\n if (limit === undefined) {\n return thresholds[threshold];\n }\n thresholds[threshold] = limit;\n if (threshold === 's') {\n thresholds.ss = limit - 1;\n }\n return true;\n }\n\n function humanize(argWithSuffix, argThresholds) {\n if (!this.isValid()) {\n return this.localeData().invalidDate();\n }\n\n var withSuffix = false,\n th = thresholds,\n locale,\n output;\n\n if (typeof argWithSuffix === 'object') {\n argThresholds = argWithSuffix;\n argWithSuffix = false;\n }\n if (typeof argWithSuffix === 'boolean') {\n withSuffix = argWithSuffix;\n }\n if (typeof argThresholds === 'object') {\n th = Object.assign({}, thresholds, argThresholds);\n if (argThresholds.s != null && argThresholds.ss == null) {\n th.ss = argThresholds.s - 1;\n }\n }\n\n locale = this.localeData();\n output = relativeTime$1(this, !withSuffix, th, locale);\n\n if (withSuffix) {\n output = locale.pastFuture(+this, output);\n }\n\n return locale.postformat(output);\n }\n\n var abs$1 = Math.abs;\n\n function sign(x) {\n return (x > 0) - (x < 0) || +x;\n }\n\n function toISOString$1() {\n // for ISO strings we do not use the normal bubbling rules:\n // * milliseconds bubble up until they become hours\n // * days do not bubble at all\n // * months bubble up until they become years\n // This is because there is no context-free conversion between hours and days\n // (think of clock changes)\n // and also not between days and months (28-31 days per month)\n if (!this.isValid()) {\n return this.localeData().invalidDate();\n }\n\n var seconds = abs$1(this._milliseconds) / 1000,\n days = abs$1(this._days),\n months = abs$1(this._months),\n minutes,\n hours,\n years,\n s,\n total = this.asSeconds(),\n totalSign,\n ymSign,\n daysSign,\n hmsSign;\n\n if (!total) {\n // this is the same as C#'s (Noda) and python (isodate)...\n // but not other JS (goog.date)\n return 'P0D';\n }\n\n // 3600 seconds -> 60 minutes -> 1 hour\n minutes = absFloor(seconds / 60);\n hours = absFloor(minutes / 60);\n seconds %= 60;\n minutes %= 60;\n\n // 12 months -> 1 year\n years = absFloor(months / 12);\n months %= 12;\n\n // inspired by https://github.com/dordille/moment-isoduration/blob/master/moment.isoduration.js\n s = seconds ? seconds.toFixed(3).replace(/\\.?0+$/, '') : '';\n\n totalSign = total < 0 ? '-' : '';\n ymSign = sign(this._months) !== sign(total) ? '-' : '';\n daysSign = sign(this._days) !== sign(total) ? '-' : '';\n hmsSign = sign(this._milliseconds) !== sign(total) ? '-' : '';\n\n return (\n totalSign +\n 'P' +\n (years ? ymSign + years + 'Y' : '') +\n (months ? ymSign + months + 'M' : '') +\n (days ? daysSign + days + 'D' : '') +\n (hours || minutes || seconds ? 'T' : '') +\n (hours ? hmsSign + hours + 'H' : '') +\n (minutes ? hmsSign + minutes + 'M' : '') +\n (seconds ? hmsSign + s + 'S' : '')\n );\n }\n\n var proto$2 = Duration.prototype;\n\n proto$2.isValid = isValid$1;\n proto$2.abs = abs;\n proto$2.add = add$1;\n proto$2.subtract = subtract$1;\n proto$2.as = as;\n proto$2.asMilliseconds = asMilliseconds;\n proto$2.asSeconds = asSeconds;\n proto$2.asMinutes = asMinutes;\n proto$2.asHours = asHours;\n proto$2.asDays = asDays;\n proto$2.asWeeks = asWeeks;\n proto$2.asMonths = asMonths;\n proto$2.asQuarters = asQuarters;\n proto$2.asYears = asYears;\n proto$2.valueOf = valueOf$1;\n proto$2._bubble = bubble;\n proto$2.clone = clone$1;\n proto$2.get = get$2;\n proto$2.milliseconds = milliseconds;\n proto$2.seconds = seconds;\n proto$2.minutes = minutes;\n proto$2.hours = hours;\n proto$2.days = days;\n proto$2.weeks = weeks;\n proto$2.months = months;\n proto$2.years = years;\n proto$2.humanize = humanize;\n proto$2.toISOString = toISOString$1;\n proto$2.toString = toISOString$1;\n proto$2.toJSON = toISOString$1;\n proto$2.locale = locale;\n proto$2.localeData = localeData;\n\n proto$2.toIsoString = deprecate(\n 'toIsoString() is deprecated. Please use toISOString() instead (notice the capitals)',\n toISOString$1\n );\n proto$2.lang = lang;\n\n // FORMATTING\n\n addFormatToken('X', 0, 0, 'unix');\n addFormatToken('x', 0, 0, 'valueOf');\n\n // PARSING\n\n addRegexToken('x', matchSigned);\n addRegexToken('X', matchTimestamp);\n addParseToken('X', function (input, array, config) {\n config._d = new Date(parseFloat(input) * 1000);\n });\n addParseToken('x', function (input, array, config) {\n config._d = new Date(toInt(input));\n });\n\n //! moment.js\n\n hooks.version = '2.29.0';\n\n setHookCallback(createLocal);\n\n hooks.fn = proto;\n hooks.min = min;\n hooks.max = max;\n hooks.now = now;\n hooks.utc = createUTC;\n hooks.unix = createUnix;\n hooks.months = listMonths;\n hooks.isDate = isDate;\n hooks.locale = getSetGlobalLocale;\n hooks.invalid = createInvalid;\n hooks.duration = createDuration;\n hooks.isMoment = isMoment;\n hooks.weekdays = listWeekdays;\n hooks.parseZone = createInZone;\n hooks.localeData = getLocale;\n hooks.isDuration = isDuration;\n hooks.monthsShort = listMonthsShort;\n hooks.weekdaysMin = listWeekdaysMin;\n hooks.defineLocale = defineLocale;\n hooks.updateLocale = updateLocale;\n hooks.locales = listLocales;\n hooks.weekdaysShort = listWeekdaysShort;\n hooks.normalizeUnits = normalizeUnits;\n hooks.relativeTimeRounding = getSetRelativeTimeRounding;\n hooks.relativeTimeThreshold = getSetRelativeTimeThreshold;\n hooks.calendarFormat = getCalendarFormat;\n hooks.prototype = proto;\n\n // currently HTML5 input type only supports 24-hour formats\n hooks.HTML5_FMT = {\n DATETIME_LOCAL: 'YYYY-MM-DDTHH:mm', // \n DATETIME_LOCAL_SECONDS: 'YYYY-MM-DDTHH:mm:ss', // \n DATETIME_LOCAL_MS: 'YYYY-MM-DDTHH:mm:ss.SSS', // \n DATE: 'YYYY-MM-DD', // \n TIME: 'HH:mm', // \n TIME_SECONDS: 'HH:mm:ss', // \n TIME_MS: 'HH:mm:ss.SSS', // \n WEEK: 'GGGG-[W]WW', // \n MONTH: 'YYYY-MM', // \n };\n\n return hooks;\n\n})));\n", "/** @typedef {import('../photoswipe.js').Point} Point */\r\n\r\n/**\r\n * @template {keyof HTMLElementTagNameMap} T\r\n * @param {string} className\r\n * @param {T} tagName\r\n * @param {Node} [appendToEl]\r\n * @returns {HTMLElementTagNameMap[T]}\r\n */\r\nexport function createElement(className, tagName, appendToEl) {\r\n const el = document.createElement(tagName);\r\n if (className) {\r\n el.className = className;\r\n }\r\n if (appendToEl) {\r\n appendToEl.appendChild(el);\r\n }\r\n return el;\r\n}\r\n\r\n/**\r\n * @param {Point} p1\r\n * @param {Point} p2\r\n * @returns {Point}\r\n */\r\nexport function equalizePoints(p1, p2) {\r\n p1.x = p2.x;\r\n p1.y = p2.y;\r\n if (p2.id !== undefined) {\r\n p1.id = p2.id;\r\n }\r\n return p1;\r\n}\r\n\r\n/**\r\n * @param {Point} p\r\n */\r\nexport function roundPoint(p) {\r\n p.x = Math.round(p.x);\r\n p.y = Math.round(p.y);\r\n}\r\n\r\n/**\r\n * Returns distance between two points.\r\n *\r\n * @param {Point} p1\r\n * @param {Point} p2\r\n * @returns {number}\r\n */\r\nexport function getDistanceBetween(p1, p2) {\r\n const x = Math.abs(p1.x - p2.x);\r\n const y = Math.abs(p1.y - p2.y);\r\n return Math.sqrt((x * x) + (y * y));\r\n}\r\n\r\n/**\r\n * Whether X and Y positions of points are equal\r\n *\r\n * @param {Point} p1\r\n * @param {Point} p2\r\n * @returns {boolean}\r\n */\r\nexport function pointsEqual(p1, p2) {\r\n return p1.x === p2.x && p1.y === p2.y;\r\n}\r\n\r\n/**\r\n * The float result between the min and max values.\r\n *\r\n * @param {number} val\r\n * @param {number} min\r\n * @param {number} max\r\n * @returns {number}\r\n */\r\nexport function clamp(val, min, max) {\r\n return Math.min(Math.max(val, min), max);\r\n}\r\n\r\n/**\r\n * Get transform string\r\n *\r\n * @param {number} x\r\n * @param {number} [y]\r\n * @param {number} [scale]\r\n * @returns {string}\r\n */\r\nexport function toTransformString(x, y, scale) {\r\n let propValue = `translate3d(${x}px,${y || 0}px,0)`;\r\n\r\n if (scale !== undefined) {\r\n propValue += ` scale3d(${scale},${scale},1)`;\r\n }\r\n\r\n return propValue;\r\n}\r\n\r\n/**\r\n * Apply transform:translate(x, y) scale(scale) to element\r\n *\r\n * @param {HTMLElement} el\r\n * @param {number} x\r\n * @param {number} [y]\r\n * @param {number} [scale]\r\n */\r\nexport function setTransform(el, x, y, scale) {\r\n el.style.transform = toTransformString(x, y, scale);\r\n}\r\n\r\nconst defaultCSSEasing = 'cubic-bezier(.4,0,.22,1)';\r\n\r\n/**\r\n * Apply CSS transition to element\r\n *\r\n * @param {HTMLElement} el\r\n * @param {string} [prop] CSS property to animate\r\n * @param {number} [duration] in ms\r\n * @param {string} [ease] CSS easing function\r\n */\r\nexport function setTransitionStyle(el, prop, duration, ease) {\r\n // inOut: 'cubic-bezier(.4, 0, .22, 1)', // for \"toggle state\" transitions\r\n // out: 'cubic-bezier(0, 0, .22, 1)', // for \"show\" transitions\r\n // in: 'cubic-bezier(.4, 0, 1, 1)'// for \"hide\" transitions\r\n el.style.transition = prop\r\n ? `${prop} ${duration}ms ${ease || defaultCSSEasing}`\r\n : 'none';\r\n}\r\n\r\n/**\r\n * Apply width and height CSS properties to element\r\n *\r\n * @param {HTMLElement} el\r\n * @param {string | number} w\r\n * @param {string | number} h\r\n */\r\nexport function setWidthHeight(el, w, h) {\r\n el.style.width = (typeof w === 'number') ? `${w}px` : w;\r\n el.style.height = (typeof h === 'number') ? `${h}px` : h;\r\n}\r\n\r\n/**\r\n * @param {HTMLElement} el\r\n */\r\nexport function removeTransitionStyle(el) {\r\n setTransitionStyle(el);\r\n}\r\n\r\n/**\r\n * @param {HTMLImageElement} img\r\n * @returns {Promise}\r\n */\r\nexport function decodeImage(img) {\r\n if ('decode' in img) {\r\n return img.decode().catch(() => {});\r\n }\r\n\r\n if (img.complete) {\r\n return Promise.resolve(img);\r\n }\r\n\r\n return new Promise((resolve, reject) => {\r\n img.onload = () => resolve(img);\r\n img.onerror = reject;\r\n });\r\n}\r\n\r\n/** @typedef {LOAD_STATE[keyof LOAD_STATE]} LoadState */\r\n/** @type {{ IDLE: 'idle'; LOADING: 'loading'; LOADED: 'loaded'; ERROR: 'error' }} */\r\nexport const LOAD_STATE = {\r\n IDLE: 'idle',\r\n LOADING: 'loading',\r\n LOADED: 'loaded',\r\n ERROR: 'error',\r\n};\r\n\r\n\r\n/**\r\n * Check if click or keydown event was dispatched\r\n * with a special key or via mouse wheel.\r\n *\r\n * @param {MouseEvent | KeyboardEvent} e\r\n * @returns {boolean}\r\n */\r\nexport function specialKeyUsed(e) {\r\n return ('button' in e && e.button === 1) || e.ctrlKey || e.metaKey || e.altKey || e.shiftKey;\r\n}\r\n\r\n/**\r\n * Parse `gallery` or `children` options.\r\n *\r\n * @param {import('../photoswipe.js').ElementProvider} [option]\r\n * @param {string} [legacySelector]\r\n * @param {HTMLElement | Document} [parent]\r\n * @returns HTMLElement[]\r\n */\r\nexport function getElementsFromOption(option, legacySelector, parent = document) {\r\n /** @type {HTMLElement[]} */\r\n let elements = [];\r\n\r\n if (option instanceof Element) {\r\n elements = [option];\r\n } else if (option instanceof NodeList || Array.isArray(option)) {\r\n elements = Array.from(option);\r\n } else {\r\n const selector = typeof option === 'string' ? option : legacySelector;\r\n if (selector) {\r\n elements = Array.from(parent.querySelectorAll(selector));\r\n }\r\n }\r\n\r\n return elements;\r\n}\r\n\r\n/**\r\n * Check if variable is PhotoSwipe class\r\n *\r\n * @param {any} fn\r\n * @returns {boolean}\r\n */\r\nexport function isPswpClass(fn) {\r\n return typeof fn === 'function'\r\n && fn.prototype\r\n && fn.prototype.goTo;\r\n}\r\n\r\n/**\r\n * Check if browser is Safari\r\n *\r\n * @returns {boolean}\r\n */\r\nexport function isSafari() {\r\n return !!(navigator.vendor && navigator.vendor.match(/apple/i));\r\n}\r\n\r\n", "// Detect passive event listener support\r\nlet supportsPassive = false;\r\n/* eslint-disable */\r\ntry {\r\n /* @ts-ignore */\r\n window.addEventListener('test', null, Object.defineProperty({}, 'passive', {\r\n get: () => {\r\n supportsPassive = true;\r\n }\r\n }));\r\n} catch (e) {}\r\n/* eslint-enable */\r\n\r\n/**\r\n * @typedef {Object} PoolItem\r\n * @prop {HTMLElement | Window | Document | undefined | null} target\r\n * @prop {string} type\r\n * @prop {EventListenerOrEventListenerObject} listener\r\n * @prop {boolean} [passive]\r\n */\r\n\r\nclass DOMEvents {\r\n constructor() {\r\n /**\r\n * @type {PoolItem[]}\r\n * @private\r\n */\r\n this._pool = [];\r\n }\r\n\r\n /**\r\n * Adds event listeners\r\n *\r\n * @param {PoolItem['target']} target\r\n * @param {PoolItem['type']} type Can be multiple, separated by space.\r\n * @param {PoolItem['listener']} listener\r\n * @param {PoolItem['passive']} [passive]\r\n */\r\n add(target, type, listener, passive) {\r\n this._toggleListener(target, type, listener, passive);\r\n }\r\n\r\n /**\r\n * Removes event listeners\r\n *\r\n * @param {PoolItem['target']} target\r\n * @param {PoolItem['type']} type\r\n * @param {PoolItem['listener']} listener\r\n * @param {PoolItem['passive']} [passive]\r\n */\r\n remove(target, type, listener, passive) {\r\n this._toggleListener(target, type, listener, passive, true);\r\n }\r\n\r\n /**\r\n * Removes all bound events\r\n */\r\n removeAll() {\r\n this._pool.forEach((poolItem) => {\r\n this._toggleListener(\r\n poolItem.target,\r\n poolItem.type,\r\n poolItem.listener,\r\n poolItem.passive,\r\n true,\r\n true\r\n );\r\n });\r\n this._pool = [];\r\n }\r\n\r\n /**\r\n * Adds or removes event\r\n *\r\n * @private\r\n * @param {PoolItem['target']} target\r\n * @param {PoolItem['type']} type\r\n * @param {PoolItem['listener']} listener\r\n * @param {PoolItem['passive']} [passive]\r\n * @param {boolean} [unbind] Whether the event should be added or removed\r\n * @param {boolean} [skipPool] Whether events pool should be skipped\r\n */\r\n _toggleListener(target, type, listener, passive, unbind, skipPool) {\r\n if (!target) {\r\n return;\r\n }\r\n\r\n const methodName = unbind ? 'removeEventListener' : 'addEventListener';\r\n const types = type.split(' ');\r\n types.forEach((eType) => {\r\n if (eType) {\r\n // Events pool is used to easily unbind all events when PhotoSwipe is closed,\r\n // so developer doesn't need to do this manually\r\n if (!skipPool) {\r\n if (unbind) {\r\n // Remove from the events pool\r\n this._pool = this._pool.filter((poolItem) => {\r\n return poolItem.type !== eType\r\n || poolItem.listener !== listener\r\n || poolItem.target !== target;\r\n });\r\n } else {\r\n // Add to the events pool\r\n this._pool.push({\r\n target,\r\n type: eType,\r\n listener,\r\n passive\r\n });\r\n }\r\n }\r\n\r\n // most PhotoSwipe events call preventDefault,\r\n // and we do not need browser to scroll the page\r\n const eventOptions = supportsPassive ? { passive: (passive || false) } : false;\r\n\r\n target[methodName](\r\n eType,\r\n listener,\r\n eventOptions\r\n );\r\n }\r\n });\r\n }\r\n}\r\n\r\nexport default DOMEvents;\r\n", "/** @typedef {import('../photoswipe.js').PhotoSwipeOptions} PhotoSwipeOptions */\r\n/** @typedef {import('../core/base.js').default} PhotoSwipeBase */\r\n/** @typedef {import('../photoswipe.js').Point} Point */\r\n/** @typedef {import('../slide/slide.js').SlideData} SlideData */\r\n\r\n/**\r\n * @param {PhotoSwipeOptions} options\r\n * @param {PhotoSwipeBase} pswp\r\n * @returns {Point}\r\n */\r\nexport function getViewportSize(options, pswp) {\r\n if (options.getViewportSizeFn) {\r\n const newViewportSize = options.getViewportSizeFn(options, pswp);\r\n if (newViewportSize) {\r\n return newViewportSize;\r\n }\r\n }\r\n\r\n return {\r\n x: document.documentElement.clientWidth,\r\n\r\n // TODO: height on mobile is very incosistent due to toolbar\r\n // find a way to improve this\r\n //\r\n // document.documentElement.clientHeight - doesn't seem to work well\r\n y: window.innerHeight\r\n };\r\n}\r\n\r\n/**\r\n * Parses padding option.\r\n * Supported formats:\r\n *\r\n * // Object\r\n * padding: {\r\n * top: 0,\r\n * bottom: 0,\r\n * left: 0,\r\n * right: 0\r\n * }\r\n *\r\n * // A function that returns the object\r\n * paddingFn: (viewportSize, itemData, index) => {\r\n * return {\r\n * top: 0,\r\n * bottom: 0,\r\n * left: 0,\r\n * right: 0\r\n * };\r\n * }\r\n *\r\n * // Legacy variant\r\n * paddingLeft: 0,\r\n * paddingRight: 0,\r\n * paddingTop: 0,\r\n * paddingBottom: 0,\r\n *\r\n * @param {'left' | 'top' | 'bottom' | 'right'} prop\r\n * @param {PhotoSwipeOptions} options PhotoSwipe options\r\n * @param {Point} viewportSize PhotoSwipe viewport size, for example: { x:800, y:600 }\r\n * @param {SlideData} itemData Data about the slide\r\n * @param {number} index Slide index\r\n * @returns {number}\r\n */\r\nexport function parsePaddingOption(prop, options, viewportSize, itemData, index) {\r\n let paddingValue = 0;\r\n\r\n if (options.paddingFn) {\r\n paddingValue = options.paddingFn(viewportSize, itemData, index)[prop];\r\n } else if (options.padding) {\r\n paddingValue = options.padding[prop];\r\n } else {\r\n const legacyPropName = 'padding' + prop[0].toUpperCase() + prop.slice(1);\r\n // @ts-expect-error\r\n if (options[legacyPropName]) {\r\n // @ts-expect-error\r\n paddingValue = options[legacyPropName];\r\n }\r\n }\r\n\r\n return Number(paddingValue) || 0;\r\n}\r\n\r\n/**\r\n * @param {PhotoSwipeOptions} options\r\n * @param {Point} viewportSize\r\n * @param {SlideData} itemData\r\n * @param {number} index\r\n * @returns {Point}\r\n */\r\nexport function getPanAreaSize(options, viewportSize, itemData, index) {\r\n return {\r\n x: viewportSize.x\r\n - parsePaddingOption('left', options, viewportSize, itemData, index)\r\n - parsePaddingOption('right', options, viewportSize, itemData, index),\r\n y: viewportSize.y\r\n - parsePaddingOption('top', options, viewportSize, itemData, index)\r\n - parsePaddingOption('bottom', options, viewportSize, itemData, index)\r\n };\r\n}\r\n", "import { clamp } from '../util/util.js';\r\nimport { parsePaddingOption } from '../util/viewport-size.js';\r\n\r\n/** @typedef {import('./slide.js').default} Slide */\r\n/** @typedef {Record} Point */\r\n/** @typedef {'x' | 'y'} Axis */\r\n\r\n/**\r\n * Calculates minimum, maximum and initial (center) bounds of a slide\r\n */\r\nclass PanBounds {\r\n /**\r\n * @param {Slide} slide\r\n */\r\n constructor(slide) {\r\n this.slide = slide;\r\n this.currZoomLevel = 1;\r\n this.center = /** @type {Point} */ { x: 0, y: 0 };\r\n this.max = /** @type {Point} */ { x: 0, y: 0 };\r\n this.min = /** @type {Point} */ { x: 0, y: 0 };\r\n }\r\n\r\n /**\r\n * _getItemBounds\r\n *\r\n * @param {number} currZoomLevel\r\n */\r\n update(currZoomLevel) {\r\n this.currZoomLevel = currZoomLevel;\r\n\r\n if (!this.slide.width) {\r\n this.reset();\r\n } else {\r\n this._updateAxis('x');\r\n this._updateAxis('y');\r\n this.slide.pswp.dispatch('calcBounds', { slide: this.slide });\r\n }\r\n }\r\n\r\n /**\r\n * _calculateItemBoundsForAxis\r\n *\r\n * @param {Axis} axis\r\n */\r\n _updateAxis(axis) {\r\n const { pswp } = this.slide;\r\n const elSize = this.slide[axis === 'x' ? 'width' : 'height'] * this.currZoomLevel;\r\n const paddingProp = axis === 'x' ? 'left' : 'top';\r\n const padding = parsePaddingOption(\r\n paddingProp,\r\n pswp.options,\r\n pswp.viewportSize,\r\n this.slide.data,\r\n this.slide.index\r\n );\r\n\r\n const panAreaSize = this.slide.panAreaSize[axis];\r\n\r\n // Default position of element.\r\n // By default, it is center of viewport:\r\n this.center[axis] = Math.round((panAreaSize - elSize) / 2) + padding;\r\n\r\n // maximum pan position\r\n this.max[axis] = (elSize > panAreaSize)\r\n ? Math.round(panAreaSize - elSize) + padding\r\n : this.center[axis];\r\n\r\n // minimum pan position\r\n this.min[axis] = (elSize > panAreaSize)\r\n ? padding\r\n : this.center[axis];\r\n }\r\n\r\n // _getZeroBounds\r\n reset() {\r\n this.center.x = 0;\r\n this.center.y = 0;\r\n this.max.x = 0;\r\n this.max.y = 0;\r\n this.min.x = 0;\r\n this.min.y = 0;\r\n }\r\n\r\n /**\r\n * Correct pan position if it's beyond the bounds\r\n *\r\n * @param {Axis} axis x or y\r\n * @param {number} panOffset\r\n * @returns {number}\r\n */\r\n correctPan(axis, panOffset) { // checkPanBounds\r\n return clamp(panOffset, this.max[axis], this.min[axis]);\r\n }\r\n}\r\n\r\nexport default PanBounds;\r\n", "const MAX_IMAGE_WIDTH = 4000;\r\n\r\n/** @typedef {import('../photoswipe.js').default} PhotoSwipe */\r\n/** @typedef {import('../photoswipe.js').PhotoSwipeOptions} PhotoSwipeOptions */\r\n/** @typedef {import('../photoswipe.js').Point} Point */\r\n/** @typedef {import('../slide/slide.js').SlideData} SlideData */\r\n\r\n/** @typedef {'fit' | 'fill' | number | ((zoomLevelObject: ZoomLevel) => number)} ZoomLevelOption */\r\n\r\n/**\r\n * Calculates zoom levels for specific slide.\r\n * Depends on viewport size and image size.\r\n */\r\nclass ZoomLevel {\r\n /**\r\n * @param {PhotoSwipeOptions} options PhotoSwipe options\r\n * @param {SlideData} itemData Slide data\r\n * @param {number} index Slide index\r\n * @param {PhotoSwipe} [pswp] PhotoSwipe instance, can be undefined if not initialized yet\r\n */\r\n constructor(options, itemData, index, pswp) {\r\n this.pswp = pswp;\r\n this.options = options;\r\n this.itemData = itemData;\r\n this.index = index;\r\n /** @type { Point | null } */\r\n this.panAreaSize = null;\r\n /** @type { Point | null } */\r\n this.elementSize = null;\r\n this.fit = 1;\r\n this.fill = 1;\r\n this.vFill = 1;\r\n this.initial = 1;\r\n this.secondary = 1;\r\n this.max = 1;\r\n this.min = 1;\r\n }\r\n\r\n /**\r\n * Calculate initial, secondary and maximum zoom level for the specified slide.\r\n *\r\n * It should be called when either image or viewport size changes.\r\n *\r\n * @param {number} maxWidth\r\n * @param {number} maxHeight\r\n * @param {Point} panAreaSize\r\n */\r\n update(maxWidth, maxHeight, panAreaSize) {\r\n /** @type {Point} */\r\n const elementSize = { x: maxWidth, y: maxHeight };\r\n this.elementSize = elementSize;\r\n this.panAreaSize = panAreaSize;\r\n\r\n const hRatio = panAreaSize.x / elementSize.x;\r\n const vRatio = panAreaSize.y / elementSize.y;\r\n\r\n this.fit = Math.min(1, hRatio < vRatio ? hRatio : vRatio);\r\n this.fill = Math.min(1, hRatio > vRatio ? hRatio : vRatio);\r\n\r\n // zoom.vFill defines zoom level of the image\r\n // when it has 100% of viewport vertical space (height)\r\n this.vFill = Math.min(1, vRatio);\r\n\r\n this.initial = this._getInitial();\r\n this.secondary = this._getSecondary();\r\n this.max = Math.max(\r\n this.initial,\r\n this.secondary,\r\n this._getMax()\r\n );\r\n\r\n this.min = Math.min(\r\n this.fit,\r\n this.initial,\r\n this.secondary\r\n );\r\n\r\n if (this.pswp) {\r\n this.pswp.dispatch('zoomLevelsUpdate', { zoomLevels: this, slideData: this.itemData });\r\n }\r\n }\r\n\r\n /**\r\n * Parses user-defined zoom option.\r\n *\r\n * @private\r\n * @param {'initial' | 'secondary' | 'max'} optionPrefix Zoom level option prefix (initial, secondary, max)\r\n * @returns { number | undefined }\r\n */\r\n _parseZoomLevelOption(optionPrefix) {\r\n const optionName = /** @type {'initialZoomLevel' | 'secondaryZoomLevel' | 'maxZoomLevel'} */ (\r\n optionPrefix + 'ZoomLevel'\r\n );\r\n const optionValue = this.options[optionName];\r\n\r\n if (!optionValue) {\r\n return;\r\n }\r\n\r\n if (typeof optionValue === 'function') {\r\n return optionValue(this);\r\n }\r\n\r\n if (optionValue === 'fill') {\r\n return this.fill;\r\n }\r\n\r\n if (optionValue === 'fit') {\r\n return this.fit;\r\n }\r\n\r\n return Number(optionValue);\r\n }\r\n\r\n /**\r\n * Get zoom level to which image will be zoomed after double-tap gesture,\r\n * or when user clicks on zoom icon,\r\n * or mouse-click on image itself.\r\n * If you return 1 image will be zoomed to its original size.\r\n *\r\n * @private\r\n * @return {number}\r\n */\r\n _getSecondary() {\r\n let currZoomLevel = this._parseZoomLevelOption('secondary');\r\n\r\n if (currZoomLevel) {\r\n return currZoomLevel;\r\n }\r\n\r\n // 3x of \"fit\" state, but not larger than original\r\n currZoomLevel = Math.min(1, this.fit * 3);\r\n\r\n if (this.elementSize && currZoomLevel * this.elementSize.x > MAX_IMAGE_WIDTH) {\r\n currZoomLevel = MAX_IMAGE_WIDTH / this.elementSize.x;\r\n }\r\n\r\n return currZoomLevel;\r\n }\r\n\r\n /**\r\n * Get initial image zoom level.\r\n *\r\n * @private\r\n * @return {number}\r\n */\r\n _getInitial() {\r\n return this._parseZoomLevelOption('initial') || this.fit;\r\n }\r\n\r\n /**\r\n * Maximum zoom level when user zooms\r\n * via zoom/pinch gesture,\r\n * via cmd/ctrl-wheel or via trackpad.\r\n *\r\n * @private\r\n * @return {number}\r\n */\r\n _getMax() {\r\n // max zoom level is x4 from \"fit state\",\r\n // used for zoom gesture and ctrl/trackpad zoom\r\n return this._parseZoomLevelOption('max') || Math.max(1, this.fit * 4);\r\n }\r\n}\r\n\r\nexport default ZoomLevel;\r\n", "/** @typedef {import('../photoswipe.js').default} PhotoSwipe */\r\n/** @typedef {import('../photoswipe.js').Point} Point */\r\n\r\n/**\r\n * @typedef {_SlideData & Record} SlideData\r\n * @typedef {Object} _SlideData\r\n * @prop {HTMLElement} [element] thumbnail element\r\n * @prop {string} [src] image URL\r\n * @prop {string} [srcset] image srcset\r\n * @prop {number} [w] image width (deprecated)\r\n * @prop {number} [h] image height (deprecated)\r\n * @prop {number} [width] image width\r\n * @prop {number} [height] image height\r\n * @prop {string} [msrc] placeholder image URL that's displayed before large image is loaded\r\n * @prop {string} [alt] image alt text\r\n * @prop {boolean} [thumbCropped] whether thumbnail is cropped client-side or not\r\n * @prop {string} [html] html content of a slide\r\n * @prop {'image' | 'html' | string} [type] slide type\r\n */\r\n\r\nimport {\r\n createElement,\r\n setTransform,\r\n equalizePoints,\r\n roundPoint,\r\n toTransformString,\r\n clamp,\r\n} from '../util/util.js';\r\n\r\nimport PanBounds from './pan-bounds.js';\r\nimport ZoomLevel from './zoom-level.js';\r\nimport { getPanAreaSize } from '../util/viewport-size.js';\r\n\r\n/**\r\n * Renders and allows to control a single slide\r\n */\r\nclass Slide {\r\n /**\r\n * @param {SlideData} data\r\n * @param {number} index\r\n * @param {PhotoSwipe} pswp\r\n */\r\n constructor(data, index, pswp) {\r\n this.data = data;\r\n this.index = index;\r\n this.pswp = pswp;\r\n this.isActive = (index === pswp.currIndex);\r\n this.currentResolution = 0;\r\n /** @type {Point} */\r\n this.panAreaSize = { x: 0, y: 0 };\r\n /** @type {Point} */\r\n this.pan = { x: 0, y: 0 };\r\n\r\n this.isFirstSlide = (this.isActive && !pswp.opener.isOpen);\r\n\r\n this.zoomLevels = new ZoomLevel(pswp.options, data, index, pswp);\r\n\r\n this.pswp.dispatch('gettingData', {\r\n slide: this,\r\n data: this.data,\r\n index\r\n });\r\n\r\n this.content = this.pswp.contentLoader.getContentBySlide(this);\r\n this.container = createElement('pswp__zoom-wrap', 'div');\r\n /** @type {HTMLElement | null} */\r\n this.holderElement = null;\r\n\r\n this.currZoomLevel = 1;\r\n /** @type {number} */\r\n this.width = this.content.width;\r\n /** @type {number} */\r\n this.height = this.content.height;\r\n this.heavyAppended = false;\r\n this.bounds = new PanBounds(this);\r\n\r\n this.prevDisplayedWidth = -1;\r\n this.prevDisplayedHeight = -1;\r\n\r\n this.pswp.dispatch('slideInit', { slide: this });\r\n }\r\n\r\n /**\r\n * If this slide is active/current/visible\r\n *\r\n * @param {boolean} isActive\r\n */\r\n setIsActive(isActive) {\r\n if (isActive && !this.isActive) {\r\n // slide just became active\r\n this.activate();\r\n } else if (!isActive && this.isActive) {\r\n // slide just became non-active\r\n this.deactivate();\r\n }\r\n }\r\n\r\n /**\r\n * Appends slide content to DOM\r\n *\r\n * @param {HTMLElement} holderElement\r\n */\r\n append(holderElement) {\r\n this.holderElement = holderElement;\r\n\r\n this.container.style.transformOrigin = '0 0';\r\n\r\n // Slide appended to DOM\r\n if (!this.data) {\r\n return;\r\n }\r\n\r\n this.calculateSize();\r\n\r\n this.load();\r\n this.updateContentSize();\r\n this.appendHeavy();\r\n\r\n this.holderElement.appendChild(this.container);\r\n\r\n this.zoomAndPanToInitial();\r\n\r\n this.pswp.dispatch('firstZoomPan', { slide: this });\r\n\r\n this.applyCurrentZoomPan();\r\n\r\n this.pswp.dispatch('afterSetContent', { slide: this });\r\n\r\n if (this.isActive) {\r\n this.activate();\r\n }\r\n }\r\n\r\n load() {\r\n this.content.load(false);\r\n this.pswp.dispatch('slideLoad', { slide: this });\r\n }\r\n\r\n /**\r\n * Append \"heavy\" DOM elements\r\n *\r\n * This may depend on a type of slide,\r\n * but generally these are large images.\r\n */\r\n appendHeavy() {\r\n const { pswp } = this;\r\n const appendHeavyNearby = true; // todo\r\n\r\n // Avoid appending heavy elements during animations\r\n if (this.heavyAppended\r\n || !pswp.opener.isOpen\r\n || pswp.mainScroll.isShifted()\r\n || (!this.isActive && !appendHeavyNearby)) {\r\n return;\r\n }\r\n\r\n if (this.pswp.dispatch('appendHeavy', { slide: this }).defaultPrevented) {\r\n return;\r\n }\r\n\r\n this.heavyAppended = true;\r\n\r\n this.content.append();\r\n\r\n this.pswp.dispatch('appendHeavyContent', { slide: this });\r\n }\r\n\r\n /**\r\n * Triggered when this slide is active (selected).\r\n *\r\n * If it's part of opening/closing transition -\r\n * activate() will trigger after the transition is ended.\r\n */\r\n activate() {\r\n this.isActive = true;\r\n this.appendHeavy();\r\n this.content.activate();\r\n this.pswp.dispatch('slideActivate', { slide: this });\r\n }\r\n\r\n /**\r\n * Triggered when this slide becomes inactive.\r\n *\r\n * Slide can become inactive only after it was active.\r\n */\r\n deactivate() {\r\n this.isActive = false;\r\n this.content.deactivate();\r\n\r\n if (this.currZoomLevel !== this.zoomLevels.initial) {\r\n // allow filtering\r\n this.calculateSize();\r\n }\r\n\r\n // reset zoom level\r\n this.currentResolution = 0;\r\n this.zoomAndPanToInitial();\r\n this.applyCurrentZoomPan();\r\n this.updateContentSize();\r\n\r\n this.pswp.dispatch('slideDeactivate', { slide: this });\r\n }\r\n\r\n /**\r\n * The slide should destroy itself, it will never be used again.\r\n * (unbind all events and destroy internal components)\r\n */\r\n destroy() {\r\n this.content.hasSlide = false;\r\n this.content.remove();\r\n this.container.remove();\r\n this.pswp.dispatch('slideDestroy', { slide: this });\r\n }\r\n\r\n resize() {\r\n if (this.currZoomLevel === this.zoomLevels.initial || !this.isActive) {\r\n // Keep initial zoom level if it was before the resize,\r\n // as well as when this slide is not active\r\n\r\n // Reset position and scale to original state\r\n this.calculateSize();\r\n this.currentResolution = 0;\r\n this.zoomAndPanToInitial();\r\n this.applyCurrentZoomPan();\r\n this.updateContentSize();\r\n } else {\r\n // readjust pan position if it's beyond the bounds\r\n this.calculateSize();\r\n this.bounds.update(this.currZoomLevel);\r\n this.panTo(this.pan.x, this.pan.y);\r\n }\r\n }\r\n\r\n\r\n /**\r\n * Apply size to current slide content,\r\n * based on the current resolution and scale.\r\n *\r\n * @param {boolean} [force] if size should be updated even if dimensions weren't changed\r\n */\r\n updateContentSize(force) {\r\n // Use initial zoom level\r\n // if resolution is not defined (user didn't zoom yet)\r\n const scaleMultiplier = this.currentResolution || this.zoomLevels.initial;\r\n\r\n if (!scaleMultiplier) {\r\n return;\r\n }\r\n\r\n const width = Math.round(this.width * scaleMultiplier) || this.pswp.viewportSize.x;\r\n const height = Math.round(this.height * scaleMultiplier) || this.pswp.viewportSize.y;\r\n\r\n if (!this.sizeChanged(width, height) && !force) {\r\n return;\r\n }\r\n this.content.setDisplayedSize(width, height);\r\n }\r\n\r\n /**\r\n * @param {number} width\r\n * @param {number} height\r\n */\r\n sizeChanged(width, height) {\r\n if (width !== this.prevDisplayedWidth\r\n || height !== this.prevDisplayedHeight) {\r\n this.prevDisplayedWidth = width;\r\n this.prevDisplayedHeight = height;\r\n return true;\r\n }\r\n\r\n return false;\r\n }\r\n\r\n /** @returns {HTMLImageElement | HTMLDivElement | null | undefined} */\r\n getPlaceholderElement() {\r\n return this.content.placeholder?.element;\r\n }\r\n\r\n /**\r\n * Zoom current slide image to...\r\n *\r\n * @param {number} destZoomLevel Destination zoom level.\r\n * @param {Point} [centerPoint]\r\n * Transform origin center point, or false if viewport center should be used.\r\n * @param {number | false} [transitionDuration] Transition duration, may be set to 0.\r\n * @param {boolean} [ignoreBounds] Minimum and maximum zoom levels will be ignored.\r\n */\r\n zoomTo(destZoomLevel, centerPoint, transitionDuration, ignoreBounds) {\r\n const { pswp } = this;\r\n if (!this.isZoomable()\r\n || pswp.mainScroll.isShifted()) {\r\n return;\r\n }\r\n\r\n pswp.dispatch('beforeZoomTo', {\r\n destZoomLevel, centerPoint, transitionDuration\r\n });\r\n\r\n // stop all pan and zoom transitions\r\n pswp.animations.stopAllPan();\r\n\r\n // if (!centerPoint) {\r\n // centerPoint = pswp.getViewportCenterPoint();\r\n // }\r\n\r\n const prevZoomLevel = this.currZoomLevel;\r\n\r\n if (!ignoreBounds) {\r\n destZoomLevel = clamp(destZoomLevel, this.zoomLevels.min, this.zoomLevels.max);\r\n }\r\n\r\n // if (transitionDuration === undefined) {\r\n // transitionDuration = this.pswp.options.zoomAnimationDuration;\r\n // }\r\n\r\n this.setZoomLevel(destZoomLevel);\r\n this.pan.x = this.calculateZoomToPanOffset('x', centerPoint, prevZoomLevel);\r\n this.pan.y = this.calculateZoomToPanOffset('y', centerPoint, prevZoomLevel);\r\n roundPoint(this.pan);\r\n\r\n const finishTransition = () => {\r\n this._setResolution(destZoomLevel);\r\n this.applyCurrentZoomPan();\r\n };\r\n\r\n if (!transitionDuration) {\r\n finishTransition();\r\n } else {\r\n pswp.animations.startTransition({\r\n isPan: true,\r\n name: 'zoomTo',\r\n target: this.container,\r\n transform: this.getCurrentTransform(),\r\n onComplete: finishTransition,\r\n duration: transitionDuration,\r\n easing: pswp.options.easing\r\n });\r\n }\r\n }\r\n\r\n /**\r\n * @param {Point} [centerPoint]\r\n */\r\n toggleZoom(centerPoint) {\r\n this.zoomTo(\r\n this.currZoomLevel === this.zoomLevels.initial\r\n ? this.zoomLevels.secondary : this.zoomLevels.initial,\r\n centerPoint,\r\n this.pswp.options.zoomAnimationDuration\r\n );\r\n }\r\n\r\n /**\r\n * Updates zoom level property and recalculates new pan bounds,\r\n * unlike zoomTo it does not apply transform (use applyCurrentZoomPan)\r\n *\r\n * @param {number} currZoomLevel\r\n */\r\n setZoomLevel(currZoomLevel) {\r\n this.currZoomLevel = currZoomLevel;\r\n this.bounds.update(this.currZoomLevel);\r\n }\r\n\r\n /**\r\n * Get pan position after zoom at a given `point`.\r\n *\r\n * Always call setZoomLevel(newZoomLevel) beforehand to recalculate\r\n * pan bounds according to the new zoom level.\r\n *\r\n * @param {'x' | 'y'} axis\r\n * @param {Point} [point]\r\n * point based on which zoom is performed, usually refers to the current mouse position,\r\n * if false - viewport center will be used.\r\n * @param {number} [prevZoomLevel] Zoom level before new zoom was applied.\r\n * @returns {number}\r\n */\r\n calculateZoomToPanOffset(axis, point, prevZoomLevel) {\r\n const totalPanDistance = this.bounds.max[axis] - this.bounds.min[axis];\r\n if (totalPanDistance === 0) {\r\n return this.bounds.center[axis];\r\n }\r\n\r\n if (!point) {\r\n point = this.pswp.getViewportCenterPoint();\r\n }\r\n\r\n if (!prevZoomLevel) {\r\n prevZoomLevel = this.zoomLevels.initial;\r\n }\r\n\r\n const zoomFactor = this.currZoomLevel / prevZoomLevel;\r\n return this.bounds.correctPan(\r\n axis,\r\n (this.pan[axis] - point[axis]) * zoomFactor + point[axis]\r\n );\r\n }\r\n\r\n /**\r\n * Apply pan and keep it within bounds.\r\n *\r\n * @param {number} panX\r\n * @param {number} panY\r\n */\r\n panTo(panX, panY) {\r\n this.pan.x = this.bounds.correctPan('x', panX);\r\n this.pan.y = this.bounds.correctPan('y', panY);\r\n this.applyCurrentZoomPan();\r\n }\r\n\r\n /**\r\n * If the slide in the current state can be panned by the user\r\n * @returns {boolean}\r\n */\r\n isPannable() {\r\n return Boolean(this.width) && (this.currZoomLevel > this.zoomLevels.fit);\r\n }\r\n\r\n /**\r\n * If the slide can be zoomed\r\n * @returns {boolean}\r\n */\r\n isZoomable() {\r\n return Boolean(this.width) && this.content.isZoomable();\r\n }\r\n\r\n /**\r\n * Apply transform and scale based on\r\n * the current pan position (this.pan) and zoom level (this.currZoomLevel)\r\n */\r\n applyCurrentZoomPan() {\r\n this._applyZoomTransform(this.pan.x, this.pan.y, this.currZoomLevel);\r\n if (this === this.pswp.currSlide) {\r\n this.pswp.dispatch('zoomPanUpdate', { slide: this });\r\n }\r\n }\r\n\r\n zoomAndPanToInitial() {\r\n this.currZoomLevel = this.zoomLevels.initial;\r\n\r\n // pan according to the zoom level\r\n this.bounds.update(this.currZoomLevel);\r\n equalizePoints(this.pan, this.bounds.center);\r\n this.pswp.dispatch('initialZoomPan', { slide: this });\r\n }\r\n\r\n /**\r\n * Set translate and scale based on current resolution\r\n *\r\n * @param {number} x\r\n * @param {number} y\r\n * @param {number} zoom\r\n * @private\r\n */\r\n _applyZoomTransform(x, y, zoom) {\r\n zoom /= this.currentResolution || this.zoomLevels.initial;\r\n setTransform(this.container, x, y, zoom);\r\n }\r\n\r\n calculateSize() {\r\n const { pswp } = this;\r\n\r\n equalizePoints(\r\n this.panAreaSize,\r\n getPanAreaSize(pswp.options, pswp.viewportSize, this.data, this.index)\r\n );\r\n\r\n this.zoomLevels.update(this.width, this.height, this.panAreaSize);\r\n\r\n pswp.dispatch('calcSlideSize', {\r\n slide: this\r\n });\r\n }\r\n\r\n /** @returns {string} */\r\n getCurrentTransform() {\r\n const scale = this.currZoomLevel / (this.currentResolution || this.zoomLevels.initial);\r\n return toTransformString(this.pan.x, this.pan.y, scale);\r\n }\r\n\r\n /**\r\n * Set resolution and re-render the image.\r\n *\r\n * For example, if the real image size is 2000x1500,\r\n * and resolution is 0.5 - it will be rendered as 1000x750.\r\n *\r\n * Image with zoom level 2 and resolution 0.5 is\r\n * the same as image with zoom level 1 and resolution 1.\r\n *\r\n * Used to optimize animations and make\r\n * sure that browser renders image in the highest quality.\r\n * Also used by responsive images to load the correct one.\r\n *\r\n * @param {number} newResolution\r\n */\r\n _setResolution(newResolution) {\r\n if (newResolution === this.currentResolution) {\r\n return;\r\n }\r\n\r\n this.currentResolution = newResolution;\r\n this.updateContentSize();\r\n\r\n this.pswp.dispatch('resolutionChanged');\r\n }\r\n}\r\n\r\nexport default Slide;\r\n", "import {\r\n equalizePoints, roundPoint, clamp\r\n} from '../util/util.js';\r\n\r\n/** @typedef {import('../photoswipe.js').Point} Point */\r\n/** @typedef {import('./gestures.js').default} Gestures */\r\n\r\nconst PAN_END_FRICTION = 0.35;\r\nconst VERTICAL_DRAG_FRICTION = 0.6;\r\n\r\n// 1 corresponds to the third of viewport height\r\nconst MIN_RATIO_TO_CLOSE = 0.4;\r\n\r\n// Minimum speed required to navigate\r\n// to next or previous slide\r\nconst MIN_NEXT_SLIDE_SPEED = 0.5;\r\n\r\n/**\r\n * @param {number} initialVelocity\r\n * @param {number} decelerationRate\r\n * @returns {number}\r\n */\r\nfunction project(initialVelocity, decelerationRate) {\r\n return initialVelocity * decelerationRate / (1 - decelerationRate);\r\n}\r\n\r\n/**\r\n * Handles single pointer dragging\r\n */\r\nclass DragHandler {\r\n /**\r\n * @param {Gestures} gestures\r\n */\r\n constructor(gestures) {\r\n this.gestures = gestures;\r\n this.pswp = gestures.pswp;\r\n /** @type {Point} */\r\n this.startPan = { x: 0, y: 0 };\r\n }\r\n\r\n start() {\r\n if (this.pswp.currSlide) {\r\n equalizePoints(this.startPan, this.pswp.currSlide.pan);\r\n }\r\n this.pswp.animations.stopAll();\r\n }\r\n\r\n change() {\r\n const { p1, prevP1, dragAxis } = this.gestures;\r\n const { currSlide } = this.pswp;\r\n\r\n if (dragAxis === 'y'\r\n && this.pswp.options.closeOnVerticalDrag\r\n && (currSlide && currSlide.currZoomLevel <= currSlide.zoomLevels.fit)\r\n && !this.gestures.isMultitouch) {\r\n // Handle vertical drag to close\r\n const panY = currSlide.pan.y + (p1.y - prevP1.y);\r\n if (!this.pswp.dispatch('verticalDrag', { panY }).defaultPrevented) {\r\n this._setPanWithFriction('y', panY, VERTICAL_DRAG_FRICTION);\r\n const bgOpacity = 1 - Math.abs(this._getVerticalDragRatio(currSlide.pan.y));\r\n this.pswp.applyBgOpacity(bgOpacity);\r\n currSlide.applyCurrentZoomPan();\r\n }\r\n } else {\r\n const mainScrollChanged = this._panOrMoveMainScroll('x');\r\n if (!mainScrollChanged) {\r\n this._panOrMoveMainScroll('y');\r\n\r\n if (currSlide) {\r\n roundPoint(currSlide.pan);\r\n currSlide.applyCurrentZoomPan();\r\n }\r\n }\r\n }\r\n }\r\n\r\n end() {\r\n const { velocity } = this.gestures;\r\n const { mainScroll, currSlide } = this.pswp;\r\n let indexDiff = 0;\r\n\r\n this.pswp.animations.stopAll();\r\n\r\n // Handle main scroll if it's shifted\r\n if (mainScroll.isShifted()) {\r\n // Position of the main scroll relative to the viewport\r\n const mainScrollShiftDiff = mainScroll.x - mainScroll.getCurrSlideX();\r\n\r\n // Ratio between 0 and 1:\r\n // 0 - slide is not visible at all,\r\n // 0.5 - half of the slide is visible\r\n // 1 - slide is fully visible\r\n const currentSlideVisibilityRatio = (mainScrollShiftDiff / this.pswp.viewportSize.x);\r\n\r\n // Go next slide.\r\n //\r\n // - if velocity and its direction is matched,\r\n // and we see at least tiny part of the next slide\r\n //\r\n // - or if we see less than 50% of the current slide\r\n // and velocity is close to 0\r\n //\r\n if ((velocity.x < -MIN_NEXT_SLIDE_SPEED && currentSlideVisibilityRatio < 0)\r\n || (velocity.x < 0.1 && currentSlideVisibilityRatio < -0.5)) {\r\n // Go to next slide\r\n indexDiff = 1;\r\n velocity.x = Math.min(velocity.x, 0);\r\n } else if ((velocity.x > MIN_NEXT_SLIDE_SPEED && currentSlideVisibilityRatio > 0)\r\n || (velocity.x > -0.1 && currentSlideVisibilityRatio > 0.5)) {\r\n // Go to prev slide\r\n indexDiff = -1;\r\n velocity.x = Math.max(velocity.x, 0);\r\n }\r\n\r\n mainScroll.moveIndexBy(indexDiff, true, velocity.x);\r\n }\r\n\r\n // Restore zoom level\r\n if ((currSlide && currSlide.currZoomLevel > currSlide.zoomLevels.max)\r\n || this.gestures.isMultitouch) {\r\n this.gestures.zoomLevels.correctZoomPan(true);\r\n } else {\r\n // we run two animations instead of one,\r\n // as each axis has own pan boundaries and thus different spring function\r\n // (correctZoomPan does not have this functionality,\r\n // it animates all properties with single timing function)\r\n this._finishPanGestureForAxis('x');\r\n this._finishPanGestureForAxis('y');\r\n }\r\n }\r\n\r\n /**\r\n * @private\r\n * @param {'x' | 'y'} axis\r\n */\r\n _finishPanGestureForAxis(axis) {\r\n const { velocity } = this.gestures;\r\n const { currSlide } = this.pswp;\r\n\r\n if (!currSlide) {\r\n return;\r\n }\r\n\r\n const { pan, bounds } = currSlide;\r\n const panPos = pan[axis];\r\n const restoreBgOpacity = (this.pswp.bgOpacity < 1 && axis === 'y');\r\n\r\n // 0.995 means - scroll view loses 0.5% of its velocity per millisecond\r\n // Increasing this number will reduce travel distance\r\n const decelerationRate = 0.995; // 0.99\r\n\r\n // Pan position if there is no bounds\r\n const projectedPosition = panPos + project(velocity[axis], decelerationRate);\r\n\r\n if (restoreBgOpacity) {\r\n const vDragRatio = this._getVerticalDragRatio(panPos);\r\n const projectedVDragRatio = this._getVerticalDragRatio(projectedPosition);\r\n\r\n // If we are above and moving upwards,\r\n // or if we are below and moving downwards\r\n if ((vDragRatio < 0 && projectedVDragRatio < -MIN_RATIO_TO_CLOSE)\r\n || (vDragRatio > 0 && projectedVDragRatio > MIN_RATIO_TO_CLOSE)) {\r\n this.pswp.close();\r\n return;\r\n }\r\n }\r\n\r\n // Pan position with corrected bounds\r\n const correctedPanPosition = bounds.correctPan(axis, projectedPosition);\r\n\r\n // Exit if pan position should not be changed\r\n // or if speed it too low\r\n if (panPos === correctedPanPosition) {\r\n return;\r\n }\r\n\r\n // Overshoot if the final position is out of pan bounds\r\n const dampingRatio = (correctedPanPosition === projectedPosition) ? 1 : 0.82;\r\n\r\n const initialBgOpacity = this.pswp.bgOpacity;\r\n const totalPanDist = correctedPanPosition - panPos;\r\n\r\n this.pswp.animations.startSpring({\r\n name: 'panGesture' + axis,\r\n isPan: true,\r\n start: panPos,\r\n end: correctedPanPosition,\r\n velocity: velocity[axis],\r\n dampingRatio,\r\n onUpdate: (pos) => {\r\n // Animate opacity of background relative to Y pan position of an image\r\n if (restoreBgOpacity && this.pswp.bgOpacity < 1) {\r\n // 0 - start of animation, 1 - end of animation\r\n const animationProgressRatio = 1 - (correctedPanPosition - pos) / totalPanDist;\r\n\r\n // We clamp opacity to keep it between 0 and 1.\r\n // As progress ratio can be larger than 1 due to overshoot,\r\n // and we do not want to bounce opacity.\r\n this.pswp.applyBgOpacity(clamp(\r\n initialBgOpacity + (1 - initialBgOpacity) * animationProgressRatio,\r\n 0,\r\n 1\r\n ));\r\n }\r\n\r\n pan[axis] = Math.floor(pos);\r\n currSlide.applyCurrentZoomPan();\r\n },\r\n });\r\n }\r\n\r\n /**\r\n * Update position of the main scroll,\r\n * or/and update pan position of the current slide.\r\n *\r\n * Should return true if it changes (or can change) main scroll.\r\n *\r\n * @private\r\n * @param {'x' | 'y'} axis\r\n * @returns {boolean}\r\n */\r\n _panOrMoveMainScroll(axis) {\r\n const { p1, dragAxis, prevP1, isMultitouch } = this.gestures;\r\n const { currSlide, mainScroll } = this.pswp;\r\n const delta = (p1[axis] - prevP1[axis]);\r\n const newMainScrollX = mainScroll.x + delta;\r\n\r\n if (!delta || !currSlide) {\r\n return false;\r\n }\r\n\r\n // Always move main scroll if image can not be panned\r\n if (axis === 'x' && !currSlide.isPannable() && !isMultitouch) {\r\n mainScroll.moveTo(newMainScrollX, true);\r\n return true; // changed main scroll\r\n }\r\n\r\n const { bounds } = currSlide;\r\n const newPan = currSlide.pan[axis] + delta;\r\n\r\n if (this.pswp.options.allowPanToNext\r\n && dragAxis === 'x'\r\n && axis === 'x'\r\n && !isMultitouch) {\r\n const currSlideMainScrollX = mainScroll.getCurrSlideX();\r\n\r\n // Position of the main scroll relative to the viewport\r\n const mainScrollShiftDiff = mainScroll.x - currSlideMainScrollX;\r\n\r\n const isLeftToRight = delta > 0;\r\n const isRightToLeft = !isLeftToRight;\r\n\r\n if (newPan > bounds.min[axis] && isLeftToRight) {\r\n // Panning from left to right, beyond the left edge\r\n\r\n // Wether the image was at minimum pan position (or less)\r\n // when this drag gesture started.\r\n // Minimum pan position refers to the left edge of the image.\r\n const wasAtMinPanPosition = (bounds.min[axis] <= this.startPan[axis]);\r\n\r\n if (wasAtMinPanPosition) {\r\n mainScroll.moveTo(newMainScrollX, true);\r\n return true;\r\n } else {\r\n this._setPanWithFriction(axis, newPan);\r\n //currSlide.pan[axis] = newPan;\r\n }\r\n } else if (newPan < bounds.max[axis] && isRightToLeft) {\r\n // Paning from right to left, beyond the right edge\r\n\r\n // Maximum pan position refers to the right edge of the image.\r\n const wasAtMaxPanPosition = (this.startPan[axis] <= bounds.max[axis]);\r\n\r\n if (wasAtMaxPanPosition) {\r\n mainScroll.moveTo(newMainScrollX, true);\r\n return true;\r\n } else {\r\n this._setPanWithFriction(axis, newPan);\r\n //currSlide.pan[axis] = newPan;\r\n }\r\n } else {\r\n // If main scroll is shifted\r\n if (mainScrollShiftDiff !== 0) {\r\n // If main scroll is shifted right\r\n if (mainScrollShiftDiff > 0 /*&& isRightToLeft*/) {\r\n mainScroll.moveTo(Math.max(newMainScrollX, currSlideMainScrollX), true);\r\n return true;\r\n } else if (mainScrollShiftDiff < 0 /*&& isLeftToRight*/) {\r\n // Main scroll is shifted left (Position is less than 0 comparing to the viewport 0)\r\n mainScroll.moveTo(Math.min(newMainScrollX, currSlideMainScrollX), true);\r\n return true;\r\n }\r\n } else {\r\n // We are within pan bounds, so just pan\r\n this._setPanWithFriction(axis, newPan);\r\n }\r\n }\r\n } else {\r\n if (axis === 'y') {\r\n // Do not pan vertically if main scroll is shifted o\r\n if (!mainScroll.isShifted() && bounds.min.y !== bounds.max.y) {\r\n this._setPanWithFriction(axis, newPan);\r\n }\r\n } else {\r\n this._setPanWithFriction(axis, newPan);\r\n }\r\n }\r\n\r\n return false;\r\n }\r\n\r\n // If we move above - the ratio is negative\r\n // If we move below the ratio is positive\r\n\r\n /**\r\n * Relation between pan Y position and third of viewport height.\r\n *\r\n * When we are at initial position (center bounds) - the ratio is 0,\r\n * if position is shifted upwards - the ratio is negative,\r\n * if position is shifted downwards - the ratio is positive.\r\n *\r\n * @private\r\n * @param {number} panY The current pan Y position.\r\n * @returns {number}\r\n */\r\n _getVerticalDragRatio(panY) {\r\n return (panY - (this.pswp.currSlide?.bounds.center.y ?? 0)) / (this.pswp.viewportSize.y / 3);\r\n }\r\n\r\n /**\r\n * Set pan position of the current slide.\r\n * Apply friction if the position is beyond the pan bounds,\r\n * or if custom friction is defined.\r\n *\r\n * @private\r\n * @param {'x' | 'y'} axis\r\n * @param {number} potentialPan\r\n * @param {number} [customFriction] (0.1 - 1)\r\n */\r\n _setPanWithFriction(axis, potentialPan, customFriction) {\r\n const { currSlide } = this.pswp;\r\n\r\n if (!currSlide) {\r\n return;\r\n }\r\n\r\n const { pan, bounds } = currSlide;\r\n const correctedPan = bounds.correctPan(axis, potentialPan);\r\n // If we are out of pan bounds\r\n if (correctedPan !== potentialPan || customFriction) {\r\n const delta = Math.round(potentialPan - pan[axis]);\r\n pan[axis] += delta * (customFriction || PAN_END_FRICTION);\r\n } else {\r\n pan[axis] = potentialPan;\r\n }\r\n }\r\n}\r\n\r\nexport default DragHandler;\r\n", "import {\r\n equalizePoints, getDistanceBetween, clamp, pointsEqual\r\n} from '../util/util.js';\r\n\r\n/** @typedef {import('../photoswipe.js').Point} Point */\r\n/** @typedef {import('./gestures.js').default} Gestures */\r\n\r\nconst UPPER_ZOOM_FRICTION = 0.05;\r\nconst LOWER_ZOOM_FRICTION = 0.15;\r\n\r\n\r\n/**\r\n * Get center point between two points\r\n *\r\n * @param {Point} p\r\n * @param {Point} p1\r\n * @param {Point} p2\r\n * @returns {Point}\r\n */\r\nfunction getZoomPointsCenter(p, p1, p2) {\r\n p.x = (p1.x + p2.x) / 2;\r\n p.y = (p1.y + p2.y) / 2;\r\n return p;\r\n}\r\n\r\nclass ZoomHandler {\r\n /**\r\n * @param {Gestures} gestures\r\n */\r\n constructor(gestures) {\r\n this.gestures = gestures;\r\n /**\r\n * @private\r\n * @type {Point}\r\n */\r\n this._startPan = { x: 0, y: 0 };\r\n /**\r\n * @private\r\n * @type {Point}\r\n */\r\n this._startZoomPoint = { x: 0, y: 0 };\r\n /**\r\n * @private\r\n * @type {Point}\r\n */\r\n this._zoomPoint = { x: 0, y: 0 };\r\n /** @private */\r\n this._wasOverFitZoomLevel = false;\r\n /** @private */\r\n this._startZoomLevel = 1;\r\n }\r\n\r\n start() {\r\n const { currSlide } = this.gestures.pswp;\r\n if (currSlide) {\r\n this._startZoomLevel = currSlide.currZoomLevel;\r\n equalizePoints(this._startPan, currSlide.pan);\r\n }\r\n\r\n this.gestures.pswp.animations.stopAllPan();\r\n this._wasOverFitZoomLevel = false;\r\n }\r\n\r\n change() {\r\n const { p1, startP1, p2, startP2, pswp } = this.gestures;\r\n const { currSlide } = pswp;\r\n\r\n if (!currSlide) {\r\n return;\r\n }\r\n\r\n const minZoomLevel = currSlide.zoomLevels.min;\r\n const maxZoomLevel = currSlide.zoomLevels.max;\r\n\r\n if (!currSlide.isZoomable() || pswp.mainScroll.isShifted()) {\r\n return;\r\n }\r\n\r\n getZoomPointsCenter(this._startZoomPoint, startP1, startP2);\r\n getZoomPointsCenter(this._zoomPoint, p1, p2);\r\n\r\n let currZoomLevel = (1 / getDistanceBetween(startP1, startP2))\r\n * getDistanceBetween(p1, p2)\r\n * this._startZoomLevel;\r\n\r\n // slightly over the zoom.fit\r\n if (currZoomLevel > currSlide.zoomLevels.initial + (currSlide.zoomLevels.initial / 15)) {\r\n this._wasOverFitZoomLevel = true;\r\n }\r\n\r\n if (currZoomLevel < minZoomLevel) {\r\n if (pswp.options.pinchToClose\r\n && !this._wasOverFitZoomLevel\r\n && this._startZoomLevel <= currSlide.zoomLevels.initial) {\r\n // fade out background if zooming out\r\n const bgOpacity = 1 - ((minZoomLevel - currZoomLevel) / (minZoomLevel / 1.2));\r\n if (!pswp.dispatch('pinchClose', { bgOpacity }).defaultPrevented) {\r\n pswp.applyBgOpacity(bgOpacity);\r\n }\r\n } else {\r\n // Apply the friction if zoom level is below the min\r\n currZoomLevel = minZoomLevel - (minZoomLevel - currZoomLevel) * LOWER_ZOOM_FRICTION;\r\n }\r\n } else if (currZoomLevel > maxZoomLevel) {\r\n // Apply the friction if zoom level is above the max\r\n currZoomLevel = maxZoomLevel + (currZoomLevel - maxZoomLevel) * UPPER_ZOOM_FRICTION;\r\n }\r\n\r\n currSlide.pan.x = this._calculatePanForZoomLevel('x', currZoomLevel);\r\n currSlide.pan.y = this._calculatePanForZoomLevel('y', currZoomLevel);\r\n\r\n currSlide.setZoomLevel(currZoomLevel);\r\n currSlide.applyCurrentZoomPan();\r\n }\r\n\r\n end() {\r\n const { pswp } = this.gestures;\r\n const { currSlide } = pswp;\r\n if ((!currSlide || currSlide.currZoomLevel < currSlide.zoomLevels.initial)\r\n && !this._wasOverFitZoomLevel\r\n && pswp.options.pinchToClose) {\r\n pswp.close();\r\n } else {\r\n this.correctZoomPan();\r\n }\r\n }\r\n\r\n /**\r\n * @private\r\n * @param {'x' | 'y'} axis\r\n * @param {number} currZoomLevel\r\n * @returns {number}\r\n */\r\n _calculatePanForZoomLevel(axis, currZoomLevel) {\r\n const zoomFactor = currZoomLevel / this._startZoomLevel;\r\n return this._zoomPoint[axis]\r\n - ((this._startZoomPoint[axis] - this._startPan[axis]) * zoomFactor);\r\n }\r\n\r\n /**\r\n * Correct currZoomLevel and pan if they are\r\n * beyond minimum or maximum values.\r\n * With animation.\r\n *\r\n * @param {boolean} [ignoreGesture]\r\n * Wether gesture coordinates should be ignored when calculating destination pan position.\r\n */\r\n correctZoomPan(ignoreGesture) {\r\n const { pswp } = this.gestures;\r\n const { currSlide } = pswp;\r\n\r\n if (!currSlide?.isZoomable()) {\r\n return;\r\n }\r\n\r\n if (this._zoomPoint.x === 0) {\r\n ignoreGesture = true;\r\n }\r\n\r\n const prevZoomLevel = currSlide.currZoomLevel;\r\n\r\n /** @type {number} */\r\n let destinationZoomLevel;\r\n let currZoomLevelNeedsChange = true;\r\n\r\n if (prevZoomLevel < currSlide.zoomLevels.initial) {\r\n destinationZoomLevel = currSlide.zoomLevels.initial;\r\n // zoom to min\r\n } else if (prevZoomLevel > currSlide.zoomLevels.max) {\r\n destinationZoomLevel = currSlide.zoomLevels.max;\r\n // zoom to max\r\n } else {\r\n currZoomLevelNeedsChange = false;\r\n destinationZoomLevel = prevZoomLevel;\r\n }\r\n\r\n const initialBgOpacity = pswp.bgOpacity;\r\n const restoreBgOpacity = pswp.bgOpacity < 1;\r\n\r\n const initialPan = equalizePoints({ x: 0, y: 0 }, currSlide.pan);\r\n let destinationPan = equalizePoints({ x: 0, y: 0 }, initialPan);\r\n\r\n if (ignoreGesture) {\r\n this._zoomPoint.x = 0;\r\n this._zoomPoint.y = 0;\r\n this._startZoomPoint.x = 0;\r\n this._startZoomPoint.y = 0;\r\n this._startZoomLevel = prevZoomLevel;\r\n equalizePoints(this._startPan, initialPan);\r\n }\r\n\r\n if (currZoomLevelNeedsChange) {\r\n destinationPan = {\r\n x: this._calculatePanForZoomLevel('x', destinationZoomLevel),\r\n y: this._calculatePanForZoomLevel('y', destinationZoomLevel)\r\n };\r\n }\r\n\r\n // set zoom level, so pan bounds are updated according to it\r\n currSlide.setZoomLevel(destinationZoomLevel);\r\n\r\n destinationPan = {\r\n x: currSlide.bounds.correctPan('x', destinationPan.x),\r\n y: currSlide.bounds.correctPan('y', destinationPan.y)\r\n };\r\n\r\n // return zoom level and its bounds to initial\r\n currSlide.setZoomLevel(prevZoomLevel);\r\n\r\n const panNeedsChange = !pointsEqual(destinationPan, initialPan);\r\n\r\n if (!panNeedsChange && !currZoomLevelNeedsChange && !restoreBgOpacity) {\r\n // update resolution after gesture\r\n currSlide._setResolution(destinationZoomLevel);\r\n currSlide.applyCurrentZoomPan();\r\n\r\n // nothing to animate\r\n return;\r\n }\r\n\r\n pswp.animations.stopAllPan();\r\n\r\n pswp.animations.startSpring({\r\n isPan: true,\r\n start: 0,\r\n end: 1000,\r\n velocity: 0,\r\n dampingRatio: 1,\r\n naturalFrequency: 40,\r\n onUpdate: (now) => {\r\n now /= 1000; // 0 - start, 1 - end\r\n\r\n if (panNeedsChange || currZoomLevelNeedsChange) {\r\n if (panNeedsChange) {\r\n currSlide.pan.x = initialPan.x + (destinationPan.x - initialPan.x) * now;\r\n currSlide.pan.y = initialPan.y + (destinationPan.y - initialPan.y) * now;\r\n }\r\n\r\n if (currZoomLevelNeedsChange) {\r\n const newZoomLevel = prevZoomLevel\r\n + (destinationZoomLevel - prevZoomLevel) * now;\r\n currSlide.setZoomLevel(newZoomLevel);\r\n }\r\n\r\n currSlide.applyCurrentZoomPan();\r\n }\r\n\r\n // Restore background opacity\r\n if (restoreBgOpacity && pswp.bgOpacity < 1) {\r\n // We clamp opacity to keep it between 0 and 1.\r\n // As progress ratio can be larger than 1 due to overshoot,\r\n // and we do not want to bounce opacity.\r\n pswp.applyBgOpacity(clamp(\r\n initialBgOpacity + (1 - initialBgOpacity) * now, 0, 1\r\n ));\r\n }\r\n },\r\n onComplete: () => {\r\n // update resolution after transition ends\r\n currSlide._setResolution(destinationZoomLevel);\r\n currSlide.applyCurrentZoomPan();\r\n }\r\n });\r\n }\r\n}\r\n\r\nexport default ZoomHandler;\r\n", "/**\r\n * @template {string} T\r\n * @template {string} P\r\n * @typedef {import('../types.js').AddPostfix} AddPostfix\r\n */\r\n\r\n/** @typedef {import('./gestures.js').default} Gestures */\r\n/** @typedef {import('../photoswipe.js').Point} Point */\r\n\r\n/** @typedef {'imageClick' | 'bgClick' | 'tap' | 'doubleTap'} Actions */\r\n\r\n/**\r\n * Whether the tap was performed on the main slide\r\n * (rather than controls or caption).\r\n *\r\n * @param {PointerEvent} event\r\n * @returns {boolean}\r\n */\r\nfunction didTapOnMainContent(event) {\r\n return !!(/** @type {HTMLElement} */ (event.target).closest('.pswp__container'));\r\n}\r\n\r\n/**\r\n * Tap, double-tap handler.\r\n */\r\nclass TapHandler {\r\n /**\r\n * @param {Gestures} gestures\r\n */\r\n constructor(gestures) {\r\n this.gestures = gestures;\r\n }\r\n\r\n /**\r\n * @param {Point} point\r\n * @param {PointerEvent} originalEvent\r\n */\r\n click(point, originalEvent) {\r\n const targetClassList = /** @type {HTMLElement} */ (originalEvent.target).classList;\r\n const isImageClick = targetClassList.contains('pswp__img');\r\n const isBackgroundClick = targetClassList.contains('pswp__item')\r\n || targetClassList.contains('pswp__zoom-wrap');\r\n\r\n if (isImageClick) {\r\n this._doClickOrTapAction('imageClick', point, originalEvent);\r\n } else if (isBackgroundClick) {\r\n this._doClickOrTapAction('bgClick', point, originalEvent);\r\n }\r\n }\r\n\r\n /**\r\n * @param {Point} point\r\n * @param {PointerEvent} originalEvent\r\n */\r\n tap(point, originalEvent) {\r\n if (didTapOnMainContent(originalEvent)) {\r\n this._doClickOrTapAction('tap', point, originalEvent);\r\n }\r\n }\r\n\r\n /**\r\n * @param {Point} point\r\n * @param {PointerEvent} originalEvent\r\n */\r\n doubleTap(point, originalEvent) {\r\n if (didTapOnMainContent(originalEvent)) {\r\n this._doClickOrTapAction('doubleTap', point, originalEvent);\r\n }\r\n }\r\n\r\n /**\r\n * @private\r\n * @param {Actions} actionName\r\n * @param {Point} point\r\n * @param {PointerEvent} originalEvent\r\n */\r\n _doClickOrTapAction(actionName, point, originalEvent) {\r\n const { pswp } = this.gestures;\r\n const { currSlide } = pswp;\r\n const actionFullName = /** @type {AddPostfix} */ (actionName + 'Action');\r\n const optionValue = pswp.options[actionFullName];\r\n\r\n if (pswp.dispatch(actionFullName, { point, originalEvent }).defaultPrevented) {\r\n return;\r\n }\r\n\r\n if (typeof optionValue === 'function') {\r\n optionValue.call(pswp, point, originalEvent);\r\n return;\r\n }\r\n\r\n switch (optionValue) {\r\n case 'close':\r\n case 'next':\r\n pswp[optionValue]();\r\n break;\r\n case 'zoom':\r\n currSlide?.toggleZoom(point);\r\n break;\r\n case 'zoom-or-close':\r\n // by default click zooms current image,\r\n // if it can not be zoomed - gallery will be closed\r\n if (currSlide?.isZoomable()\r\n && currSlide.zoomLevels.secondary !== currSlide.zoomLevels.initial) {\r\n currSlide.toggleZoom(point);\r\n } else if (pswp.options.clickToCloseNonZoomable) {\r\n pswp.close();\r\n }\r\n break;\r\n case 'toggle-controls':\r\n this.gestures.pswp.element?.classList.toggle('pswp--ui-visible');\r\n // if (_controlsVisible) {\r\n // _ui.hideControls();\r\n // } else {\r\n // _ui.showControls();\r\n // }\r\n break;\r\n }\r\n }\r\n}\r\n\r\nexport default TapHandler;\r\n", "import {\r\n equalizePoints, pointsEqual, getDistanceBetween\r\n} from '../util/util.js';\r\n\r\nimport DragHandler from './drag-handler.js';\r\nimport ZoomHandler from './zoom-handler.js';\r\nimport TapHandler from './tap-handler.js';\r\n\r\n/** @typedef {import('../photoswipe.js').default} PhotoSwipe */\r\n/** @typedef {import('../photoswipe.js').Point} Point */\r\n\r\n// How far should user should drag\r\n// until we can determine that the gesture is swipe and its direction\r\nconst AXIS_SWIPE_HYSTERISIS = 10;\r\n//const PAN_END_FRICTION = 0.35;\r\n\r\nconst DOUBLE_TAP_DELAY = 300; // ms\r\nconst MIN_TAP_DISTANCE = 25; // px\r\n\r\n/**\r\n * Gestures class bind touch, pointer or mouse events\r\n * and emits drag to drag-handler and zoom events zoom-handler.\r\n *\r\n * Drag and zoom events are emited in requestAnimationFrame,\r\n * and only when one of pointers was actually changed.\r\n */\r\nclass Gestures {\r\n /**\r\n * @param {PhotoSwipe} pswp\r\n */\r\n constructor(pswp) {\r\n this.pswp = pswp;\r\n\r\n /** @type {'x' | 'y' | null} */\r\n this.dragAxis = null;\r\n\r\n // point objects are defined once and reused\r\n // PhotoSwipe keeps track only of two pointers, others are ignored\r\n /** @type {Point} */\r\n this.p1 = { x: 0, y: 0 }; // the first pressed pointer\r\n /** @type {Point} */\r\n this.p2 = { x: 0, y: 0 }; // the second pressed pointer\r\n /** @type {Point} */\r\n this.prevP1 = { x: 0, y: 0 };\r\n /** @type {Point} */\r\n this.prevP2 = { x: 0, y: 0 };\r\n /** @type {Point} */\r\n this.startP1 = { x: 0, y: 0 };\r\n /** @type {Point} */\r\n this.startP2 = { x: 0, y: 0 };\r\n /** @type {Point} */\r\n this.velocity = { x: 0, y: 0 };\r\n\r\n /** @type {Point}\r\n * @private\r\n */\r\n this._lastStartP1 = { x: 0, y: 0 };\r\n /** @type {Point}\r\n * @private\r\n */\r\n this._intervalP1 = { x: 0, y: 0 };\r\n /** @private */\r\n this._numActivePoints = 0;\r\n /** @type {Point[]}\r\n * @private\r\n */\r\n this._ongoingPointers = [];\r\n /** @private */\r\n this._touchEventEnabled = 'ontouchstart' in window;\r\n /** @private */\r\n this._pointerEventEnabled = !!(window.PointerEvent);\r\n this.supportsTouch = this._touchEventEnabled\r\n || (this._pointerEventEnabled && navigator.maxTouchPoints > 1);\r\n /** @private */\r\n this._numActivePoints = 0;\r\n /** @private */\r\n this._intervalTime = 0;\r\n /** @private */\r\n this._velocityCalculated = false;\r\n this.isMultitouch = false;\r\n this.isDragging = false;\r\n this.isZooming = false;\r\n /** @type {number | null} */\r\n this.raf = null;\r\n /** @type {NodeJS.Timeout | null}\r\n * @private\r\n */\r\n this._tapTimer = null;\r\n\r\n if (!this.supportsTouch) {\r\n // disable pan to next slide for non-touch devices\r\n pswp.options.allowPanToNext = false;\r\n }\r\n\r\n this.drag = new DragHandler(this);\r\n this.zoomLevels = new ZoomHandler(this);\r\n this.tapHandler = new TapHandler(this);\r\n\r\n pswp.on('bindEvents', () => {\r\n pswp.events.add(\r\n pswp.scrollWrap,\r\n 'click',\r\n /** @type EventListener */(this._onClick.bind(this))\r\n );\r\n\r\n if (this._pointerEventEnabled) {\r\n this._bindEvents('pointer', 'down', 'up', 'cancel');\r\n } else if (this._touchEventEnabled) {\r\n this._bindEvents('touch', 'start', 'end', 'cancel');\r\n\r\n // In previous versions we also bound mouse event here,\r\n // in case device supports both touch and mouse events,\r\n // but newer versions of browsers now support PointerEvent.\r\n\r\n // on iOS10 if you bind touchmove/end after touchstart,\r\n // and you don't preventDefault touchstart (which PhotoSwipe does),\r\n // preventDefault will have no effect on touchmove and touchend.\r\n // Unless you bind it previously.\r\n if (pswp.scrollWrap) {\r\n pswp.scrollWrap.ontouchmove = () => {};\r\n pswp.scrollWrap.ontouchend = () => {};\r\n }\r\n } else {\r\n this._bindEvents('mouse', 'down', 'up');\r\n }\r\n });\r\n }\r\n\r\n /**\r\n * @private\r\n * @param {'mouse' | 'touch' | 'pointer'} pref\r\n * @param {'down' | 'start'} down\r\n * @param {'up' | 'end'} up\r\n * @param {'cancel'} [cancel]\r\n */\r\n _bindEvents(pref, down, up, cancel) {\r\n const { pswp } = this;\r\n const { events } = pswp;\r\n\r\n const cancelEvent = cancel ? pref + cancel : '';\r\n\r\n events.add(\r\n pswp.scrollWrap,\r\n pref + down,\r\n /** @type EventListener */(this.onPointerDown.bind(this))\r\n );\r\n events.add(window, pref + 'move', /** @type EventListener */(this.onPointerMove.bind(this)));\r\n events.add(window, pref + up, /** @type EventListener */(this.onPointerUp.bind(this)));\r\n if (cancelEvent) {\r\n events.add(\r\n pswp.scrollWrap,\r\n cancelEvent,\r\n /** @type EventListener */(this.onPointerUp.bind(this))\r\n );\r\n }\r\n }\r\n\r\n /**\r\n * @param {PointerEvent} e\r\n */\r\n onPointerDown(e) {\r\n // We do not call preventDefault for touch events\r\n // to allow browser to show native dialog on longpress\r\n // (the one that allows to save image or open it in new tab).\r\n //\r\n // Desktop Safari allows to drag images when preventDefault isn't called on mousedown,\r\n // even though preventDefault IS called on mousemove. That's why we preventDefault mousedown.\r\n const isMousePointer = e.type === 'mousedown' || e.pointerType === 'mouse';\r\n\r\n // Allow dragging only via left mouse button.\r\n // http://www.quirksmode.org/js/events_properties.html\r\n // https://developer.mozilla.org/en-US/docs/Web/API/event.button\r\n if (isMousePointer && e.button > 0) {\r\n return;\r\n }\r\n\r\n const { pswp } = this;\r\n\r\n // if PhotoSwipe is opening or closing\r\n if (!pswp.opener.isOpen) {\r\n e.preventDefault();\r\n return;\r\n }\r\n\r\n if (pswp.dispatch('pointerDown', { originalEvent: e }).defaultPrevented) {\r\n return;\r\n }\r\n\r\n if (isMousePointer) {\r\n pswp.mouseDetected();\r\n\r\n // preventDefault mouse event to prevent\r\n // browser image drag feature\r\n this._preventPointerEventBehaviour(e, 'down');\r\n }\r\n\r\n pswp.animations.stopAll();\r\n\r\n this._updatePoints(e, 'down');\r\n\r\n if (this._numActivePoints === 1) {\r\n this.dragAxis = null;\r\n // we need to store initial point to determine the main axis,\r\n // drag is activated only after the axis is determined\r\n equalizePoints(this.startP1, this.p1);\r\n }\r\n\r\n if (this._numActivePoints > 1) {\r\n // Tap or double tap should not trigger if more than one pointer\r\n this._clearTapTimer();\r\n this.isMultitouch = true;\r\n } else {\r\n this.isMultitouch = false;\r\n }\r\n }\r\n\r\n /**\r\n * @param {PointerEvent} e\r\n */\r\n onPointerMove(e) {\r\n this._preventPointerEventBehaviour(e, 'move');\r\n\r\n if (!this._numActivePoints) {\r\n return;\r\n }\r\n\r\n this._updatePoints(e, 'move');\r\n\r\n if (this.pswp.dispatch('pointerMove', { originalEvent: e }).defaultPrevented) {\r\n return;\r\n }\r\n\r\n if (this._numActivePoints === 1 && !this.isDragging) {\r\n if (!this.dragAxis) {\r\n this._calculateDragDirection();\r\n }\r\n\r\n // Drag axis was detected, emit drag.start\r\n if (this.dragAxis && !this.isDragging) {\r\n if (this.isZooming) {\r\n this.isZooming = false;\r\n this.zoomLevels.end();\r\n }\r\n\r\n this.isDragging = true;\r\n this._clearTapTimer(); // Tap can not trigger after drag\r\n\r\n // Adjust starting point\r\n this._updateStartPoints();\r\n this._intervalTime = Date.now();\r\n //this._startTime = this._intervalTime;\r\n this._velocityCalculated = false;\r\n equalizePoints(this._intervalP1, this.p1);\r\n this.velocity.x = 0;\r\n this.velocity.y = 0;\r\n this.drag.start();\r\n\r\n this._rafStopLoop();\r\n this._rafRenderLoop();\r\n }\r\n } else if (this._numActivePoints > 1 && !this.isZooming) {\r\n this._finishDrag();\r\n\r\n this.isZooming = true;\r\n\r\n // Adjust starting points\r\n this._updateStartPoints();\r\n\r\n this.zoomLevels.start();\r\n\r\n this._rafStopLoop();\r\n this._rafRenderLoop();\r\n }\r\n }\r\n\r\n /**\r\n * @private\r\n */\r\n _finishDrag() {\r\n if (this.isDragging) {\r\n this.isDragging = false;\r\n\r\n // Try to calculate velocity,\r\n // if it wasn't calculated yet in drag.change\r\n if (!this._velocityCalculated) {\r\n this._updateVelocity(true);\r\n }\r\n\r\n this.drag.end();\r\n this.dragAxis = null;\r\n }\r\n }\r\n\r\n /**\r\n * @param {PointerEvent} e\r\n */\r\n onPointerUp(e) {\r\n if (!this._numActivePoints) {\r\n return;\r\n }\r\n\r\n this._updatePoints(e, 'up');\r\n\r\n if (this.pswp.dispatch('pointerUp', { originalEvent: e }).defaultPrevented) {\r\n return;\r\n }\r\n\r\n if (this._numActivePoints === 0) {\r\n this._rafStopLoop();\r\n\r\n if (this.isDragging) {\r\n this._finishDrag();\r\n } else if (!this.isZooming && !this.isMultitouch) {\r\n //this.zoomLevels.correctZoomPan();\r\n this._finishTap(e);\r\n }\r\n }\r\n\r\n if (this._numActivePoints < 2 && this.isZooming) {\r\n this.isZooming = false;\r\n this.zoomLevels.end();\r\n\r\n if (this._numActivePoints === 1) {\r\n // Since we have 1 point left, we need to reinitiate drag\r\n this.dragAxis = null;\r\n this._updateStartPoints();\r\n }\r\n }\r\n }\r\n\r\n /**\r\n * @private\r\n */\r\n _rafRenderLoop() {\r\n if (this.isDragging || this.isZooming) {\r\n this._updateVelocity();\r\n\r\n if (this.isDragging) {\r\n // make sure that pointer moved since the last update\r\n if (!pointsEqual(this.p1, this.prevP1)) {\r\n this.drag.change();\r\n }\r\n } else /* if (this.isZooming) */ {\r\n if (!pointsEqual(this.p1, this.prevP1)\r\n || !pointsEqual(this.p2, this.prevP2)) {\r\n this.zoomLevels.change();\r\n }\r\n }\r\n\r\n this._updatePrevPoints();\r\n this.raf = requestAnimationFrame(this._rafRenderLoop.bind(this));\r\n }\r\n }\r\n\r\n /**\r\n * Update velocity at 50ms interval\r\n *\r\n * @private\r\n * @param {boolean} [force]\r\n */\r\n _updateVelocity(force) {\r\n const time = Date.now();\r\n const duration = time - this._intervalTime;\r\n\r\n if (duration < 50 && !force) {\r\n return;\r\n }\r\n\r\n\r\n this.velocity.x = this._getVelocity('x', duration);\r\n this.velocity.y = this._getVelocity('y', duration);\r\n\r\n this._intervalTime = time;\r\n equalizePoints(this._intervalP1, this.p1);\r\n this._velocityCalculated = true;\r\n }\r\n\r\n /**\r\n * @private\r\n * @param {PointerEvent} e\r\n */\r\n _finishTap(e) {\r\n const { mainScroll } = this.pswp;\r\n\r\n // Do not trigger tap events if main scroll is shifted\r\n if (mainScroll.isShifted()) {\r\n // restore main scroll position\r\n // (usually happens if stopped in the middle of animation)\r\n mainScroll.moveIndexBy(0, true);\r\n return;\r\n }\r\n\r\n // Do not trigger tap for touchcancel or pointercancel\r\n if (e.type.indexOf('cancel') > 0) {\r\n return;\r\n }\r\n\r\n // Trigger click instead of tap for mouse events\r\n if (e.type === 'mouseup' || e.pointerType === 'mouse') {\r\n this.tapHandler.click(this.startP1, e);\r\n return;\r\n }\r\n\r\n // Disable delay if there is no doubleTapAction\r\n const tapDelay = this.pswp.options.doubleTapAction ? DOUBLE_TAP_DELAY : 0;\r\n\r\n // If tapTimer is defined - we tapped recently,\r\n // check if the current tap is close to the previous one,\r\n // if yes - trigger double tap\r\n if (this._tapTimer) {\r\n this._clearTapTimer();\r\n // Check if two taps were more or less on the same place\r\n if (getDistanceBetween(this._lastStartP1, this.startP1) < MIN_TAP_DISTANCE) {\r\n this.tapHandler.doubleTap(this.startP1, e);\r\n }\r\n } else {\r\n equalizePoints(this._lastStartP1, this.startP1);\r\n this._tapTimer = setTimeout(() => {\r\n this.tapHandler.tap(this.startP1, e);\r\n this._clearTapTimer();\r\n }, tapDelay);\r\n }\r\n }\r\n\r\n /**\r\n * @private\r\n */\r\n _clearTapTimer() {\r\n if (this._tapTimer) {\r\n clearTimeout(this._tapTimer);\r\n this._tapTimer = null;\r\n }\r\n }\r\n\r\n /**\r\n * Get velocity for axis\r\n *\r\n * @private\r\n * @param {'x' | 'y'} axis\r\n * @param {number} duration\r\n * @returns {number}\r\n */\r\n _getVelocity(axis, duration) {\r\n // displacement is like distance, but can be negative.\r\n const displacement = this.p1[axis] - this._intervalP1[axis];\r\n\r\n if (Math.abs(displacement) > 1 && duration > 5) {\r\n return displacement / duration;\r\n }\r\n\r\n return 0;\r\n }\r\n\r\n /**\r\n * @private\r\n */\r\n _rafStopLoop() {\r\n if (this.raf) {\r\n cancelAnimationFrame(this.raf);\r\n this.raf = null;\r\n }\r\n }\r\n\r\n /**\r\n * @private\r\n * @param {PointerEvent} e\r\n * @param {'up' | 'down' | 'move'} pointerType Normalized pointer type\r\n */\r\n _preventPointerEventBehaviour(e, pointerType) {\r\n const preventPointerEvent = this.pswp.applyFilters('preventPointerEvent', true, e, pointerType);\r\n if (preventPointerEvent) {\r\n e.preventDefault();\r\n }\r\n }\r\n\r\n /**\r\n * Parses and normalizes points from the touch, mouse or pointer event.\r\n * Updates p1 and p2.\r\n *\r\n * @private\r\n * @param {PointerEvent | TouchEvent} e\r\n * @param {'up' | 'down' | 'move'} pointerType Normalized pointer type\r\n */\r\n _updatePoints(e, pointerType) {\r\n if (this._pointerEventEnabled) {\r\n const pointerEvent = /** @type {PointerEvent} */ (e);\r\n // Try to find the current pointer in ongoing pointers by its ID\r\n const pointerIndex = this._ongoingPointers.findIndex((ongoingPointer) => {\r\n return ongoingPointer.id === pointerEvent.pointerId;\r\n });\r\n\r\n if (pointerType === 'up' && pointerIndex > -1) {\r\n // release the pointer - remove it from ongoing\r\n this._ongoingPointers.splice(pointerIndex, 1);\r\n } else if (pointerType === 'down' && pointerIndex === -1) {\r\n // add new pointer\r\n this._ongoingPointers.push(this._convertEventPosToPoint(pointerEvent, { x: 0, y: 0 }));\r\n } else if (pointerIndex > -1) {\r\n // update existing pointer\r\n this._convertEventPosToPoint(pointerEvent, this._ongoingPointers[pointerIndex]);\r\n }\r\n\r\n this._numActivePoints = this._ongoingPointers.length;\r\n\r\n // update points that PhotoSwipe uses\r\n // to calculate position and scale\r\n if (this._numActivePoints > 0) {\r\n equalizePoints(this.p1, this._ongoingPointers[0]);\r\n }\r\n\r\n if (this._numActivePoints > 1) {\r\n equalizePoints(this.p2, this._ongoingPointers[1]);\r\n }\r\n } else {\r\n const touchEvent = /** @type {TouchEvent} */ (e);\r\n\r\n this._numActivePoints = 0;\r\n if (touchEvent.type.indexOf('touch') > -1) {\r\n // Touch Event\r\n // https://developer.mozilla.org/en-US/docs/Web/API/TouchEvent\r\n if (touchEvent.touches && touchEvent.touches.length > 0) {\r\n this._convertEventPosToPoint(touchEvent.touches[0], this.p1);\r\n this._numActivePoints++;\r\n if (touchEvent.touches.length > 1) {\r\n this._convertEventPosToPoint(touchEvent.touches[1], this.p2);\r\n this._numActivePoints++;\r\n }\r\n }\r\n } else {\r\n // Mouse Event\r\n this._convertEventPosToPoint(/** @type {PointerEvent} */ (e), this.p1);\r\n if (pointerType === 'up') {\r\n // clear all points on mouseup\r\n this._numActivePoints = 0;\r\n } else {\r\n this._numActivePoints++;\r\n }\r\n }\r\n }\r\n }\r\n\r\n /** update points that were used during previous rAF tick\r\n * @private\r\n */\r\n _updatePrevPoints() {\r\n equalizePoints(this.prevP1, this.p1);\r\n equalizePoints(this.prevP2, this.p2);\r\n }\r\n\r\n /** update points at the start of gesture\r\n * @private\r\n */\r\n _updateStartPoints() {\r\n equalizePoints(this.startP1, this.p1);\r\n equalizePoints(this.startP2, this.p2);\r\n this._updatePrevPoints();\r\n }\r\n\r\n /** @private */\r\n _calculateDragDirection() {\r\n if (this.pswp.mainScroll.isShifted()) {\r\n // if main scroll position is shifted – direction is always horizontal\r\n this.dragAxis = 'x';\r\n } else {\r\n // calculate delta of the last touchmove tick\r\n const diff = Math.abs(this.p1.x - this.startP1.x) - Math.abs(this.p1.y - this.startP1.y);\r\n\r\n if (diff !== 0) {\r\n // check if pointer was shifted horizontally or vertically\r\n const axisToCheck = diff > 0 ? 'x' : 'y';\r\n\r\n if (Math.abs(this.p1[axisToCheck] - this.startP1[axisToCheck]) >= AXIS_SWIPE_HYSTERISIS) {\r\n this.dragAxis = axisToCheck;\r\n }\r\n }\r\n }\r\n }\r\n\r\n /**\r\n * Converts touch, pointer or mouse event\r\n * to PhotoSwipe point.\r\n *\r\n * @private\r\n * @param {Touch | PointerEvent} e\r\n * @param {Point} p\r\n * @returns {Point}\r\n */\r\n _convertEventPosToPoint(e, p) {\r\n p.x = e.pageX - this.pswp.offset.x;\r\n p.y = e.pageY - this.pswp.offset.y;\r\n\r\n if ('pointerId' in e) {\r\n p.id = e.pointerId;\r\n } else if (e.identifier !== undefined) {\r\n p.id = e.identifier;\r\n }\r\n\r\n return p;\r\n }\r\n\r\n /**\r\n * @private\r\n * @param {PointerEvent} e\r\n */\r\n _onClick(e) {\r\n // Do not allow click event to pass through after drag\r\n if (this.pswp.mainScroll.isShifted()) {\r\n e.preventDefault();\r\n e.stopPropagation();\r\n }\r\n }\r\n}\r\n\r\nexport default Gestures;\r\n", "import {\r\n setTransform,\r\n createElement,\r\n} from './util/util.js';\r\n\r\n/** @typedef {import('./photoswipe.js').default} PhotoSwipe */\r\n/** @typedef {import('./slide/slide.js').default} Slide */\r\n\r\n/** @typedef {{ el: HTMLDivElement; slide?: Slide }} ItemHolder */\r\n\r\nconst MAIN_SCROLL_END_FRICTION = 0.35;\r\n\r\n\r\n// const MIN_SWIPE_TRANSITION_DURATION = 250;\r\n// const MAX_SWIPE_TRABSITION_DURATION = 500;\r\n// const DEFAULT_SWIPE_TRANSITION_DURATION = 333;\r\n\r\n/**\r\n * Handles movement of the main scrolling container\r\n * (for example, it repositions when user swipes left or right).\r\n *\r\n * Also stores its state.\r\n */\r\nclass MainScroll {\r\n /**\r\n * @param {PhotoSwipe} pswp\r\n */\r\n constructor(pswp) {\r\n this.pswp = pswp;\r\n this.x = 0;\r\n this.slideWidth = 0;\r\n /** @private */\r\n this._currPositionIndex = 0;\r\n /** @private */\r\n this._prevPositionIndex = 0;\r\n /** @private */\r\n this._containerShiftIndex = -1;\r\n\r\n /** @type {ItemHolder[]} */\r\n this.itemHolders = [];\r\n }\r\n\r\n /**\r\n * Position the scroller and slide containers\r\n * according to viewport size.\r\n *\r\n * @param {boolean} [resizeSlides] Whether slides content should resized\r\n */\r\n resize(resizeSlides) {\r\n const { pswp } = this;\r\n const newSlideWidth = Math.round(\r\n pswp.viewportSize.x + pswp.viewportSize.x * pswp.options.spacing\r\n );\r\n // Mobile browsers might trigger a resize event during a gesture.\r\n // (due to toolbar appearing or hiding).\r\n // Avoid re-adjusting main scroll position if width wasn't changed\r\n const slideWidthChanged = (newSlideWidth !== this.slideWidth);\r\n\r\n if (slideWidthChanged) {\r\n this.slideWidth = newSlideWidth;\r\n this.moveTo(this.getCurrSlideX());\r\n }\r\n\r\n this.itemHolders.forEach((itemHolder, index) => {\r\n if (slideWidthChanged) {\r\n setTransform(itemHolder.el, (index + this._containerShiftIndex)\r\n * this.slideWidth);\r\n }\r\n\r\n if (resizeSlides && itemHolder.slide) {\r\n itemHolder.slide.resize();\r\n }\r\n });\r\n }\r\n\r\n /**\r\n * Reset X position of the main scroller to zero\r\n */\r\n resetPosition() {\r\n // Position on the main scroller (offset)\r\n // it is independent from slide index\r\n this._currPositionIndex = 0;\r\n this._prevPositionIndex = 0;\r\n\r\n // This will force recalculation of size on next resize()\r\n this.slideWidth = 0;\r\n\r\n // _containerShiftIndex*viewportSize will give you amount of transform of the current slide\r\n this._containerShiftIndex = -1;\r\n }\r\n\r\n /**\r\n * Create and append array of three items\r\n * that hold data about slides in DOM\r\n */\r\n appendHolders() {\r\n this.itemHolders = [];\r\n\r\n // append our three slide holders -\r\n // previous, current, and next\r\n for (let i = 0; i < 3; i++) {\r\n const el = createElement('pswp__item', 'div', this.pswp.container);\r\n el.setAttribute('role', 'group');\r\n el.setAttribute('aria-roledescription', 'slide');\r\n el.setAttribute('aria-hidden', 'true');\r\n\r\n // hide nearby item holders until initial zoom animation finishes (to avoid extra Paints)\r\n el.style.display = (i === 1) ? 'block' : 'none';\r\n\r\n this.itemHolders.push({\r\n el,\r\n //index: -1\r\n });\r\n }\r\n }\r\n\r\n /**\r\n * Whether the main scroll can be horizontally swiped to the next or previous slide.\r\n * @returns {boolean}\r\n */\r\n canBeSwiped() {\r\n return this.pswp.getNumItems() > 1;\r\n }\r\n\r\n /**\r\n * Move main scroll by X amount of slides.\r\n * For example:\r\n * `-1` will move to the previous slide,\r\n * `0` will reset the scroll position of the current slide,\r\n * `3` will move three slides forward\r\n *\r\n * If loop option is enabled - index will be automatically looped too,\r\n * (for example `-1` will move to the last slide of the gallery).\r\n *\r\n * @param {number} diff\r\n * @param {boolean} [animate]\r\n * @param {number} [velocityX]\r\n * @returns {boolean} whether index was changed or not\r\n */\r\n moveIndexBy(diff, animate, velocityX) {\r\n const { pswp } = this;\r\n let newIndex = pswp.potentialIndex + diff;\r\n const numSlides = pswp.getNumItems();\r\n\r\n if (pswp.canLoop()) {\r\n newIndex = pswp.getLoopedIndex(newIndex);\r\n const distance = (diff + numSlides) % numSlides;\r\n if (distance <= numSlides / 2) {\r\n // go forward\r\n diff = distance;\r\n } else {\r\n // go backwards\r\n diff = distance - numSlides;\r\n }\r\n } else {\r\n if (newIndex < 0) {\r\n newIndex = 0;\r\n } else if (newIndex >= numSlides) {\r\n newIndex = numSlides - 1;\r\n }\r\n diff = newIndex - pswp.potentialIndex;\r\n }\r\n\r\n pswp.potentialIndex = newIndex;\r\n this._currPositionIndex -= diff;\r\n\r\n pswp.animations.stopMainScroll();\r\n\r\n const destinationX = this.getCurrSlideX();\r\n if (!animate) {\r\n this.moveTo(destinationX);\r\n this.updateCurrItem();\r\n } else {\r\n pswp.animations.startSpring({\r\n isMainScroll: true,\r\n start: this.x,\r\n end: destinationX,\r\n velocity: velocityX || 0,\r\n naturalFrequency: 30,\r\n dampingRatio: 1, //0.7,\r\n onUpdate: (x) => {\r\n this.moveTo(x);\r\n },\r\n onComplete: () => {\r\n this.updateCurrItem();\r\n pswp.appendHeavy();\r\n }\r\n });\r\n\r\n let currDiff = pswp.potentialIndex - pswp.currIndex;\r\n if (pswp.canLoop()) {\r\n const currDistance = (currDiff + numSlides) % numSlides;\r\n if (currDistance <= numSlides / 2) {\r\n // go forward\r\n currDiff = currDistance;\r\n } else {\r\n // go backwards\r\n currDiff = currDistance - numSlides;\r\n }\r\n }\r\n\r\n // Force-append new slides during transition\r\n // if difference between slides is more than 1\r\n if (Math.abs(currDiff) > 1) {\r\n this.updateCurrItem();\r\n }\r\n }\r\n\r\n return Boolean(diff);\r\n }\r\n\r\n /**\r\n * X position of the main scroll for the current slide\r\n * (ignores position during dragging)\r\n * @returns {number}\r\n */\r\n getCurrSlideX() {\r\n return this.slideWidth * this._currPositionIndex;\r\n }\r\n\r\n /**\r\n * Whether scroll position is shifted.\r\n * For example, it will return true if the scroll is being dragged or animated.\r\n * @returns {boolean}\r\n */\r\n isShifted() {\r\n return this.x !== this.getCurrSlideX();\r\n }\r\n\r\n /**\r\n * Update slides X positions and set their content\r\n */\r\n updateCurrItem() {\r\n const { pswp } = this;\r\n const positionDifference = this._prevPositionIndex - this._currPositionIndex;\r\n\r\n if (!positionDifference) {\r\n return;\r\n }\r\n\r\n this._prevPositionIndex = this._currPositionIndex;\r\n\r\n pswp.currIndex = pswp.potentialIndex;\r\n\r\n let diffAbs = Math.abs(positionDifference);\r\n /** @type {ItemHolder | undefined} */\r\n let tempHolder;\r\n\r\n if (diffAbs >= 3) {\r\n this._containerShiftIndex += positionDifference + (positionDifference > 0 ? -3 : 3);\r\n diffAbs = 3;\r\n\r\n // If slides are changed by 3 screens or more - clean up previous slides\r\n this.itemHolders.forEach((itemHolder) => {\r\n itemHolder.slide?.destroy();\r\n itemHolder.slide = undefined;\r\n });\r\n }\r\n\r\n for (let i = 0; i < diffAbs; i++) {\r\n if (positionDifference > 0) {\r\n tempHolder = this.itemHolders.shift();\r\n if (tempHolder) {\r\n this.itemHolders[2] = tempHolder; // move first to last\r\n\r\n this._containerShiftIndex++;\r\n\r\n setTransform(tempHolder.el, (this._containerShiftIndex + 2) * this.slideWidth);\r\n\r\n pswp.setContent(tempHolder, (pswp.currIndex - diffAbs) + i + 2);\r\n }\r\n } else {\r\n tempHolder = this.itemHolders.pop();\r\n if (tempHolder) {\r\n this.itemHolders.unshift(tempHolder); // move last to first\r\n\r\n this._containerShiftIndex--;\r\n\r\n setTransform(tempHolder.el, this._containerShiftIndex * this.slideWidth);\r\n\r\n pswp.setContent(tempHolder, (pswp.currIndex + diffAbs) - i - 2);\r\n }\r\n }\r\n }\r\n\r\n // Reset transfrom every 50ish navigations in one direction.\r\n //\r\n // Otherwise transform will keep growing indefinitely,\r\n // which might cause issues as browsers have a maximum transform limit.\r\n // I wasn't able to reach it, but just to be safe.\r\n // This should not cause noticable lag.\r\n if (Math.abs(this._containerShiftIndex) > 50 && !this.isShifted()) {\r\n this.resetPosition();\r\n this.resize();\r\n }\r\n\r\n // Pan transition might be running (and consntantly updating pan position)\r\n pswp.animations.stopAllPan();\r\n\r\n this.itemHolders.forEach((itemHolder, i) => {\r\n if (itemHolder.slide) {\r\n // Slide in the 2nd holder is always active\r\n itemHolder.slide.setIsActive(i === 1);\r\n }\r\n });\r\n\r\n pswp.currSlide = this.itemHolders[1]?.slide;\r\n pswp.contentLoader.updateLazy(positionDifference);\r\n\r\n if (pswp.currSlide) {\r\n pswp.currSlide.applyCurrentZoomPan();\r\n }\r\n\r\n pswp.dispatch('change');\r\n }\r\n\r\n /**\r\n * Move the X position of the main scroll container\r\n *\r\n * @param {number} x\r\n * @param {boolean} [dragging]\r\n */\r\n moveTo(x, dragging) {\r\n if (!this.pswp.canLoop() && dragging) {\r\n // Apply friction\r\n let newSlideIndexOffset = ((this.slideWidth * this._currPositionIndex) - x) / this.slideWidth;\r\n newSlideIndexOffset += this.pswp.currIndex;\r\n const delta = Math.round(x - this.x);\r\n\r\n if ((newSlideIndexOffset < 0 && delta > 0)\r\n || (newSlideIndexOffset >= this.pswp.getNumItems() - 1 && delta < 0)) {\r\n x = this.x + (delta * MAIN_SCROLL_END_FRICTION);\r\n }\r\n }\r\n\r\n this.x = x;\r\n\r\n if (this.pswp.container) {\r\n setTransform(this.pswp.container, x);\r\n }\r\n\r\n this.pswp.dispatch('moveMainScroll', { x, dragging: dragging ?? false });\r\n }\r\n}\r\n\r\nexport default MainScroll;\r\n", "import { specialKeyUsed } from './util/util.js';\r\n\r\n/** @typedef {import('./photoswipe.js').default} PhotoSwipe */\r\n\r\n/**\r\n * @template T\r\n * @typedef {import('./types.js').Methods} Methods\r\n */\r\n\r\nconst KeyboardKeyCodesMap = {\r\n Escape: 27,\r\n z: 90,\r\n ArrowLeft: 37,\r\n ArrowUp: 38,\r\n ArrowRight: 39,\r\n ArrowDown: 40,\r\n Tab: 9,\r\n};\r\n\r\n/**\r\n * @template {keyof KeyboardKeyCodesMap} T\r\n * @param {T} key\r\n * @param {boolean} isKeySupported\r\n * @returns {T | number | undefined}\r\n */\r\nconst getKeyboardEventKey = (key, isKeySupported) => {\r\n return isKeySupported ? key : KeyboardKeyCodesMap[key];\r\n};\r\n\r\n/**\r\n * - Manages keyboard shortcuts.\r\n * - Helps trap focus within photoswipe.\r\n */\r\nclass Keyboard {\r\n /**\r\n * @param {PhotoSwipe} pswp\r\n */\r\n constructor(pswp) {\r\n this.pswp = pswp;\r\n /** @private */\r\n this._wasFocused = false;\r\n\r\n pswp.on('bindEvents', () => {\r\n if (pswp.options.trapFocus) {\r\n // Dialog was likely opened by keyboard if initial point is not defined\r\n if (!pswp.options.initialPointerPos) {\r\n // focus causes layout,\r\n // which causes lag during the animation,\r\n // that's why we delay it until the opener transition ends\r\n this._focusRoot();\r\n }\r\n\r\n pswp.events.add(\r\n document,\r\n 'focusin',\r\n /** @type EventListener */(this._onFocusIn.bind(this))\r\n );\r\n }\r\n\r\n pswp.events.add(document, 'keydown', /** @type EventListener */(this._onKeyDown.bind(this)));\r\n });\r\n\r\n const lastActiveElement = /** @type {HTMLElement} */ (document.activeElement);\r\n pswp.on('destroy', () => {\r\n if (pswp.options.returnFocus\r\n && lastActiveElement\r\n && this._wasFocused) {\r\n lastActiveElement.focus();\r\n }\r\n });\r\n }\r\n\r\n /** @private */\r\n _focusRoot() {\r\n if (!this._wasFocused && this.pswp.element) {\r\n this.pswp.element.focus();\r\n this._wasFocused = true;\r\n }\r\n }\r\n\r\n /**\r\n * @private\r\n * @param {KeyboardEvent} e\r\n */\r\n _onKeyDown(e) {\r\n const { pswp } = this;\r\n\r\n if (pswp.dispatch('keydown', { originalEvent: e }).defaultPrevented) {\r\n return;\r\n }\r\n\r\n if (specialKeyUsed(e)) {\r\n // don't do anything if special key pressed\r\n // to prevent from overriding default browser actions\r\n // for example, in Chrome on Mac cmd+arrow-left returns to previous page\r\n return;\r\n }\r\n\r\n /** @type {Methods | undefined} */\r\n let keydownAction;\r\n /** @type {'x' | 'y' | undefined} */\r\n let axis;\r\n let isForward = false;\r\n const isKeySupported = 'key' in e;\r\n\r\n switch (isKeySupported ? e.key : e.keyCode) {\r\n case getKeyboardEventKey('Escape', isKeySupported):\r\n if (pswp.options.escKey) {\r\n keydownAction = 'close';\r\n }\r\n break;\r\n case getKeyboardEventKey('z', isKeySupported):\r\n keydownAction = 'toggleZoom';\r\n break;\r\n case getKeyboardEventKey('ArrowLeft', isKeySupported):\r\n axis = 'x';\r\n break;\r\n case getKeyboardEventKey('ArrowUp', isKeySupported):\r\n axis = 'y';\r\n break;\r\n case getKeyboardEventKey('ArrowRight', isKeySupported):\r\n axis = 'x';\r\n isForward = true;\r\n break;\r\n case getKeyboardEventKey('ArrowDown', isKeySupported):\r\n isForward = true;\r\n axis = 'y';\r\n break;\r\n case getKeyboardEventKey('Tab', isKeySupported):\r\n this._focusRoot();\r\n break;\r\n default:\r\n }\r\n\r\n // if left/right/top/bottom key\r\n if (axis) {\r\n // prevent page scroll\r\n e.preventDefault();\r\n\r\n const { currSlide } = pswp;\r\n\r\n if (pswp.options.arrowKeys\r\n && axis === 'x'\r\n && pswp.getNumItems() > 1) {\r\n keydownAction = isForward ? 'next' : 'prev';\r\n } else if (currSlide && currSlide.currZoomLevel > currSlide.zoomLevels.fit) {\r\n // up/down arrow keys pan the image vertically\r\n // left/right arrow keys pan horizontally.\r\n // Unless there is only one image,\r\n // or arrowKeys option is disabled\r\n currSlide.pan[axis] += isForward ? -80 : 80;\r\n currSlide.panTo(currSlide.pan.x, currSlide.pan.y);\r\n }\r\n }\r\n\r\n if (keydownAction) {\r\n e.preventDefault();\r\n // @ts-ignore\r\n pswp[keydownAction]();\r\n }\r\n }\r\n\r\n /**\r\n * Trap focus inside photoswipe\r\n *\r\n * @private\r\n * @param {FocusEvent} e\r\n */\r\n _onFocusIn(e) {\r\n const { template } = this.pswp;\r\n if (template\r\n && document !== e.target\r\n && template !== e.target\r\n && !template.contains(/** @type {Node} */ (e.target))) {\r\n // focus root element\r\n template.focus();\r\n }\r\n }\r\n}\r\n\r\nexport default Keyboard;\r\n", "import { setTransitionStyle, removeTransitionStyle } from './util.js';\r\n\r\nconst DEFAULT_EASING = 'cubic-bezier(.4,0,.22,1)';\r\n\r\n/** @typedef {import('./animations.js').SharedAnimationProps} SharedAnimationProps */\r\n\r\n/** @typedef {Object} DefaultCssAnimationProps\r\n *\r\n * @prop {HTMLElement} target\r\n * @prop {number} [duration]\r\n * @prop {string} [easing]\r\n * @prop {string} [transform]\r\n * @prop {string} [opacity]\r\n * */\r\n\r\n/** @typedef {SharedAnimationProps & DefaultCssAnimationProps} CssAnimationProps */\r\n\r\n/**\r\n * Runs CSS transition.\r\n */\r\nclass CSSAnimation {\r\n /**\r\n * onComplete can be unpredictable, be careful about current state\r\n *\r\n * @param {CssAnimationProps} props\r\n */\r\n constructor(props) {\r\n this.props = props;\r\n const {\r\n target,\r\n onComplete,\r\n transform,\r\n onFinish = () => {},\r\n duration = 333,\r\n easing = DEFAULT_EASING,\r\n } = props;\r\n\r\n this.onFinish = onFinish;\r\n\r\n // support only transform and opacity\r\n const prop = transform ? 'transform' : 'opacity';\r\n const propValue = props[prop] ?? '';\r\n\r\n /** @private */\r\n this._target = target;\r\n /** @private */\r\n this._onComplete = onComplete;\r\n /** @private */\r\n this._finished = false;\r\n\r\n /** @private */\r\n this._onTransitionEnd = this._onTransitionEnd.bind(this);\r\n\r\n // Using timeout hack to make sure that animation\r\n // starts even if the animated property was changed recently,\r\n // otherwise transitionend might not fire or transition won't start.\r\n // https://drafts.csswg.org/css-transitions/#starting\r\n //\r\n // ¯\\_(ツ)_/¯\r\n /** @private */\r\n this._helperTimeout = setTimeout(() => {\r\n setTransitionStyle(target, prop, duration, easing);\r\n this._helperTimeout = setTimeout(() => {\r\n target.addEventListener('transitionend', this._onTransitionEnd, false);\r\n target.addEventListener('transitioncancel', this._onTransitionEnd, false);\r\n\r\n // Safari occasionally does not emit transitionend event\r\n // if element property was modified during the transition,\r\n // which may be caused by resize or third party component,\r\n // using timeout as a safety fallback\r\n this._helperTimeout = setTimeout(() => {\r\n this._finalizeAnimation();\r\n }, duration + 500);\r\n target.style[prop] = propValue;\r\n }, 30); // Do not reduce this number\r\n }, 0);\r\n }\r\n\r\n /**\r\n * @private\r\n * @param {TransitionEvent} e\r\n */\r\n _onTransitionEnd(e) {\r\n if (e.target === this._target) {\r\n this._finalizeAnimation();\r\n }\r\n }\r\n\r\n /**\r\n * @private\r\n */\r\n _finalizeAnimation() {\r\n if (!this._finished) {\r\n this._finished = true;\r\n this.onFinish();\r\n if (this._onComplete) {\r\n this._onComplete();\r\n }\r\n }\r\n }\r\n\r\n // Destroy is called automatically onFinish\r\n destroy() {\r\n if (this._helperTimeout) {\r\n clearTimeout(this._helperTimeout);\r\n }\r\n removeTransitionStyle(this._target);\r\n this._target.removeEventListener('transitionend', this._onTransitionEnd, false);\r\n this._target.removeEventListener('transitioncancel', this._onTransitionEnd, false);\r\n if (!this._finished) {\r\n this._finalizeAnimation();\r\n }\r\n }\r\n}\r\n\r\nexport default CSSAnimation;\r\n", "const DEFAULT_NATURAL_FREQUENCY = 12;\r\nconst DEFAULT_DAMPING_RATIO = 0.75;\r\n\r\n/**\r\n * Spring easing helper\r\n */\r\nclass SpringEaser {\r\n /**\r\n * @param {number} initialVelocity Initial velocity, px per ms.\r\n *\r\n * @param {number} [dampingRatio]\r\n * Determines how bouncy animation will be.\r\n * From 0 to 1, 0 - always overshoot, 1 - do not overshoot.\r\n * \"overshoot\" refers to part of animation that\r\n * goes beyond the final value.\r\n *\r\n * @param {number} [naturalFrequency]\r\n * Determines how fast animation will slow down.\r\n * The higher value - the stiffer the transition will be,\r\n * and the faster it will slow down.\r\n * Recommended value from 10 to 50\r\n */\r\n constructor(initialVelocity, dampingRatio, naturalFrequency) {\r\n this.velocity = initialVelocity * 1000; // convert to \"pixels per second\"\r\n\r\n // https://en.wikipedia.org/wiki/Damping_ratio\r\n this._dampingRatio = dampingRatio || DEFAULT_DAMPING_RATIO;\r\n\r\n // https://en.wikipedia.org/wiki/Natural_frequency\r\n this._naturalFrequency = naturalFrequency || DEFAULT_NATURAL_FREQUENCY;\r\n\r\n this._dampedFrequency = this._naturalFrequency;\r\n\r\n if (this._dampingRatio < 1) {\r\n this._dampedFrequency *= Math.sqrt(1 - this._dampingRatio * this._dampingRatio);\r\n }\r\n }\r\n\r\n /**\r\n * @param {number} deltaPosition Difference between current and end position of the animation\r\n * @param {number} deltaTime Frame duration in milliseconds\r\n *\r\n * @returns {number} Displacement, relative to the end position.\r\n */\r\n easeFrame(deltaPosition, deltaTime) {\r\n // Inspired by Apple Webkit and Android spring function implementation\r\n // https://en.wikipedia.org/wiki/Oscillation\r\n // https://en.wikipedia.org/wiki/Damping_ratio\r\n // we ignore mass (assume that it's 1kg)\r\n\r\n let displacement = 0;\r\n let coeff;\r\n\r\n deltaTime /= 1000;\r\n\r\n const naturalDumpingPow = Math.E ** (-this._dampingRatio * this._naturalFrequency * deltaTime);\r\n\r\n if (this._dampingRatio === 1) {\r\n coeff = this.velocity + this._naturalFrequency * deltaPosition;\r\n\r\n displacement = (deltaPosition + coeff * deltaTime) * naturalDumpingPow;\r\n\r\n this.velocity = displacement\r\n * (-this._naturalFrequency) + coeff\r\n * naturalDumpingPow;\r\n } else if (this._dampingRatio < 1) {\r\n coeff = (1 / this._dampedFrequency)\r\n * (this._dampingRatio * this._naturalFrequency * deltaPosition + this.velocity);\r\n\r\n const dumpedFCos = Math.cos(this._dampedFrequency * deltaTime);\r\n const dumpedFSin = Math.sin(this._dampedFrequency * deltaTime);\r\n\r\n displacement = naturalDumpingPow\r\n * (deltaPosition * dumpedFCos + coeff * dumpedFSin);\r\n\r\n this.velocity = displacement\r\n * (-this._naturalFrequency)\r\n * this._dampingRatio\r\n + naturalDumpingPow\r\n * (-this._dampedFrequency * deltaPosition * dumpedFSin\r\n + this._dampedFrequency * coeff * dumpedFCos);\r\n }\r\n\r\n // Overdamped (>1) damping ratio is not supported\r\n\r\n return displacement;\r\n }\r\n}\r\n\r\nexport default SpringEaser;\r\n", "import SpringEaser from './spring-easer.js';\r\n\r\n/** @typedef {import('./animations.js').SharedAnimationProps} SharedAnimationProps */\r\n\r\n/**\r\n * @typedef {Object} DefaultSpringAnimationProps\r\n *\r\n * @prop {number} start\r\n * @prop {number} end\r\n * @prop {number} velocity\r\n * @prop {number} [dampingRatio]\r\n * @prop {number} [naturalFrequency]\r\n * @prop {(end: number) => void} onUpdate\r\n */\r\n\r\n/** @typedef {SharedAnimationProps & DefaultSpringAnimationProps} SpringAnimationProps */\r\n\r\nclass SpringAnimation {\r\n /**\r\n * @param {SpringAnimationProps} props\r\n */\r\n constructor(props) {\r\n this.props = props;\r\n this._raf = 0;\r\n\r\n const {\r\n start,\r\n end,\r\n velocity,\r\n onUpdate,\r\n onComplete,\r\n onFinish = () => {},\r\n dampingRatio,\r\n naturalFrequency\r\n } = props;\r\n\r\n this.onFinish = onFinish;\r\n\r\n const easer = new SpringEaser(velocity, dampingRatio, naturalFrequency);\r\n let prevTime = Date.now();\r\n let deltaPosition = start - end;\r\n\r\n const animationLoop = () => {\r\n if (this._raf) {\r\n deltaPosition = easer.easeFrame(deltaPosition, Date.now() - prevTime);\r\n\r\n // Stop the animation if velocity is low and position is close to end\r\n if (Math.abs(deltaPosition) < 1 && Math.abs(easer.velocity) < 50) {\r\n // Finalize the animation\r\n onUpdate(end);\r\n if (onComplete) {\r\n onComplete();\r\n }\r\n this.onFinish();\r\n } else {\r\n prevTime = Date.now();\r\n onUpdate(deltaPosition + end);\r\n this._raf = requestAnimationFrame(animationLoop);\r\n }\r\n }\r\n };\r\n\r\n this._raf = requestAnimationFrame(animationLoop);\r\n }\r\n\r\n // Destroy is called automatically onFinish\r\n destroy() {\r\n if (this._raf >= 0) {\r\n cancelAnimationFrame(this._raf);\r\n }\r\n this._raf = 0;\r\n }\r\n}\r\n\r\nexport default SpringAnimation;\r\n", "import CSSAnimation from './css-animation.js';\r\nimport SpringAnimation from './spring-animation.js';\r\n\r\n/** @typedef {import('./css-animation.js').CssAnimationProps} CssAnimationProps */\r\n/** @typedef {import('./spring-animation.js').SpringAnimationProps} SpringAnimationProps */\r\n\r\n/** @typedef {Object} SharedAnimationProps\r\n * @prop {string} [name]\r\n * @prop {boolean} [isPan]\r\n * @prop {boolean} [isMainScroll]\r\n * @prop {VoidFunction} [onComplete]\r\n * @prop {VoidFunction} [onFinish]\r\n */\r\n\r\n/** @typedef {SpringAnimation | CSSAnimation} Animation */\r\n/** @typedef {SpringAnimationProps | CssAnimationProps} AnimationProps */\r\n\r\n/**\r\n * Manages animations\r\n */\r\nclass Animations {\r\n constructor() {\r\n /** @type {Animation[]} */\r\n this.activeAnimations = [];\r\n }\r\n\r\n /**\r\n * @param {SpringAnimationProps} props\r\n */\r\n startSpring(props) {\r\n this._start(props, true);\r\n }\r\n\r\n /**\r\n * @param {CssAnimationProps} props\r\n */\r\n startTransition(props) {\r\n this._start(props);\r\n }\r\n\r\n /**\r\n * @private\r\n * @param {AnimationProps} props\r\n * @param {boolean} [isSpring]\r\n * @returns {Animation}\r\n */\r\n _start(props, isSpring) {\r\n const animation = isSpring\r\n ? new SpringAnimation(/** @type SpringAnimationProps */ (props))\r\n : new CSSAnimation(/** @type CssAnimationProps */ (props));\r\n\r\n this.activeAnimations.push(animation);\r\n animation.onFinish = () => this.stop(animation);\r\n\r\n return animation;\r\n }\r\n\r\n /**\r\n * @param {Animation} animation\r\n */\r\n stop(animation) {\r\n animation.destroy();\r\n const index = this.activeAnimations.indexOf(animation);\r\n if (index > -1) {\r\n this.activeAnimations.splice(index, 1);\r\n }\r\n }\r\n\r\n stopAll() { // _stopAllAnimations\r\n this.activeAnimations.forEach((animation) => {\r\n animation.destroy();\r\n });\r\n this.activeAnimations = [];\r\n }\r\n\r\n /**\r\n * Stop all pan or zoom transitions\r\n */\r\n stopAllPan() {\r\n this.activeAnimations = this.activeAnimations.filter((animation) => {\r\n if (animation.props.isPan) {\r\n animation.destroy();\r\n return false;\r\n }\r\n\r\n return true;\r\n });\r\n }\r\n\r\n stopMainScroll() {\r\n this.activeAnimations = this.activeAnimations.filter((animation) => {\r\n if (animation.props.isMainScroll) {\r\n animation.destroy();\r\n return false;\r\n }\r\n\r\n return true;\r\n });\r\n }\r\n\r\n /**\r\n * Returns true if main scroll transition is running\r\n */\r\n // isMainScrollRunning() {\r\n // return this.activeAnimations.some((animation) => {\r\n // return animation.props.isMainScroll;\r\n // });\r\n // }\r\n\r\n /**\r\n * Returns true if any pan or zoom transition is running\r\n */\r\n isPanRunning() {\r\n return this.activeAnimations.some((animation) => {\r\n return animation.props.isPan;\r\n });\r\n }\r\n}\r\n\r\nexport default Animations;\r\n", "/** @typedef {import('./photoswipe.js').default} PhotoSwipe */\r\n\r\n/**\r\n * Handles scroll wheel.\r\n * Can pan and zoom current slide image.\r\n */\r\nclass ScrollWheel {\r\n /**\r\n * @param {PhotoSwipe} pswp\r\n */\r\n constructor(pswp) {\r\n this.pswp = pswp;\r\n pswp.events.add(pswp.element, 'wheel', /** @type EventListener */(this._onWheel.bind(this)));\r\n }\r\n\r\n /**\r\n * @private\r\n * @param {WheelEvent} e\r\n */\r\n _onWheel(e) {\r\n e.preventDefault();\r\n const { currSlide } = this.pswp;\r\n let { deltaX, deltaY } = e;\r\n\r\n if (!currSlide) {\r\n return;\r\n }\r\n\r\n if (this.pswp.dispatch('wheel', { originalEvent: e }).defaultPrevented) {\r\n return;\r\n }\r\n\r\n if (e.ctrlKey || this.pswp.options.wheelToZoom) {\r\n // zoom\r\n if (currSlide.isZoomable()) {\r\n let zoomFactor = -deltaY;\r\n if (e.deltaMode === 1 /* DOM_DELTA_LINE */) {\r\n zoomFactor *= 0.05;\r\n } else {\r\n zoomFactor *= e.deltaMode ? 1 : 0.002;\r\n }\r\n zoomFactor = 2 ** zoomFactor;\r\n\r\n const destZoomLevel = currSlide.currZoomLevel * zoomFactor;\r\n currSlide.zoomTo(destZoomLevel, {\r\n x: e.clientX,\r\n y: e.clientY\r\n });\r\n }\r\n } else {\r\n // pan\r\n if (currSlide.isPannable()) {\r\n if (e.deltaMode === 1 /* DOM_DELTA_LINE */) {\r\n // 18 - average line height\r\n deltaX *= 18;\r\n deltaY *= 18;\r\n }\r\n\r\n currSlide.panTo(\r\n currSlide.pan.x - deltaX,\r\n currSlide.pan.y - deltaY\r\n );\r\n }\r\n }\r\n }\r\n}\r\n\r\nexport default ScrollWheel;\r\n", "import { createElement } from '../util/util.js';\r\n\r\n/** @typedef {import('../photoswipe.js').default} PhotoSwipe */\r\n\r\n/**\r\n * @template T\r\n * @typedef {import('../types.js').Methods} Methods\r\n */\r\n\r\n/**\r\n * @typedef {Object} UIElementMarkupProps\r\n * @prop {boolean} [isCustomSVG]\r\n * @prop {string} inner\r\n * @prop {string} [outlineID]\r\n * @prop {number | string} [size]\r\n */\r\n\r\n/**\r\n * @typedef {Object} UIElementData\r\n * @prop {DefaultUIElements | string} [name]\r\n * @prop {string} [className]\r\n * @prop {UIElementMarkup} [html]\r\n * @prop {boolean} [isButton]\r\n * @prop {keyof HTMLElementTagNameMap} [tagName]\r\n * @prop {string} [title]\r\n * @prop {string} [ariaLabel]\r\n * @prop {(element: HTMLElement, pswp: PhotoSwipe) => void} [onInit]\r\n * @prop {Methods | ((e: MouseEvent, element: HTMLElement, pswp: PhotoSwipe) => void)} [onClick]\r\n * @prop {'bar' | 'wrapper' | 'root'} [appendTo]\r\n * @prop {number} [order]\r\n */\r\n\r\n/** @typedef {'arrowPrev' | 'arrowNext' | 'close' | 'zoom' | 'counter'} DefaultUIElements */\r\n\r\n/** @typedef {string | UIElementMarkupProps} UIElementMarkup */\r\n\r\n/**\r\n * @param {UIElementMarkup} [htmlData]\r\n * @returns {string}\r\n */\r\nfunction addElementHTML(htmlData) {\r\n if (typeof htmlData === 'string') {\r\n // Allow developers to provide full svg,\r\n // For example:\r\n // \r\n // \r\n // \r\n // \r\n // Can also be any HTML string.\r\n return htmlData;\r\n }\r\n\r\n if (!htmlData || !htmlData.isCustomSVG) {\r\n return '';\r\n }\r\n\r\n const svgData = htmlData;\r\n let out = '';\r\n // replace all %d with size\r\n out = out.split('%d').join(/** @type {string} */ (svgData.size || 32));\r\n\r\n // Icons may contain outline/shadow,\r\n // to make it we \"clone\" base icon shape and add border to it.\r\n // Icon itself and border are styled via CSS.\r\n //\r\n // Property shadowID defines ID of element that should be cloned.\r\n if (svgData.outlineID) {\r\n out += '';\r\n }\r\n\r\n out += svgData.inner;\r\n\r\n out += '';\r\n\r\n return out;\r\n}\r\n\r\nclass UIElement {\r\n /**\r\n * @param {PhotoSwipe} pswp\r\n * @param {UIElementData} data\r\n */\r\n constructor(pswp, data) {\r\n const name = data.name || data.className;\r\n let elementHTML = data.html;\r\n\r\n // @ts-expect-error lookup only by `data.name` maybe?\r\n if (pswp.options[name] === false) {\r\n // exit if element is disabled from options\r\n return;\r\n }\r\n\r\n // Allow to override SVG icons from options\r\n // @ts-expect-error lookup only by `data.name` maybe?\r\n if (typeof pswp.options[name + 'SVG'] === 'string') {\r\n // arrowPrevSVG\r\n // arrowNextSVG\r\n // closeSVG\r\n // zoomSVG\r\n // @ts-expect-error lookup only by `data.name` maybe?\r\n elementHTML = pswp.options[name + 'SVG'];\r\n }\r\n\r\n pswp.dispatch('uiElementCreate', { data });\r\n\r\n let className = '';\r\n if (data.isButton) {\r\n className += 'pswp__button ';\r\n className += (data.className || `pswp__button--${data.name}`);\r\n } else {\r\n className += (data.className || `pswp__${data.name}`);\r\n }\r\n\r\n let tagName = data.isButton ? (data.tagName || 'button') : (data.tagName || 'div');\r\n tagName = /** @type {keyof HTMLElementTagNameMap} */ (tagName.toLowerCase());\r\n /** @type {HTMLElement} */\r\n const element = createElement(className, tagName);\r\n\r\n if (data.isButton) {\r\n if (tagName === 'button') {\r\n /** @type {HTMLButtonElement} */ (element).type = 'button';\r\n }\r\n\r\n let { title } = data;\r\n const { ariaLabel } = data;\r\n\r\n // @ts-expect-error lookup only by `data.name` maybe?\r\n if (typeof pswp.options[name + 'Title'] === 'string') {\r\n // @ts-expect-error lookup only by `data.name` maybe?\r\n title = pswp.options[name + 'Title'];\r\n }\r\n\r\n if (title) {\r\n element.title = title;\r\n }\r\n\r\n const ariaText = ariaLabel || title;\r\n if (ariaText) {\r\n element.setAttribute('aria-label', ariaText);\r\n }\r\n }\r\n\r\n element.innerHTML = addElementHTML(elementHTML);\r\n\r\n if (data.onInit) {\r\n data.onInit(element, pswp);\r\n }\r\n\r\n if (data.onClick) {\r\n element.onclick = (e) => {\r\n if (typeof data.onClick === 'string') {\r\n // @ts-ignore\r\n pswp[data.onClick]();\r\n } else if (typeof data.onClick === 'function') {\r\n data.onClick(e, element, pswp);\r\n }\r\n };\r\n }\r\n\r\n // Top bar is default position\r\n const appendTo = data.appendTo || 'bar';\r\n /** @type {HTMLElement | undefined} root element by default */\r\n let container = pswp.element;\r\n if (appendTo === 'bar') {\r\n if (!pswp.topBar) {\r\n pswp.topBar = createElement('pswp__top-bar pswp__hide-on-close', 'div', pswp.scrollWrap);\r\n }\r\n container = pswp.topBar;\r\n } else {\r\n // element outside of top bar gets a secondary class\r\n // that makes element fade out on close\r\n element.classList.add('pswp__hide-on-close');\r\n\r\n if (appendTo === 'wrapper') {\r\n container = pswp.scrollWrap;\r\n }\r\n }\r\n\r\n container?.appendChild(pswp.applyFilters('uiElement', element, data));\r\n }\r\n}\r\n\r\nexport default UIElement;\r\n", "/*\r\n Backward and forward arrow buttons\r\n */\r\n\r\n/** @typedef {import('./ui-element.js').UIElementData} UIElementData */\r\n/** @typedef {import('../photoswipe.js').default} PhotoSwipe */\r\n\r\n/**\r\n *\r\n * @param {HTMLElement} element\r\n * @param {PhotoSwipe} pswp\r\n * @param {boolean} [isNextButton]\r\n */\r\nfunction initArrowButton(element, pswp, isNextButton) {\r\n element.classList.add('pswp__button--arrow');\r\n // TODO: this should point to a unique id for this instance\r\n element.setAttribute('aria-controls', 'pswp__items');\r\n pswp.on('change', () => {\r\n if (!pswp.options.loop) {\r\n if (isNextButton) {\r\n /** @type {HTMLButtonElement} */\r\n (element).disabled = !(pswp.currIndex < pswp.getNumItems() - 1);\r\n } else {\r\n /** @type {HTMLButtonElement} */\r\n (element).disabled = !(pswp.currIndex > 0);\r\n }\r\n }\r\n });\r\n}\r\n\r\n/** @type {UIElementData} */\r\nexport const arrowPrev = {\r\n name: 'arrowPrev',\r\n className: 'pswp__button--arrow--prev',\r\n title: 'Previous',\r\n order: 10,\r\n isButton: true,\r\n appendTo: 'wrapper',\r\n html: {\r\n isCustomSVG: true,\r\n size: 60,\r\n inner: '',\r\n outlineID: 'pswp__icn-arrow'\r\n },\r\n onClick: 'prev',\r\n onInit: initArrowButton\r\n};\r\n\r\n/** @type {UIElementData} */\r\nexport const arrowNext = {\r\n name: 'arrowNext',\r\n className: 'pswp__button--arrow--next',\r\n title: 'Next',\r\n order: 11,\r\n isButton: true,\r\n appendTo: 'wrapper',\r\n html: {\r\n isCustomSVG: true,\r\n size: 60,\r\n inner: '',\r\n outlineID: 'pswp__icn-arrow'\r\n },\r\n onClick: 'next',\r\n onInit: (el, pswp) => {\r\n initArrowButton(el, pswp, true);\r\n }\r\n};\r\n", "/** @type {import('./ui-element.js').UIElementData} UIElementData */\r\nconst closeButton = {\r\n name: 'close',\r\n title: 'Close',\r\n order: 20,\r\n isButton: true,\r\n html: {\r\n isCustomSVG: true,\r\n inner: '',\r\n outlineID: 'pswp__icn-close'\r\n },\r\n onClick: 'close'\r\n};\r\n\r\nexport default closeButton;\r\n", "/** @type {import('./ui-element.js').UIElementData} UIElementData */\r\nconst zoomButton = {\r\n name: 'zoom',\r\n title: 'Zoom',\r\n order: 10,\r\n isButton: true,\r\n html: {\r\n isCustomSVG: true,\r\n // eslint-disable-next-line max-len\r\n inner: ''\r\n + ''\r\n + '',\r\n outlineID: 'pswp__icn-zoom'\r\n },\r\n onClick: 'toggleZoom'\r\n};\r\n\r\nexport default zoomButton;\r\n", "/** @type {import('./ui-element.js').UIElementData} UIElementData */\r\nexport const loadingIndicator = {\r\n name: 'preloader',\r\n appendTo: 'bar',\r\n order: 7,\r\n html: {\r\n isCustomSVG: true,\r\n // eslint-disable-next-line max-len\r\n inner: '',\r\n outlineID: 'pswp__icn-loading'\r\n },\r\n onInit: (indicatorElement, pswp) => {\r\n /** @type {boolean | undefined} */\r\n let isVisible;\r\n /** @type {NodeJS.Timeout | null} */\r\n let delayTimeout = null;\r\n\r\n /**\r\n * @param {string} className\r\n * @param {boolean} add\r\n */\r\n const toggleIndicatorClass = (className, add) => {\r\n indicatorElement.classList.toggle('pswp__preloader--' + className, add);\r\n };\r\n\r\n /**\r\n * @param {boolean} visible\r\n */\r\n const setIndicatorVisibility = (visible) => {\r\n if (isVisible !== visible) {\r\n isVisible = visible;\r\n toggleIndicatorClass('active', visible);\r\n }\r\n };\r\n\r\n const updatePreloaderVisibility = () => {\r\n if (!pswp.currSlide?.content.isLoading()) {\r\n setIndicatorVisibility(false);\r\n if (delayTimeout) {\r\n clearTimeout(delayTimeout);\r\n delayTimeout = null;\r\n }\r\n return;\r\n }\r\n\r\n if (!delayTimeout) {\r\n // display loading indicator with delay\r\n delayTimeout = setTimeout(() => {\r\n setIndicatorVisibility(Boolean(pswp.currSlide?.content.isLoading()));\r\n delayTimeout = null;\r\n }, pswp.options.preloaderDelay);\r\n }\r\n };\r\n\r\n pswp.on('change', updatePreloaderVisibility);\r\n\r\n pswp.on('loadComplete', (e) => {\r\n if (pswp.currSlide === e.slide) {\r\n updatePreloaderVisibility();\r\n }\r\n });\r\n\r\n // expose the method\r\n if (pswp.ui) {\r\n pswp.ui.updatePreloaderVisibility = updatePreloaderVisibility;\r\n }\r\n }\r\n};\r\n", "/** @type {import('./ui-element.js').UIElementData} UIElementData */\r\nexport const counterIndicator = {\r\n name: 'counter',\r\n order: 5,\r\n onInit: (counterElement, pswp) => {\r\n pswp.on('change', () => {\r\n counterElement.innerText = (pswp.currIndex + 1)\r\n + pswp.options.indexIndicatorSep\r\n + pswp.getNumItems();\r\n });\r\n }\r\n};\r\n", "import UIElement from './ui-element.js';\r\nimport { arrowPrev, arrowNext } from './button-arrow.js';\r\nimport closeButton from './button-close.js';\r\nimport zoomButton from './button-zoom.js';\r\nimport { loadingIndicator } from './loading-indicator.js';\r\nimport { counterIndicator } from './counter-indicator.js';\r\n\r\n/** @typedef {import('../photoswipe.js').default} PhotoSwipe */\r\n/** @typedef {import('./ui-element.js').UIElementData} UIElementData */\r\n\r\n/**\r\n * Set special class on element when image is zoomed.\r\n *\r\n * By default, it is used to adjust\r\n * zoom icon and zoom cursor via CSS.\r\n *\r\n * @param {HTMLElement} el\r\n * @param {boolean} isZoomedIn\r\n */\r\nfunction setZoomedIn(el, isZoomedIn) {\r\n el.classList.toggle('pswp--zoomed-in', isZoomedIn);\r\n}\r\n\r\nclass UI {\r\n /**\r\n * @param {PhotoSwipe} pswp\r\n */\r\n constructor(pswp) {\r\n this.pswp = pswp;\r\n this.isRegistered = false;\r\n /** @type {UIElementData[]} */\r\n this.uiElementsData = [];\r\n /** @type {(UIElement | UIElementData)[]} */\r\n this.items = [];\r\n /** @type {() => void} */\r\n this.updatePreloaderVisibility = () => {};\r\n\r\n /**\r\n * @private\r\n * @type {number | undefined}\r\n */\r\n this._lastUpdatedZoomLevel = undefined;\r\n }\r\n\r\n init() {\r\n const { pswp } = this;\r\n this.isRegistered = false;\r\n this.uiElementsData = [\r\n closeButton,\r\n arrowPrev,\r\n arrowNext,\r\n zoomButton,\r\n loadingIndicator,\r\n counterIndicator\r\n ];\r\n\r\n pswp.dispatch('uiRegister');\r\n\r\n // sort by order\r\n this.uiElementsData.sort((a, b) => {\r\n // default order is 0\r\n return (a.order || 0) - (b.order || 0);\r\n });\r\n\r\n this.items = [];\r\n\r\n this.isRegistered = true;\r\n this.uiElementsData.forEach((uiElementData) => {\r\n this.registerElement(uiElementData);\r\n });\r\n\r\n pswp.on('change', () => {\r\n pswp.element?.classList.toggle('pswp--one-slide', pswp.getNumItems() === 1);\r\n });\r\n\r\n pswp.on('zoomPanUpdate', () => this._onZoomPanUpdate());\r\n }\r\n\r\n /**\r\n * @param {UIElementData} elementData\r\n */\r\n registerElement(elementData) {\r\n if (this.isRegistered) {\r\n this.items.push(\r\n new UIElement(this.pswp, elementData)\r\n );\r\n } else {\r\n this.uiElementsData.push(elementData);\r\n }\r\n }\r\n\r\n /**\r\n * Fired each time zoom or pan position is changed.\r\n * Update classes that control visibility of zoom button and cursor icon.\r\n *\r\n * @private\r\n */\r\n _onZoomPanUpdate() {\r\n const { template, currSlide, options } = this.pswp;\r\n\r\n if (this.pswp.opener.isClosing || !template || !currSlide) {\r\n return;\r\n }\r\n\r\n let { currZoomLevel } = currSlide;\r\n\r\n // if not open yet - check against initial zoom level\r\n if (!this.pswp.opener.isOpen) {\r\n currZoomLevel = currSlide.zoomLevels.initial;\r\n }\r\n\r\n if (currZoomLevel === this._lastUpdatedZoomLevel) {\r\n return;\r\n }\r\n this._lastUpdatedZoomLevel = currZoomLevel;\r\n\r\n const currZoomLevelDiff = currSlide.zoomLevels.initial - currSlide.zoomLevels.secondary;\r\n\r\n // Initial and secondary zoom levels are almost equal\r\n if (Math.abs(currZoomLevelDiff) < 0.01 || !currSlide.isZoomable()) {\r\n // disable zoom\r\n setZoomedIn(template, false);\r\n template.classList.remove('pswp--zoom-allowed');\r\n return;\r\n }\r\n\r\n template.classList.add('pswp--zoom-allowed');\r\n\r\n const potentialZoomLevel = currZoomLevel === currSlide.zoomLevels.initial\r\n ? currSlide.zoomLevels.secondary : currSlide.zoomLevels.initial;\r\n\r\n setZoomedIn(template, potentialZoomLevel <= currZoomLevel);\r\n\r\n if (options.imageClickAction === 'zoom'\r\n || options.imageClickAction === 'zoom-or-close') {\r\n template.classList.add('pswp--click-to-zoom');\r\n }\r\n }\r\n}\r\n\r\nexport default UI;\r\n", "/** @typedef {import('./slide.js').SlideData} SlideData */\r\n/** @typedef {import('../photoswipe.js').default} PhotoSwipe */\r\n\r\n/** @typedef {{ x: number; y: number; w: number; innerRect?: { w: number; h: number; x: number; y: number } }} Bounds */\r\n\r\n/**\r\n * @param {HTMLElement} el\r\n * @returns Bounds\r\n */\r\nfunction getBoundsByElement(el) {\r\n const thumbAreaRect = el.getBoundingClientRect();\r\n return {\r\n x: thumbAreaRect.left,\r\n y: thumbAreaRect.top,\r\n w: thumbAreaRect.width\r\n };\r\n}\r\n\r\n/**\r\n * @param {HTMLElement} el\r\n * @param {number} imageWidth\r\n * @param {number} imageHeight\r\n * @returns Bounds\r\n */\r\nfunction getCroppedBoundsByElement(el, imageWidth, imageHeight) {\r\n const thumbAreaRect = el.getBoundingClientRect();\r\n\r\n // fill image into the area\r\n // (do they same as object-fit:cover does to retrieve coordinates)\r\n const hRatio = thumbAreaRect.width / imageWidth;\r\n const vRatio = thumbAreaRect.height / imageHeight;\r\n const fillZoomLevel = hRatio > vRatio ? hRatio : vRatio;\r\n\r\n const offsetX = (thumbAreaRect.width - imageWidth * fillZoomLevel) / 2;\r\n const offsetY = (thumbAreaRect.height - imageHeight * fillZoomLevel) / 2;\r\n\r\n /**\r\n * Coordinates of the image,\r\n * as if it was not cropped,\r\n * height is calculated automatically\r\n *\r\n * @type {Bounds}\r\n */\r\n const bounds = {\r\n x: thumbAreaRect.left + offsetX,\r\n y: thumbAreaRect.top + offsetY,\r\n w: imageWidth * fillZoomLevel\r\n };\r\n\r\n // Coordinates of inner crop area\r\n // relative to the image\r\n bounds.innerRect = {\r\n w: thumbAreaRect.width,\r\n h: thumbAreaRect.height,\r\n x: offsetX,\r\n y: offsetY\r\n };\r\n\r\n return bounds;\r\n}\r\n\r\n/**\r\n * Get dimensions of thumbnail image\r\n * (click on which opens photoswipe or closes photoswipe to)\r\n *\r\n * @param {number} index\r\n * @param {SlideData} itemData\r\n * @param {PhotoSwipe} instance PhotoSwipe instance\r\n * @returns {Bounds | undefined}\r\n */\r\nexport function getThumbBounds(index, itemData, instance) {\r\n // legacy event, before filters were introduced\r\n const event = instance.dispatch('thumbBounds', {\r\n index,\r\n itemData,\r\n instance\r\n });\r\n // @ts-expect-error\r\n if (event.thumbBounds) {\r\n // @ts-expect-error\r\n return event.thumbBounds;\r\n }\r\n\r\n const { element } = itemData;\r\n /** @type {Bounds | undefined} */\r\n let thumbBounds;\r\n /** @type {HTMLElement | null | undefined} */\r\n let thumbnail;\r\n\r\n if (element && instance.options.thumbSelector !== false) {\r\n const thumbSelector = instance.options.thumbSelector || 'img';\r\n thumbnail = element.matches(thumbSelector)\r\n ? element : /** @type {HTMLElement | null} */ (element.querySelector(thumbSelector));\r\n }\r\n\r\n thumbnail = instance.applyFilters('thumbEl', thumbnail, itemData, index);\r\n\r\n if (thumbnail) {\r\n if (!itemData.thumbCropped) {\r\n thumbBounds = getBoundsByElement(thumbnail);\r\n } else {\r\n thumbBounds = getCroppedBoundsByElement(\r\n thumbnail,\r\n itemData.width || itemData.w || 0,\r\n itemData.height || itemData.h || 0\r\n );\r\n }\r\n }\r\n\r\n return instance.applyFilters('thumbBounds', thumbBounds, itemData, index);\r\n}\r\n", "/** @typedef {import('../lightbox/lightbox.js').default} PhotoSwipeLightbox */\r\n/** @typedef {import('../photoswipe.js').default} PhotoSwipe */\r\n/** @typedef {import('../photoswipe.js').PhotoSwipeOptions} PhotoSwipeOptions */\r\n/** @typedef {import('../photoswipe.js').DataSource} DataSource */\r\n/** @typedef {import('../ui/ui-element.js').UIElementData} UIElementData */\r\n/** @typedef {import('../slide/content.js').default} ContentDefault */\r\n/** @typedef {import('../slide/slide.js').default} Slide */\r\n/** @typedef {import('../slide/slide.js').SlideData} SlideData */\r\n/** @typedef {import('../slide/zoom-level.js').default} ZoomLevel */\r\n/** @typedef {import('../slide/get-thumb-bounds.js').Bounds} Bounds */\r\n\r\n/**\r\n * Allow adding an arbitrary props to the Content\r\n * https://photoswipe.com/custom-content/#using-webp-image-format\r\n * @typedef {ContentDefault & Record} Content\r\n */\r\n/** @typedef {{ x?: number; y?: number }} Point */\r\n\r\n/**\r\n * @typedef {Object} PhotoSwipeEventsMap https://photoswipe.com/events/\r\n *\r\n *\r\n * https://photoswipe.com/adding-ui-elements/\r\n *\r\n * @prop {undefined} uiRegister\r\n * @prop {{ data: UIElementData }} uiElementCreate\r\n *\r\n *\r\n * https://photoswipe.com/events/#initialization-events\r\n *\r\n * @prop {undefined} beforeOpen\r\n * @prop {undefined} firstUpdate\r\n * @prop {undefined} initialLayout\r\n * @prop {undefined} change\r\n * @prop {undefined} afterInit\r\n * @prop {undefined} bindEvents\r\n *\r\n *\r\n * https://photoswipe.com/events/#opening-or-closing-transition-events\r\n *\r\n * @prop {undefined} openingAnimationStart\r\n * @prop {undefined} openingAnimationEnd\r\n * @prop {undefined} closingAnimationStart\r\n * @prop {undefined} closingAnimationEnd\r\n *\r\n *\r\n * https://photoswipe.com/events/#closing-events\r\n *\r\n * @prop {undefined} close\r\n * @prop {undefined} destroy\r\n *\r\n *\r\n * https://photoswipe.com/events/#pointer-and-gesture-events\r\n *\r\n * @prop {{ originalEvent: PointerEvent }} pointerDown\r\n * @prop {{ originalEvent: PointerEvent }} pointerMove\r\n * @prop {{ originalEvent: PointerEvent }} pointerUp\r\n * @prop {{ bgOpacity: number }} pinchClose can be default prevented\r\n * @prop {{ panY: number }} verticalDrag can be default prevented\r\n *\r\n *\r\n * https://photoswipe.com/events/#slide-content-events\r\n *\r\n * @prop {{ content: Content }} contentInit\r\n * @prop {{ content: Content; isLazy: boolean }} contentLoad can be default prevented\r\n * @prop {{ content: Content; isLazy: boolean }} contentLoadImage can be default prevented\r\n * @prop {{ content: Content; slide: Slide; isError?: boolean }} loadComplete\r\n * @prop {{ content: Content; slide: Slide }} loadError\r\n * @prop {{ content: Content; width: number; height: number }} contentResize can be default prevented\r\n * @prop {{ content: Content; width: number; height: number; slide: Slide }} imageSizeChange\r\n * @prop {{ content: Content }} contentLazyLoad can be default prevented\r\n * @prop {{ content: Content }} contentAppend can be default prevented\r\n * @prop {{ content: Content }} contentActivate can be default prevented\r\n * @prop {{ content: Content }} contentDeactivate can be default prevented\r\n * @prop {{ content: Content }} contentRemove can be default prevented\r\n * @prop {{ content: Content }} contentDestroy can be default prevented\r\n *\r\n *\r\n * undocumented\r\n *\r\n * @prop {{ point: Point; originalEvent: PointerEvent }} imageClickAction can be default prevented\r\n * @prop {{ point: Point; originalEvent: PointerEvent }} bgClickAction can be default prevented\r\n * @prop {{ point: Point; originalEvent: PointerEvent }} tapAction can be default prevented\r\n * @prop {{ point: Point; originalEvent: PointerEvent }} doubleTapAction can be default prevented\r\n *\r\n * @prop {{ originalEvent: KeyboardEvent }} keydown can be default prevented\r\n * @prop {{ x: number; dragging: boolean }} moveMainScroll\r\n * @prop {{ slide: Slide }} firstZoomPan\r\n * @prop {{ slide: Slide | undefined, data: SlideData, index: number }} gettingData\r\n * @prop {undefined} beforeResize\r\n * @prop {undefined} resize\r\n * @prop {undefined} viewportSize\r\n * @prop {undefined} updateScrollOffset\r\n * @prop {{ slide: Slide }} slideInit\r\n * @prop {{ slide: Slide }} afterSetContent\r\n * @prop {{ slide: Slide }} slideLoad\r\n * @prop {{ slide: Slide }} appendHeavy can be default prevented\r\n * @prop {{ slide: Slide }} appendHeavyContent\r\n * @prop {{ slide: Slide }} slideActivate\r\n * @prop {{ slide: Slide }} slideDeactivate\r\n * @prop {{ slide: Slide }} slideDestroy\r\n * @prop {{ destZoomLevel: number, centerPoint: Point | undefined, transitionDuration: number | false | undefined }} beforeZoomTo\r\n * @prop {{ slide: Slide }} zoomPanUpdate\r\n * @prop {{ slide: Slide }} initialZoomPan\r\n * @prop {{ slide: Slide }} calcSlideSize\r\n * @prop {undefined} resolutionChanged\r\n * @prop {{ originalEvent: WheelEvent }} wheel can be default prevented\r\n * @prop {{ content: Content }} contentAppendImage can be default prevented\r\n * @prop {{ index: number; itemData: SlideData }} lazyLoadSlide can be default prevented\r\n * @prop {undefined} lazyLoad\r\n * @prop {{ slide: Slide }} calcBounds\r\n * @prop {{ zoomLevels: ZoomLevel, slideData: SlideData }} zoomLevelsUpdate\r\n *\r\n *\r\n * legacy\r\n *\r\n * @prop {undefined} init\r\n * @prop {undefined} initialZoomIn\r\n * @prop {undefined} initialZoomOut\r\n * @prop {undefined} initialZoomInEnd\r\n * @prop {undefined} initialZoomOutEnd\r\n * @prop {{ dataSource: DataSource | undefined, numItems: number }} numItems\r\n * @prop {{ itemData: SlideData; index: number }} itemData\r\n * @prop {{ index: number, itemData: SlideData, instance: PhotoSwipe }} thumbBounds\r\n */\r\n\r\n/**\r\n * @typedef {Object} PhotoSwipeFiltersMap https://photoswipe.com/filters/\r\n *\r\n * @prop {(numItems: number, dataSource: DataSource | undefined) => number} numItems\r\n * Modify the total amount of slides. Example on Data sources page.\r\n * https://photoswipe.com/filters/#numitems\r\n *\r\n * @prop {(itemData: SlideData, index: number) => SlideData} itemData\r\n * Modify slide item data. Example on Data sources page.\r\n * https://photoswipe.com/filters/#itemdata\r\n *\r\n * @prop {(itemData: SlideData, element: HTMLElement, linkEl: HTMLAnchorElement) => SlideData} domItemData\r\n * Modify item data when it's parsed from DOM element. Example on Data sources page.\r\n * https://photoswipe.com/filters/#domitemdata\r\n *\r\n * @prop {(clickedIndex: number, e: MouseEvent, instance: PhotoSwipeLightbox) => number} clickedIndex\r\n * Modify clicked gallery item index.\r\n * https://photoswipe.com/filters/#clickedindex\r\n *\r\n * @prop {(placeholderSrc: string | false, content: Content) => string | false} placeholderSrc\r\n * Modify placeholder image source.\r\n * https://photoswipe.com/filters/#placeholdersrc\r\n *\r\n * @prop {(isContentLoading: boolean, content: Content) => boolean} isContentLoading\r\n * Modify if the content is currently loading.\r\n * https://photoswipe.com/filters/#iscontentloading\r\n *\r\n * @prop {(isContentZoomable: boolean, content: Content) => boolean} isContentZoomable\r\n * Modify if the content can be zoomed.\r\n * https://photoswipe.com/filters/#iscontentzoomable\r\n *\r\n * @prop {(useContentPlaceholder: boolean, content: Content) => boolean} useContentPlaceholder\r\n * Modify if the placeholder should be used for the content.\r\n * https://photoswipe.com/filters/#usecontentplaceholder\r\n *\r\n * @prop {(isKeepingPlaceholder: boolean, content: Content) => boolean} isKeepingPlaceholder\r\n * Modify if the placeholder should be kept after the content is loaded.\r\n * https://photoswipe.com/filters/#iskeepingplaceholder\r\n *\r\n *\r\n * @prop {(contentErrorElement: HTMLElement, content: Content) => HTMLElement} contentErrorElement\r\n * Modify an element when the content has error state (for example, if image cannot be loaded).\r\n * https://photoswipe.com/filters/#contenterrorelement\r\n *\r\n * @prop {(element: HTMLElement, data: UIElementData) => HTMLElement} uiElement\r\n * Modify a UI element that's being created.\r\n * https://photoswipe.com/filters/#uielement\r\n *\r\n * @prop {(thumbnail: HTMLElement | null | undefined, itemData: SlideData, index: number) => HTMLElement} thumbEl\r\n * Modify the thumbnail element from which opening zoom animation starts or ends.\r\n * https://photoswipe.com/filters/#thumbel\r\n *\r\n * @prop {(thumbBounds: Bounds | undefined, itemData: SlideData, index: number) => Bounds} thumbBounds\r\n * Modify the thumbnail bounds from which opening zoom animation starts or ends.\r\n * https://photoswipe.com/filters/#thumbbounds\r\n *\r\n * @prop {(srcsetSizesWidth: number, content: Content) => number} srcsetSizesWidth\r\n *\r\n * @prop {(preventPointerEvent: boolean, event: PointerEvent, pointerType: string) => boolean} preventPointerEvent\r\n *\r\n */\r\n\r\n/**\r\n * @template {keyof PhotoSwipeFiltersMap} T\r\n * @typedef {{ fn: PhotoSwipeFiltersMap[T], priority: number }} Filter\r\n */\r\n\r\n/**\r\n * @template {keyof PhotoSwipeEventsMap} T\r\n * @typedef {PhotoSwipeEventsMap[T] extends undefined ? PhotoSwipeEvent : PhotoSwipeEvent & PhotoSwipeEventsMap[T]} AugmentedEvent\r\n */\r\n\r\n/**\r\n * @template {keyof PhotoSwipeEventsMap} T\r\n * @typedef {(event: AugmentedEvent) => void} EventCallback\r\n */\r\n\r\n/**\r\n * Base PhotoSwipe event object\r\n *\r\n * @template {keyof PhotoSwipeEventsMap} T\r\n */\r\nclass PhotoSwipeEvent {\r\n /**\r\n * @param {T} type\r\n * @param {PhotoSwipeEventsMap[T]} [details]\r\n */\r\n constructor(type, details) {\r\n this.type = type;\r\n this.defaultPrevented = false;\r\n if (details) {\r\n Object.assign(this, details);\r\n }\r\n }\r\n\r\n preventDefault() {\r\n this.defaultPrevented = true;\r\n }\r\n}\r\n\r\n/**\r\n * PhotoSwipe base class that can listen and dispatch for events.\r\n * Shared by PhotoSwipe Core and PhotoSwipe Lightbox, extended by base.js\r\n */\r\nclass Eventable {\r\n constructor() {\r\n /**\r\n * @type {{ [T in keyof PhotoSwipeEventsMap]?: ((event: AugmentedEvent) => void)[] }}\r\n */\r\n this._listeners = {};\r\n\r\n /**\r\n * @type {{ [T in keyof PhotoSwipeFiltersMap]?: Filter[] }}\r\n */\r\n this._filters = {};\r\n\r\n /** @type {PhotoSwipe | undefined} */\r\n this.pswp = undefined;\r\n\r\n /** @type {PhotoSwipeOptions | undefined} */\r\n this.options = undefined;\r\n }\r\n\r\n /**\r\n * @template {keyof PhotoSwipeFiltersMap} T\r\n * @param {T} name\r\n * @param {PhotoSwipeFiltersMap[T]} fn\r\n * @param {number} priority\r\n */\r\n addFilter(name, fn, priority = 100) {\r\n if (!this._filters[name]) {\r\n this._filters[name] = [];\r\n }\r\n\r\n this._filters[name]?.push({ fn, priority });\r\n this._filters[name]?.sort((f1, f2) => f1.priority - f2.priority);\r\n\r\n this.pswp?.addFilter(name, fn, priority);\r\n }\r\n\r\n /**\r\n * @template {keyof PhotoSwipeFiltersMap} T\r\n * @param {T} name\r\n * @param {PhotoSwipeFiltersMap[T]} fn\r\n */\r\n removeFilter(name, fn) {\r\n if (this._filters[name]) {\r\n // @ts-expect-error\r\n this._filters[name] = this._filters[name].filter(filter => (filter.fn !== fn));\r\n }\r\n\r\n if (this.pswp) {\r\n this.pswp.removeFilter(name, fn);\r\n }\r\n }\r\n\r\n /**\r\n * @template {keyof PhotoSwipeFiltersMap} T\r\n * @param {T} name\r\n * @param {Parameters} args\r\n * @returns {Parameters[0]}\r\n */\r\n applyFilters(name, ...args) {\r\n this._filters[name]?.forEach((filter) => {\r\n // @ts-expect-error\r\n args[0] = filter.fn.apply(this, args);\r\n });\r\n return args[0];\r\n }\r\n\r\n /**\r\n * @template {keyof PhotoSwipeEventsMap} T\r\n * @param {T} name\r\n * @param {EventCallback} fn\r\n */\r\n on(name, fn) {\r\n if (!this._listeners[name]) {\r\n this._listeners[name] = [];\r\n }\r\n this._listeners[name]?.push(fn);\r\n\r\n // When binding events to lightbox,\r\n // also bind events to PhotoSwipe Core,\r\n // if it's open.\r\n this.pswp?.on(name, fn);\r\n }\r\n\r\n /**\r\n * @template {keyof PhotoSwipeEventsMap} T\r\n * @param {T} name\r\n * @param {EventCallback} fn\r\n */\r\n off(name, fn) {\r\n if (this._listeners[name]) {\r\n // @ts-expect-error\r\n this._listeners[name] = this._listeners[name].filter(listener => (fn !== listener));\r\n }\r\n\r\n this.pswp?.off(name, fn);\r\n }\r\n\r\n /**\r\n * @template {keyof PhotoSwipeEventsMap} T\r\n * @param {T} name\r\n * @param {PhotoSwipeEventsMap[T]} [details]\r\n * @returns {AugmentedEvent}\r\n */\r\n dispatch(name, details) {\r\n if (this.pswp) {\r\n return this.pswp.dispatch(name, details);\r\n }\r\n\r\n const event = /** @type {AugmentedEvent} */ (new PhotoSwipeEvent(name, details));\r\n\r\n this._listeners[name]?.forEach((listener) => {\r\n listener.call(this, event);\r\n });\r\n\r\n return event;\r\n }\r\n}\r\n\r\nexport default Eventable;\r\n", "import { createElement, setWidthHeight, toTransformString } from '../util/util.js';\r\n\r\nclass Placeholder {\r\n /**\r\n * @param {string | false} imageSrc\r\n * @param {HTMLElement} container\r\n */\r\n constructor(imageSrc, container) {\r\n // Create placeholder\r\n // (stretched thumbnail or simple div behind the main image)\r\n /** @type {HTMLImageElement | HTMLDivElement | null} */\r\n this.element = createElement(\r\n 'pswp__img pswp__img--placeholder',\r\n imageSrc ? 'img' : 'div',\r\n container\r\n );\r\n\r\n if (imageSrc) {\r\n const imgEl = /** @type {HTMLImageElement} */ (this.element);\r\n imgEl.decoding = 'async';\r\n imgEl.alt = '';\r\n imgEl.src = imageSrc;\r\n imgEl.setAttribute('role', 'presentation');\r\n }\r\n\r\n this.element.setAttribute('aria-hidden', 'true');\r\n }\r\n\r\n /**\r\n * @param {number} width\r\n * @param {number} height\r\n */\r\n setDisplayedSize(width, height) {\r\n if (!this.element) {\r\n return;\r\n }\r\n\r\n if (this.element.tagName === 'IMG') {\r\n // Use transform scale() to modify img placeholder size\r\n // (instead of changing width/height directly).\r\n // This helps with performance, specifically in iOS15 Safari.\r\n setWidthHeight(this.element, 250, 'auto');\r\n this.element.style.transformOrigin = '0 0';\r\n this.element.style.transform = toTransformString(0, 0, width / 250);\r\n } else {\r\n setWidthHeight(this.element, width, height);\r\n }\r\n }\r\n\r\n destroy() {\r\n if (this.element?.parentNode) {\r\n this.element.remove();\r\n }\r\n this.element = null;\r\n }\r\n}\r\n\r\nexport default Placeholder;\r\n", "import { createElement, isSafari, LOAD_STATE, setWidthHeight } from '../util/util.js';\r\nimport Placeholder from './placeholder.js';\r\n\r\n/** @typedef {import('./slide.js').default} Slide */\r\n/** @typedef {import('./slide.js').SlideData} SlideData */\r\n/** @typedef {import('../core/base.js').default} PhotoSwipeBase */\r\n/** @typedef {import('../util/util.js').LoadState} LoadState */\r\n\r\nclass Content {\r\n /**\r\n * @param {SlideData} itemData Slide data\r\n * @param {PhotoSwipeBase} instance PhotoSwipe or PhotoSwipeLightbox instance\r\n * @param {number} index\r\n */\r\n constructor(itemData, instance, index) {\r\n this.instance = instance;\r\n this.data = itemData;\r\n this.index = index;\r\n\r\n /** @type {HTMLImageElement | HTMLDivElement | undefined} */\r\n this.element = undefined;\r\n /** @type {Placeholder | undefined} */\r\n this.placeholder = undefined;\r\n /** @type {Slide | undefined} */\r\n this.slide = undefined;\r\n\r\n this.displayedImageWidth = 0;\r\n this.displayedImageHeight = 0;\r\n\r\n this.width = Number(this.data.w) || Number(this.data.width) || 0;\r\n this.height = Number(this.data.h) || Number(this.data.height) || 0;\r\n\r\n this.isAttached = false;\r\n this.hasSlide = false;\r\n this.isDecoding = false;\r\n /** @type {LoadState} */\r\n this.state = LOAD_STATE.IDLE;\r\n\r\n if (this.data.type) {\r\n this.type = this.data.type;\r\n } else if (this.data.src) {\r\n this.type = 'image';\r\n } else {\r\n this.type = 'html';\r\n }\r\n\r\n this.instance.dispatch('contentInit', { content: this });\r\n }\r\n\r\n removePlaceholder() {\r\n if (this.placeholder && !this.keepPlaceholder()) {\r\n // With delay, as image might be loaded, but not rendered\r\n setTimeout(() => {\r\n if (this.placeholder) {\r\n this.placeholder.destroy();\r\n this.placeholder = undefined;\r\n }\r\n }, 1000);\r\n }\r\n }\r\n\r\n /**\r\n * Preload content\r\n *\r\n * @param {boolean} isLazy\r\n * @param {boolean} [reload]\r\n */\r\n load(isLazy, reload) {\r\n if (this.slide && this.usePlaceholder()) {\r\n if (!this.placeholder) {\r\n const placeholderSrc = this.instance.applyFilters(\r\n 'placeholderSrc',\r\n // use image-based placeholder only for the first slide,\r\n // as rendering (even small stretched thumbnail) is an expensive operation\r\n (this.data.msrc && this.slide.isFirstSlide) ? this.data.msrc : false,\r\n this\r\n );\r\n this.placeholder = new Placeholder(\r\n placeholderSrc,\r\n this.slide.container\r\n );\r\n } else {\r\n const placeholderEl = this.placeholder.element;\r\n // Add placeholder to DOM if it was already created\r\n if (placeholderEl && !placeholderEl.parentElement) {\r\n this.slide.container.prepend(placeholderEl);\r\n }\r\n }\r\n }\r\n\r\n if (this.element && !reload) {\r\n return;\r\n }\r\n\r\n if (this.instance.dispatch('contentLoad', { content: this, isLazy }).defaultPrevented) {\r\n return;\r\n }\r\n\r\n if (this.isImageContent()) {\r\n this.element = createElement('pswp__img', 'img');\r\n // Start loading only after width is defined, as sizes might depend on it.\r\n // Due to Safari feature, we must define sizes before srcset.\r\n if (this.displayedImageWidth) {\r\n this.loadImage(isLazy);\r\n }\r\n } else {\r\n this.element = createElement('pswp__content', 'div');\r\n this.element.innerHTML = this.data.html || '';\r\n }\r\n\r\n if (reload && this.slide) {\r\n this.slide.updateContentSize(true);\r\n }\r\n }\r\n\r\n /**\r\n * Preload image\r\n *\r\n * @param {boolean} isLazy\r\n */\r\n loadImage(isLazy) {\r\n if (!this.isImageContent()\r\n || !this.element\r\n || this.instance.dispatch('contentLoadImage', { content: this, isLazy }).defaultPrevented) {\r\n return;\r\n }\r\n\r\n const imageElement = /** @type HTMLImageElement */ (this.element);\r\n\r\n this.updateSrcsetSizes();\r\n\r\n if (this.data.srcset) {\r\n imageElement.srcset = this.data.srcset;\r\n }\r\n\r\n imageElement.src = this.data.src ?? '';\r\n imageElement.alt = this.data.alt ?? '';\r\n\r\n this.state = LOAD_STATE.LOADING;\r\n\r\n if (imageElement.complete) {\r\n this.onLoaded();\r\n } else {\r\n imageElement.onload = () => {\r\n this.onLoaded();\r\n };\r\n\r\n imageElement.onerror = () => {\r\n this.onError();\r\n };\r\n }\r\n }\r\n\r\n /**\r\n * Assign slide to content\r\n *\r\n * @param {Slide} slide\r\n */\r\n setSlide(slide) {\r\n this.slide = slide;\r\n this.hasSlide = true;\r\n this.instance = slide.pswp;\r\n\r\n // todo: do we need to unset slide?\r\n }\r\n\r\n /**\r\n * Content load success handler\r\n */\r\n onLoaded() {\r\n this.state = LOAD_STATE.LOADED;\r\n\r\n if (this.slide && this.element) {\r\n this.instance.dispatch('loadComplete', { slide: this.slide, content: this });\r\n\r\n // if content is reloaded\r\n if (this.slide.isActive\r\n && this.slide.heavyAppended\r\n && !this.element.parentNode) {\r\n this.append();\r\n this.slide.updateContentSize(true);\r\n }\r\n\r\n if (this.state === LOAD_STATE.LOADED || this.state === LOAD_STATE.ERROR) {\r\n this.removePlaceholder();\r\n }\r\n }\r\n }\r\n\r\n /**\r\n * Content load error handler\r\n */\r\n onError() {\r\n this.state = LOAD_STATE.ERROR;\r\n\r\n if (this.slide) {\r\n this.displayError();\r\n this.instance.dispatch('loadComplete', { slide: this.slide, isError: true, content: this });\r\n this.instance.dispatch('loadError', { slide: this.slide, content: this });\r\n }\r\n }\r\n\r\n /**\r\n * @returns {Boolean} If the content is currently loading\r\n */\r\n isLoading() {\r\n return this.instance.applyFilters(\r\n 'isContentLoading',\r\n this.state === LOAD_STATE.LOADING,\r\n this\r\n );\r\n }\r\n\r\n /**\r\n * @returns {Boolean} If the content is in error state\r\n */\r\n isError() {\r\n return this.state === LOAD_STATE.ERROR;\r\n }\r\n\r\n /**\r\n * @returns {boolean} If the content is image\r\n */\r\n isImageContent() {\r\n return this.type === 'image';\r\n }\r\n\r\n /**\r\n * Update content size\r\n *\r\n * @param {Number} width\r\n * @param {Number} height\r\n */\r\n setDisplayedSize(width, height) {\r\n if (!this.element) {\r\n return;\r\n }\r\n\r\n if (this.placeholder) {\r\n this.placeholder.setDisplayedSize(width, height);\r\n }\r\n\r\n if (this.instance.dispatch(\r\n 'contentResize',\r\n { content: this, width, height }).defaultPrevented\r\n ) {\r\n return;\r\n }\r\n\r\n setWidthHeight(this.element, width, height);\r\n\r\n if (this.isImageContent() && !this.isError()) {\r\n const isInitialSizeUpdate = (!this.displayedImageWidth && width);\r\n\r\n this.displayedImageWidth = width;\r\n this.displayedImageHeight = height;\r\n\r\n if (isInitialSizeUpdate) {\r\n this.loadImage(false);\r\n } else {\r\n this.updateSrcsetSizes();\r\n }\r\n\r\n if (this.slide) {\r\n this.instance.dispatch(\r\n 'imageSizeChange',\r\n { slide: this.slide, width, height, content: this }\r\n );\r\n }\r\n }\r\n }\r\n\r\n /**\r\n * @returns {boolean} If the content can be zoomed\r\n */\r\n isZoomable() {\r\n return this.instance.applyFilters(\r\n 'isContentZoomable',\r\n this.isImageContent() && (this.state !== LOAD_STATE.ERROR),\r\n this\r\n );\r\n }\r\n\r\n /**\r\n * Update image srcset sizes attribute based on width and height\r\n */\r\n updateSrcsetSizes() {\r\n // Handle srcset sizes attribute.\r\n //\r\n // Never lower quality, if it was increased previously.\r\n // Chrome does this automatically, Firefox and Safari do not,\r\n // so we store largest used size in dataset.\r\n if (!this.isImageContent() || !this.element || !this.data.srcset) {\r\n return;\r\n }\r\n\r\n const image = /** @type HTMLImageElement */ (this.element);\r\n const sizesWidth = this.instance.applyFilters(\r\n 'srcsetSizesWidth',\r\n this.displayedImageWidth,\r\n this\r\n );\r\n\r\n if (\r\n !image.dataset.largestUsedSize\r\n || sizesWidth > parseInt(image.dataset.largestUsedSize, 10)\r\n ) {\r\n image.sizes = sizesWidth + 'px';\r\n image.dataset.largestUsedSize = String(sizesWidth);\r\n }\r\n }\r\n\r\n /**\r\n * @returns {boolean} If content should use a placeholder (from msrc by default)\r\n */\r\n usePlaceholder() {\r\n return this.instance.applyFilters(\r\n 'useContentPlaceholder',\r\n this.isImageContent(),\r\n this\r\n );\r\n }\r\n\r\n /**\r\n * Preload content with lazy-loading param\r\n */\r\n lazyLoad() {\r\n if (this.instance.dispatch('contentLazyLoad', { content: this }).defaultPrevented) {\r\n return;\r\n }\r\n\r\n this.load(true);\r\n }\r\n\r\n /**\r\n * @returns {boolean} If placeholder should be kept after content is loaded\r\n */\r\n keepPlaceholder() {\r\n return this.instance.applyFilters(\r\n 'isKeepingPlaceholder',\r\n this.isLoading(),\r\n this\r\n );\r\n }\r\n\r\n /**\r\n * Destroy the content\r\n */\r\n destroy() {\r\n this.hasSlide = false;\r\n this.slide = undefined;\r\n\r\n if (this.instance.dispatch('contentDestroy', { content: this }).defaultPrevented) {\r\n return;\r\n }\r\n\r\n this.remove();\r\n\r\n if (this.placeholder) {\r\n this.placeholder.destroy();\r\n this.placeholder = undefined;\r\n }\r\n\r\n if (this.isImageContent() && this.element) {\r\n this.element.onload = null;\r\n this.element.onerror = null;\r\n this.element = undefined;\r\n }\r\n }\r\n\r\n /**\r\n * Display error message\r\n */\r\n displayError() {\r\n if (this.slide) {\r\n let errorMsgEl = createElement('pswp__error-msg', 'div');\r\n errorMsgEl.innerText = this.instance.options?.errorMsg ?? '';\r\n errorMsgEl = /** @type {HTMLDivElement} */ (this.instance.applyFilters(\r\n 'contentErrorElement',\r\n errorMsgEl,\r\n this\r\n ));\r\n this.element = createElement('pswp__content pswp__error-msg-container', 'div');\r\n this.element.appendChild(errorMsgEl);\r\n this.slide.container.innerText = '';\r\n this.slide.container.appendChild(this.element);\r\n this.slide.updateContentSize(true);\r\n this.removePlaceholder();\r\n }\r\n }\r\n\r\n /**\r\n * Append the content\r\n */\r\n append() {\r\n if (this.isAttached || !this.element) {\r\n return;\r\n }\r\n\r\n this.isAttached = true;\r\n\r\n if (this.state === LOAD_STATE.ERROR) {\r\n this.displayError();\r\n return;\r\n }\r\n\r\n if (this.instance.dispatch('contentAppend', { content: this }).defaultPrevented) {\r\n return;\r\n }\r\n\r\n const supportsDecode = ('decode' in this.element);\r\n\r\n if (this.isImageContent()) {\r\n // Use decode() on nearby slides\r\n //\r\n // Nearby slide images are in DOM and not hidden via display:none.\r\n // However, they are placed offscreen (to the left and right side).\r\n //\r\n // Some browsers do not composite the image until it's actually visible,\r\n // using decode() helps.\r\n //\r\n // You might ask \"why dont you just decode() and then append all images\",\r\n // that's because I want to show image before it's fully loaded,\r\n // as browser can render parts of image while it is loading.\r\n // We do not do this in Safari due to partial loading bug.\r\n if (supportsDecode && this.slide && (!this.slide.isActive || isSafari())) {\r\n this.isDecoding = true;\r\n // purposefully using finally instead of then,\r\n // as if srcset sizes changes dynamically - it may cause decode error\r\n /** @type {HTMLImageElement} */\r\n (this.element).decode().catch(() => {}).finally(() => {\r\n this.isDecoding = false;\r\n this.appendImage();\r\n });\r\n } else {\r\n this.appendImage();\r\n }\r\n } else if (this.slide && !this.element.parentNode) {\r\n this.slide.container.appendChild(this.element);\r\n }\r\n }\r\n\r\n /**\r\n * Activate the slide,\r\n * active slide is generally the current one,\r\n * meaning the user can see it.\r\n */\r\n activate() {\r\n if (this.instance.dispatch('contentActivate', { content: this }).defaultPrevented\r\n || !this.slide) {\r\n return;\r\n }\r\n\r\n if (this.isImageContent() && this.isDecoding && !isSafari()) {\r\n // add image to slide when it becomes active,\r\n // even if it's not finished decoding\r\n this.appendImage();\r\n } else if (this.isError()) {\r\n this.load(false, true); // try to reload\r\n }\r\n\r\n if (this.slide.holderElement) {\r\n this.slide.holderElement.setAttribute('aria-hidden', 'false');\r\n }\r\n }\r\n\r\n /**\r\n * Deactivate the content\r\n */\r\n deactivate() {\r\n this.instance.dispatch('contentDeactivate', { content: this });\r\n if (this.slide && this.slide.holderElement) {\r\n this.slide.holderElement.setAttribute('aria-hidden', 'true');\r\n }\r\n }\r\n\r\n\r\n /**\r\n * Remove the content from DOM\r\n */\r\n remove() {\r\n this.isAttached = false;\r\n\r\n if (this.instance.dispatch('contentRemove', { content: this }).defaultPrevented) {\r\n return;\r\n }\r\n\r\n if (this.element && this.element.parentNode) {\r\n this.element.remove();\r\n }\r\n\r\n if (this.placeholder && this.placeholder.element) {\r\n this.placeholder.element.remove();\r\n }\r\n }\r\n\r\n /**\r\n * Append the image content to slide container\r\n */\r\n appendImage() {\r\n if (!this.isAttached) {\r\n return;\r\n }\r\n\r\n if (this.instance.dispatch('contentAppendImage', { content: this }).defaultPrevented) {\r\n return;\r\n }\r\n\r\n // ensure that element exists and is not already appended\r\n if (this.slide && this.element && !this.element.parentNode) {\r\n this.slide.container.appendChild(this.element);\r\n }\r\n\r\n if (this.state === LOAD_STATE.LOADED || this.state === LOAD_STATE.ERROR) {\r\n this.removePlaceholder();\r\n }\r\n }\r\n}\r\n\r\nexport default Content;\r\n", "import { getViewportSize, getPanAreaSize } from '../util/viewport-size.js';\r\nimport ZoomLevel from './zoom-level.js';\r\n\r\n/** @typedef {import('./content.js').default} Content */\r\n/** @typedef {import('./slide.js').default} Slide */\r\n/** @typedef {import('./slide.js').SlideData} SlideData */\r\n/** @typedef {import('../core/base.js').default} PhotoSwipeBase */\r\n/** @typedef {import('../photoswipe.js').default} PhotoSwipe */\r\n\r\nconst MIN_SLIDES_TO_CACHE = 5;\r\n\r\n/**\r\n * Lazy-load an image\r\n * This function is used both by Lightbox and PhotoSwipe core,\r\n * thus it can be called before dialog is opened.\r\n *\r\n * @param {SlideData} itemData Data about the slide\r\n * @param {PhotoSwipeBase} instance PhotoSwipe or PhotoSwipeLightbox instance\r\n * @param {number} index\r\n * @returns {Content} Image that is being decoded or false.\r\n */\r\nexport function lazyLoadData(itemData, instance, index) {\r\n const content = instance.createContentFromData(itemData, index);\r\n /** @type {ZoomLevel | undefined} */\r\n let zoomLevel;\r\n\r\n const { options } = instance;\r\n\r\n // We need to know dimensions of the image to preload it,\r\n // as it might use srcset, and we need to define sizes\r\n if (options) {\r\n zoomLevel = new ZoomLevel(options, itemData, -1);\r\n\r\n let viewportSize;\r\n if (instance.pswp) {\r\n viewportSize = instance.pswp.viewportSize;\r\n } else {\r\n viewportSize = getViewportSize(options, instance);\r\n }\r\n\r\n const panAreaSize = getPanAreaSize(options, viewportSize, itemData, index);\r\n zoomLevel.update(content.width, content.height, panAreaSize);\r\n }\r\n\r\n content.lazyLoad();\r\n\r\n if (zoomLevel) {\r\n content.setDisplayedSize(\r\n Math.ceil(content.width * zoomLevel.initial),\r\n Math.ceil(content.height * zoomLevel.initial)\r\n );\r\n }\r\n\r\n return content;\r\n}\r\n\r\n\r\n/**\r\n * Lazy-loads specific slide.\r\n * This function is used both by Lightbox and PhotoSwipe core,\r\n * thus it can be called before dialog is opened.\r\n *\r\n * By default, it loads image based on viewport size and initial zoom level.\r\n *\r\n * @param {number} index Slide index\r\n * @param {PhotoSwipeBase} instance PhotoSwipe or PhotoSwipeLightbox eventable instance\r\n * @returns {Content | undefined}\r\n */\r\nexport function lazyLoadSlide(index, instance) {\r\n const itemData = instance.getItemData(index);\r\n\r\n if (instance.dispatch('lazyLoadSlide', { index, itemData }).defaultPrevented) {\r\n return;\r\n }\r\n\r\n return lazyLoadData(itemData, instance, index);\r\n}\r\n\r\nclass ContentLoader {\r\n /**\r\n * @param {PhotoSwipe} pswp\r\n */\r\n constructor(pswp) {\r\n this.pswp = pswp;\r\n // Total amount of cached images\r\n this.limit = Math.max(\r\n pswp.options.preload[0] + pswp.options.preload[1] + 1,\r\n MIN_SLIDES_TO_CACHE\r\n );\r\n /** @type {Content[]} */\r\n this._cachedItems = [];\r\n }\r\n\r\n /**\r\n * Lazy load nearby slides based on `preload` option.\r\n *\r\n * @param {number} [diff] Difference between slide indexes that was changed recently, or 0.\r\n */\r\n updateLazy(diff) {\r\n const { pswp } = this;\r\n\r\n if (pswp.dispatch('lazyLoad').defaultPrevented) {\r\n return;\r\n }\r\n\r\n const { preload } = pswp.options;\r\n const isForward = diff === undefined ? true : (diff >= 0);\r\n let i;\r\n\r\n // preload[1] - num items to preload in forward direction\r\n for (i = 0; i <= preload[1]; i++) {\r\n this.loadSlideByIndex(pswp.currIndex + (isForward ? i : (-i)));\r\n }\r\n\r\n // preload[0] - num items to preload in backward direction\r\n for (i = 1; i <= preload[0]; i++) {\r\n this.loadSlideByIndex(pswp.currIndex + (isForward ? (-i) : i));\r\n }\r\n }\r\n\r\n /**\r\n * @param {number} initialIndex\r\n */\r\n loadSlideByIndex(initialIndex) {\r\n const index = this.pswp.getLoopedIndex(initialIndex);\r\n // try to get cached content\r\n let content = this.getContentByIndex(index);\r\n if (!content) {\r\n // no cached content, so try to load from scratch:\r\n content = lazyLoadSlide(index, this.pswp);\r\n // if content can be loaded, add it to cache:\r\n if (content) {\r\n this.addToCache(content);\r\n }\r\n }\r\n }\r\n\r\n /**\r\n * @param {Slide} slide\r\n * @returns {Content}\r\n */\r\n getContentBySlide(slide) {\r\n let content = this.getContentByIndex(slide.index);\r\n if (!content) {\r\n // create content if not found in cache\r\n content = this.pswp.createContentFromData(slide.data, slide.index);\r\n this.addToCache(content);\r\n }\r\n\r\n // assign slide to content\r\n content.setSlide(slide);\r\n\r\n return content;\r\n }\r\n\r\n /**\r\n * @param {Content} content\r\n */\r\n addToCache(content) {\r\n // move to the end of array\r\n this.removeByIndex(content.index);\r\n this._cachedItems.push(content);\r\n\r\n if (this._cachedItems.length > this.limit) {\r\n // Destroy the first content that's not attached\r\n const indexToRemove = this._cachedItems.findIndex((item) => {\r\n return !item.isAttached && !item.hasSlide;\r\n });\r\n if (indexToRemove !== -1) {\r\n const removedItem = this._cachedItems.splice(indexToRemove, 1)[0];\r\n removedItem.destroy();\r\n }\r\n }\r\n }\r\n\r\n /**\r\n * Removes an image from cache, does not destroy() it, just removes.\r\n *\r\n * @param {number} index\r\n */\r\n removeByIndex(index) {\r\n const indexToRemove = this._cachedItems.findIndex(item => item.index === index);\r\n if (indexToRemove !== -1) {\r\n this._cachedItems.splice(indexToRemove, 1);\r\n }\r\n }\r\n\r\n /**\r\n * @param {number} index\r\n * @returns {Content | undefined}\r\n */\r\n getContentByIndex(index) {\r\n return this._cachedItems.find(content => content.index === index);\r\n }\r\n\r\n destroy() {\r\n this._cachedItems.forEach(content => content.destroy());\r\n this._cachedItems = [];\r\n }\r\n}\r\n\r\nexport default ContentLoader;\r\n", "import Eventable from './eventable.js';\r\nimport { getElementsFromOption } from '../util/util.js';\r\nimport Content from '../slide/content.js';\r\nimport { lazyLoadData } from '../slide/loader.js';\r\n\r\n/** @typedef {import(\"../photoswipe.js\").default} PhotoSwipe */\r\n/** @typedef {import(\"../slide/slide.js\").SlideData} SlideData */\r\n\r\n/**\r\n * PhotoSwipe base class that can retrieve data about every slide.\r\n * Shared by PhotoSwipe Core and PhotoSwipe Lightbox\r\n */\r\nclass PhotoSwipeBase extends Eventable {\r\n /**\r\n * Get total number of slides\r\n *\r\n * @returns {number}\r\n */\r\n getNumItems() {\r\n let numItems = 0;\r\n const dataSource = this.options?.dataSource;\r\n\r\n if (dataSource && 'length' in dataSource) {\r\n // may be an array or just object with length property\r\n numItems = dataSource.length;\r\n } else if (dataSource && 'gallery' in dataSource) {\r\n // query DOM elements\r\n if (!dataSource.items) {\r\n dataSource.items = this._getGalleryDOMElements(dataSource.gallery);\r\n }\r\n\r\n if (dataSource.items) {\r\n numItems = dataSource.items.length;\r\n }\r\n }\r\n\r\n // legacy event, before filters were introduced\r\n const event = this.dispatch('numItems', {\r\n dataSource,\r\n numItems\r\n });\r\n return this.applyFilters('numItems', event.numItems, dataSource);\r\n }\r\n\r\n /**\r\n * @param {SlideData} slideData\r\n * @param {number} index\r\n * @returns {Content}\r\n */\r\n createContentFromData(slideData, index) {\r\n return new Content(slideData, this, index);\r\n }\r\n\r\n /**\r\n * Get item data by index.\r\n *\r\n * \"item data\" should contain normalized information that PhotoSwipe needs to generate a slide.\r\n * For example, it may contain properties like\r\n * `src`, `srcset`, `w`, `h`, which will be used to generate a slide with image.\r\n *\r\n * @param {number} index\r\n * @returns {SlideData}\r\n */\r\n getItemData(index) {\r\n const dataSource = this.options?.dataSource;\r\n /** @type {SlideData | HTMLElement} */\r\n let dataSourceItem = {};\r\n if (Array.isArray(dataSource)) {\r\n // Datasource is an array of elements\r\n dataSourceItem = dataSource[index];\r\n } else if (dataSource && 'gallery' in dataSource) {\r\n // dataSource has gallery property,\r\n // thus it was created by Lightbox, based on\r\n // gallery and children options\r\n\r\n // query DOM elements\r\n if (!dataSource.items) {\r\n dataSource.items = this._getGalleryDOMElements(dataSource.gallery);\r\n }\r\n\r\n dataSourceItem = dataSource.items[index];\r\n }\r\n\r\n let itemData = dataSourceItem;\r\n\r\n if (itemData instanceof Element) {\r\n itemData = this._domElementToItemData(itemData);\r\n }\r\n\r\n // Dispatching the itemData event,\r\n // it's a legacy verion before filters were introduced\r\n const event = this.dispatch('itemData', {\r\n itemData: itemData || {},\r\n index\r\n });\r\n\r\n return this.applyFilters('itemData', event.itemData, index);\r\n }\r\n\r\n /**\r\n * Get array of gallery DOM elements,\r\n * based on childSelector and gallery element.\r\n *\r\n * @param {HTMLElement} galleryElement\r\n * @returns {HTMLElement[]}\r\n */\r\n _getGalleryDOMElements(galleryElement) {\r\n if (this.options?.children || this.options?.childSelector) {\r\n return getElementsFromOption(\r\n this.options.children,\r\n this.options.childSelector,\r\n galleryElement\r\n ) || [];\r\n }\r\n\r\n return [galleryElement];\r\n }\r\n\r\n /**\r\n * Converts DOM element to item data object.\r\n *\r\n * @param {HTMLElement} element DOM element\r\n * @returns {SlideData}\r\n */\r\n _domElementToItemData(element) {\r\n /** @type {SlideData} */\r\n const itemData = {\r\n element\r\n };\r\n\r\n const linkEl = /** @type {HTMLAnchorElement} */ (\r\n element.tagName === 'A'\r\n ? element\r\n : element.querySelector('a')\r\n );\r\n\r\n if (linkEl) {\r\n // src comes from data-pswp-src attribute,\r\n // if it's empty link href is used\r\n itemData.src = linkEl.dataset.pswpSrc || linkEl.href;\r\n\r\n if (linkEl.dataset.pswpSrcset) {\r\n itemData.srcset = linkEl.dataset.pswpSrcset;\r\n }\r\n\r\n itemData.width = linkEl.dataset.pswpWidth ? parseInt(linkEl.dataset.pswpWidth, 10) : 0;\r\n itemData.height = linkEl.dataset.pswpHeight ? parseInt(linkEl.dataset.pswpHeight, 10) : 0;\r\n\r\n // support legacy w & h properties\r\n itemData.w = itemData.width;\r\n itemData.h = itemData.height;\r\n\r\n if (linkEl.dataset.pswpType) {\r\n itemData.type = linkEl.dataset.pswpType;\r\n }\r\n\r\n const thumbnailEl = element.querySelector('img');\r\n\r\n if (thumbnailEl) {\r\n // msrc is URL to placeholder image that's displayed before large image is loaded\r\n // by default it's displayed only for the first slide\r\n itemData.msrc = thumbnailEl.currentSrc || thumbnailEl.src;\r\n itemData.alt = thumbnailEl.getAttribute('alt') ?? '';\r\n }\r\n\r\n if (linkEl.dataset.pswpCropped || linkEl.dataset.cropped) {\r\n itemData.thumbCropped = true;\r\n }\r\n }\r\n\r\n return this.applyFilters('domItemData', itemData, element, linkEl);\r\n }\r\n\r\n /**\r\n * Lazy-load by slide data\r\n *\r\n * @param {SlideData} itemData Data about the slide\r\n * @param {number} index\r\n * @returns {Content} Image that is being decoded or false.\r\n */\r\n lazyLoadData(itemData, index) {\r\n return lazyLoadData(itemData, this, index);\r\n }\r\n}\r\n\r\nexport default PhotoSwipeBase;\r\n", "import {\r\n setTransform,\r\n equalizePoints,\r\n decodeImage,\r\n toTransformString\r\n} from './util/util.js';\r\n\r\n/** @typedef {import('./photoswipe.js').default} PhotoSwipe */\r\n/** @typedef {import('./slide/get-thumb-bounds.js').Bounds} Bounds */\r\n/** @typedef {import('./util/animations.js').AnimationProps} AnimationProps */\r\n\r\n// some browsers do not paint\r\n// elements which opacity is set to 0,\r\n// since we need to pre-render elements for the animation -\r\n// we set it to the minimum amount\r\nconst MIN_OPACITY = 0.003;\r\n\r\n/**\r\n * Manages opening and closing transitions of the PhotoSwipe.\r\n *\r\n * It can perform zoom, fade or no transition.\r\n */\r\nclass Opener {\r\n /**\r\n * @param {PhotoSwipe} pswp\r\n */\r\n constructor(pswp) {\r\n this.pswp = pswp;\r\n this.isClosed = true;\r\n this.isOpen = false;\r\n this.isClosing = false;\r\n this.isOpening = false;\r\n /**\r\n * @private\r\n * @type {number | false | undefined}\r\n */\r\n this._duration = undefined;\r\n /** @private */\r\n this._useAnimation = false;\r\n /** @private */\r\n this._croppedZoom = false;\r\n /** @private */\r\n this._animateRootOpacity = false;\r\n /** @private */\r\n this._animateBgOpacity = false;\r\n /**\r\n * @private\r\n * @type { HTMLDivElement | HTMLImageElement | null | undefined }\r\n */\r\n this._placeholder = undefined;\r\n /**\r\n * @private\r\n * @type { HTMLDivElement | undefined }\r\n */\r\n this._opacityElement = undefined;\r\n /**\r\n * @private\r\n * @type { HTMLDivElement | undefined }\r\n */\r\n this._cropContainer1 = undefined;\r\n /**\r\n * @private\r\n * @type { HTMLElement | null | undefined }\r\n */\r\n this._cropContainer2 = undefined;\r\n\r\n /**\r\n * @private\r\n * @type {Bounds | undefined}\r\n */\r\n this._thumbBounds = undefined;\r\n\r\n\r\n this._prepareOpen = this._prepareOpen.bind(this);\r\n\r\n // Override initial zoom and pan position\r\n pswp.on('firstZoomPan', this._prepareOpen);\r\n }\r\n\r\n open() {\r\n this._prepareOpen();\r\n this._start();\r\n }\r\n\r\n close() {\r\n if (this.isClosed || this.isClosing || this.isOpening) {\r\n // if we close during opening animation\r\n // for now do nothing,\r\n // browsers aren't good at changing the direction of the CSS transition\r\n return;\r\n }\r\n\r\n const slide = this.pswp.currSlide;\r\n\r\n this.isOpen = false;\r\n this.isOpening = false;\r\n this.isClosing = true;\r\n this._duration = this.pswp.options.hideAnimationDuration;\r\n\r\n if (slide && slide.currZoomLevel * slide.width >= this.pswp.options.maxWidthToAnimate) {\r\n this._duration = 0;\r\n }\r\n\r\n this._applyStartProps();\r\n setTimeout(() => {\r\n this._start();\r\n }, this._croppedZoom ? 30 : 0);\r\n }\r\n\r\n /** @private */\r\n _prepareOpen() {\r\n this.pswp.off('firstZoomPan', this._prepareOpen);\r\n if (!this.isOpening) {\r\n const slide = this.pswp.currSlide;\r\n this.isOpening = true;\r\n this.isClosing = false;\r\n this._duration = this.pswp.options.showAnimationDuration;\r\n if (slide && slide.zoomLevels.initial * slide.width >= this.pswp.options.maxWidthToAnimate) {\r\n this._duration = 0;\r\n }\r\n this._applyStartProps();\r\n }\r\n }\r\n\r\n /** @private */\r\n _applyStartProps() {\r\n const { pswp } = this;\r\n const slide = this.pswp.currSlide;\r\n const { options } = pswp;\r\n\r\n if (options.showHideAnimationType === 'fade') {\r\n options.showHideOpacity = true;\r\n this._thumbBounds = undefined;\r\n } else if (options.showHideAnimationType === 'none') {\r\n options.showHideOpacity = false;\r\n this._duration = 0;\r\n this._thumbBounds = undefined;\r\n } else if (this.isOpening && pswp._initialThumbBounds) {\r\n // Use initial bounds if defined\r\n this._thumbBounds = pswp._initialThumbBounds;\r\n } else {\r\n this._thumbBounds = this.pswp.getThumbBounds();\r\n }\r\n\r\n this._placeholder = slide?.getPlaceholderElement();\r\n\r\n pswp.animations.stopAll();\r\n\r\n // Discard animations when duration is less than 50ms\r\n this._useAnimation = Boolean(this._duration && this._duration > 50);\r\n this._animateZoom = Boolean(this._thumbBounds)\r\n && slide?.content.usePlaceholder()\r\n && (!this.isClosing || !pswp.mainScroll.isShifted());\r\n if (!this._animateZoom) {\r\n this._animateRootOpacity = true;\r\n\r\n if (this.isOpening && slide) {\r\n slide.zoomAndPanToInitial();\r\n slide.applyCurrentZoomPan();\r\n }\r\n } else {\r\n this._animateRootOpacity = options.showHideOpacity ?? false;\r\n }\r\n this._animateBgOpacity = !this._animateRootOpacity && this.pswp.options.bgOpacity > MIN_OPACITY;\r\n this._opacityElement = this._animateRootOpacity ? pswp.element : pswp.bg;\r\n\r\n if (!this._useAnimation) {\r\n this._duration = 0;\r\n this._animateZoom = false;\r\n this._animateBgOpacity = false;\r\n this._animateRootOpacity = true;\r\n if (this.isOpening) {\r\n if (pswp.element) {\r\n pswp.element.style.opacity = String(MIN_OPACITY);\r\n }\r\n pswp.applyBgOpacity(1);\r\n }\r\n return;\r\n }\r\n\r\n if (this._animateZoom && this._thumbBounds && this._thumbBounds.innerRect) {\r\n // Properties are used when animation from cropped thumbnail\r\n this._croppedZoom = true;\r\n this._cropContainer1 = this.pswp.container;\r\n this._cropContainer2 = this.pswp.currSlide?.holderElement;\r\n\r\n if (pswp.container) {\r\n pswp.container.style.overflow = 'hidden';\r\n pswp.container.style.width = pswp.viewportSize.x + 'px';\r\n }\r\n } else {\r\n this._croppedZoom = false;\r\n }\r\n\r\n if (this.isOpening) {\r\n // Apply styles before opening transition\r\n if (this._animateRootOpacity) {\r\n if (pswp.element) {\r\n pswp.element.style.opacity = String(MIN_OPACITY);\r\n }\r\n pswp.applyBgOpacity(1);\r\n } else {\r\n if (this._animateBgOpacity && pswp.bg) {\r\n pswp.bg.style.opacity = String(MIN_OPACITY);\r\n }\r\n if (pswp.element) {\r\n pswp.element.style.opacity = '1';\r\n }\r\n }\r\n\r\n if (this._animateZoom) {\r\n this._setClosedStateZoomPan();\r\n if (this._placeholder) {\r\n // tell browser that we plan to animate the placeholder\r\n this._placeholder.style.willChange = 'transform';\r\n\r\n // hide placeholder to allow hiding of\r\n // elements that overlap it (such as icons over the thumbnail)\r\n this._placeholder.style.opacity = String(MIN_OPACITY);\r\n }\r\n }\r\n } else if (this.isClosing) {\r\n // hide nearby slides to make sure that\r\n // they are not painted during the transition\r\n if (pswp.mainScroll.itemHolders[0]) {\r\n pswp.mainScroll.itemHolders[0].el.style.display = 'none';\r\n }\r\n if (pswp.mainScroll.itemHolders[2]) {\r\n pswp.mainScroll.itemHolders[2].el.style.display = 'none';\r\n }\r\n\r\n if (this._croppedZoom) {\r\n if (pswp.mainScroll.x !== 0) {\r\n // shift the main scroller to zero position\r\n pswp.mainScroll.resetPosition();\r\n pswp.mainScroll.resize();\r\n }\r\n }\r\n }\r\n }\r\n\r\n /** @private */\r\n _start() {\r\n if (this.isOpening\r\n && this._useAnimation\r\n && this._placeholder\r\n && this._placeholder.tagName === 'IMG') {\r\n // To ensure smooth animation\r\n // we wait till the current slide image placeholder is decoded,\r\n // but no longer than 250ms,\r\n // and no shorter than 50ms\r\n // (just using requestanimationframe is not enough in Firefox,\r\n // for some reason)\r\n new Promise((resolve) => {\r\n let decoded = false;\r\n let isDelaying = true;\r\n decodeImage(/** @type {HTMLImageElement} */ (this._placeholder)).finally(() => {\r\n decoded = true;\r\n if (!isDelaying) {\r\n resolve(true);\r\n }\r\n });\r\n setTimeout(() => {\r\n isDelaying = false;\r\n if (decoded) {\r\n resolve(true);\r\n }\r\n }, 50);\r\n setTimeout(resolve, 250);\r\n }).finally(() => this._initiate());\r\n } else {\r\n this._initiate();\r\n }\r\n }\r\n\r\n /** @private */\r\n _initiate() {\r\n this.pswp.element?.style.setProperty('--pswp-transition-duration', this._duration + 'ms');\r\n\r\n this.pswp.dispatch(\r\n this.isOpening ? 'openingAnimationStart' : 'closingAnimationStart'\r\n );\r\n\r\n // legacy event\r\n this.pswp.dispatch(\r\n /** @type {'initialZoomIn' | 'initialZoomOut'} */\r\n ('initialZoom' + (this.isOpening ? 'In' : 'Out'))\r\n );\r\n\r\n this.pswp.element?.classList.toggle('pswp--ui-visible', this.isOpening);\r\n\r\n if (this.isOpening) {\r\n if (this._placeholder) {\r\n // unhide the placeholder\r\n this._placeholder.style.opacity = '1';\r\n }\r\n this._animateToOpenState();\r\n } else if (this.isClosing) {\r\n this._animateToClosedState();\r\n }\r\n\r\n if (!this._useAnimation) {\r\n this._onAnimationComplete();\r\n }\r\n }\r\n\r\n /** @private */\r\n _onAnimationComplete() {\r\n const { pswp } = this;\r\n this.isOpen = this.isOpening;\r\n this.isClosed = this.isClosing;\r\n this.isOpening = false;\r\n this.isClosing = false;\r\n\r\n pswp.dispatch(\r\n this.isOpen ? 'openingAnimationEnd' : 'closingAnimationEnd'\r\n );\r\n\r\n // legacy event\r\n pswp.dispatch(\r\n /** @type {'initialZoomInEnd' | 'initialZoomOutEnd'} */\r\n ('initialZoom' + (this.isOpen ? 'InEnd' : 'OutEnd'))\r\n );\r\n\r\n if (this.isClosed) {\r\n pswp.destroy();\r\n } else if (this.isOpen) {\r\n if (this._animateZoom && pswp.container) {\r\n pswp.container.style.overflow = 'visible';\r\n pswp.container.style.width = '100%';\r\n }\r\n pswp.currSlide?.applyCurrentZoomPan();\r\n }\r\n }\r\n\r\n /** @private */\r\n _animateToOpenState() {\r\n const { pswp } = this;\r\n if (this._animateZoom) {\r\n if (this._croppedZoom && this._cropContainer1 && this._cropContainer2) {\r\n this._animateTo(this._cropContainer1, 'transform', 'translate3d(0,0,0)');\r\n this._animateTo(this._cropContainer2, 'transform', 'none');\r\n }\r\n\r\n if (pswp.currSlide) {\r\n pswp.currSlide.zoomAndPanToInitial();\r\n this._animateTo(\r\n pswp.currSlide.container,\r\n 'transform',\r\n pswp.currSlide.getCurrentTransform()\r\n );\r\n }\r\n }\r\n\r\n if (this._animateBgOpacity && pswp.bg) {\r\n this._animateTo(pswp.bg, 'opacity', String(pswp.options.bgOpacity));\r\n }\r\n\r\n if (this._animateRootOpacity && pswp.element) {\r\n this._animateTo(pswp.element, 'opacity', '1');\r\n }\r\n }\r\n\r\n /** @private */\r\n _animateToClosedState() {\r\n const { pswp } = this;\r\n\r\n if (this._animateZoom) {\r\n this._setClosedStateZoomPan(true);\r\n }\r\n\r\n // do not animate opacity if it's already at 0\r\n if (this._animateBgOpacity && pswp.bgOpacity > 0.01 && pswp.bg) {\r\n this._animateTo(pswp.bg, 'opacity', '0');\r\n }\r\n\r\n if (this._animateRootOpacity && pswp.element) {\r\n this._animateTo(pswp.element, 'opacity', '0');\r\n }\r\n }\r\n\r\n /**\r\n * @private\r\n * @param {boolean} [animate]\r\n */\r\n _setClosedStateZoomPan(animate) {\r\n if (!this._thumbBounds) return;\r\n\r\n const { pswp } = this;\r\n const { innerRect } = this._thumbBounds;\r\n const { currSlide, viewportSize } = pswp;\r\n\r\n if (this._croppedZoom && innerRect && this._cropContainer1 && this._cropContainer2) {\r\n const containerOnePanX = -viewportSize.x + (this._thumbBounds.x - innerRect.x) + innerRect.w;\r\n const containerOnePanY = -viewportSize.y + (this._thumbBounds.y - innerRect.y) + innerRect.h;\r\n const containerTwoPanX = viewportSize.x - innerRect.w;\r\n const containerTwoPanY = viewportSize.y - innerRect.h;\r\n\r\n\r\n if (animate) {\r\n this._animateTo(\r\n this._cropContainer1,\r\n 'transform',\r\n toTransformString(containerOnePanX, containerOnePanY)\r\n );\r\n\r\n this._animateTo(\r\n this._cropContainer2,\r\n 'transform',\r\n toTransformString(containerTwoPanX, containerTwoPanY)\r\n );\r\n } else {\r\n setTransform(this._cropContainer1, containerOnePanX, containerOnePanY);\r\n setTransform(this._cropContainer2, containerTwoPanX, containerTwoPanY);\r\n }\r\n }\r\n\r\n if (currSlide) {\r\n equalizePoints(currSlide.pan, innerRect || this._thumbBounds);\r\n currSlide.currZoomLevel = this._thumbBounds.w / currSlide.width;\r\n if (animate) {\r\n this._animateTo(currSlide.container, 'transform', currSlide.getCurrentTransform());\r\n } else {\r\n currSlide.applyCurrentZoomPan();\r\n }\r\n }\r\n }\r\n\r\n /**\r\n * @private\r\n * @param {HTMLElement} target\r\n * @param {'transform' | 'opacity'} prop\r\n * @param {string} propValue\r\n */\r\n _animateTo(target, prop, propValue) {\r\n if (!this._duration) {\r\n target.style[prop] = propValue;\r\n return;\r\n }\r\n\r\n const { animations } = this.pswp;\r\n /** @type {AnimationProps} */\r\n const animProps = {\r\n duration: this._duration,\r\n easing: this.pswp.options.easing,\r\n onComplete: () => {\r\n if (!animations.activeAnimations.length) {\r\n this._onAnimationComplete();\r\n }\r\n },\r\n target,\r\n };\r\n animProps[prop] = propValue;\r\n animations.startTransition(animProps);\r\n }\r\n}\r\n\r\nexport default Opener;\r\n", "import {\r\n createElement,\r\n equalizePoints,\r\n pointsEqual,\r\n clamp,\r\n} from './util/util.js';\r\n\r\nimport DOMEvents from './util/dom-events.js';\r\nimport Slide from './slide/slide.js';\r\nimport Gestures from './gestures/gestures.js';\r\nimport MainScroll from './main-scroll.js';\r\n\r\nimport Keyboard from './keyboard.js';\r\nimport Animations from './util/animations.js';\r\nimport ScrollWheel from './scroll-wheel.js';\r\nimport UI from './ui/ui.js';\r\nimport { getViewportSize } from './util/viewport-size.js';\r\nimport { getThumbBounds } from './slide/get-thumb-bounds.js';\r\nimport PhotoSwipeBase from './core/base.js';\r\nimport Opener from './opener.js';\r\nimport ContentLoader from './slide/loader.js';\r\n\r\n/**\r\n * @template T\r\n * @typedef {import('./types.js').Type} Type\r\n */\r\n\r\n/** @typedef {import('./slide/slide.js').SlideData} SlideData */\r\n/** @typedef {import('./slide/zoom-level.js').ZoomLevelOption} ZoomLevelOption */\r\n/** @typedef {import('./ui/ui-element.js').UIElementData} UIElementData */\r\n/** @typedef {import('./main-scroll.js').ItemHolder} ItemHolder */\r\n/** @typedef {import('./core/eventable.js').PhotoSwipeEventsMap} PhotoSwipeEventsMap */\r\n/** @typedef {import('./core/eventable.js').PhotoSwipeFiltersMap} PhotoSwipeFiltersMap */\r\n/** @typedef {import('./slide/get-thumb-bounds').Bounds} Bounds */\r\n/**\r\n * @template {keyof PhotoSwipeEventsMap} T\r\n * @typedef {import('./core/eventable.js').EventCallback} EventCallback\r\n */\r\n/**\r\n * @template {keyof PhotoSwipeEventsMap} T\r\n * @typedef {import('./core/eventable.js').AugmentedEvent} AugmentedEvent\r\n */\r\n\r\n/** @typedef {{ x: number; y: number; id?: string | number }} Point */\r\n/** @typedef {{ top: number; bottom: number; left: number; right: number }} Padding */\r\n/** @typedef {SlideData[]} DataSourceArray */\r\n/** @typedef {{ gallery: HTMLElement; items?: HTMLElement[] }} DataSourceObject */\r\n/** @typedef {DataSourceArray | DataSourceObject} DataSource */\r\n/** @typedef {(point: Point, originalEvent: PointerEvent) => void} ActionFn */\r\n/** @typedef {'close' | 'next' | 'zoom' | 'zoom-or-close' | 'toggle-controls'} ActionType */\r\n/** @typedef {Type | { default: Type }} PhotoSwipeModule */\r\n/** @typedef {PhotoSwipeModule | Promise | (() => Promise)} PhotoSwipeModuleOption */\r\n\r\n/**\r\n * @typedef {string | NodeListOf | HTMLElement[] | HTMLElement} ElementProvider\r\n */\r\n\r\n/** @typedef {Partial} PhotoSwipeOptions https://photoswipe.com/options/ */\r\n/**\r\n * @typedef {Object} PreparedPhotoSwipeOptions\r\n *\r\n * @prop {DataSource} [dataSource]\r\n * Pass an array of any items via dataSource option. Its length will determine amount of slides\r\n * (which may be modified further from numItems event).\r\n *\r\n * Each item should contain data that you need to generate slide\r\n * (for image slide it would be src (image URL), width (image width), height, srcset, alt).\r\n *\r\n * If these properties are not present in your initial array, you may \"pre-parse\" each item from itemData filter.\r\n *\r\n * @prop {number} bgOpacity\r\n * Background backdrop opacity, always define it via this option and not via CSS rgba color.\r\n *\r\n * @prop {number} spacing\r\n * Spacing between slides. Defined as ratio relative to the viewport width (0.1 = 10% of viewport).\r\n *\r\n * @prop {boolean} allowPanToNext\r\n * Allow swipe navigation to the next slide when the current slide is zoomed. Does not apply to mouse events.\r\n *\r\n * @prop {boolean} loop\r\n * If set to true you'll be able to swipe from the last to the first image.\r\n * Option is always false when there are less than 3 slides.\r\n *\r\n * @prop {boolean} [wheelToZoom]\r\n * By default PhotoSwipe zooms image with ctrl-wheel, if you enable this option - image will zoom just via wheel.\r\n *\r\n * @prop {boolean} pinchToClose\r\n * Pinch touch gesture to close the gallery.\r\n *\r\n * @prop {boolean} closeOnVerticalDrag\r\n * Vertical drag gesture to close the PhotoSwipe.\r\n *\r\n * @prop {Padding} [padding]\r\n * Slide area padding (in pixels).\r\n *\r\n * @prop {(viewportSize: Point, itemData: SlideData, index: number) => Padding} [paddingFn]\r\n * The option is checked frequently, so make sure it's performant. Overrides padding option if defined. For example:\r\n *\r\n * @prop {number | false} hideAnimationDuration\r\n * Transition duration in milliseconds, can be 0.\r\n *\r\n * @prop {number | false} showAnimationDuration\r\n * Transition duration in milliseconds, can be 0.\r\n *\r\n * @prop {number | false} zoomAnimationDuration\r\n * Transition duration in milliseconds, can be 0.\r\n *\r\n * @prop {string} easing\r\n * String, 'cubic-bezier(.4,0,.22,1)'. CSS easing function for open/close/zoom transitions.\r\n *\r\n * @prop {boolean} escKey\r\n * Esc key to close.\r\n *\r\n * @prop {boolean} arrowKeys\r\n * Left/right arrow keys for navigation.\r\n *\r\n * @prop {boolean} trapFocus\r\n * Trap focus within PhotoSwipe element while it's open.\r\n *\r\n * @prop {boolean} returnFocus\r\n * Restore focus the last active element after PhotoSwipe is closed.\r\n *\r\n * @prop {boolean} clickToCloseNonZoomable\r\n * If image is not zoomable (for example, smaller than viewport) it can be closed by clicking on it.\r\n *\r\n * @prop {ActionType | ActionFn | false} imageClickAction\r\n * Refer to click and tap actions page.\r\n *\r\n * @prop {ActionType | ActionFn | false} bgClickAction\r\n * Refer to click and tap actions page.\r\n *\r\n * @prop {ActionType | ActionFn | false} tapAction\r\n * Refer to click and tap actions page.\r\n *\r\n * @prop {ActionType | ActionFn | false} doubleTapAction\r\n * Refer to click and tap actions page.\r\n *\r\n * @prop {number} preloaderDelay\r\n * Delay before the loading indicator will be displayed,\r\n * if image is loaded during it - the indicator will not be displayed at all. Can be zero.\r\n *\r\n * @prop {string} indexIndicatorSep\r\n * Used for slide count indicator (\"1 of 10 \").\r\n *\r\n * @prop {(options: PhotoSwipeOptions, pswp: PhotoSwipeBase) => Point} [getViewportSizeFn]\r\n * A function that should return slide viewport width and height, in format {x: 100, y: 100}.\r\n *\r\n * @prop {string} errorMsg\r\n * Message to display when the image wasn't able to load. If you need to display HTML - use contentErrorElement filter.\r\n *\r\n * @prop {[number, number]} preload\r\n * Lazy loading of nearby slides based on direction of movement. Should be an array with two integers,\r\n * first one - number of items to preload before the current image, second one - after the current image.\r\n * Two nearby images are always loaded.\r\n *\r\n * @prop {string} [mainClass]\r\n * Class that will be added to the root element of PhotoSwipe, may contain multiple separated by space.\r\n * Example on Styling page.\r\n *\r\n * @prop {HTMLElement} [appendToEl]\r\n * Element to which PhotoSwipe dialog will be appended when it opens.\r\n *\r\n * @prop {number} maxWidthToAnimate\r\n * Maximum width of image to animate, if initial rendered image width\r\n * is larger than this value - the opening/closing transition will be automatically disabled.\r\n *\r\n * @prop {string} [closeTitle]\r\n * Translating\r\n *\r\n * @prop {string} [zoomTitle]\r\n * Translating\r\n *\r\n * @prop {string} [arrowPrevTitle]\r\n * Translating\r\n *\r\n * @prop {string} [arrowNextTitle]\r\n * Translating\r\n *\r\n * @prop {'zoom' | 'fade' | 'none'} [showHideAnimationType]\r\n * To adjust opening or closing transition type use lightbox option `showHideAnimationType` (`String`).\r\n * It supports three values - `zoom` (default), `fade` (default if there is no thumbnail) and `none`.\r\n *\r\n * Animations are automatically disabled if user `(prefers-reduced-motion: reduce)`.\r\n *\r\n * @prop {number} index\r\n * Defines start slide index.\r\n *\r\n * @prop {(e: MouseEvent) => number} [getClickedIndexFn]\r\n *\r\n * @prop {boolean} [arrowPrev]\r\n * @prop {boolean} [arrowNext]\r\n * @prop {boolean} [zoom]\r\n * @prop {boolean} [close]\r\n * @prop {boolean} [counter]\r\n *\r\n * @prop {string} [arrowPrevSVG]\r\n * @prop {string} [arrowNextSVG]\r\n * @prop {string} [zoomSVG]\r\n * @prop {string} [closeSVG]\r\n * @prop {string} [counterSVG]\r\n *\r\n * @prop {string} [arrowPrevTitle]\r\n * @prop {string} [arrowNextTitle]\r\n * @prop {string} [zoomTitle]\r\n * @prop {string} [closeTitle]\r\n * @prop {string} [counterTitle]\r\n *\r\n * @prop {ZoomLevelOption} [initialZoomLevel]\r\n * @prop {ZoomLevelOption} [secondaryZoomLevel]\r\n * @prop {ZoomLevelOption} [maxZoomLevel]\r\n *\r\n * @prop {boolean} [mouseMovePan]\r\n * @prop {Point | null} [initialPointerPos]\r\n * @prop {boolean} [showHideOpacity]\r\n *\r\n * @prop {PhotoSwipeModuleOption} [pswpModule]\r\n * @prop {() => Promise} [openPromise]\r\n * @prop {boolean} [preloadFirstSlide]\r\n * @prop {ElementProvider} [gallery]\r\n * @prop {string} [gallerySelector]\r\n * @prop {ElementProvider} [children]\r\n * @prop {string} [childSelector]\r\n * @prop {string | false} [thumbSelector]\r\n */\r\n\r\n/** @type {PreparedPhotoSwipeOptions} */\r\nconst defaultOptions = {\r\n allowPanToNext: true,\r\n spacing: 0.1,\r\n loop: true,\r\n pinchToClose: true,\r\n closeOnVerticalDrag: true,\r\n hideAnimationDuration: 333,\r\n showAnimationDuration: 333,\r\n zoomAnimationDuration: 333,\r\n escKey: true,\r\n arrowKeys: true,\r\n trapFocus: true,\r\n returnFocus: true,\r\n maxWidthToAnimate: 4000,\r\n clickToCloseNonZoomable: true,\r\n imageClickAction: 'zoom-or-close',\r\n bgClickAction: 'close',\r\n tapAction: 'toggle-controls',\r\n doubleTapAction: 'zoom',\r\n indexIndicatorSep: ' / ',\r\n preloaderDelay: 2000,\r\n bgOpacity: 0.8,\r\n\r\n index: 0,\r\n errorMsg: 'The image cannot be loaded',\r\n preload: [1, 2],\r\n easing: 'cubic-bezier(.4,0,.22,1)'\r\n};\r\n\r\n/**\r\n * PhotoSwipe Core\r\n */\r\nclass PhotoSwipe extends PhotoSwipeBase {\r\n /**\r\n * @param {PhotoSwipeOptions} [options]\r\n */\r\n constructor(options) {\r\n super();\r\n\r\n this.options = this._prepareOptions(options || {});\r\n\r\n /**\r\n * offset of viewport relative to document\r\n *\r\n * @type {Point}\r\n */\r\n this.offset = { x: 0, y: 0 };\r\n\r\n /**\r\n * @type {Point}\r\n * @private\r\n */\r\n this._prevViewportSize = { x: 0, y: 0 };\r\n\r\n /**\r\n * Size of scrollable PhotoSwipe viewport\r\n *\r\n * @type {Point}\r\n */\r\n this.viewportSize = { x: 0, y: 0 };\r\n\r\n /**\r\n * background (backdrop) opacity\r\n */\r\n this.bgOpacity = 1;\r\n this.currIndex = 0;\r\n this.potentialIndex = 0;\r\n this.isOpen = false;\r\n this.isDestroying = false;\r\n this.hasMouse = false;\r\n\r\n /**\r\n * @private\r\n * @type {SlideData}\r\n */\r\n this._initialItemData = {};\r\n /** @type {Bounds | undefined} */\r\n this._initialThumbBounds = undefined;\r\n\r\n /** @type {HTMLDivElement | undefined} */\r\n this.topBar = undefined;\r\n /** @type {HTMLDivElement | undefined} */\r\n this.element = undefined;\r\n /** @type {HTMLDivElement | undefined} */\r\n this.template = undefined;\r\n /** @type {HTMLDivElement | undefined} */\r\n this.container = undefined;\r\n /** @type {HTMLElement | undefined} */\r\n this.scrollWrap = undefined;\r\n /** @type {Slide | undefined} */\r\n this.currSlide = undefined;\r\n\r\n this.events = new DOMEvents();\r\n this.animations = new Animations();\r\n this.mainScroll = new MainScroll(this);\r\n this.gestures = new Gestures(this);\r\n this.opener = new Opener(this);\r\n this.keyboard = new Keyboard(this);\r\n this.contentLoader = new ContentLoader(this);\r\n }\r\n\r\n /** @returns {boolean} */\r\n init() {\r\n if (this.isOpen || this.isDestroying) {\r\n return false;\r\n }\r\n\r\n this.isOpen = true;\r\n this.dispatch('init'); // legacy\r\n this.dispatch('beforeOpen');\r\n\r\n this._createMainStructure();\r\n\r\n // add classes to the root element of PhotoSwipe\r\n let rootClasses = 'pswp--open';\r\n if (this.gestures.supportsTouch) {\r\n rootClasses += ' pswp--touch';\r\n }\r\n if (this.options.mainClass) {\r\n rootClasses += ' ' + this.options.mainClass;\r\n }\r\n if (this.element) {\r\n this.element.className += ' ' + rootClasses;\r\n }\r\n\r\n this.currIndex = this.options.index || 0;\r\n this.potentialIndex = this.currIndex;\r\n this.dispatch('firstUpdate'); // starting index can be modified here\r\n\r\n // initialize scroll wheel handler to block the scroll\r\n this.scrollWheel = new ScrollWheel(this);\r\n\r\n // sanitize index\r\n if (Number.isNaN(this.currIndex)\r\n || this.currIndex < 0\r\n || this.currIndex >= this.getNumItems()) {\r\n this.currIndex = 0;\r\n }\r\n\r\n if (!this.gestures.supportsTouch) {\r\n // enable mouse features if no touch support detected\r\n this.mouseDetected();\r\n }\r\n\r\n // causes forced synchronous layout\r\n this.updateSize();\r\n\r\n this.offset.y = window.pageYOffset;\r\n\r\n this._initialItemData = this.getItemData(this.currIndex);\r\n this.dispatch('gettingData', {\r\n index: this.currIndex,\r\n data: this._initialItemData,\r\n slide: undefined\r\n });\r\n\r\n // *Layout* - calculate size and position of elements here\r\n this._initialThumbBounds = this.getThumbBounds();\r\n this.dispatch('initialLayout');\r\n\r\n this.on('openingAnimationEnd', () => {\r\n const { itemHolders } = this.mainScroll;\r\n\r\n // Add content to the previous and next slide\r\n if (itemHolders[0]) {\r\n itemHolders[0].el.style.display = 'block';\r\n this.setContent(itemHolders[0], this.currIndex - 1);\r\n }\r\n if (itemHolders[2]) {\r\n itemHolders[2].el.style.display = 'block';\r\n this.setContent(itemHolders[2], this.currIndex + 1);\r\n }\r\n\r\n this.appendHeavy();\r\n\r\n this.contentLoader.updateLazy();\r\n\r\n this.events.add(window, 'resize', this._handlePageResize.bind(this));\r\n this.events.add(window, 'scroll', this._updatePageScrollOffset.bind(this));\r\n this.dispatch('bindEvents');\r\n });\r\n\r\n // set content for center slide (first time)\r\n if (this.mainScroll.itemHolders[1]) {\r\n this.setContent(this.mainScroll.itemHolders[1], this.currIndex);\r\n }\r\n this.dispatch('change');\r\n\r\n this.opener.open();\r\n\r\n this.dispatch('afterInit');\r\n\r\n return true;\r\n }\r\n\r\n /**\r\n * Get looped slide index\r\n * (for example, -1 will return the last slide)\r\n *\r\n * @param {number} index\r\n * @returns {number}\r\n */\r\n getLoopedIndex(index) {\r\n const numSlides = this.getNumItems();\r\n\r\n if (this.options.loop) {\r\n if (index > numSlides - 1) {\r\n index -= numSlides;\r\n }\r\n\r\n if (index < 0) {\r\n index += numSlides;\r\n }\r\n }\r\n\r\n return clamp(index, 0, numSlides - 1);\r\n }\r\n\r\n appendHeavy() {\r\n this.mainScroll.itemHolders.forEach((itemHolder) => {\r\n itemHolder.slide?.appendHeavy();\r\n });\r\n }\r\n\r\n /**\r\n * Change the slide\r\n * @param {number} index New index\r\n */\r\n goTo(index) {\r\n this.mainScroll.moveIndexBy(\r\n this.getLoopedIndex(index) - this.potentialIndex\r\n );\r\n }\r\n\r\n /**\r\n * Go to the next slide.\r\n */\r\n next() {\r\n this.goTo(this.potentialIndex + 1);\r\n }\r\n\r\n /**\r\n * Go to the previous slide.\r\n */\r\n prev() {\r\n this.goTo(this.potentialIndex - 1);\r\n }\r\n\r\n /**\r\n * @see slide/slide.js zoomTo\r\n *\r\n * @param {Parameters} args\r\n */\r\n zoomTo(...args) {\r\n this.currSlide?.zoomTo(...args);\r\n }\r\n\r\n /**\r\n * @see slide/slide.js toggleZoom\r\n */\r\n toggleZoom() {\r\n this.currSlide?.toggleZoom();\r\n }\r\n\r\n /**\r\n * Close the gallery.\r\n * After closing transition ends - destroy it\r\n */\r\n close() {\r\n if (!this.opener.isOpen || this.isDestroying) {\r\n return;\r\n }\r\n\r\n this.isDestroying = true;\r\n\r\n this.dispatch('close');\r\n\r\n this.events.removeAll();\r\n this.opener.close();\r\n }\r\n\r\n /**\r\n * Destroys the gallery:\r\n * - instantly closes the gallery\r\n * - unbinds events,\r\n * - cleans intervals and timeouts\r\n * - removes elements from DOM\r\n */\r\n destroy() {\r\n if (!this.isDestroying) {\r\n this.options.showHideAnimationType = 'none';\r\n this.close();\r\n return;\r\n }\r\n\r\n this.dispatch('destroy');\r\n\r\n this._listeners = {};\r\n\r\n if (this.scrollWrap) {\r\n this.scrollWrap.ontouchmove = null;\r\n this.scrollWrap.ontouchend = null;\r\n }\r\n\r\n this.element?.remove();\r\n\r\n this.mainScroll.itemHolders.forEach((itemHolder) => {\r\n itemHolder.slide?.destroy();\r\n });\r\n\r\n this.contentLoader.destroy();\r\n this.events.removeAll();\r\n }\r\n\r\n /**\r\n * Refresh/reload content of a slide by its index\r\n *\r\n * @param {number} slideIndex\r\n */\r\n refreshSlideContent(slideIndex) {\r\n this.contentLoader.removeByIndex(slideIndex);\r\n this.mainScroll.itemHolders.forEach((itemHolder, i) => {\r\n let potentialHolderIndex = (this.currSlide?.index ?? 0) - 1 + i;\r\n if (this.canLoop()) {\r\n potentialHolderIndex = this.getLoopedIndex(potentialHolderIndex);\r\n }\r\n if (potentialHolderIndex === slideIndex) {\r\n // set the new slide content\r\n this.setContent(itemHolder, slideIndex, true);\r\n\r\n // activate the new slide if it's current\r\n if (i === 1) {\r\n this.currSlide = itemHolder.slide;\r\n itemHolder.slide?.setIsActive(true);\r\n }\r\n }\r\n });\r\n\r\n this.dispatch('change');\r\n }\r\n\r\n\r\n /**\r\n * Set slide content\r\n *\r\n * @param {ItemHolder} holder mainScroll.itemHolders array item\r\n * @param {number} index Slide index\r\n * @param {boolean} [force] If content should be set even if index wasn't changed\r\n */\r\n setContent(holder, index, force) {\r\n if (this.canLoop()) {\r\n index = this.getLoopedIndex(index);\r\n }\r\n\r\n if (holder.slide) {\r\n if (holder.slide.index === index && !force) {\r\n // exit if holder already contains this slide\r\n // this could be common when just three slides are used\r\n return;\r\n }\r\n\r\n // destroy previous slide\r\n holder.slide.destroy();\r\n holder.slide = undefined;\r\n }\r\n\r\n // exit if no loop and index is out of bounds\r\n if (!this.canLoop() && (index < 0 || index >= this.getNumItems())) {\r\n return;\r\n }\r\n\r\n const itemData = this.getItemData(index);\r\n holder.slide = new Slide(itemData, index, this);\r\n\r\n // set current slide\r\n if (index === this.currIndex) {\r\n this.currSlide = holder.slide;\r\n }\r\n\r\n holder.slide.append(holder.el);\r\n }\r\n\r\n /** @returns {Point} */\r\n getViewportCenterPoint() {\r\n return {\r\n x: this.viewportSize.x / 2,\r\n y: this.viewportSize.y / 2\r\n };\r\n }\r\n\r\n /**\r\n * Update size of all elements.\r\n * Executed on init and on page resize.\r\n *\r\n * @param {boolean} [force] Update size even if size of viewport was not changed.\r\n */\r\n updateSize(force) {\r\n // let item;\r\n // let itemIndex;\r\n\r\n if (this.isDestroying) {\r\n // exit if PhotoSwipe is closed or closing\r\n // (to avoid errors, as resize event might be delayed)\r\n return;\r\n }\r\n\r\n //const newWidth = this.scrollWrap.clientWidth;\r\n //const newHeight = this.scrollWrap.clientHeight;\r\n\r\n const newViewportSize = getViewportSize(this.options, this);\r\n\r\n if (!force && pointsEqual(newViewportSize, this._prevViewportSize)) {\r\n // Exit if dimensions were not changed\r\n return;\r\n }\r\n\r\n //this._prevViewportSize.x = newWidth;\r\n //this._prevViewportSize.y = newHeight;\r\n equalizePoints(this._prevViewportSize, newViewportSize);\r\n\r\n this.dispatch('beforeResize');\r\n\r\n equalizePoints(this.viewportSize, this._prevViewportSize);\r\n\r\n this._updatePageScrollOffset();\r\n\r\n this.dispatch('viewportSize');\r\n\r\n // Resize slides only after opener animation is finished\r\n // and don't re-calculate size on inital size update\r\n this.mainScroll.resize(this.opener.isOpen);\r\n\r\n if (!this.hasMouse && window.matchMedia('(any-hover: hover)').matches) {\r\n this.mouseDetected();\r\n }\r\n\r\n this.dispatch('resize');\r\n }\r\n\r\n /**\r\n * @param {number} opacity\r\n */\r\n applyBgOpacity(opacity) {\r\n this.bgOpacity = Math.max(opacity, 0);\r\n if (this.bg) {\r\n this.bg.style.opacity = String(this.bgOpacity * this.options.bgOpacity);\r\n }\r\n }\r\n\r\n /**\r\n * Whether mouse is detected\r\n */\r\n mouseDetected() {\r\n if (!this.hasMouse) {\r\n this.hasMouse = true;\r\n this.element?.classList.add('pswp--has_mouse');\r\n }\r\n }\r\n\r\n /**\r\n * Page resize event handler\r\n *\r\n * @private\r\n */\r\n _handlePageResize() {\r\n this.updateSize();\r\n\r\n // In iOS webview, if element size depends on document size,\r\n // it'll be measured incorrectly in resize event\r\n //\r\n // https://bugs.webkit.org/show_bug.cgi?id=170595\r\n // https://hackernoon.com/onresize-event-broken-in-mobile-safari-d8469027bf4d\r\n if (/iPhone|iPad|iPod/i.test(window.navigator.userAgent)) {\r\n setTimeout(() => {\r\n this.updateSize();\r\n }, 500);\r\n }\r\n }\r\n\r\n /**\r\n * Page scroll offset is used\r\n * to get correct coordinates\r\n * relative to PhotoSwipe viewport.\r\n *\r\n * @private\r\n */\r\n _updatePageScrollOffset() {\r\n this.setScrollOffset(0, window.pageYOffset);\r\n }\r\n\r\n /**\r\n * @param {number} x\r\n * @param {number} y\r\n */\r\n setScrollOffset(x, y) {\r\n this.offset.x = x;\r\n this.offset.y = y;\r\n this.dispatch('updateScrollOffset');\r\n }\r\n\r\n /**\r\n * Create main HTML structure of PhotoSwipe,\r\n * and add it to DOM\r\n *\r\n * @private\r\n */\r\n _createMainStructure() {\r\n // root DOM element of PhotoSwipe (.pswp)\r\n this.element = createElement('pswp', 'div');\r\n this.element.setAttribute('tabindex', '-1');\r\n this.element.setAttribute('role', 'dialog');\r\n\r\n // template is legacy prop\r\n this.template = this.element;\r\n\r\n // Background is added as a separate element,\r\n // as animating opacity is faster than animating rgba()\r\n this.bg = createElement('pswp__bg', 'div', this.element);\r\n this.scrollWrap = createElement('pswp__scroll-wrap', 'section', this.element);\r\n this.container = createElement('pswp__container', 'div', this.scrollWrap);\r\n\r\n // aria pattern: carousel\r\n this.scrollWrap.setAttribute('aria-roledescription', 'carousel');\r\n this.container.setAttribute('aria-live', 'off');\r\n this.container.setAttribute('id', 'pswp__items');\r\n\r\n this.mainScroll.appendHolders();\r\n\r\n this.ui = new UI(this);\r\n this.ui.init();\r\n\r\n // append to DOM\r\n (this.options.appendToEl || document.body).appendChild(this.element);\r\n }\r\n\r\n\r\n /**\r\n * Get position and dimensions of small thumbnail\r\n * {x:,y:,w:}\r\n *\r\n * Height is optional (calculated based on the large image)\r\n *\r\n * @returns {Bounds | undefined}\r\n */\r\n getThumbBounds() {\r\n return getThumbBounds(\r\n this.currIndex,\r\n this.currSlide ? this.currSlide.data : this._initialItemData,\r\n this\r\n );\r\n }\r\n\r\n /**\r\n * If the PhotoSwipe can have continuous loop\r\n * @returns Boolean\r\n */\r\n canLoop() {\r\n return (this.options.loop && this.getNumItems() > 2);\r\n }\r\n\r\n /**\r\n * @private\r\n * @param {PhotoSwipeOptions} options\r\n * @returns {PreparedPhotoSwipeOptions}\r\n */\r\n _prepareOptions(options) {\r\n if (window.matchMedia('(prefers-reduced-motion), (update: slow)').matches) {\r\n options.showHideAnimationType = 'none';\r\n options.zoomAnimationDuration = 0;\r\n }\r\n\r\n /** @type {PreparedPhotoSwipeOptions} */\r\n return {\r\n ...defaultOptions,\r\n ...options\r\n };\r\n }\r\n}\r\n\r\nexport default PhotoSwipe;\r\n", "/*\nUnobtrusive JavaScript\nhttps://github.com/rails/rails/blob/main/actionview/app/javascript\nReleased under the MIT license\n */\n(function(global, factory) {\n typeof exports === \"object\" && typeof module !== \"undefined\" ? module.exports = factory() : typeof define === \"function\" && define.amd ? define(factory) : (global = typeof globalThis !== \"undefined\" ? globalThis : global || self, \n global.Rails = factory());\n})(this, (function() {\n \"use strict\";\n const linkClickSelector = \"a[data-confirm], a[data-method], a[data-remote]:not([disabled]), a[data-disable-with], a[data-disable]\";\n const buttonClickSelector = {\n selector: \"button[data-remote]:not([form]), button[data-confirm]:not([form])\",\n exclude: \"form button\"\n };\n const inputChangeSelector = \"select[data-remote], input[data-remote], textarea[data-remote]\";\n const formSubmitSelector = \"form:not([data-turbo=true])\";\n const 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 const 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 const 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 const fileInputSelector = \"input[name][type=file]:not([disabled])\";\n const linkDisableSelector = \"a[data-disable-with], a[data-disable]\";\n const buttonDisableSelector = \"button[data-remote][data-disable-with], button[data-remote][data-disable]\";\n let nonce = null;\n const loadCSPNonce = () => {\n const metaTag = document.querySelector(\"meta[name=csp-nonce]\");\n return nonce = metaTag && metaTag.content;\n };\n const cspNonce = () => nonce || loadCSPNonce();\n const m = Element.prototype.matches || Element.prototype.matchesSelector || Element.prototype.mozMatchesSelector || Element.prototype.msMatchesSelector || Element.prototype.oMatchesSelector || Element.prototype.webkitMatchesSelector;\n const matches = function(element, selector) {\n if (selector.exclude) {\n return m.call(element, selector.selector) && !m.call(element, selector.exclude);\n } else {\n return m.call(element, selector);\n }\n };\n const EXPANDO = \"_ujsData\";\n const getData = (element, key) => element[EXPANDO] ? element[EXPANDO][key] : undefined;\n const setData = function(element, key, value) {\n if (!element[EXPANDO]) {\n element[EXPANDO] = {};\n }\n return element[EXPANDO][key] = value;\n };\n const $ = selector => Array.prototype.slice.call(document.querySelectorAll(selector));\n const isContentEditable = function(element) {\n var isEditable = false;\n do {\n if (element.isContentEditable) {\n isEditable = true;\n break;\n }\n element = element.parentElement;\n } while (element);\n return isEditable;\n };\n const csrfToken = () => {\n const meta = document.querySelector(\"meta[name=csrf-token]\");\n return meta && meta.content;\n };\n const csrfParam = () => {\n const meta = document.querySelector(\"meta[name=csrf-param]\");\n return meta && meta.content;\n };\n const CSRFProtection = xhr => {\n const token = csrfToken();\n if (token) {\n return xhr.setRequestHeader(\"X-CSRF-Token\", token);\n }\n };\n const refreshCSRFTokens = () => {\n const token = csrfToken();\n const param = csrfParam();\n if (token && param) {\n return $('form input[name=\"' + param + '\"]').forEach((input => input.value = token));\n }\n };\n const 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 const ajax = options => {\n options = prepareOptions(options);\n var xhr = createXHR(options, (function() {\n const response = processResponse(xhr.response != null ? xhr.response : 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) : undefined;\n }));\n if (options.beforeSend && !options.beforeSend(xhr, options)) {\n return false;\n }\n if (xhr.readyState === XMLHttpRequest.OPENED) {\n return xhr.send(options.data);\n }\n };\n var 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 (!(options.dataType in AcceptHeaders)) {\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 var createXHR = function(options, done) {\n const 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 var processResponse = function(response, type) {\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 const 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 const parser = new DOMParser;\n type = type.replace(/;.+/, \"\");\n try {\n response = parser.parseFromString(response, type);\n } catch (error1) {}\n }\n }\n return response;\n };\n const href = element => element.href;\n const isCrossDomain = function(url) {\n const originAnchor = document.createElement(\"a\");\n originAnchor.href = location.href;\n const 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 (e) {\n return true;\n }\n };\n let preventDefault;\n let {CustomEvent: CustomEvent} = window;\n if (typeof CustomEvent !== \"function\") {\n CustomEvent = function(event, params) {\n const 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: preventDefault} = CustomEvent.prototype);\n CustomEvent.prototype.preventDefault = function() {\n const result = preventDefault.call(this);\n if (this.cancelable && !this.defaultPrevented) {\n Object.defineProperty(this, \"defaultPrevented\", {\n get() {\n return true;\n }\n });\n }\n return result;\n };\n }\n const fire = (obj, name, data) => {\n const event = new CustomEvent(name, {\n bubbles: true,\n cancelable: true,\n detail: data\n });\n obj.dispatchEvent(event);\n return !event.defaultPrevented;\n };\n const stopEverything = e => {\n fire(e.target, \"ujs:everythingStopped\");\n e.preventDefault();\n e.stopPropagation();\n e.stopImmediatePropagation();\n };\n const delegate = (element, selector, eventType, handler) => element.addEventListener(eventType, (function(e) {\n let {target: target} = e;\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 e.stopPropagation();\n }\n }));\n const toArray = e => Array.prototype.slice.call(e);\n const serializeElement = (element, additionalParam) => {\n let inputs = [ element ];\n if (matches(element, \"form\")) {\n inputs = toArray(element.elements);\n }\n const 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 toArray(input.options).forEach((function(option) {\n if (option.selected) {\n 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 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) {\n return `${encodeURIComponent(param.name)}=${encodeURIComponent(param.value)}`;\n } else {\n return param;\n }\n })).join(\"&\");\n };\n const formElements = (form, selector) => {\n if (matches(form, \"form\")) {\n return toArray(form.elements).filter((el => matches(el, selector)));\n } else {\n return toArray(form.querySelectorAll(selector));\n }\n };\n const handleConfirmWithRails = rails => function(e) {\n if (!allowAction(this, rails)) {\n stopEverything(e);\n }\n };\n const confirm = (message, element) => window.confirm(message);\n var allowAction = function(element, rails) {\n let callback;\n const message = element.getAttribute(\"data-confirm\");\n if (!message) {\n return true;\n }\n let 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 const handleDisabledElement = function(e) {\n const element = this;\n if (element.disabled) {\n stopEverything(e);\n }\n };\n const enableElement = e => {\n let 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, linkDisableSelector)) {\n return enableLinkElement(element);\n } else if (matches(element, buttonDisableSelector) || matches(element, formEnableSelector)) {\n return enableFormElement(element);\n } else if (matches(element, formSubmitSelector)) {\n return enableFormElements(element);\n }\n };\n const disableElement = e => {\n const element = e instanceof Event ? e.target : e;\n if (isContentEditable(element)) {\n return;\n }\n if (matches(element, linkDisableSelector)) {\n return disableLinkElement(element);\n } else if (matches(element, buttonDisableSelector) || matches(element, formDisableSelector)) {\n return disableFormElement(element);\n } else if (matches(element, formSubmitSelector)) {\n return disableFormElements(element);\n }\n };\n var disableLinkElement = function(element) {\n if (getData(element, \"ujs:disabled\")) {\n return;\n }\n const 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 var enableLinkElement = function(element) {\n const 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 var disableFormElements = form => formElements(form, formDisableSelector).forEach(disableFormElement);\n var disableFormElement = function(element) {\n if (getData(element, \"ujs:disabled\")) {\n return;\n }\n const 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 var enableFormElements = form => formElements(form, formEnableSelector).forEach((element => enableFormElement(element)));\n var enableFormElement = function(element) {\n const 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 var isXhrRedirect = function(event) {\n const xhr = event.detail ? event.detail[0] : undefined;\n return xhr && xhr.getResponseHeader(\"X-Xhr-Redirect\");\n };\n const handleMethodWithRails = rails => function(e) {\n const link = this;\n const method = link.getAttribute(\"data-method\");\n if (!method) {\n return;\n }\n if (isContentEditable(this)) {\n return;\n }\n const href = rails.href(link);\n const csrfToken$1 = csrfToken();\n const csrfParam$1 = csrfParam();\n const form = document.createElement(\"form\");\n let formContent = ``;\n if (csrfParam$1 && csrfToken$1 && !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 stopEverything(e);\n };\n const isRemote = function(element) {\n const value = element.getAttribute(\"data-remote\");\n return value != null && value !== \"false\";\n };\n const handleRemoteWithRails = rails => function(e) {\n let data, method, url;\n const 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 const withCredentials = element.getAttribute(\"data-with-credentials\");\n const dataType = element.getAttribute(\"data-type\") || \"script\";\n if (matches(element, formSubmitSelector)) {\n const button = getData(element, \"ujs:submit-button\");\n method = getData(element, \"ujs:submit-button-formmethod\") || element.getAttribute(\"method\") || \"get\";\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, buttonClickSelector) || matches(element, 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(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(...args) {\n return fire(element, \"ajax:success\", args);\n },\n error(...args) {\n return fire(element, \"ajax:error\", args);\n },\n complete(...args) {\n return fire(element, \"ajax:complete\", args);\n },\n crossDomain: isCrossDomain(url),\n withCredentials: withCredentials != null && withCredentials !== \"false\"\n });\n stopEverything(e);\n };\n const formSubmitButtonClick = function(e) {\n const button = this;\n const {form: form} = button;\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 const preventInsignificantClick = function(e) {\n const link = this;\n const method = (link.getAttribute(\"data-method\") || \"GET\").toUpperCase();\n const data = link.getAttribute(\"data-params\");\n const metaClick = e.metaKey || e.ctrlKey;\n const insignificantMetaClick = metaClick && method === \"GET\" && !data;\n const nonPrimaryMouseClick = e.button != null && e.button !== 0;\n if (nonPrimaryMouseClick || insignificantMetaClick) {\n e.stopImmediatePropagation();\n }\n };\n const Rails = {\n $: $,\n ajax: ajax,\n buttonClickSelector: buttonClickSelector,\n buttonDisableSelector: buttonDisableSelector,\n confirm: confirm,\n cspNonce: cspNonce,\n csrfToken: csrfToken,\n csrfParam: csrfParam,\n CSRFProtection: CSRFProtection,\n delegate: delegate,\n disableElement: disableElement,\n enableElement: enableElement,\n fileInputSelector: fileInputSelector,\n fire: fire,\n formElements: formElements,\n formEnableSelector: formEnableSelector,\n formDisableSelector: formDisableSelector,\n formInputClickSelector: formInputClickSelector,\n formSubmitButtonClick: formSubmitButtonClick,\n formSubmitSelector: formSubmitSelector,\n getData: getData,\n handleDisabledElement: handleDisabledElement,\n href: href,\n inputChangeSelector: inputChangeSelector,\n isCrossDomain: isCrossDomain,\n linkClickSelector: linkClickSelector,\n linkDisableSelector: linkDisableSelector,\n loadCSPNonce: loadCSPNonce,\n matches: matches,\n preventInsignificantClick: preventInsignificantClick,\n refreshCSRFTokens: refreshCSRFTokens,\n serializeElement: serializeElement,\n setData: setData,\n stopEverything: stopEverything\n };\n const handleConfirm = handleConfirmWithRails(Rails);\n Rails.handleConfirm = handleConfirm;\n const handleMethod = handleMethodWithRails(Rails);\n Rails.handleMethod = handleMethod;\n const handleRemote = handleRemoteWithRails(Rails);\n Rails.handleRemote = handleRemote;\n const start = function() {\n if (window._rails_loaded) {\n throw new Error(\"rails-ujs has already been loaded!\");\n }\n window.addEventListener(\"pageshow\", (function() {\n $(formEnableSelector).forEach((function(el) {\n if (getData(el, \"ujs:disabled\")) {\n enableElement(el);\n }\n }));\n $(linkDisableSelector).forEach((function(el) {\n if (getData(el, \"ujs:disabled\")) {\n enableElement(el);\n }\n }));\n }));\n delegate(document, linkDisableSelector, \"ajax:complete\", enableElement);\n delegate(document, linkDisableSelector, \"ajax:stopped\", enableElement);\n delegate(document, buttonDisableSelector, \"ajax:complete\", enableElement);\n delegate(document, buttonDisableSelector, \"ajax:stopped\", enableElement);\n delegate(document, linkClickSelector, \"click\", preventInsignificantClick);\n delegate(document, linkClickSelector, \"click\", handleDisabledElement);\n delegate(document, linkClickSelector, \"click\", handleConfirm);\n delegate(document, linkClickSelector, \"click\", disableElement);\n delegate(document, linkClickSelector, \"click\", handleRemote);\n delegate(document, linkClickSelector, \"click\", handleMethod);\n delegate(document, buttonClickSelector, \"click\", preventInsignificantClick);\n delegate(document, buttonClickSelector, \"click\", handleDisabledElement);\n delegate(document, buttonClickSelector, \"click\", handleConfirm);\n delegate(document, buttonClickSelector, \"click\", disableElement);\n delegate(document, buttonClickSelector, \"click\", handleRemote);\n delegate(document, inputChangeSelector, \"change\", handleDisabledElement);\n delegate(document, inputChangeSelector, \"change\", handleConfirm);\n delegate(document, inputChangeSelector, \"change\", handleRemote);\n delegate(document, formSubmitSelector, \"submit\", handleDisabledElement);\n delegate(document, formSubmitSelector, \"submit\", handleConfirm);\n delegate(document, formSubmitSelector, \"submit\", handleRemote);\n delegate(document, formSubmitSelector, \"submit\", (e => setTimeout((() => disableElement(e)), 13)));\n delegate(document, formSubmitSelector, \"ajax:send\", disableElement);\n delegate(document, formSubmitSelector, \"ajax:complete\", enableElement);\n delegate(document, formInputClickSelector, \"click\", preventInsignificantClick);\n delegate(document, formInputClickSelector, \"click\", handleDisabledElement);\n delegate(document, formInputClickSelector, \"click\", handleConfirm);\n delegate(document, formInputClickSelector, \"click\", formSubmitButtonClick);\n document.addEventListener(\"DOMContentLoaded\", refreshCSRFTokens);\n document.addEventListener(\"DOMContentLoaded\", loadCSPNonce);\n return window._rails_loaded = true;\n };\n Rails.start = start;\n if (typeof jQuery !== \"undefined\" && jQuery && jQuery.ajax) {\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 if (typeof exports !== \"object\" && typeof module === \"undefined\") {\n window.Rails = Rails;\n if (fire(document, \"rails:attachBindings\")) {\n start();\n }\n }\n return Rails;\n}));\n", "/*!\nTurbo 8.0.12\nCopyright \u00A9 2024 37signals LLC\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 ||\n 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();\n\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?.type == \"submit\" ? candidate : null\n}\n\nfunction clickCaptured(event) {\n const submitter = findSubmitterFromClickTarget(event.target);\n\n if (submitter && submitter.form) {\n submittersByForm.set(submitter.form, submitter);\n }\n}\n\n(function () {\n if (\"submitter\" in Event.prototype) return\n\n let prototype = window.Event.prototype;\n // Certain versions of Safari 15 have a bug where they won't\n // populate the submitter. This hurts TurboDrive's enable/disable detection.\n // See https://bugs.webkit.org/show_bug.cgi?id=229660\n if (\"SubmitEvent\" in window) {\n const prototypeOfSubmitEvent = window.SubmitEvent.prototype;\n\n if (/Apple Computer/.test(navigator.vendor) && !(\"submitter\" in prototypeOfSubmitEvent)) {\n prototype = prototypeOfSubmitEvent;\n } else {\n return // polyfill not needed\n }\n }\n\n addEventListener(\"click\", clickCaptured, true);\n\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\nconst FrameLoadingStyle = {\n eager: \"eager\",\n lazy: \"lazy\"\n};\n\n/**\n * Contains a fragment of HTML which is updated based on navigation within\n * it (e.g. via links or form submissions).\n *\n * @customElement turbo-frame\n * @example\n * \n * \n * Show all expanded messages in this frame.\n * \n *\n *
\n * Show response from this form within this frame.\n *
\n *
\n */\nclass FrameElement extends HTMLElement {\n static delegateConstructor = undefined\n\n loaded = Promise.resolve()\n\n static get observedAttributes() {\n return [\"disabled\", \"loading\", \"src\"]\n }\n\n constructor() {\n super();\n this.delegate = new FrameElement.delegateConstructor(this);\n }\n\n connectedCallback() {\n this.delegate.connect();\n }\n\n disconnectedCallback() {\n this.delegate.disconnect();\n }\n\n reload() {\n return this.delegate.sourceURLReloaded()\n }\n\n attributeChangedCallback(name) {\n if (name == \"loading\") {\n this.delegate.loadingStyleChanged();\n } else if (name == \"src\") {\n this.delegate.sourceURLChanged();\n } else if (name == \"disabled\") {\n this.delegate.disabledChanged();\n }\n }\n\n /**\n * Gets the URL to lazily load source HTML from\n */\n get src() {\n return this.getAttribute(\"src\")\n }\n\n /**\n * Sets the URL to lazily load source HTML from\n */\n set src(value) {\n if (value) {\n this.setAttribute(\"src\", value);\n } else {\n this.removeAttribute(\"src\");\n }\n }\n\n /**\n * Gets the refresh mode for the frame.\n */\n get refresh() {\n return this.getAttribute(\"refresh\")\n }\n\n /**\n * Sets the refresh mode for the frame.\n */\n set refresh(value) {\n if (value) {\n this.setAttribute(\"refresh\", value);\n } else {\n this.removeAttribute(\"refresh\");\n }\n }\n\n get shouldReloadWithMorph() {\n return this.src && this.refresh === \"morph\"\n }\n\n /**\n * Determines if the element is loading\n */\n get loading() {\n return frameLoadingStyleFromString(this.getAttribute(\"loading\") || \"\")\n }\n\n /**\n * Sets the value of if the element is loading\n */\n set loading(value) {\n if (value) {\n this.setAttribute(\"loading\", value);\n } else {\n this.removeAttribute(\"loading\");\n }\n }\n\n /**\n * Gets the disabled state of the frame.\n *\n * If disabled, no requests will be intercepted by the frame.\n */\n get disabled() {\n return this.hasAttribute(\"disabled\")\n }\n\n /**\n * Sets the disabled state of the frame.\n *\n * If disabled, no requests will be intercepted by the frame.\n */\n set disabled(value) {\n if (value) {\n this.setAttribute(\"disabled\", \"\");\n } else {\n this.removeAttribute(\"disabled\");\n }\n }\n\n /**\n * Gets the autoscroll state of the frame.\n *\n * If true, the frame will be scrolled into view automatically on update.\n */\n get autoscroll() {\n return this.hasAttribute(\"autoscroll\")\n }\n\n /**\n * Sets the autoscroll state of the frame.\n *\n * If true, the frame will be scrolled into view automatically on update.\n */\n set autoscroll(value) {\n if (value) {\n this.setAttribute(\"autoscroll\", \"\");\n } else {\n this.removeAttribute(\"autoscroll\");\n }\n }\n\n /**\n * Determines if the element has finished loading\n */\n get complete() {\n return !this.delegate.isLoading\n }\n\n /**\n * Gets the active state of the frame.\n *\n * If inactive, source changes will not be observed.\n */\n get isActive() {\n return this.ownerDocument === document && !this.isPreview\n }\n\n /**\n * Sets the active state of the frame.\n *\n * If inactive, source changes will not be observed.\n */\n get isPreview() {\n return this.ownerDocument?.documentElement?.hasAttribute(\"data-turbo-preview\")\n }\n}\n\nfunction frameLoadingStyleFromString(style) {\n switch (style.toLowerCase()) {\n case \"lazy\":\n return FrameLoadingStyle.lazy\n default:\n return FrameLoadingStyle.eager\n }\n}\n\nconst drive = {\n enabled: true,\n progressBarDelay: 500,\n unvisitableExtensions: new Set(\n [\n \".7z\", \".aac\", \".apk\", \".avi\", \".bmp\", \".bz2\", \".css\", \".csv\", \".deb\", \".dmg\", \".doc\",\n \".docx\", \".exe\", \".gif\", \".gz\", \".heic\", \".heif\", \".ico\", \".iso\", \".jpeg\", \".jpg\",\n \".js\", \".json\", \".m4a\", \".mkv\", \".mov\", \".mp3\", \".mp4\", \".mpeg\", \".mpg\", \".msi\",\n \".ogg\", \".ogv\", \".pdf\", \".pkg\", \".png\", \".ppt\", \".pptx\", \".rar\", \".rtf\",\n \".svg\", \".tar\", \".tif\", \".tiff\", \".txt\", \".wav\", \".webm\", \".webp\", \".wma\", \".wmv\",\n \".xls\", \".xlsx\", \".xml\", \".zip\"\n ]\n )\n};\n\nfunction activateScriptElement(element) {\n if (element.getAttribute(\"data-turbo-eval\") == \"false\") {\n return element\n } else {\n const createdScriptElement = document.createElement(\"script\");\n const cspNonce = getCspNonce();\n if (cspNonce) {\n createdScriptElement.nonce = cspNonce;\n }\n createdScriptElement.textContent = element.textContent;\n createdScriptElement.async = false;\n copyElementAttributes(createdScriptElement, element);\n return createdScriptElement\n }\n}\n\nfunction copyElementAttributes(destinationElement, sourceElement) {\n for (const { name, value } of sourceElement.attributes) {\n destinationElement.setAttribute(name, value);\n }\n}\n\nfunction createDocumentFragment(html) {\n const template = document.createElement(\"template\");\n template.innerHTML = html;\n return template.content\n}\n\nfunction dispatch(eventName, { target, cancelable, detail } = {}) {\n const event = new CustomEvent(eventName, {\n cancelable,\n bubbles: true,\n composed: true,\n detail\n });\n\n if (target && target.isConnected) {\n target.dispatchEvent(event);\n } else {\n document.documentElement.dispatchEvent(event);\n }\n\n return event\n}\n\nfunction cancelEvent(event) {\n event.preventDefault();\n event.stopImmediatePropagation();\n}\n\nfunction nextRepaint() {\n if (document.visibilityState === \"hidden\") {\n return nextEventLoopTick()\n } else {\n return nextAnimationFrame()\n }\n}\n\nfunction nextAnimationFrame() {\n return new Promise((resolve) => requestAnimationFrame(() => resolve()))\n}\n\nfunction nextEventLoopTick() {\n return new Promise((resolve) => setTimeout(() => resolve(), 0))\n}\n\nfunction nextMicrotask() {\n return Promise.resolve()\n}\n\nfunction parseHTMLDocument(html = \"\") {\n return new DOMParser().parseFromString(html, \"text/html\")\n}\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}\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}\n\nfunction uuid() {\n return Array.from({ length: 36 })\n .map((_, i) => {\n if (i == 8 || i == 13 || i == 18 || i == 23) {\n return \"-\"\n } else if (i == 14) {\n return \"4\"\n } else if (i == 19) {\n return (Math.floor(Math.random() * 4) + 8).toString(16)\n } else {\n return Math.floor(Math.random() * 15).toString(16)\n }\n })\n .join(\"\")\n}\n\nfunction getAttribute(attributeName, ...elements) {\n for (const value of elements.map((element) => element?.getAttribute(attributeName))) {\n if (typeof value == \"string\") return value\n }\n\n return null\n}\n\nfunction hasAttribute(attributeName, ...elements) {\n return elements.some((element) => element && element.hasAttribute(attributeName))\n}\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}\n\nfunction clearBusyState(...elements) {\n for (const element of elements) {\n if (element.localName == \"turbo-frame\") {\n element.removeAttribute(\"busy\");\n }\n\n element.removeAttribute(\"aria-busy\");\n }\n}\n\nfunction waitForLoad(element, timeoutInMilliseconds = 2000) {\n return new Promise((resolve) => {\n const onComplete = () => {\n element.removeEventListener(\"error\", onComplete);\n element.removeEventListener(\"load\", onComplete);\n resolve();\n };\n\n element.addEventListener(\"load\", onComplete, { once: true });\n element.addEventListener(\"error\", onComplete, { once: true });\n setTimeout(resolve, timeoutInMilliseconds);\n })\n}\n\nfunction getHistoryMethodForAction(action) {\n switch (action) {\n case \"replace\":\n return history.replaceState\n case \"advance\":\n case \"restore\":\n return history.pushState\n }\n}\n\nfunction isAction(action) {\n return action == \"advance\" || action == \"replace\" || action == \"restore\"\n}\n\nfunction getVisitAction(...elements) {\n const action = getAttribute(\"data-turbo-action\", ...elements);\n\n return isAction(action) ? action : null\n}\n\nfunction getMetaElement(name) {\n return document.querySelector(`meta[name=\"${name}\"]`)\n}\n\nfunction getMetaContent(name) {\n const element = getMetaElement(name);\n return element && element.content\n}\n\nfunction getCspNonce() {\n const element = getMetaElement(\"csp-nonce\");\n\n if (element) {\n const { nonce, content } = element;\n return nonce == \"\" ? content : nonce\n }\n}\n\nfunction setMetaContent(name, content) {\n let element = getMetaElement(name);\n\n if (!element) {\n element = document.createElement(\"meta\");\n element.setAttribute(\"name\", name);\n\n document.head.appendChild(element);\n }\n\n element.setAttribute(\"content\", content);\n\n return element\n}\n\nfunction findClosestRecursively(element, selector) {\n if (element instanceof Element) {\n return (\n element.closest(selector) || findClosestRecursively(element.assignedSlot || element.getRootNode()?.host, selector)\n )\n }\n}\n\nfunction elementIsFocusable(element) {\n const inertDisabledOrHidden = \"[inert], :disabled, [hidden], details:not([open]), dialog:not([open])\";\n\n return !!element && element.closest(inertDisabledOrHidden) == null && typeof element.focus == \"function\"\n}\n\nfunction queryAutofocusableElement(elementOrDocumentFragment) {\n return Array.from(elementOrDocumentFragment.querySelectorAll(\"[autofocus]\")).find(elementIsFocusable)\n}\n\nasync function around(callback, reader) {\n const before = reader();\n\n callback();\n\n await nextAnimationFrame();\n\n const after = reader();\n\n return [before, after]\n}\n\nfunction doesNotTargetIFrame(name) {\n if (name === \"_blank\") {\n return false\n } else if (name) {\n for (const element of document.getElementsByName(name)) {\n if (element instanceof HTMLIFrameElement) return false\n }\n\n return true\n } else {\n return true\n }\n}\n\nfunction findLinkFromClickTarget(target) {\n return findClosestRecursively(target, \"a[href]:not([target^=_]):not([download])\")\n}\n\nfunction getLocationForLink(link) {\n return expandURL(link.getAttribute(\"href\") || \"\")\n}\n\nfunction debounce(fn, delay) {\n let timeoutId = null;\n\n return (...args) => {\n const callback = () => fn.apply(this, args);\n clearTimeout(timeoutId);\n timeoutId = setTimeout(callback, delay);\n }\n}\n\nconst submitter = {\n \"aria-disabled\": {\n beforeSubmit: submitter => {\n submitter.setAttribute(\"aria-disabled\", \"true\");\n submitter.addEventListener(\"click\", cancelEvent);\n },\n\n afterSubmit: submitter => {\n submitter.removeAttribute(\"aria-disabled\");\n submitter.removeEventListener(\"click\", cancelEvent);\n }\n },\n\n \"disabled\": {\n beforeSubmit: submitter => submitter.disabled = true,\n afterSubmit: submitter => submitter.disabled = false\n }\n};\n\nclass Config {\n #submitter = null\n\n constructor(config) {\n Object.assign(this, config);\n }\n\n get submitter() {\n return this.#submitter\n }\n\n set submitter(value) {\n this.#submitter = submitter[value] || value;\n }\n}\n\nconst forms = new Config({\n mode: \"on\",\n submitter: \"disabled\"\n});\n\nconst config = {\n drive,\n forms\n};\n\nfunction expandURL(locatable) {\n return new URL(locatable.toString(), document.baseURI)\n}\n\nfunction getAnchor(url) {\n let anchorMatch;\n if (url.hash) {\n return url.hash.slice(1)\n // eslint-disable-next-line no-cond-assign\n } else if ((anchorMatch = url.href.match(/#(.*)$/))) {\n return anchorMatch[1]\n }\n}\n\nfunction getAction$1(form, submitter) {\n const action = submitter?.getAttribute(\"formaction\") || form.getAttribute(\"action\") || form.action;\n\n return expandURL(action)\n}\n\nfunction getExtension(url) {\n return (getLastPathComponent(url).match(/\\.[^.]*$/) || [])[0] || \"\"\n}\n\nfunction isPrefixedBy(baseURL, url) {\n const prefix = getPrefix(url);\n return baseURL.href === expandURL(prefix).href || baseURL.href.startsWith(prefix)\n}\n\nfunction locationIsVisitable(location, rootLocation) {\n return isPrefixedBy(location, rootLocation) && !config.drive.unvisitableExtensions.has(getExtension(location))\n}\n\nfunction getRequestURL(url) {\n const anchor = getAnchor(url);\n return anchor != null ? url.href.slice(0, -(anchor.length + 1)) : url.href\n}\n\nfunction toCacheKey(url) {\n return getRequestURL(url)\n}\n\nfunction urlsAreEqual(left, right) {\n return expandURL(left).href == expandURL(right).href\n}\n\nfunction getPathComponents(url) {\n return url.pathname.split(\"/\").slice(1)\n}\n\nfunction getLastPathComponent(url) {\n return getPathComponents(url).slice(-1)[0]\n}\n\nfunction getPrefix(url) {\n return addTrailingSlash(url.origin + url.pathname)\n}\n\nfunction addTrailingSlash(value) {\n return value.endsWith(\"/\") ? value : value + \"/\"\n}\n\nclass FetchResponse {\n constructor(response) {\n this.response = response;\n }\n\n get succeeded() {\n return this.response.ok\n }\n\n get failed() {\n return !this.succeeded\n }\n\n get clientError() {\n return this.statusCode >= 400 && this.statusCode <= 499\n }\n\n get serverError() {\n return this.statusCode >= 500 && this.statusCode <= 599\n }\n\n get redirected() {\n return this.response.redirected\n }\n\n get location() {\n return expandURL(this.response.url)\n }\n\n get isHTML() {\n return this.contentType && this.contentType.match(/^(?:text\\/([^\\s;,]+\\b)?html|application\\/xhtml\\+xml)\\b/)\n }\n\n get statusCode() {\n return this.response.status\n }\n\n get contentType() {\n return this.header(\"Content-Type\")\n }\n\n get responseText() {\n return this.response.clone().text()\n }\n\n get responseHTML() {\n if (this.isHTML) {\n return this.response.clone().text()\n } else {\n return Promise.resolve(undefined)\n }\n }\n\n header(name) {\n return this.response.headers.get(name)\n }\n}\n\nclass LimitedSet extends Set {\n constructor(maxSize) {\n super();\n this.maxSize = maxSize;\n }\n\n add(value) {\n if (this.size >= this.maxSize) {\n const iterator = this.values();\n const oldestValue = iterator.next().value;\n this.delete(oldestValue);\n }\n super.add(value);\n }\n}\n\nconst recentRequests = new LimitedSet(20);\n\nconst nativeFetch = window.fetch;\n\nfunction fetchWithTurboHeaders(url, options = {}) {\n const modifiedHeaders = new Headers(options.headers || {});\n const requestUID = uuid();\n recentRequests.add(requestUID);\n modifiedHeaders.append(\"X-Turbo-Request-Id\", requestUID);\n\n return nativeFetch(url, {\n ...options,\n headers: modifiedHeaders\n })\n}\n\nfunction fetchMethodFromString(method) {\n switch (method.toLowerCase()) {\n case \"get\":\n return FetchMethod.get\n case \"post\":\n return FetchMethod.post\n case \"put\":\n return FetchMethod.put\n case \"patch\":\n return FetchMethod.patch\n case \"delete\":\n return FetchMethod.delete\n }\n}\n\nconst FetchMethod = {\n get: \"get\",\n post: \"post\",\n put: \"put\",\n patch: \"patch\",\n delete: \"delete\"\n};\n\nfunction fetchEnctypeFromString(encoding) {\n switch (encoding.toLowerCase()) {\n case FetchEnctype.multipart:\n return FetchEnctype.multipart\n case FetchEnctype.plain:\n return FetchEnctype.plain\n default:\n return FetchEnctype.urlEncoded\n }\n}\n\nconst FetchEnctype = {\n urlEncoded: \"application/x-www-form-urlencoded\",\n multipart: \"multipart/form-data\",\n plain: \"text/plain\"\n};\n\nclass FetchRequest {\n abortController = new AbortController()\n #resolveRequestPromise = (_value) => {}\n\n constructor(delegate, method, location, requestBody = new URLSearchParams(), target = null, enctype = FetchEnctype.urlEncoded) {\n const [url, body] = buildResourceAndBody(expandURL(location), method, requestBody, enctype);\n\n this.delegate = delegate;\n this.url = url;\n this.target = target;\n this.fetchOptions = {\n credentials: \"same-origin\",\n redirect: \"follow\",\n method: method.toUpperCase(),\n headers: { ...this.defaultHeaders },\n body: body,\n signal: this.abortSignal,\n referrer: this.delegate.referrer?.href\n };\n this.enctype = enctype;\n }\n\n get method() {\n return this.fetchOptions.method\n }\n\n set method(value) {\n const fetchBody = this.isSafe ? this.url.searchParams : this.fetchOptions.body || new FormData();\n const fetchMethod = fetchMethodFromString(value) || FetchMethod.get;\n\n this.url.search = \"\";\n\n const [url, body] = buildResourceAndBody(this.url, fetchMethod, fetchBody, this.enctype);\n\n this.url = url;\n this.fetchOptions.body = body;\n this.fetchOptions.method = fetchMethod.toUpperCase();\n }\n\n get headers() {\n return this.fetchOptions.headers\n }\n\n set headers(value) {\n this.fetchOptions.headers = value;\n }\n\n get body() {\n if (this.isSafe) {\n return this.url.searchParams\n } else {\n return this.fetchOptions.body\n }\n }\n\n set body(value) {\n this.fetchOptions.body = value;\n }\n\n get location() {\n return this.url\n }\n\n get params() {\n return this.url.searchParams\n }\n\n get entries() {\n return this.body ? Array.from(this.body.entries()) : []\n }\n\n cancel() {\n this.abortController.abort();\n }\n\n async perform() {\n const { fetchOptions } = this;\n this.delegate.prepareRequest(this);\n const event = await this.#allowRequestToBeIntercepted(fetchOptions);\n try {\n this.delegate.requestStarted(this);\n\n if (event.detail.fetchRequest) {\n this.response = event.detail.fetchRequest.response;\n } else {\n this.response = fetchWithTurboHeaders(this.url.href, fetchOptions);\n }\n\n const response = await this.response;\n return await this.receive(response)\n } catch (error) {\n if (error.name !== \"AbortError\") {\n if (this.#willDelegateErrorHandling(error)) {\n this.delegate.requestErrored(this, error);\n }\n throw error\n }\n } finally {\n this.delegate.requestFinished(this);\n }\n }\n\n async receive(response) {\n const fetchResponse = new FetchResponse(response);\n const event = dispatch(\"turbo:before-fetch-response\", {\n cancelable: true,\n detail: { fetchResponse },\n target: this.target\n });\n if (event.defaultPrevented) {\n this.delegate.requestPreventedHandlingResponse(this, fetchResponse);\n } else if (fetchResponse.succeeded) {\n this.delegate.requestSucceededWithResponse(this, fetchResponse);\n } else {\n this.delegate.requestFailedWithResponse(this, fetchResponse);\n }\n return fetchResponse\n }\n\n get defaultHeaders() {\n return {\n Accept: \"text/html, application/xhtml+xml\"\n }\n }\n\n get isSafe() {\n return isSafe(this.method)\n }\n\n get abortSignal() {\n return this.abortController.signal\n }\n\n acceptResponseType(mimeType) {\n this.headers[\"Accept\"] = [mimeType, this.headers[\"Accept\"]].join(\", \");\n }\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 this.url = event.detail.url;\n if (event.defaultPrevented) await requestInterception;\n\n return event\n }\n\n #willDelegateErrorHandling(error) {\n const event = dispatch(\"turbo:fetch-request-error\", {\n target: this.target,\n cancelable: true,\n detail: { request: this, error: error }\n });\n\n return !event.defaultPrevented\n }\n}\n\nfunction isSafe(fetchMethod) {\n return fetchMethodFromString(fetchMethod) == FetchMethod.get\n}\n\nfunction buildResourceAndBody(resource, method, requestBody, enctype) {\n const searchParams =\n Array.from(requestBody).length > 0 ? new URLSearchParams(entriesExcludingFiles(requestBody)) : resource.searchParams;\n\n if (isSafe(method)) {\n return [mergeIntoURLSearchParams(resource, searchParams), null]\n } else if (enctype == FetchEnctype.urlEncoded) {\n return [resource, searchParams]\n } else {\n return [resource, requestBody]\n }\n}\n\nfunction entriesExcludingFiles(requestBody) {\n const entries = [];\n\n for (const [name, value] of requestBody) {\n if (value instanceof File) continue\n else entries.push([name, value]);\n }\n\n return entries\n}\n\nfunction mergeIntoURLSearchParams(url, requestBody) {\n const searchParams = new URLSearchParams(entriesExcludingFiles(requestBody));\n\n url.search = searchParams.toString();\n\n return url\n}\n\nclass AppearanceObserver {\n started = false\n\n constructor(delegate, element) {\n this.delegate = delegate;\n this.element = element;\n this.intersectionObserver = new IntersectionObserver(this.intersect);\n }\n\n start() {\n if (!this.started) {\n this.started = true;\n this.intersectionObserver.observe(this.element);\n }\n }\n\n stop() {\n if (this.started) {\n this.started = false;\n this.intersectionObserver.unobserve(this.element);\n }\n }\n\n intersect = (entries) => {\n const lastEntry = entries.slice(-1)[0];\n if (lastEntry?.isIntersecting) {\n this.delegate.elementAppearedInViewport(this.element);\n }\n }\n}\n\nclass StreamMessage {\n static contentType = \"text/vnd.turbo-stream.html\"\n\n static wrap(message) {\n if (typeof message == \"string\") {\n return new this(createDocumentFragment(message))\n } else {\n return message\n }\n }\n\n constructor(fragment) {\n this.fragment = importStreamElements(fragment);\n }\n}\n\nfunction importStreamElements(fragment) {\n for (const element of fragment.querySelectorAll(\"turbo-stream\")) {\n const streamElement = document.importNode(element, true);\n\n for (const inertScriptElement of streamElement.templateElement.content.querySelectorAll(\"script\")) {\n inertScriptElement.replaceWith(activateScriptElement(inertScriptElement));\n }\n\n element.replaceWith(streamElement);\n }\n\n return fragment\n}\n\nconst PREFETCH_DELAY = 100;\n\nclass PrefetchCache {\n #prefetchTimeout = null\n #prefetched = null\n\n get(url) {\n if (this.#prefetched && this.#prefetched.url === url && this.#prefetched.expire > Date.now()) {\n return this.#prefetched.request\n }\n }\n\n setLater(url, request, ttl) {\n this.clear();\n\n this.#prefetchTimeout = setTimeout(() => {\n request.perform();\n this.set(url, request, ttl);\n this.#prefetchTimeout = null;\n }, PREFETCH_DELAY);\n }\n\n set(url, request, ttl) {\n this.#prefetched = { url, request, expire: new Date(new Date().getTime() + ttl) };\n }\n\n clear() {\n if (this.#prefetchTimeout) clearTimeout(this.#prefetchTimeout);\n this.#prefetched = null;\n }\n}\n\nconst cacheTtl = 10 * 1000;\nconst prefetchCache = new PrefetchCache();\n\nconst FormSubmissionState = {\n initialized: \"initialized\",\n requesting: \"requesting\",\n waiting: \"waiting\",\n receiving: \"receiving\",\n stopping: \"stopping\",\n stopped: \"stopped\"\n};\n\nclass FormSubmission {\n state = FormSubmissionState.initialized\n\n static confirmMethod(message) {\n return Promise.resolve(confirm(message))\n }\n\n constructor(delegate, formElement, submitter, mustRedirect = false) {\n const method = getMethod(formElement, submitter);\n const action = getAction(getFormAction(formElement, submitter), method);\n const body = buildFormData(formElement, submitter);\n const enctype = getEnctype(formElement, submitter);\n\n this.delegate = delegate;\n this.formElement = formElement;\n this.submitter = submitter;\n this.fetchRequest = new FetchRequest(this, method, action, body, formElement, enctype);\n this.mustRedirect = mustRedirect;\n }\n\n get method() {\n return this.fetchRequest.method\n }\n\n set method(value) {\n this.fetchRequest.method = value;\n }\n\n get action() {\n return this.fetchRequest.url.toString()\n }\n\n set action(value) {\n this.fetchRequest.url = expandURL(value);\n }\n\n get body() {\n return this.fetchRequest.body\n }\n\n get enctype() {\n return this.fetchRequest.enctype\n }\n\n get isSafe() {\n return this.fetchRequest.isSafe\n }\n\n get location() {\n return this.fetchRequest.url\n }\n\n // The submission process\n\n async start() {\n const { initialized, requesting } = FormSubmissionState;\n const confirmationMessage = getAttribute(\"data-turbo-confirm\", this.submitter, this.formElement);\n\n if (typeof confirmationMessage === \"string\") {\n const confirmMethod = typeof config.forms.confirm === \"function\" ?\n config.forms.confirm :\n FormSubmission.confirmMethod;\n\n const answer = await confirmMethod(confirmationMessage, this.formElement, this.submitter);\n if (!answer) {\n return\n }\n }\n\n if (this.state == initialized) {\n this.state = requesting;\n return this.fetchRequest.perform()\n }\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\n // Fetch request delegate\n\n prepareRequest(request) {\n if (!request.isSafe) {\n const token = getCookieValue(getMetaContent(\"csrf-param\")) || getMetaContent(\"csrf-token\");\n if (token) {\n request.headers[\"X-CSRF-Token\"] = token;\n }\n }\n\n if (this.requestAcceptsTurboStreamResponse(request)) {\n request.acceptResponseType(StreamMessage.contentType);\n }\n }\n\n requestStarted(_request) {\n this.state = FormSubmissionState.waiting;\n if (this.submitter) config.forms.submitter.beforeSubmit(this.submitter);\n this.setSubmitsWith();\n markAsBusy(this.formElement);\n dispatch(\"turbo:submit-start\", {\n target: this.formElement,\n detail: { formSubmission: this }\n });\n this.delegate.formSubmissionStarted(this);\n }\n\n requestPreventedHandlingResponse(request, response) {\n prefetchCache.clear();\n\n this.result = { success: response.succeeded, fetchResponse: response };\n }\n\n requestSucceededWithResponse(request, response) {\n if (response.clientError || response.serverError) {\n this.delegate.formSubmissionFailedWithResponse(this, response);\n return\n }\n\n prefetchCache.clear();\n\n 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 } else {\n this.state = FormSubmissionState.receiving;\n this.result = { success: true, fetchResponse: response };\n this.delegate.formSubmissionSucceededWithResponse(this, response);\n }\n }\n\n requestFailedWithResponse(request, response) {\n this.result = { success: false, fetchResponse: response };\n this.delegate.formSubmissionFailedWithResponse(this, response);\n }\n\n requestErrored(request, error) {\n this.result = { success: false, error };\n this.delegate.formSubmissionErrored(this, error);\n }\n\n requestFinished(_request) {\n this.state = FormSubmissionState.stopped;\n if (this.submitter) config.forms.submitter.afterSubmit(this.submitter);\n this.resetSubmitterText();\n clearBusyState(this.formElement);\n dispatch(\"turbo:submit-end\", {\n target: this.formElement,\n detail: { formSubmission: this, ...this.result }\n });\n this.delegate.formSubmissionFinished(this);\n }\n\n // Private\n\n setSubmitsWith() {\n if (!this.submitter || !this.submitsWith) return\n\n if (this.submitter.matches(\"button\")) {\n this.originalSubmitText = this.submitter.innerHTML;\n this.submitter.innerHTML = this.submitsWith;\n } else if (this.submitter.matches(\"input\")) {\n const input = this.submitter;\n this.originalSubmitText = input.value;\n input.value = this.submitsWith;\n }\n }\n\n resetSubmitterText() {\n if (!this.submitter || !this.originalSubmitText) return\n\n if (this.submitter.matches(\"button\")) {\n this.submitter.innerHTML = this.originalSubmitText;\n } else if (this.submitter.matches(\"input\")) {\n const input = this.submitter;\n input.value = this.originalSubmitText;\n }\n }\n\n requestMustRedirect(request) {\n return !request.isSafe && this.mustRedirect\n }\n\n requestAcceptsTurboStreamResponse(request) {\n return !request.isSafe || hasAttribute(\"data-turbo-stream\", this.submitter, this.formElement)\n }\n\n get submitsWith() {\n return this.submitter?.getAttribute(\"data-turbo-submits-with\")\n }\n}\n\nfunction buildFormData(formElement, submitter) {\n const formData = new FormData(formElement);\n const name = submitter?.getAttribute(\"name\");\n const value = submitter?.getAttribute(\"value\");\n\n if (name) {\n formData.append(name, value || \"\");\n }\n\n return formData\n}\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}\n\nfunction responseSucceededWithoutRedirect(response) {\n return response.statusCode == 200 && !response.redirected\n}\n\nfunction getFormAction(formElement, submitter) {\n const formElementAction = typeof formElement.action === \"string\" ? formElement.action : null;\n\n if (submitter?.hasAttribute(\"formaction\")) {\n return submitter.getAttribute(\"formaction\") || \"\"\n } else {\n return formElement.getAttribute(\"action\") || formElementAction || \"\"\n }\n}\n\nfunction getAction(formAction, fetchMethod) {\n const action = expandURL(formAction);\n\n if (isSafe(fetchMethod)) {\n action.search = \"\";\n }\n\n return action\n}\n\nfunction getMethod(formElement, submitter) {\n const method = submitter?.getAttribute(\"formmethod\") || formElement.getAttribute(\"method\") || \"\";\n return fetchMethodFromString(method.toLowerCase()) || FetchMethod.get\n}\n\nfunction getEnctype(formElement, submitter) {\n return fetchEnctypeFromString(submitter?.getAttribute(\"formenctype\") || formElement.enctype)\n}\n\nclass Snapshot {\n constructor(element) {\n this.element = element;\n }\n\n get activeElement() {\n return this.element.ownerDocument.activeElement\n }\n\n get children() {\n return [...this.element.children]\n }\n\n hasAnchor(anchor) {\n return this.getElementForAnchor(anchor) != null\n }\n\n getElementForAnchor(anchor) {\n return anchor ? this.element.querySelector(`[id='${anchor}'], a[name='${anchor}']`) : null\n }\n\n get isConnected() {\n return this.element.isConnected\n }\n\n get firstAutofocusableElement() {\n return queryAutofocusableElement(this.element)\n }\n\n get permanentElements() {\n return queryPermanentElementsAll(this.element)\n }\n\n getPermanentElementById(id) {\n return getPermanentElementById(this.element, id)\n }\n\n getPermanentElementMapForSnapshot(snapshot) {\n const permanentElementMap = {};\n\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\n return permanentElementMap\n }\n}\n\nfunction getPermanentElementById(node, id) {\n return node.querySelector(`#${id}[data-turbo-permanent]`)\n}\n\nfunction queryPermanentElementsAll(node) {\n return node.querySelectorAll(\"[id][data-turbo-permanent]\")\n}\n\nclass FormSubmitObserver {\n started = false\n\n constructor(delegate, eventTarget) {\n this.delegate = delegate;\n this.eventTarget = eventTarget;\n }\n\n start() {\n if (!this.started) {\n this.eventTarget.addEventListener(\"submit\", this.submitCaptured, true);\n this.started = true;\n }\n }\n\n stop() {\n if (this.started) {\n this.eventTarget.removeEventListener(\"submit\", this.submitCaptured, true);\n this.started = false;\n }\n }\n\n submitCaptured = () => {\n this.eventTarget.removeEventListener(\"submit\", this.submitBubbled, false);\n this.eventTarget.addEventListener(\"submit\", this.submitBubbled, false);\n }\n\n submitBubbled = (event) => {\n if (!event.defaultPrevented) {\n const form = event.target instanceof HTMLFormElement ? event.target : undefined;\n const submitter = event.submitter || undefined;\n\n if (\n form &&\n submissionDoesNotDismissDialog(form, submitter) &&\n submissionDoesNotTargetIFrame(form, submitter) &&\n this.delegate.willSubmitForm(form, submitter)\n ) {\n event.preventDefault();\n event.stopImmediatePropagation();\n this.delegate.formSubmitted(form, submitter);\n }\n }\n }\n}\n\nfunction submissionDoesNotDismissDialog(form, submitter) {\n const method = submitter?.getAttribute(\"formmethod\") || form.getAttribute(\"method\");\n\n return method != \"dialog\"\n}\n\nfunction submissionDoesNotTargetIFrame(form, submitter) {\n const target = submitter?.getAttribute(\"formtarget\") || form.getAttribute(\"target\");\n\n return doesNotTargetIFrame(target)\n}\n\nclass View {\n #resolveRenderPromise = (_value) => {}\n #resolveInterceptionPromise = (_value) => {}\n\n constructor(delegate, element) {\n this.delegate = delegate;\n this.element = element;\n }\n\n // Scrolling\n\n scrollToAnchor(anchor) {\n const element = this.snapshot.getElementForAnchor(anchor);\n if (element) {\n this.scrollToElement(element);\n this.focusElement(element);\n } else {\n this.scrollToPosition({ x: 0, y: 0 });\n }\n }\n\n scrollToAnchorFromLocation(location) {\n this.scrollToAnchor(getAnchor(location));\n }\n\n scrollToElement(element) {\n element.scrollIntoView();\n }\n\n focusElement(element) {\n if (element instanceof HTMLElement) {\n if (element.hasAttribute(\"tabindex\")) {\n element.focus();\n } else {\n element.setAttribute(\"tabindex\", \"-1\");\n element.focus();\n element.removeAttribute(\"tabindex\");\n }\n }\n }\n\n scrollToPosition({ x, y }) {\n this.scrollRoot.scrollTo(x, y);\n }\n\n scrollToTop() {\n this.scrollToPosition({ x: 0, y: 0 });\n }\n\n get scrollRoot() {\n return window\n }\n\n // Rendering\n\n async render(renderer) {\n const { isPreview, shouldRender, willRender, newSnapshot: snapshot } = renderer;\n\n // A workaround to ignore tracked element mismatch reloads when performing\n // a promoted Visit from a frame navigation\n const shouldInvalidate = willRender;\n\n if (shouldRender) {\n try {\n this.renderPromise = new Promise((resolve) => (this.#resolveRenderPromise = resolve));\n this.renderer = renderer;\n await this.prepareToRenderSnapshot(renderer);\n\n const renderInterception = new Promise((resolve) => (this.#resolveInterceptionPromise = resolve));\n const options = { resume: this.#resolveInterceptionPromise, render: this.renderer.renderElement, renderMethod: this.renderer.renderMethod };\n const immediateRender = this.delegate.allowsImmediateRender(snapshot, options);\n if (!immediateRender) await renderInterception;\n\n await this.renderSnapshot(renderer);\n this.delegate.viewRenderedSnapshot(snapshot, isPreview, this.renderer.renderMethod);\n this.delegate.preloadOnLoadLinksForView(this.element);\n this.finishRenderingSnapshot(renderer);\n } finally {\n delete this.renderer;\n this.#resolveRenderPromise(undefined);\n delete this.renderPromise;\n }\n } else if (shouldInvalidate) {\n this.invalidate(renderer.reloadReason);\n }\n }\n\n invalidate(reason) {\n this.delegate.viewInvalidated(reason);\n }\n\n async prepareToRenderSnapshot(renderer) {\n this.markAsPreview(renderer.isPreview);\n await renderer.prepareToRender();\n }\n\n markAsPreview(isPreview) {\n if (isPreview) {\n this.element.setAttribute(\"data-turbo-preview\", \"\");\n } else {\n this.element.removeAttribute(\"data-turbo-preview\");\n }\n }\n\n markVisitDirection(direction) {\n this.element.setAttribute(\"data-turbo-visit-direction\", direction);\n }\n\n unmarkVisitDirection() {\n this.element.removeAttribute(\"data-turbo-visit-direction\");\n }\n\n async renderSnapshot(renderer) {\n await renderer.render();\n }\n\n finishRenderingSnapshot(renderer) {\n renderer.finishRendering();\n }\n}\n\nclass FrameView extends View {\n missing() {\n this.element.innerHTML = `Content missing`;\n }\n\n get snapshot() {\n return new Snapshot(this.element)\n }\n}\n\nclass LinkInterceptor {\n constructor(delegate, element) {\n this.delegate = delegate;\n this.element = element;\n }\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\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\n clickBubbled = (event) => {\n if (this.clickEventIsSignificant(event)) {\n this.clickEvent = event;\n } else {\n delete this.clickEvent;\n }\n }\n\n linkClicked = (event) => {\n if (this.clickEvent && this.clickEventIsSignificant(event)) {\n if (this.delegate.shouldInterceptLinkClick(event.target, event.detail.url, event.detail.originalEvent)) {\n this.clickEvent.preventDefault();\n event.preventDefault();\n this.delegate.linkClickIntercepted(event.target, event.detail.url, event.detail.originalEvent);\n }\n }\n delete this.clickEvent;\n }\n\n willVisit = (_event) => {\n delete this.clickEvent;\n }\n\n clickEventIsSignificant(event) {\n const target = event.composed ? event.target?.parentElement : event.target;\n const element = findLinkFromClickTarget(target) || target;\n\n return element instanceof Element && element.closest(\"turbo-frame, html\") == this.element\n }\n}\n\nclass LinkClickObserver {\n started = false\n\n constructor(delegate, eventTarget) {\n this.delegate = delegate;\n this.eventTarget = eventTarget;\n }\n\n start() {\n if (!this.started) {\n this.eventTarget.addEventListener(\"click\", this.clickCaptured, true);\n this.started = true;\n }\n }\n\n stop() {\n if (this.started) {\n this.eventTarget.removeEventListener(\"click\", this.clickCaptured, true);\n this.started = false;\n }\n }\n\n clickCaptured = () => {\n this.eventTarget.removeEventListener(\"click\", this.clickBubbled, false);\n this.eventTarget.addEventListener(\"click\", this.clickBubbled, false);\n }\n\n clickBubbled = (event) => {\n if (event instanceof MouseEvent && this.clickEventIsSignificant(event)) {\n const target = (event.composedPath && event.composedPath()[0]) || event.target;\n const link = findLinkFromClickTarget(target);\n if (link && doesNotTargetIFrame(link.target)) {\n const location = getLocationForLink(link);\n if (this.delegate.willFollowLinkToLocation(link, location, event)) {\n event.preventDefault();\n this.delegate.followedLinkToLocation(link, location);\n }\n }\n }\n }\n\n clickEventIsSignificant(event) {\n return !(\n (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 }\n}\n\nclass FormLinkClickObserver {\n constructor(delegate, element) {\n this.delegate = delegate;\n this.linkInterceptor = new LinkClickObserver(this, element);\n }\n\n start() {\n this.linkInterceptor.start();\n }\n\n stop() {\n this.linkInterceptor.stop();\n }\n\n // Link hover observer delegate\n\n canPrefetchRequestToLocation(link, location) {\n return false\n }\n\n prefetchAndCacheRequestToLocation(link, location) {\n return\n }\n\n // Link click observer delegate\n\n willFollowLinkToLocation(link, location, originalEvent) {\n return (\n this.delegate.willSubmitFormLinkToLocation(link, location, originalEvent) &&\n (link.hasAttribute(\"data-turbo-method\") || link.hasAttribute(\"data-turbo-stream\"))\n )\n }\n\n followedLinkToLocation(link, location) {\n const form = document.createElement(\"form\");\n\n const type = \"hidden\";\n for (const [name, value] of location.searchParams) {\n form.append(Object.assign(document.createElement(\"input\"), { type, name, value }));\n }\n\n const action = Object.assign(location, { search: \"\" });\n form.setAttribute(\"data-turbo\", \"true\");\n form.setAttribute(\"action\", action.href);\n form.setAttribute(\"hidden\", \"\");\n\n const method = link.getAttribute(\"data-turbo-method\");\n if (method) form.setAttribute(\"method\", method);\n\n const turboFrame = link.getAttribute(\"data-turbo-frame\");\n if (turboFrame) form.setAttribute(\"data-turbo-frame\", turboFrame);\n\n const turboAction = getVisitAction(link);\n if (turboAction) form.setAttribute(\"data-turbo-action\", turboAction);\n\n const turboConfirm = link.getAttribute(\"data-turbo-confirm\");\n if (turboConfirm) form.setAttribute(\"data-turbo-confirm\", turboConfirm);\n\n const turboStream = link.hasAttribute(\"data-turbo-stream\");\n if (turboStream) form.setAttribute(\"data-turbo-stream\", \"\");\n\n this.delegate.submittedFormLinkToLocation(link, location, form);\n\n document.body.appendChild(form);\n form.addEventListener(\"turbo:submit-end\", () => form.remove(), { once: true });\n requestAnimationFrame(() => form.requestSubmit());\n }\n}\n\nclass Bardo {\n static async preservingPermanentElements(delegate, permanentElementMap, callback) {\n const bardo = new this(delegate, permanentElementMap);\n bardo.enter();\n await callback();\n bardo.leave();\n }\n\n constructor(delegate, permanentElementMap) {\n this.delegate = delegate;\n this.permanentElementMap = permanentElementMap;\n }\n\n enter() {\n for (const id in this.permanentElementMap) {\n const [currentPermanentElement, newPermanentElement] = this.permanentElementMap[id];\n this.delegate.enteringBardo(currentPermanentElement, newPermanentElement);\n this.replaceNewPermanentElementWithPlaceholder(newPermanentElement);\n }\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 this.delegate.leavingBardo(currentPermanentElement);\n }\n }\n\n replaceNewPermanentElementWithPlaceholder(permanentElement) {\n const placeholder = createPlaceholderForPermanentElement(permanentElement);\n permanentElement.replaceWith(placeholder);\n }\n\n replaceCurrentPermanentElementWithClone(permanentElement) {\n const clone = permanentElement.cloneNode(true);\n permanentElement.replaceWith(clone);\n }\n\n replacePlaceholderWithPermanentElement(permanentElement) {\n const placeholder = this.getPlaceholderById(permanentElement.id);\n placeholder?.replaceWith(permanentElement);\n }\n\n getPlaceholderById(id) {\n return this.placeholders.find((element) => element.content == id)\n }\n\n get placeholders() {\n return [...document.querySelectorAll(\"meta[name=turbo-permanent-placeholder][content]\")]\n }\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 #activeElement = null\n\n static renderElement(currentElement, newElement) {\n // Abstract method\n }\n\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.renderElement = this.constructor.renderElement;\n this.promise = new Promise((resolve, reject) => (this.resolvingFunctions = { resolve, reject }));\n }\n\n get shouldRender() {\n return true\n }\n\n get shouldAutofocus() {\n return true\n }\n\n get reloadReason() {\n return\n }\n\n prepareToRender() {\n return\n }\n\n render() {\n // Abstract method\n }\n\n finishRendering() {\n if (this.resolvingFunctions) {\n this.resolvingFunctions.resolve();\n delete this.resolvingFunctions;\n }\n }\n\n async preservingPermanentElements(callback) {\n await Bardo.preservingPermanentElements(this, this.permanentElementMap, callback);\n }\n\n focusFirstAutofocusableElement() {\n if (this.shouldAutofocus) {\n const element = this.connectedSnapshot.firstAutofocusableElement;\n if (element) {\n element.focus();\n }\n }\n }\n\n // Bardo delegate\n\n enteringBardo(currentPermanentElement) {\n if (this.#activeElement) return\n\n if (currentPermanentElement.contains(this.currentSnapshot.activeElement)) {\n this.#activeElement = this.currentSnapshot.activeElement;\n }\n }\n\n leavingBardo(currentPermanentElement) {\n if (currentPermanentElement.contains(this.#activeElement) && this.#activeElement instanceof HTMLElement) {\n this.#activeElement.focus();\n\n this.#activeElement = null;\n }\n }\n\n get connectedSnapshot() {\n return this.newSnapshot.isConnected ? this.newSnapshot : this.currentSnapshot\n }\n\n get currentElement() {\n return this.currentSnapshot.element\n }\n\n get newElement() {\n return this.newSnapshot.element\n }\n\n get permanentElementMap() {\n return this.currentSnapshot.getPermanentElementMapForSnapshot(this.newSnapshot)\n }\n\n get renderMethod() {\n return \"replace\"\n }\n}\n\nclass FrameRenderer extends Renderer {\n static renderElement(currentElement, newElement) {\n const destinationRange = document.createRange();\n destinationRange.selectNodeContents(currentElement);\n destinationRange.deleteContents();\n\n const frameElement = newElement;\n const sourceRange = frameElement.ownerDocument?.createRange();\n if (sourceRange) {\n sourceRange.selectNodeContents(frameElement);\n currentElement.appendChild(sourceRange.extractContents());\n }\n }\n\n constructor(delegate, currentSnapshot, newSnapshot, renderElement, isPreview, willRender = true) {\n super(currentSnapshot, newSnapshot, renderElement, isPreview, willRender);\n this.delegate = delegate;\n }\n\n get shouldRender() {\n return true\n }\n\n async render() {\n await nextRepaint();\n this.preservingPermanentElements(() => {\n this.loadFrameElement();\n });\n this.scrollFrameIntoView();\n await nextRepaint();\n this.focusFirstAutofocusableElement();\n await nextRepaint();\n this.activateScriptElements();\n }\n\n loadFrameElement() {\n this.delegate.willRenderFrame(this.currentElement, this.newElement);\n this.renderElement(this.currentElement, this.newElement);\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 const behavior = readScrollBehavior(this.currentElement.getAttribute(\"data-autoscroll-behavior\"), \"auto\");\n\n if (element) {\n element.scrollIntoView({ block, behavior });\n return true\n }\n }\n return false\n }\n\n activateScriptElements() {\n for (const inertScriptElement of this.newScriptElements) {\n const activatedScriptElement = activateScriptElement(inertScriptElement);\n inertScriptElement.replaceWith(activatedScriptElement);\n }\n }\n\n get newScriptElements() {\n return this.currentElement.querySelectorAll(\"script\")\n }\n}\n\nfunction readScrollLogicalPosition(value, defaultValue) {\n if (value == \"end\" || value == \"start\" || value == \"center\" || value == \"nearest\") {\n return value\n } else {\n return defaultValue\n }\n}\n\nfunction readScrollBehavior(value, defaultValue) {\n if (value == \"auto\" || value == \"smooth\") {\n return value\n } else {\n return defaultValue\n }\n}\n\n// base IIFE to define idiomorph\nvar Idiomorph = (function () {\n\n //=============================================================================\n // AND NOW IT BEGINS...\n //=============================================================================\n let EMPTY_SET = new Set();\n\n // default configuration values, updatable by users now\n let defaults = {\n morphStyle: \"outerHTML\",\n callbacks : {\n beforeNodeAdded: noOp,\n afterNodeAdded: noOp,\n beforeNodeMorphed: noOp,\n afterNodeMorphed: noOp,\n beforeNodeRemoved: noOp,\n afterNodeRemoved: noOp,\n beforeAttributeUpdated: noOp,\n\n },\n head: {\n style: 'merge',\n shouldPreserve: function (elt) {\n return elt.getAttribute(\"im-preserve\") === \"true\";\n },\n shouldReAppend: function (elt) {\n return elt.getAttribute(\"im-re-append\") === \"true\";\n },\n shouldRemove: noOp,\n afterHeadMorphed: noOp,\n }\n };\n\n //=============================================================================\n // Core Morphing Algorithm - morph, morphNormalizedContent, morphOldNodeTo, morphChildren\n //=============================================================================\n function morph(oldNode, newContent, config = {}) {\n\n if (oldNode instanceof Document) {\n oldNode = oldNode.documentElement;\n }\n\n if (typeof newContent === 'string') {\n newContent = parseContent(newContent);\n }\n\n let normalizedContent = normalizeContent(newContent);\n\n let ctx = createMorphContext(oldNode, normalizedContent, config);\n\n return morphNormalizedContent(oldNode, normalizedContent, ctx);\n }\n\n function morphNormalizedContent(oldNode, normalizedNewContent, ctx) {\n if (ctx.head.block) {\n let oldHead = oldNode.querySelector('head');\n let newHead = normalizedNewContent.querySelector('head');\n if (oldHead && newHead) {\n let promises = handleHeadElement(newHead, oldHead, ctx);\n // when head promises resolve, call morph again, ignoring the head tag\n Promise.all(promises).then(function () {\n morphNormalizedContent(oldNode, normalizedNewContent, Object.assign(ctx, {\n head: {\n block: false,\n ignore: true\n }\n }));\n });\n return;\n }\n }\n\n if (ctx.morphStyle === \"innerHTML\") {\n\n // innerHTML, so we are only updating the children\n morphChildren(normalizedNewContent, oldNode, ctx);\n return oldNode.children;\n\n } else if (ctx.morphStyle === \"outerHTML\" || ctx.morphStyle == null) {\n // otherwise find the best element match in the new content, morph that, and merge its siblings\n // into either side of the best match\n let bestMatch = findBestNodeMatch(normalizedNewContent, oldNode, ctx);\n\n // stash the siblings that will need to be inserted on either side of the best match\n let previousSibling = bestMatch?.previousSibling;\n let nextSibling = bestMatch?.nextSibling;\n\n // morph it\n let morphedNode = morphOldNodeTo(oldNode, bestMatch, ctx);\n\n if (bestMatch) {\n // if there was a best match, merge the siblings in too and return the\n // whole bunch\n return insertSiblings(previousSibling, morphedNode, nextSibling);\n } else {\n // otherwise nothing was added to the DOM\n return []\n }\n } else {\n throw \"Do not understand how to morph style \" + ctx.morphStyle;\n }\n }\n\n\n /**\n * @param possibleActiveElement\n * @param ctx\n * @returns {boolean}\n */\n function ignoreValueOfActiveElement(possibleActiveElement, ctx) {\n return ctx.ignoreActiveValue && possibleActiveElement === document.activeElement && possibleActiveElement !== document.body;\n }\n\n /**\n * @param oldNode root node to merge content into\n * @param newContent new content to merge\n * @param ctx the merge context\n * @returns {Element} the element that ended up in the DOM\n */\n function morphOldNodeTo(oldNode, newContent, ctx) {\n if (ctx.ignoreActive && oldNode === document.activeElement) ; else if (newContent == null) {\n if (ctx.callbacks.beforeNodeRemoved(oldNode) === false) return oldNode;\n\n oldNode.remove();\n ctx.callbacks.afterNodeRemoved(oldNode);\n return null;\n } else if (!isSoftMatch(oldNode, newContent)) {\n if (ctx.callbacks.beforeNodeRemoved(oldNode) === false) return oldNode;\n if (ctx.callbacks.beforeNodeAdded(newContent) === false) return oldNode;\n\n oldNode.parentElement.replaceChild(newContent, oldNode);\n ctx.callbacks.afterNodeAdded(newContent);\n ctx.callbacks.afterNodeRemoved(oldNode);\n return newContent;\n } else {\n if (ctx.callbacks.beforeNodeMorphed(oldNode, newContent) === false) return oldNode;\n\n if (oldNode instanceof HTMLHeadElement && ctx.head.ignore) ; else if (oldNode instanceof HTMLHeadElement && ctx.head.style !== \"morph\") {\n handleHeadElement(newContent, oldNode, ctx);\n } else {\n syncNodeFrom(newContent, oldNode, ctx);\n if (!ignoreValueOfActiveElement(oldNode, ctx)) {\n morphChildren(newContent, oldNode, ctx);\n }\n }\n ctx.callbacks.afterNodeMorphed(oldNode, newContent);\n return oldNode;\n }\n }\n\n /**\n * This is the core algorithm for matching up children. The idea is to use id sets to try to match up\n * nodes as faithfully as possible. We greedily match, which allows us to keep the algorithm fast, but\n * by using id sets, we are able to better match up with content deeper in the DOM.\n *\n * Basic algorithm is, for each node in the new content:\n *\n * - if we have reached the end of the old parent, append the new content\n * - if the new content has an id set match with the current insertion point, morph\n * - search for an id set match\n * - if id set match found, morph\n * - otherwise search for a \"soft\" match\n * - if a soft match is found, morph\n * - otherwise, prepend the new node before the current insertion point\n *\n * The two search algorithms terminate if competing node matches appear to outweigh what can be achieved\n * with the current node. See findIdSetMatch() and findSoftMatch() for details.\n *\n * @param {Element} newParent the parent element of the new content\n * @param {Element } oldParent the old content that we are merging the new content into\n * @param ctx the merge context\n */\n function morphChildren(newParent, oldParent, ctx) {\n\n let nextNewChild = newParent.firstChild;\n let insertionPoint = oldParent.firstChild;\n let newChild;\n\n // run through all the new content\n while (nextNewChild) {\n\n newChild = nextNewChild;\n nextNewChild = newChild.nextSibling;\n\n // if we are at the end of the exiting parent's children, just append\n if (insertionPoint == null) {\n if (ctx.callbacks.beforeNodeAdded(newChild) === false) return;\n\n oldParent.appendChild(newChild);\n ctx.callbacks.afterNodeAdded(newChild);\n removeIdsFromConsideration(ctx, newChild);\n continue;\n }\n\n // if the current node has an id set match then morph\n if (isIdSetMatch(newChild, insertionPoint, ctx)) {\n morphOldNodeTo(insertionPoint, newChild, ctx);\n insertionPoint = insertionPoint.nextSibling;\n removeIdsFromConsideration(ctx, newChild);\n continue;\n }\n\n // otherwise search forward in the existing old children for an id set match\n let idSetMatch = findIdSetMatch(newParent, oldParent, newChild, insertionPoint, ctx);\n\n // if we found a potential match, remove the nodes until that point and morph\n if (idSetMatch) {\n insertionPoint = removeNodesBetween(insertionPoint, idSetMatch, ctx);\n morphOldNodeTo(idSetMatch, newChild, ctx);\n removeIdsFromConsideration(ctx, newChild);\n continue;\n }\n\n // no id set match found, so scan forward for a soft match for the current node\n let softMatch = findSoftMatch(newParent, oldParent, newChild, insertionPoint, ctx);\n\n // if we found a soft match for the current node, morph\n if (softMatch) {\n insertionPoint = removeNodesBetween(insertionPoint, softMatch, ctx);\n morphOldNodeTo(softMatch, newChild, ctx);\n removeIdsFromConsideration(ctx, newChild);\n continue;\n }\n\n // abandon all hope of morphing, just insert the new child before the insertion point\n // and move on\n if (ctx.callbacks.beforeNodeAdded(newChild) === false) return;\n\n oldParent.insertBefore(newChild, insertionPoint);\n ctx.callbacks.afterNodeAdded(newChild);\n removeIdsFromConsideration(ctx, newChild);\n }\n\n // remove any remaining old nodes that didn't match up with new content\n while (insertionPoint !== null) {\n\n let tempNode = insertionPoint;\n insertionPoint = insertionPoint.nextSibling;\n removeNode(tempNode, ctx);\n }\n }\n\n //=============================================================================\n // Attribute Syncing Code\n //=============================================================================\n\n /**\n * @param attr {String} the attribute to be mutated\n * @param to {Element} the element that is going to be updated\n * @param updateType {(\"update\"|\"remove\")}\n * @param ctx the merge context\n * @returns {boolean} true if the attribute should be ignored, false otherwise\n */\n function ignoreAttribute(attr, to, updateType, ctx) {\n if(attr === 'value' && ctx.ignoreActiveValue && to === document.activeElement){\n return true;\n }\n return ctx.callbacks.beforeAttributeUpdated(attr, to, updateType) === false;\n }\n\n /**\n * syncs a given node with another node, copying over all attributes and\n * inner element state from the 'from' node to the 'to' node\n *\n * @param {Element} from the element to copy attributes & state from\n * @param {Element} to the element to copy attributes & state to\n * @param ctx the merge context\n */\n function syncNodeFrom(from, to, ctx) {\n let type = from.nodeType;\n\n // if is an element type, sync the attributes from the\n // new node into the new node\n if (type === 1 /* element type */) {\n const fromAttributes = from.attributes;\n const toAttributes = to.attributes;\n for (const fromAttribute of fromAttributes) {\n if (ignoreAttribute(fromAttribute.name, to, 'update', ctx)) {\n continue;\n }\n if (to.getAttribute(fromAttribute.name) !== fromAttribute.value) {\n to.setAttribute(fromAttribute.name, fromAttribute.value);\n }\n }\n // iterate backwards to avoid skipping over items when a delete occurs\n for (let i = toAttributes.length - 1; 0 <= i; i--) {\n const toAttribute = toAttributes[i];\n if (ignoreAttribute(toAttribute.name, to, 'remove', ctx)) {\n continue;\n }\n if (!from.hasAttribute(toAttribute.name)) {\n to.removeAttribute(toAttribute.name);\n }\n }\n }\n\n // sync text nodes\n if (type === 8 /* comment */ || type === 3 /* text */) {\n if (to.nodeValue !== from.nodeValue) {\n to.nodeValue = from.nodeValue;\n }\n }\n\n if (!ignoreValueOfActiveElement(to, ctx)) {\n // sync input values\n syncInputValue(from, to, ctx);\n }\n }\n\n /**\n * @param from {Element} element to sync the value from\n * @param to {Element} element to sync the value to\n * @param attributeName {String} the attribute name\n * @param ctx the merge context\n */\n function syncBooleanAttribute(from, to, attributeName, ctx) {\n if (from[attributeName] !== to[attributeName]) {\n let ignoreUpdate = ignoreAttribute(attributeName, to, 'update', ctx);\n if (!ignoreUpdate) {\n to[attributeName] = from[attributeName];\n }\n if (from[attributeName]) {\n if (!ignoreUpdate) {\n to.setAttribute(attributeName, from[attributeName]);\n }\n } else {\n if (!ignoreAttribute(attributeName, to, 'remove', ctx)) {\n to.removeAttribute(attributeName);\n }\n }\n }\n }\n\n /**\n * NB: many bothans died to bring us information:\n *\n * https://github.com/patrick-steele-idem/morphdom/blob/master/src/specialElHandlers.js\n * https://github.com/choojs/nanomorph/blob/master/lib/morph.jsL113\n *\n * @param from {Element} the element to sync the input value from\n * @param to {Element} the element to sync the input value to\n * @param ctx the merge context\n */\n function syncInputValue(from, to, ctx) {\n if (from instanceof HTMLInputElement &&\n to instanceof HTMLInputElement &&\n from.type !== 'file') {\n\n let fromValue = from.value;\n let toValue = to.value;\n\n // sync boolean attributes\n syncBooleanAttribute(from, to, 'checked', ctx);\n syncBooleanAttribute(from, to, 'disabled', ctx);\n\n if (!from.hasAttribute('value')) {\n if (!ignoreAttribute('value', to, 'remove', ctx)) {\n to.value = '';\n to.removeAttribute('value');\n }\n } else if (fromValue !== toValue) {\n if (!ignoreAttribute('value', to, 'update', ctx)) {\n to.setAttribute('value', fromValue);\n to.value = fromValue;\n }\n }\n } else if (from instanceof HTMLOptionElement) {\n syncBooleanAttribute(from, to, 'selected', ctx);\n } else if (from instanceof HTMLTextAreaElement && to instanceof HTMLTextAreaElement) {\n let fromValue = from.value;\n let toValue = to.value;\n if (ignoreAttribute('value', to, 'update', ctx)) {\n return;\n }\n if (fromValue !== toValue) {\n to.value = fromValue;\n }\n if (to.firstChild && to.firstChild.nodeValue !== fromValue) {\n to.firstChild.nodeValue = fromValue;\n }\n }\n }\n\n //=============================================================================\n // the HEAD tag can be handled specially, either w/ a 'merge' or 'append' style\n //=============================================================================\n function handleHeadElement(newHeadTag, currentHead, ctx) {\n\n let added = [];\n let removed = [];\n let preserved = [];\n let nodesToAppend = [];\n\n let headMergeStyle = ctx.head.style;\n\n // put all new head elements into a Map, by their outerHTML\n let srcToNewHeadNodes = new Map();\n for (const newHeadChild of newHeadTag.children) {\n srcToNewHeadNodes.set(newHeadChild.outerHTML, newHeadChild);\n }\n\n // for each elt in the current head\n for (const currentHeadElt of currentHead.children) {\n\n // If the current head element is in the map\n let inNewContent = srcToNewHeadNodes.has(currentHeadElt.outerHTML);\n let isReAppended = ctx.head.shouldReAppend(currentHeadElt);\n let isPreserved = ctx.head.shouldPreserve(currentHeadElt);\n if (inNewContent || isPreserved) {\n if (isReAppended) {\n // remove the current version and let the new version replace it and re-execute\n removed.push(currentHeadElt);\n } else {\n // this element already exists and should not be re-appended, so remove it from\n // the new content map, preserving it in the DOM\n srcToNewHeadNodes.delete(currentHeadElt.outerHTML);\n preserved.push(currentHeadElt);\n }\n } else {\n if (headMergeStyle === \"append\") {\n // we are appending and this existing element is not new content\n // so if and only if it is marked for re-append do we do anything\n if (isReAppended) {\n removed.push(currentHeadElt);\n nodesToAppend.push(currentHeadElt);\n }\n } else {\n // if this is a merge, we remove this content since it is not in the new head\n if (ctx.head.shouldRemove(currentHeadElt) !== false) {\n removed.push(currentHeadElt);\n }\n }\n }\n }\n\n // Push the remaining new head elements in the Map into the\n // nodes to append to the head tag\n nodesToAppend.push(...srcToNewHeadNodes.values());\n\n let promises = [];\n for (const newNode of nodesToAppend) {\n let newElt = document.createRange().createContextualFragment(newNode.outerHTML).firstChild;\n if (ctx.callbacks.beforeNodeAdded(newElt) !== false) {\n if (newElt.href || newElt.src) {\n let resolve = null;\n let promise = new Promise(function (_resolve) {\n resolve = _resolve;\n });\n newElt.addEventListener('load', function () {\n resolve();\n });\n promises.push(promise);\n }\n currentHead.appendChild(newElt);\n ctx.callbacks.afterNodeAdded(newElt);\n added.push(newElt);\n }\n }\n\n // remove all removed elements, after we have appended the new elements to avoid\n // additional network requests for things like style sheets\n for (const removedElement of removed) {\n if (ctx.callbacks.beforeNodeRemoved(removedElement) !== false) {\n currentHead.removeChild(removedElement);\n ctx.callbacks.afterNodeRemoved(removedElement);\n }\n }\n\n ctx.head.afterHeadMorphed(currentHead, {added: added, kept: preserved, removed: removed});\n return promises;\n }\n\n function noOp() {\n }\n\n /*\n Deep merges the config object and the Idiomoroph.defaults object to\n produce a final configuration object\n */\n function mergeDefaults(config) {\n let finalConfig = {};\n // copy top level stuff into final config\n Object.assign(finalConfig, defaults);\n Object.assign(finalConfig, config);\n\n // copy callbacks into final config (do this to deep merge the callbacks)\n finalConfig.callbacks = {};\n Object.assign(finalConfig.callbacks, defaults.callbacks);\n Object.assign(finalConfig.callbacks, config.callbacks);\n\n // copy head config into final config (do this to deep merge the head)\n finalConfig.head = {};\n Object.assign(finalConfig.head, defaults.head);\n Object.assign(finalConfig.head, config.head);\n return finalConfig;\n }\n\n function createMorphContext(oldNode, newContent, config) {\n config = mergeDefaults(config);\n return {\n target: oldNode,\n newContent: newContent,\n config: config,\n morphStyle: config.morphStyle,\n ignoreActive: config.ignoreActive,\n ignoreActiveValue: config.ignoreActiveValue,\n idMap: createIdMap(oldNode, newContent),\n deadIds: new Set(),\n callbacks: config.callbacks,\n head: config.head\n }\n }\n\n function isIdSetMatch(node1, node2, ctx) {\n if (node1 == null || node2 == null) {\n return false;\n }\n if (node1.nodeType === node2.nodeType && node1.tagName === node2.tagName) {\n if (node1.id !== \"\" && node1.id === node2.id) {\n return true;\n } else {\n return getIdIntersectionCount(ctx, node1, node2) > 0;\n }\n }\n return false;\n }\n\n function isSoftMatch(node1, node2) {\n if (node1 == null || node2 == null) {\n return false;\n }\n return node1.nodeType === node2.nodeType && node1.tagName === node2.tagName\n }\n\n function removeNodesBetween(startInclusive, endExclusive, ctx) {\n while (startInclusive !== endExclusive) {\n let tempNode = startInclusive;\n startInclusive = startInclusive.nextSibling;\n removeNode(tempNode, ctx);\n }\n removeIdsFromConsideration(ctx, endExclusive);\n return endExclusive.nextSibling;\n }\n\n //=============================================================================\n // Scans forward from the insertionPoint in the old parent looking for a potential id match\n // for the newChild. We stop if we find a potential id match for the new child OR\n // if the number of potential id matches we are discarding is greater than the\n // potential id matches for the new child\n //=============================================================================\n function findIdSetMatch(newContent, oldParent, newChild, insertionPoint, ctx) {\n\n // max id matches we are willing to discard in our search\n let newChildPotentialIdCount = getIdIntersectionCount(ctx, newChild, oldParent);\n\n let potentialMatch = null;\n\n // only search forward if there is a possibility of an id match\n if (newChildPotentialIdCount > 0) {\n let potentialMatch = insertionPoint;\n // if there is a possibility of an id match, scan forward\n // keep track of the potential id match count we are discarding (the\n // newChildPotentialIdCount must be greater than this to make it likely\n // worth it)\n let otherMatchCount = 0;\n while (potentialMatch != null) {\n\n // If we have an id match, return the current potential match\n if (isIdSetMatch(newChild, potentialMatch, ctx)) {\n return potentialMatch;\n }\n\n // computer the other potential matches of this new content\n otherMatchCount += getIdIntersectionCount(ctx, potentialMatch, newContent);\n if (otherMatchCount > newChildPotentialIdCount) {\n // if we have more potential id matches in _other_ content, we\n // do not have a good candidate for an id match, so return null\n return null;\n }\n\n // advanced to the next old content child\n potentialMatch = potentialMatch.nextSibling;\n }\n }\n return potentialMatch;\n }\n\n //=============================================================================\n // Scans forward from the insertionPoint in the old parent looking for a potential soft match\n // for the newChild. We stop if we find a potential soft match for the new child OR\n // if we find a potential id match in the old parents children OR if we find two\n // potential soft matches for the next two pieces of new content\n //=============================================================================\n function findSoftMatch(newContent, oldParent, newChild, insertionPoint, ctx) {\n\n let potentialSoftMatch = insertionPoint;\n let nextSibling = newChild.nextSibling;\n let siblingSoftMatchCount = 0;\n\n while (potentialSoftMatch != null) {\n\n if (getIdIntersectionCount(ctx, potentialSoftMatch, newContent) > 0) {\n // the current potential soft match has a potential id set match with the remaining new\n // content so bail out of looking\n return null;\n }\n\n // if we have a soft match with the current node, return it\n if (isSoftMatch(newChild, potentialSoftMatch)) {\n return potentialSoftMatch;\n }\n\n if (isSoftMatch(nextSibling, potentialSoftMatch)) {\n // the next new node has a soft match with this node, so\n // increment the count of future soft matches\n siblingSoftMatchCount++;\n nextSibling = nextSibling.nextSibling;\n\n // If there are two future soft matches, bail to allow the siblings to soft match\n // so that we don't consume future soft matches for the sake of the current node\n if (siblingSoftMatchCount >= 2) {\n return null;\n }\n }\n\n // advanced to the next old content child\n potentialSoftMatch = potentialSoftMatch.nextSibling;\n }\n\n return potentialSoftMatch;\n }\n\n function parseContent(newContent) {\n let parser = new DOMParser();\n\n // remove svgs to avoid false-positive matches on head, etc.\n let contentWithSvgsRemoved = newContent.replace(/]*>|>)([\\s\\S]*?)<\\/svg>/gim, '');\n\n // if the newContent contains a html, head or body tag, we can simply parse it w/o wrapping\n if (contentWithSvgsRemoved.match(/<\\/html>/) || contentWithSvgsRemoved.match(/<\\/head>/) || contentWithSvgsRemoved.match(/<\\/body>/)) {\n let content = parser.parseFromString(newContent, \"text/html\");\n // if it is a full HTML document, return the document itself as the parent container\n if (contentWithSvgsRemoved.match(/<\\/html>/)) {\n content.generatedByIdiomorph = true;\n return content;\n } else {\n // otherwise return the html element as the parent container\n let htmlElement = content.firstChild;\n if (htmlElement) {\n htmlElement.generatedByIdiomorph = true;\n return htmlElement;\n } else {\n return null;\n }\n }\n } else {\n // if it is partial HTML, wrap it in a template tag to provide a parent element and also to help\n // deal with touchy tags like tr, tbody, etc.\n let responseDoc = parser.parseFromString(\"\", \"text/html\");\n let content = responseDoc.body.querySelector('template').content;\n content.generatedByIdiomorph = true;\n return content\n }\n }\n\n function normalizeContent(newContent) {\n if (newContent == null) {\n // noinspection UnnecessaryLocalVariableJS\n const dummyParent = document.createElement('div');\n return dummyParent;\n } else if (newContent.generatedByIdiomorph) {\n // the template tag created by idiomorph parsing can serve as a dummy parent\n return newContent;\n } else if (newContent instanceof Node) {\n // a single node is added as a child to a dummy parent\n const dummyParent = document.createElement('div');\n dummyParent.append(newContent);\n return dummyParent;\n } else {\n // all nodes in the array or HTMLElement collection are consolidated under\n // a single dummy parent element\n const dummyParent = document.createElement('div');\n for (const elt of [...newContent]) {\n dummyParent.append(elt);\n }\n return dummyParent;\n }\n }\n\n function insertSiblings(previousSibling, morphedNode, nextSibling) {\n let stack = [];\n let added = [];\n while (previousSibling != null) {\n stack.push(previousSibling);\n previousSibling = previousSibling.previousSibling;\n }\n while (stack.length > 0) {\n let node = stack.pop();\n added.push(node); // push added preceding siblings on in order and insert\n morphedNode.parentElement.insertBefore(node, morphedNode);\n }\n added.push(morphedNode);\n while (nextSibling != null) {\n stack.push(nextSibling);\n added.push(nextSibling); // here we are going in order, so push on as we scan, rather than add\n nextSibling = nextSibling.nextSibling;\n }\n while (stack.length > 0) {\n morphedNode.parentElement.insertBefore(stack.pop(), morphedNode.nextSibling);\n }\n return added;\n }\n\n function findBestNodeMatch(newContent, oldNode, ctx) {\n let currentElement;\n currentElement = newContent.firstChild;\n let bestElement = currentElement;\n let score = 0;\n while (currentElement) {\n let newScore = scoreElement(currentElement, oldNode, ctx);\n if (newScore > score) {\n bestElement = currentElement;\n score = newScore;\n }\n currentElement = currentElement.nextSibling;\n }\n return bestElement;\n }\n\n function scoreElement(node1, node2, ctx) {\n if (isSoftMatch(node1, node2)) {\n return .5 + getIdIntersectionCount(ctx, node1, node2);\n }\n return 0;\n }\n\n function removeNode(tempNode, ctx) {\n removeIdsFromConsideration(ctx, tempNode);\n if (ctx.callbacks.beforeNodeRemoved(tempNode) === false) return;\n\n tempNode.remove();\n ctx.callbacks.afterNodeRemoved(tempNode);\n }\n\n //=============================================================================\n // ID Set Functions\n //=============================================================================\n\n function isIdInConsideration(ctx, id) {\n return !ctx.deadIds.has(id);\n }\n\n function idIsWithinNode(ctx, id, targetNode) {\n let idSet = ctx.idMap.get(targetNode) || EMPTY_SET;\n return idSet.has(id);\n }\n\n function removeIdsFromConsideration(ctx, node) {\n let idSet = ctx.idMap.get(node) || EMPTY_SET;\n for (const id of idSet) {\n ctx.deadIds.add(id);\n }\n }\n\n function getIdIntersectionCount(ctx, node1, node2) {\n let sourceSet = ctx.idMap.get(node1) || EMPTY_SET;\n let matchCount = 0;\n for (const id of sourceSet) {\n // a potential match is an id in the source and potentialIdsSet, but\n // that has not already been merged into the DOM\n if (isIdInConsideration(ctx, id) && idIsWithinNode(ctx, id, node2)) {\n ++matchCount;\n }\n }\n return matchCount;\n }\n\n /**\n * A bottom up algorithm that finds all elements with ids inside of the node\n * argument and populates id sets for those nodes and all their parents, generating\n * a set of ids contained within all nodes for the entire hierarchy in the DOM\n *\n * @param node {Element}\n * @param {Map>} idMap\n */\n function populateIdMapForNode(node, idMap) {\n let nodeParent = node.parentElement;\n // find all elements with an id property\n let idElements = node.querySelectorAll('[id]');\n for (const elt of idElements) {\n let current = elt;\n // walk up the parent hierarchy of that element, adding the id\n // of element to the parent's id set\n while (current !== nodeParent && current != null) {\n let idSet = idMap.get(current);\n // if the id set doesn't exist, create it and insert it in the map\n if (idSet == null) {\n idSet = new Set();\n idMap.set(current, idSet);\n }\n idSet.add(elt.id);\n current = current.parentElement;\n }\n }\n }\n\n /**\n * This function computes a map of nodes to all ids contained within that node (inclusive of the\n * node). This map can be used to ask if two nodes have intersecting sets of ids, which allows\n * for a looser definition of \"matching\" than tradition id matching, and allows child nodes\n * to contribute to a parent nodes matching.\n *\n * @param {Element} oldContent the old content that will be morphed\n * @param {Element} newContent the new content to morph to\n * @returns {Map>} a map of nodes to id sets for the\n */\n function createIdMap(oldContent, newContent) {\n let idMap = new Map();\n populateIdMapForNode(oldContent, idMap);\n populateIdMapForNode(newContent, idMap);\n return idMap;\n }\n\n //=============================================================================\n // This is what ends up becoming the Idiomorph global object\n //=============================================================================\n return {\n morph,\n defaults\n }\n })();\n\nfunction morphElements(currentElement, newElement, { callbacks, ...options } = {}) {\n Idiomorph.morph(currentElement, newElement, {\n ...options,\n callbacks: new DefaultIdiomorphCallbacks(callbacks)\n });\n}\n\nfunction morphChildren(currentElement, newElement) {\n morphElements(currentElement, newElement.children, {\n morphStyle: \"innerHTML\"\n });\n}\n\nclass DefaultIdiomorphCallbacks {\n #beforeNodeMorphed\n\n constructor({ beforeNodeMorphed } = {}) {\n this.#beforeNodeMorphed = beforeNodeMorphed || (() => true);\n }\n\n beforeNodeAdded = (node) => {\n return !(node.id && node.hasAttribute(\"data-turbo-permanent\") && document.getElementById(node.id))\n }\n\n beforeNodeMorphed = (currentElement, newElement) => {\n if (currentElement instanceof Element) {\n if (!currentElement.hasAttribute(\"data-turbo-permanent\") && this.#beforeNodeMorphed(currentElement, newElement)) {\n const event = dispatch(\"turbo:before-morph-element\", {\n cancelable: true,\n target: currentElement,\n detail: { currentElement, newElement }\n });\n\n return !event.defaultPrevented\n } else {\n return false\n }\n }\n }\n\n beforeAttributeUpdated = (attributeName, target, mutationType) => {\n const event = dispatch(\"turbo:before-morph-attribute\", {\n cancelable: true,\n target,\n detail: { attributeName, mutationType }\n });\n\n return !event.defaultPrevented\n }\n\n beforeNodeRemoved = (node) => {\n return this.beforeNodeMorphed(node)\n }\n\n afterNodeMorphed = (currentElement, newElement) => {\n if (currentElement instanceof Element) {\n dispatch(\"turbo:morph-element\", {\n target: currentElement,\n detail: { currentElement, newElement }\n });\n }\n }\n}\n\nclass MorphingFrameRenderer extends FrameRenderer {\n static renderElement(currentElement, newElement) {\n dispatch(\"turbo:before-frame-morph\", {\n target: currentElement,\n detail: { currentElement, newElement }\n });\n\n morphChildren(currentElement, newElement);\n }\n\n async preservingPermanentElements(callback) {\n return await callback()\n }\n}\n\nclass ProgressBar {\n static animationDuration = 300 /*ms*/\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: 2147483647;\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\n hiding = false\n value = 0\n visible = false\n\n constructor() {\n this.stylesheetElement = this.createStylesheetElement();\n this.progressElement = this.createProgressElement();\n this.installStylesheetElement();\n this.setValue(0);\n }\n\n show() {\n if (!this.visible) {\n this.visible = true;\n this.installProgressElement();\n this.startTrickling();\n }\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\n setValue(value) {\n this.value = value;\n this.refresh();\n }\n\n // Private\n\n installStylesheetElement() {\n document.head.insertBefore(this.stylesheetElement, document.head.firstChild);\n }\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\n fadeProgressElement(callback) {\n this.progressElement.style.opacity = \"0\";\n setTimeout(callback, ProgressBar.animationDuration * 1.5);\n }\n\n uninstallProgressElement() {\n if (this.progressElement.parentNode) {\n document.documentElement.removeChild(this.progressElement);\n }\n }\n\n startTrickling() {\n if (!this.trickleInterval) {\n this.trickleInterval = window.setInterval(this.trickle, ProgressBar.animationDuration);\n }\n }\n\n stopTrickling() {\n window.clearInterval(this.trickleInterval);\n delete this.trickleInterval;\n }\n\n trickle = () => {\n this.setValue(this.value + Math.random() / 100);\n }\n\n refresh() {\n requestAnimationFrame(() => {\n this.progressElement.style.width = `${10 + this.value * 90}%`;\n });\n }\n\n createStylesheetElement() {\n const element = document.createElement(\"style\");\n element.type = \"text/css\";\n element.textContent = ProgressBar.defaultCSS;\n const cspNonce = getCspNonce();\n if (cspNonce) {\n element.nonce = cspNonce;\n }\n return element\n }\n\n createProgressElement() {\n const element = document.createElement(\"div\");\n element.className = \"turbo-progress-bar\";\n return element\n }\n}\n\nclass HeadSnapshot extends Snapshot {\n detailsByOuterHTML = this.children\n .filter((element) => !elementIsNoscript(element))\n .map((element) => elementWithoutNonce(element))\n .reduce((result, element) => {\n const { outerHTML } = element;\n const details =\n outerHTML in result\n ? result[outerHTML]\n : {\n type: elementType(element),\n tracked: elementIsTracked(element),\n elements: []\n };\n return {\n ...result,\n [outerHTML]: {\n ...details,\n elements: [...details.elements, element]\n }\n }\n }, {})\n\n get trackedElementSignature() {\n return Object.keys(this.detailsByOuterHTML)\n .filter((outerHTML) => this.detailsByOuterHTML[outerHTML].tracked)\n .join(\"\")\n }\n\n getScriptElementsNotInSnapshot(snapshot) {\n return this.getElementsMatchingTypeNotInSnapshot(\"script\", snapshot)\n }\n\n getStylesheetElementsNotInSnapshot(snapshot) {\n return this.getElementsMatchingTypeNotInSnapshot(\"stylesheet\", snapshot)\n }\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\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 } else if (elements.length > 1) {\n return [...result, ...elements.slice(1)]\n } else {\n return result\n }\n }, [])\n }\n\n getMetaValue(name) {\n const element = this.findMetaElementByName(name);\n return element ? element.getAttribute(\"content\") : null\n }\n\n findMetaElementByName(name) {\n return Object.keys(this.detailsByOuterHTML).reduce((result, outerHTML) => {\n const {\n elements: [element]\n } = this.detailsByOuterHTML[outerHTML];\n return elementIsMetaElementWithName(element, name) ? element : result\n }, undefined | undefined)\n }\n}\n\nfunction elementType(element) {\n if (elementIsScript(element)) {\n return \"script\"\n } else if (elementIsStylesheet(element)) {\n return \"stylesheet\"\n }\n}\n\nfunction elementIsTracked(element) {\n return element.getAttribute(\"data-turbo-track\") == \"reload\"\n}\n\nfunction elementIsScript(element) {\n const tagName = element.localName;\n return tagName == \"script\"\n}\n\nfunction elementIsNoscript(element) {\n const tagName = element.localName;\n return tagName == \"noscript\"\n}\n\nfunction elementIsStylesheet(element) {\n const tagName = element.localName;\n return tagName == \"style\" || (tagName == \"link\" && element.getAttribute(\"rel\") == \"stylesheet\")\n}\n\nfunction elementIsMetaElementWithName(element, name) {\n const tagName = element.localName;\n return tagName == \"meta\" && element.getAttribute(\"name\") == name\n}\n\nfunction elementWithoutNonce(element) {\n if (element.hasAttribute(\"nonce\")) {\n element.setAttribute(\"nonce\", \"\");\n }\n\n return element\n}\n\nclass PageSnapshot extends Snapshot {\n static fromHTMLString(html = \"\") {\n return this.fromDocument(parseHTMLDocument(html))\n }\n\n static fromElement(element) {\n return this.fromDocument(element.ownerDocument)\n }\n\n static fromDocument({ documentElement, body, head }) {\n return new this(documentElement, body, new HeadSnapshot(head))\n }\n\n constructor(documentElement, body, headSnapshot) {\n super(body);\n this.documentElement = documentElement;\n this.headSnapshot = headSnapshot;\n }\n\n clone() {\n const clonedElement = this.element.cloneNode(true);\n\n const selectElements = this.element.querySelectorAll(\"select\");\n const clonedSelectElements = clonedElement.querySelectorAll(\"select\");\n\n for (const [index, source] of selectElements.entries()) {\n const clone = clonedSelectElements[index];\n for (const option of clone.selectedOptions) option.selected = false;\n for (const option of source.selectedOptions) clone.options[option.index].selected = true;\n }\n\n for (const clonedPasswordInput of clonedElement.querySelectorAll('input[type=\"password\"]')) {\n clonedPasswordInput.value = \"\";\n }\n\n return new PageSnapshot(this.documentElement, clonedElement, this.headSnapshot)\n }\n\n get lang() {\n return this.documentElement.getAttribute(\"lang\")\n }\n\n get headElement() {\n return this.headSnapshot.element\n }\n\n get rootLocation() {\n const root = this.getSetting(\"root\") ?? \"/\";\n return expandURL(root)\n }\n\n get cacheControlValue() {\n return this.getSetting(\"cache-control\")\n }\n\n get isPreviewable() {\n return this.cacheControlValue != \"no-preview\"\n }\n\n get isCacheable() {\n return this.cacheControlValue != \"no-cache\"\n }\n\n get isVisitable() {\n return this.getSetting(\"visit-control\") != \"reload\"\n }\n\n get prefersViewTransitions() {\n return this.headSnapshot.getMetaValue(\"view-transition\") === \"same-origin\"\n }\n\n get shouldMorphPage() {\n return this.getSetting(\"refresh-method\") === \"morph\"\n }\n\n get shouldPreserveScrollPosition() {\n return this.getSetting(\"refresh-scroll\") === \"preserve\"\n }\n\n // Private\n\n getSetting(name) {\n return this.headSnapshot.getMetaValue(`turbo-${name}`)\n }\n}\n\nclass ViewTransitioner {\n #viewTransitionStarted = false\n #lastOperation = Promise.resolve()\n\n renderChange(useViewTransition, render) {\n if (useViewTransition && this.viewTransitionsAvailable && !this.#viewTransitionStarted) {\n this.#viewTransitionStarted = true;\n this.#lastOperation = this.#lastOperation.then(async () => {\n await document.startViewTransition(render).finished;\n });\n } else {\n this.#lastOperation = this.#lastOperation.then(render);\n }\n\n return this.#lastOperation\n }\n\n get viewTransitionsAvailable() {\n return document.startViewTransition\n }\n}\n\nconst defaultOptions = {\n action: \"advance\",\n historyChanged: false,\n visitCachedSnapshot: () => {},\n willRender: true,\n updateHistory: true,\n shouldCacheSnapshot: true,\n acceptsStreamResponse: false\n};\n\nconst TimingMetric = {\n visitStart: \"visitStart\",\n requestStart: \"requestStart\",\n requestEnd: \"requestEnd\",\n visitEnd: \"visitEnd\"\n};\n\nconst VisitState = {\n initialized: \"initialized\",\n started: \"started\",\n canceled: \"canceled\",\n failed: \"failed\",\n completed: \"completed\"\n};\n\nconst SystemStatusCode = {\n networkFailure: 0,\n timeoutFailure: -1,\n contentTypeMismatch: -2\n};\n\nconst Direction = {\n advance: \"forward\",\n restore: \"back\",\n replace: \"none\"\n};\n\nclass Visit {\n identifier = uuid() // Required by turbo-ios\n timingMetrics = {}\n\n followedRedirect = false\n historyChanged = false\n scrolled = false\n shouldCacheSnapshot = true\n acceptsStreamResponse = false\n snapshotCached = false\n state = VisitState.initialized\n viewTransitioner = new ViewTransitioner()\n\n constructor(delegate, location, restorationIdentifier, options = {}) {\n this.delegate = delegate;\n this.location = location;\n this.restorationIdentifier = restorationIdentifier || uuid();\n\n const {\n action,\n historyChanged,\n referrer,\n snapshot,\n snapshotHTML,\n response,\n visitCachedSnapshot,\n willRender,\n updateHistory,\n shouldCacheSnapshot,\n acceptsStreamResponse,\n direction\n } = {\n ...defaultOptions,\n ...options\n };\n this.action = action;\n this.historyChanged = historyChanged;\n this.referrer = referrer;\n this.snapshot = snapshot;\n this.snapshotHTML = snapshotHTML;\n this.response = response;\n this.isSamePage = this.delegate.locationWithActionIsSamePage(this.location, this.action);\n this.isPageRefresh = this.view.isPageRefresh(this);\n this.visitCachedSnapshot = visitCachedSnapshot;\n this.willRender = willRender;\n this.updateHistory = updateHistory;\n this.scrolled = !willRender;\n this.shouldCacheSnapshot = shouldCacheSnapshot;\n this.acceptsStreamResponse = acceptsStreamResponse;\n this.direction = direction || Direction[action];\n }\n\n get adapter() {\n return this.delegate.adapter\n }\n\n get view() {\n return this.delegate.view\n }\n\n get history() {\n return this.delegate.history\n }\n\n get restorationData() {\n return this.history.getRestorationDataForIdentifier(this.restorationIdentifier)\n }\n\n get silent() {\n return this.isSamePage\n }\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\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\n complete() {\n if (this.state == VisitState.started) {\n this.recordTimingMetric(TimingMetric.visitEnd);\n this.adapter.visitCompleted(this);\n this.state = VisitState.completed;\n this.followRedirect();\n\n if (!this.followedRedirect) {\n this.delegate.visitCompleted(this);\n }\n }\n }\n\n fail() {\n if (this.state == VisitState.started) {\n this.state = VisitState.failed;\n this.adapter.visitFailed(this);\n this.delegate.visitCompleted(this);\n }\n }\n\n changeHistory() {\n if (!this.historyChanged && this.updateHistory) {\n const actionForHistory = this.location.href === this.referrer?.href ? \"replace\" : this.action;\n const method = getHistoryMethodForAction(actionForHistory);\n this.history.update(method, this.location, this.restorationIdentifier);\n this.historyChanged = true;\n }\n }\n\n issueRequest() {\n if (this.hasPreloadedResponse()) {\n this.simulateRequest();\n } else if (this.shouldIssueRequest() && !this.request) {\n this.request = new FetchRequest(this, FetchMethod.get, this.location);\n this.request.perform();\n }\n }\n\n simulateRequest() {\n if (this.response) {\n this.startRequest();\n this.recordResponse();\n this.finishRequest();\n }\n }\n\n startRequest() {\n this.recordTimingMetric(TimingMetric.requestStart);\n this.adapter.visitRequestStarted(this);\n }\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 } else {\n this.adapter.visitRequestFailedWithStatusCode(this, statusCode);\n }\n }\n }\n\n finishRequest() {\n this.recordTimingMetric(TimingMetric.requestEnd);\n this.adapter.visitRequestFinished(this);\n }\n\n loadResponse() {\n if (this.response) {\n const { statusCode, responseHTML } = this.response;\n this.render(async () => {\n if (this.shouldCacheSnapshot) this.cacheSnapshot();\n if (this.view.renderPromise) await this.view.renderPromise;\n\n if (isSuccessful(statusCode) && responseHTML != null) {\n const snapshot = PageSnapshot.fromHTMLString(responseHTML);\n await this.renderPageSnapshot(snapshot, false);\n\n this.adapter.visitRendered(this);\n this.complete();\n } else {\n await this.view.renderError(PageSnapshot.fromHTMLString(responseHTML), this);\n this.adapter.visitRendered(this);\n this.fail();\n }\n });\n }\n }\n\n getCachedSnapshot() {\n const snapshot = this.view.getCachedSnapshotForLocation(this.location) || this.getPreloadedSnapshot();\n\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\n getPreloadedSnapshot() {\n if (this.snapshotHTML) {\n return PageSnapshot.fromHTMLString(this.snapshotHTML)\n }\n }\n\n hasCachedSnapshot() {\n return this.getCachedSnapshot() != null\n }\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 || this.isPageRefresh) {\n this.adapter.visitRendered(this);\n } else {\n if (this.view.renderPromise) await this.view.renderPromise;\n\n await this.renderPageSnapshot(snapshot, isPreview);\n\n this.adapter.visitRendered(this);\n if (!isPreview) {\n this.complete();\n }\n }\n });\n }\n }\n\n followRedirect() {\n if (this.redirectedToLocation && !this.followedRedirect && this.response?.redirected) {\n this.adapter.visitProposedToLocation(this.redirectedToLocation, {\n action: \"replace\",\n response: this.response,\n shouldCacheSnapshot: false,\n willRender: false\n });\n this.followedRedirect = true;\n }\n }\n\n goToSamePageAnchor() {\n if (this.isSamePage) {\n this.render(async () => {\n this.cacheSnapshot();\n this.performScroll();\n this.changeHistory();\n this.adapter.visitRendered(this);\n });\n }\n }\n\n // Fetch request delegate\n\n prepareRequest(request) {\n if (this.acceptsStreamResponse) {\n request.acceptResponseType(StreamMessage.contentType);\n }\n }\n\n requestStarted() {\n this.startRequest();\n }\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({\n statusCode: SystemStatusCode.contentTypeMismatch,\n redirected\n });\n } else {\n this.redirectedToLocation = response.redirected ? response.location : undefined;\n this.recordResponse({ statusCode: statusCode, responseHTML, redirected });\n }\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({\n statusCode: SystemStatusCode.contentTypeMismatch,\n redirected\n });\n } else {\n this.recordResponse({ statusCode: statusCode, responseHTML, redirected });\n }\n }\n\n requestErrored(_request, _error) {\n this.recordResponse({\n statusCode: SystemStatusCode.networkFailure,\n redirected: false\n });\n }\n\n requestFinished() {\n this.finishRequest();\n }\n\n // Scrolling\n\n performScroll() {\n if (!this.scrolled && !this.view.forceReloaded && !this.view.shouldPreserveScrollPosition(this)) {\n if (this.action == \"restore\") {\n this.scrollToRestoredPosition() || this.scrollToAnchor() || this.view.scrollToTop();\n } else {\n this.scrollToAnchor() || this.view.scrollToTop();\n }\n if (this.isSamePage) {\n this.delegate.visitScrolledToSamePageLocation(this.view.lastRenderedLocation, this.location);\n }\n\n this.scrolled = true;\n }\n }\n\n scrollToRestoredPosition() {\n const { scrollPosition } = this.restorationData;\n if (scrollPosition) {\n this.view.scrollToPosition(scrollPosition);\n return true\n }\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\n // Instrumentation\n\n recordTimingMetric(metric) {\n this.timingMetrics[metric] = new Date().getTime();\n }\n\n getTimingMetrics() {\n return { ...this.timingMetrics }\n }\n\n // Private\n\n getHistoryMethodForAction(action) {\n switch (action) {\n case \"replace\":\n return history.replaceState\n case \"advance\":\n case \"restore\":\n return history.pushState\n }\n }\n\n hasPreloadedResponse() {\n return typeof this.response == \"object\"\n }\n\n shouldIssueRequest() {\n if (this.isSamePage) {\n return false\n } else if (this.action == \"restore\") {\n return !this.hasCachedSnapshot()\n } else {\n return this.willRender\n }\n }\n\n cacheSnapshot() {\n if (!this.snapshotCached) {\n this.view.cacheSnapshot(this.snapshot).then((snapshot) => snapshot && this.visitCachedSnapshot(snapshot));\n this.snapshotCached = true;\n }\n }\n\n async render(callback) {\n this.cancelRender();\n await new Promise((resolve) => {\n this.frame =\n document.visibilityState === \"hidden\" ? setTimeout(() => resolve(), 0) : requestAnimationFrame(() => resolve());\n });\n await callback();\n delete this.frame;\n }\n\n async renderPageSnapshot(snapshot, isPreview) {\n await this.viewTransitioner.renderChange(this.view.shouldTransitionTo(snapshot), async () => {\n await this.view.renderPage(snapshot, isPreview, this.willRender, this);\n this.performScroll();\n });\n }\n\n cancelRender() {\n if (this.frame) {\n cancelAnimationFrame(this.frame);\n delete this.frame;\n }\n }\n}\n\nfunction isSuccessful(statusCode) {\n return statusCode >= 200 && statusCode < 300\n}\n\nclass BrowserAdapter {\n progressBar = new ProgressBar()\n\n constructor(session) {\n this.session = session;\n }\n\n visitProposedToLocation(location, options) {\n if (locationIsVisitable(location, this.navigator.rootLocation)) {\n this.navigator.startVisit(location, options?.restorationIdentifier || uuid(), options);\n } else {\n window.location.href = location.toString();\n }\n }\n\n visitStarted(visit) {\n this.location = visit.location;\n visit.loadCachedSnapshot();\n visit.issueRequest();\n visit.goToSamePageAnchor();\n }\n\n visitRequestStarted(visit) {\n this.progressBar.setValue(0);\n if (visit.hasCachedSnapshot() || visit.action != \"restore\") {\n this.showVisitProgressBarAfterDelay();\n } else {\n this.showProgressBar();\n }\n }\n\n visitRequestCompleted(visit) {\n visit.loadResponse();\n }\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 reason: \"request_failed\",\n context: {\n statusCode\n }\n })\n default:\n return visit.loadResponse()\n }\n }\n\n visitRequestFinished(_visit) {}\n\n visitCompleted(_visit) {\n this.progressBar.setValue(1);\n this.hideVisitProgressBar();\n }\n\n pageInvalidated(reason) {\n this.reload(reason);\n }\n\n visitFailed(_visit) {\n this.progressBar.setValue(1);\n this.hideVisitProgressBar();\n }\n\n visitRendered(_visit) {}\n\n // Form Submission Delegate\n\n formSubmissionStarted(_formSubmission) {\n this.progressBar.setValue(0);\n this.showFormProgressBarAfterDelay();\n }\n\n formSubmissionFinished(_formSubmission) {\n this.progressBar.setValue(1);\n this.hideFormProgressBar();\n }\n\n // Private\n\n showVisitProgressBarAfterDelay() {\n this.visitProgressBarTimeout = window.setTimeout(this.showProgressBar, this.session.progressBarDelay);\n }\n\n hideVisitProgressBar() {\n this.progressBar.hide();\n if (this.visitProgressBarTimeout != null) {\n window.clearTimeout(this.visitProgressBarTimeout);\n delete this.visitProgressBarTimeout;\n }\n }\n\n showFormProgressBarAfterDelay() {\n if (this.formProgressBarTimeout == null) {\n this.formProgressBarTimeout = window.setTimeout(this.showProgressBar, this.session.progressBarDelay);\n }\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\n showProgressBar = () => {\n this.progressBar.show();\n }\n\n reload(reason) {\n dispatch(\"turbo:reload\", { detail: reason });\n\n window.location.href = this.location?.toString() || window.location.href;\n }\n\n get navigator() {\n return this.session.navigator\n }\n}\n\nclass CacheObserver {\n selector = \"[data-turbo-temporary]\"\n deprecatedSelector = \"[data-turbo-cache=false]\"\n\n started = false\n\n start() {\n if (!this.started) {\n this.started = true;\n addEventListener(\"turbo:before-cache\", this.removeTemporaryElements, false);\n }\n }\n\n stop() {\n if (this.started) {\n this.started = false;\n removeEventListener(\"turbo:before-cache\", this.removeTemporaryElements, false);\n }\n }\n\n removeTemporaryElements = (_event) => {\n for (const element of this.temporaryElements) {\n element.remove();\n }\n }\n\n get temporaryElements() {\n return [...document.querySelectorAll(this.selector), ...this.temporaryElementsWithDeprecation]\n }\n\n get temporaryElementsWithDeprecation() {\n const elements = document.querySelectorAll(this.deprecatedSelector);\n\n if (elements.length) {\n console.warn(\n `The ${this.deprecatedSelector} selector is deprecated and will be removed in a future version. Use ${this.selector} instead.`\n );\n }\n\n return [...elements]\n }\n}\n\nclass FrameRedirector {\n constructor(session, element) {\n this.session = session;\n this.element = element;\n this.linkInterceptor = new LinkInterceptor(this, element);\n this.formSubmitObserver = new FormSubmitObserver(this, element);\n }\n\n start() {\n this.linkInterceptor.start();\n this.formSubmitObserver.start();\n }\n\n stop() {\n this.linkInterceptor.stop();\n this.formSubmitObserver.stop();\n }\n\n // Link interceptor delegate\n\n shouldInterceptLinkClick(element, _location, _event) {\n return this.#shouldRedirect(element)\n }\n\n linkClickIntercepted(element, url, event) {\n const frame = this.#findFrameElement(element);\n if (frame) {\n frame.delegate.linkClickIntercepted(element, url, event);\n }\n }\n\n // Form submit observer delegate\n\n willSubmitForm(element, submitter) {\n return (\n element.closest(\"turbo-frame\") == null &&\n this.#shouldSubmit(element, submitter) &&\n this.#shouldRedirect(element, submitter)\n )\n }\n\n formSubmitted(element, submitter) {\n const frame = this.#findFrameElement(element, submitter);\n if (frame) {\n frame.delegate.formSubmitted(element, submitter);\n }\n }\n\n #shouldSubmit(form, submitter) {\n const action = getAction$1(form, submitter);\n const meta = this.element.ownerDocument.querySelector(`meta[name=\"turbo-root\"]`);\n const rootLocation = expandURL(meta?.content ?? \"/\");\n\n return this.#shouldRedirect(form, submitter) && locationIsVisitable(action, rootLocation)\n }\n\n #shouldRedirect(element, submitter) {\n const isNavigatable =\n element instanceof HTMLFormElement\n ? this.session.submissionIsNavigatable(element, submitter)\n : this.session.elementIsNavigatable(element);\n\n if (isNavigatable) {\n const frame = this.#findFrameElement(element, submitter);\n return frame ? frame != element.closest(\"turbo-frame\") : false\n } else {\n return false\n }\n }\n\n #findFrameElement(element, submitter) {\n const id = 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 location\n restorationIdentifier = uuid()\n restorationData = {}\n started = false\n pageLoaded = false\n currentIndex = 0\n\n constructor(delegate) {\n this.delegate = delegate;\n }\n\n start() {\n if (!this.started) {\n addEventListener(\"popstate\", this.onPopState, false);\n addEventListener(\"load\", this.onPageLoad, false);\n this.currentIndex = history.state?.turbo?.restorationIndex || 0;\n this.started = true;\n this.replace(new URL(window.location.href));\n }\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\n push(location, restorationIdentifier) {\n this.update(history.pushState, location, restorationIdentifier);\n }\n\n replace(location, restorationIdentifier) {\n this.update(history.replaceState, location, restorationIdentifier);\n }\n\n update(method, location, restorationIdentifier = uuid()) {\n if (method === history.pushState) ++this.currentIndex;\n\n const state = { turbo: { restorationIdentifier, restorationIndex: this.currentIndex } };\n method.call(history, state, \"\", location.href);\n this.location = location;\n this.restorationIdentifier = restorationIdentifier;\n }\n\n // Restoration data\n\n getRestorationDataForIdentifier(restorationIdentifier) {\n return this.restorationData[restorationIdentifier] || {}\n }\n\n updateRestorationData(additionalData) {\n const { restorationIdentifier } = this;\n const restorationData = this.restorationData[restorationIdentifier];\n this.restorationData[restorationIdentifier] = {\n ...restorationData,\n ...additionalData\n };\n }\n\n // Scroll restoration\n\n assumeControlOfScrollRestoration() {\n if (!this.previousScrollRestoration) {\n this.previousScrollRestoration = history.scrollRestoration ?? \"auto\";\n history.scrollRestoration = \"manual\";\n }\n }\n\n relinquishControlOfScrollRestoration() {\n if (this.previousScrollRestoration) {\n history.scrollRestoration = this.previousScrollRestoration;\n delete this.previousScrollRestoration;\n }\n }\n\n // Event handlers\n\n 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, restorationIndex } = turbo;\n this.restorationIdentifier = restorationIdentifier;\n const direction = restorationIndex > this.currentIndex ? \"forward\" : \"back\";\n this.delegate.historyPoppedToLocationWithRestorationIdentifierAndDirection(this.location, restorationIdentifier, direction);\n this.currentIndex = restorationIndex;\n }\n }\n }\n\n onPageLoad = async (_event) => {\n await nextMicrotask();\n this.pageLoaded = true;\n }\n\n // Private\n\n shouldHandlePopState() {\n // Safari dispatches a popstate event after window's load event, ignore it\n return this.pageIsLoaded()\n }\n\n pageIsLoaded() {\n return this.pageLoaded || document.readyState == \"complete\"\n }\n}\n\nclass LinkPrefetchObserver {\n started = false\n #prefetchedLink = null\n\n constructor(delegate, eventTarget) {\n this.delegate = delegate;\n this.eventTarget = eventTarget;\n }\n\n start() {\n if (this.started) return\n\n if (this.eventTarget.readyState === \"loading\") {\n this.eventTarget.addEventListener(\"DOMContentLoaded\", this.#enable, { once: true });\n } else {\n this.#enable();\n }\n }\n\n stop() {\n if (!this.started) return\n\n this.eventTarget.removeEventListener(\"mouseenter\", this.#tryToPrefetchRequest, {\n capture: true,\n passive: true\n });\n this.eventTarget.removeEventListener(\"mouseleave\", this.#cancelRequestIfObsolete, {\n capture: true,\n passive: true\n });\n\n this.eventTarget.removeEventListener(\"turbo:before-fetch-request\", this.#tryToUsePrefetchedRequest, true);\n this.started = false;\n }\n\n #enable = () => {\n this.eventTarget.addEventListener(\"mouseenter\", this.#tryToPrefetchRequest, {\n capture: true,\n passive: true\n });\n this.eventTarget.addEventListener(\"mouseleave\", this.#cancelRequestIfObsolete, {\n capture: true,\n passive: true\n });\n\n this.eventTarget.addEventListener(\"turbo:before-fetch-request\", this.#tryToUsePrefetchedRequest, true);\n this.started = true;\n }\n\n #tryToPrefetchRequest = (event) => {\n if (getMetaContent(\"turbo-prefetch\") === \"false\") return\n\n const target = event.target;\n const isLink = target.matches && target.matches(\"a[href]:not([target^=_]):not([download])\");\n\n if (isLink && this.#isPrefetchable(target)) {\n const link = target;\n const location = getLocationForLink(link);\n\n if (this.delegate.canPrefetchRequestToLocation(link, location)) {\n this.#prefetchedLink = link;\n\n const fetchRequest = new FetchRequest(\n this,\n FetchMethod.get,\n location,\n new URLSearchParams(),\n target\n );\n\n prefetchCache.setLater(location.toString(), fetchRequest, this.#cacheTtl);\n }\n }\n }\n\n #cancelRequestIfObsolete = (event) => {\n if (event.target === this.#prefetchedLink) this.#cancelPrefetchRequest();\n }\n\n #cancelPrefetchRequest = () => {\n prefetchCache.clear();\n this.#prefetchedLink = null;\n }\n\n #tryToUsePrefetchedRequest = (event) => {\n if (event.target.tagName !== \"FORM\" && event.detail.fetchOptions.method === \"GET\") {\n const cached = prefetchCache.get(event.detail.url.toString());\n\n if (cached) {\n // User clicked link, use cache response\n event.detail.fetchRequest = cached;\n }\n\n prefetchCache.clear();\n }\n }\n\n prepareRequest(request) {\n const link = request.target;\n\n request.headers[\"X-Sec-Purpose\"] = \"prefetch\";\n\n const turboFrame = link.closest(\"turbo-frame\");\n const turboFrameTarget = link.getAttribute(\"data-turbo-frame\") || turboFrame?.getAttribute(\"target\") || turboFrame?.id;\n\n if (turboFrameTarget && turboFrameTarget !== \"_top\") {\n request.headers[\"Turbo-Frame\"] = turboFrameTarget;\n }\n }\n\n // Fetch request interface\n\n requestSucceededWithResponse() {}\n\n requestStarted(fetchRequest) {}\n\n requestErrored(fetchRequest) {}\n\n requestFinished(fetchRequest) {}\n\n requestPreventedHandlingResponse(fetchRequest, fetchResponse) {}\n\n requestFailedWithResponse(fetchRequest, fetchResponse) {}\n\n get #cacheTtl() {\n return Number(getMetaContent(\"turbo-prefetch-cache-time\")) || cacheTtl\n }\n\n #isPrefetchable(link) {\n const href = link.getAttribute(\"href\");\n\n if (!href) return false\n\n if (unfetchableLink(link)) return false\n if (linkToTheSamePage(link)) return false\n if (linkOptsOut(link)) return false\n if (nonSafeLink(link)) return false\n if (eventPrevented(link)) return false\n\n return true\n }\n}\n\nconst unfetchableLink = (link) => {\n return link.origin !== document.location.origin || ![\"http:\", \"https:\"].includes(link.protocol) || link.hasAttribute(\"target\")\n};\n\nconst linkToTheSamePage = (link) => {\n return (link.pathname + link.search === document.location.pathname + document.location.search) || link.href.startsWith(\"#\")\n};\n\nconst linkOptsOut = (link) => {\n if (link.getAttribute(\"data-turbo-prefetch\") === \"false\") return true\n if (link.getAttribute(\"data-turbo\") === \"false\") return true\n\n const turboPrefetchParent = findClosestRecursively(link, \"[data-turbo-prefetch]\");\n if (turboPrefetchParent && turboPrefetchParent.getAttribute(\"data-turbo-prefetch\") === \"false\") return true\n\n return false\n};\n\nconst nonSafeLink = (link) => {\n const turboMethod = link.getAttribute(\"data-turbo-method\");\n if (turboMethod && turboMethod.toLowerCase() !== \"get\") return true\n\n if (isUJS(link)) return true\n if (link.hasAttribute(\"data-turbo-confirm\")) return true\n if (link.hasAttribute(\"data-turbo-stream\")) return true\n\n return false\n};\n\nconst isUJS = (link) => {\n return link.hasAttribute(\"data-remote\") || link.hasAttribute(\"data-behavior\") || link.hasAttribute(\"data-confirm\") || link.hasAttribute(\"data-method\")\n};\n\nconst eventPrevented = (link) => {\n const event = dispatch(\"turbo:before-prefetch\", { target: link, cancelable: true });\n return event.defaultPrevented\n};\n\nclass Navigator {\n constructor(delegate) {\n this.delegate = delegate;\n }\n\n proposeVisit(location, options = {}) {\n if (this.delegate.allowsVisitingLocationWithAction(location, options.action)) {\n this.delegate.visitProposedToLocation(location, options);\n }\n }\n\n startVisit(locatable, restorationIdentifier, options = {}) {\n this.stop();\n this.currentVisit = new Visit(this, expandURL(locatable), restorationIdentifier, {\n referrer: this.location,\n ...options\n });\n this.currentVisit.start();\n }\n\n submitForm(form, submitter) {\n this.stop();\n this.formSubmission = new FormSubmission(this, form, submitter, true);\n\n this.formSubmission.start();\n }\n\n stop() {\n if (this.formSubmission) {\n this.formSubmission.stop();\n delete this.formSubmission;\n }\n\n if (this.currentVisit) {\n this.currentVisit.cancel();\n delete this.currentVisit;\n }\n }\n\n get adapter() {\n return this.delegate.adapter\n }\n\n get view() {\n return this.delegate.view\n }\n\n get rootLocation() {\n return this.view.snapshot.rootLocation\n }\n\n get history() {\n return this.delegate.history\n }\n\n // Form submission delegate\n\n formSubmissionStarted(formSubmission) {\n // Not all adapters implement formSubmissionStarted\n if (typeof this.adapter.formSubmissionStarted === \"function\") {\n this.adapter.formSubmissionStarted(formSubmission);\n }\n }\n\n async formSubmissionSucceededWithResponse(formSubmission, fetchResponse) {\n if (formSubmission == this.formSubmission) {\n const responseHTML = await fetchResponse.responseHTML;\n if (responseHTML) {\n const shouldCacheSnapshot = formSubmission.isSafe;\n if (!shouldCacheSnapshot) {\n this.view.clearSnapshotCache();\n }\n\n const { statusCode, redirected } = fetchResponse;\n const action = this.#getActionForFormSubmission(formSubmission, fetchResponse);\n const visitOptions = {\n action,\n shouldCacheSnapshot,\n response: { statusCode, responseHTML, redirected }\n };\n this.proposeVisit(fetchResponse.location, visitOptions);\n }\n }\n }\n\n async formSubmissionFailedWithResponse(formSubmission, fetchResponse) {\n const responseHTML = await fetchResponse.responseHTML;\n\n if (responseHTML) {\n const snapshot = PageSnapshot.fromHTMLString(responseHTML);\n if (fetchResponse.serverError) {\n await this.view.renderError(snapshot, this.currentVisit);\n } else {\n await this.view.renderPage(snapshot, false, true, this.currentVisit);\n }\n if(!snapshot.shouldPreserveScrollPosition) {\n this.view.scrollToTop();\n }\n this.view.clearSnapshotCache();\n }\n }\n\n formSubmissionErrored(formSubmission, error) {\n console.error(error);\n }\n\n formSubmissionFinished(formSubmission) {\n // Not all adapters implement formSubmissionFinished\n if (typeof this.adapter.formSubmissionFinished === \"function\") {\n this.adapter.formSubmissionFinished(formSubmission);\n }\n }\n\n // Visit delegate\n\n visitStarted(visit) {\n this.delegate.visitStarted(visit);\n }\n\n visitCompleted(visit) {\n this.delegate.visitCompleted(visit);\n delete this.currentVisit;\n }\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\n return (\n action !== \"replace\" &&\n getRequestURL(location) === getRequestURL(this.view.lastRenderedLocation) &&\n (isRestorationToTop || (anchor != null && anchor !== currentAnchor))\n )\n }\n\n visitScrolledToSamePageLocation(oldURL, newURL) {\n this.delegate.visitScrolledToSamePageLocation(oldURL, newURL);\n }\n\n // Visits\n\n get location() {\n return this.history.location\n }\n\n get restorationIdentifier() {\n return this.history.restorationIdentifier\n }\n\n #getActionForFormSubmission(formSubmission, fetchResponse) {\n const { submitter, formElement } = formSubmission;\n return getVisitAction(submitter, formElement) || this.#getDefaultAction(fetchResponse)\n }\n\n #getDefaultAction(fetchResponse) {\n const sameLocationRedirect = fetchResponse.redirected && fetchResponse.location.href === this.location?.href;\n return sameLocationRedirect ? \"replace\" : \"advance\"\n }\n}\n\nconst PageStage = {\n initial: 0,\n loading: 1,\n interactive: 2,\n complete: 3\n};\n\nclass PageObserver {\n stage = PageStage.initial\n started = false\n\n constructor(delegate) {\n this.delegate = delegate;\n }\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\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\n interpretReadyState = () => {\n const { readyState } = this;\n if (readyState == \"interactive\") {\n this.pageIsInteractive();\n } else if (readyState == \"complete\") {\n this.pageIsComplete();\n }\n }\n\n pageIsInteractive() {\n if (this.stage == PageStage.loading) {\n this.stage = PageStage.interactive;\n this.delegate.pageBecameInteractive();\n }\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\n pageWillUnload = () => {\n this.delegate.pageWillUnload();\n }\n\n get readyState() {\n return document.readyState\n }\n}\n\nclass ScrollObserver {\n started = false\n\n constructor(delegate) {\n this.delegate = delegate;\n }\n\n start() {\n if (!this.started) {\n addEventListener(\"scroll\", this.onScroll, false);\n this.onScroll();\n this.started = true;\n }\n }\n\n stop() {\n if (this.started) {\n removeEventListener(\"scroll\", this.onScroll, false);\n this.started = false;\n }\n }\n\n onScroll = () => {\n this.updatePosition({ x: window.pageXOffset, y: window.pageYOffset });\n }\n\n // Private\n\n updatePosition(position) {\n this.delegate.scrollPositionChanged(position);\n }\n}\n\nclass StreamMessageRenderer {\n render({ fragment }) {\n Bardo.preservingPermanentElements(this, getPermanentElementMapForFragment(fragment), () => {\n withAutofocusFromFragment(fragment, () => {\n withPreservedFocus(() => {\n document.documentElement.appendChild(fragment);\n });\n });\n });\n }\n\n // Bardo delegate\n\n enteringBardo(currentPermanentElement, newPermanentElement) {\n newPermanentElement.replaceWith(currentPermanentElement.cloneNode(true));\n }\n\n leavingBardo() {}\n}\n\nfunction getPermanentElementMapForFragment(fragment) {\n const permanentElementsInDocument = queryPermanentElementsAll(document.documentElement);\n const permanentElementMap = {};\n for (const permanentElementInDocument of permanentElementsInDocument) {\n const { id } = permanentElementInDocument;\n\n for (const streamElement of fragment.querySelectorAll(\"turbo-stream\")) {\n const elementInStream = getPermanentElementById(streamElement.templateElement.content, id);\n\n if (elementInStream) {\n permanentElementMap[id] = [permanentElementInDocument, elementInStream];\n }\n }\n }\n\n return permanentElementMap\n}\n\nasync function withAutofocusFromFragment(fragment, callback) {\n const generatedID = `turbo-stream-autofocus-${uuid()}`;\n const turboStreams = fragment.querySelectorAll(\"turbo-stream\");\n const elementWithAutofocus = firstAutofocusableElementInStreams(turboStreams);\n let willAutofocusId = null;\n\n if (elementWithAutofocus) {\n if (elementWithAutofocus.id) {\n willAutofocusId = elementWithAutofocus.id;\n } else {\n willAutofocusId = generatedID;\n }\n\n elementWithAutofocus.id = willAutofocusId;\n }\n\n callback();\n await nextRepaint();\n\n const hasNoActiveElement = document.activeElement == null || document.activeElement == document.body;\n\n if (hasNoActiveElement && willAutofocusId) {\n const elementToAutofocus = document.getElementById(willAutofocusId);\n\n if (elementIsFocusable(elementToAutofocus)) {\n elementToAutofocus.focus();\n }\n if (elementToAutofocus && elementToAutofocus.id == generatedID) {\n elementToAutofocus.removeAttribute(\"id\");\n }\n }\n}\n\nasync function withPreservedFocus(callback) {\n const [activeElementBeforeRender, activeElementAfterRender] = await around(callback, () => document.activeElement);\n\n const restoreFocusTo = activeElementBeforeRender && activeElementBeforeRender.id;\n\n if (restoreFocusTo) {\n const elementToFocus = document.getElementById(restoreFocusTo);\n\n if (elementIsFocusable(elementToFocus) && elementToFocus != activeElementAfterRender) {\n elementToFocus.focus();\n }\n }\n}\n\nfunction firstAutofocusableElementInStreams(nodeListOfStreamElements) {\n for (const streamElement of nodeListOfStreamElements) {\n const elementWithAutofocus = queryAutofocusableElement(streamElement.templateElement.content);\n\n if (elementWithAutofocus) return elementWithAutofocus\n }\n\n return null\n}\n\nclass StreamObserver {\n sources = new Set()\n #started = false\n\n constructor(delegate) {\n this.delegate = delegate;\n }\n\n start() {\n if (!this.#started) {\n this.#started = true;\n addEventListener(\"turbo:before-fetch-response\", this.inspectFetchResponse, false);\n }\n }\n\n stop() {\n if (this.#started) {\n this.#started = false;\n removeEventListener(\"turbo:before-fetch-response\", this.inspectFetchResponse, false);\n }\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\n disconnectStreamSource(source) {\n if (this.streamSourceIsConnected(source)) {\n this.sources.delete(source);\n source.removeEventListener(\"message\", this.receiveMessageEvent, false);\n }\n }\n\n streamSourceIsConnected(source) {\n return this.sources.has(source)\n }\n\n inspectFetchResponse = (event) => {\n const response = fetchResponseFromEvent(event);\n if (response && fetchResponseIsStream(response)) {\n event.preventDefault();\n this.receiveMessageResponse(response);\n }\n }\n\n receiveMessageEvent = (event) => {\n if (this.#started && typeof event.data == \"string\") {\n this.receiveMessageHTML(event.data);\n }\n }\n\n async receiveMessageResponse(response) {\n const html = await response.responseHTML;\n if (html) {\n this.receiveMessageHTML(html);\n }\n }\n\n receiveMessageHTML(html) {\n this.delegate.receivedMessageFromStream(StreamMessage.wrap(html));\n }\n}\n\nfunction fetchResponseFromEvent(event) {\n const fetchResponse = event.detail?.fetchResponse;\n if (fetchResponse instanceof FetchResponse) {\n return fetchResponse\n }\n}\n\nfunction fetchResponseIsStream(response) {\n const contentType = response.contentType ?? \"\";\n return contentType.startsWith(StreamMessage.contentType)\n}\n\nclass ErrorRenderer extends Renderer {\n static renderElement(currentElement, newElement) {\n const { documentElement, body } = document;\n\n documentElement.replaceChild(newElement, body);\n }\n\n async render() {\n this.replaceHeadAndBody();\n this.activateScriptElements();\n }\n\n replaceHeadAndBody() {\n const { documentElement, head } = document;\n documentElement.replaceChild(this.newHead, head);\n this.renderElement(this.currentElement, this.newElement);\n }\n\n activateScriptElements() {\n for (const replaceableElement of this.scriptElements) {\n const parentNode = replaceableElement.parentNode;\n if (parentNode) {\n const element = activateScriptElement(replaceableElement);\n parentNode.replaceChild(element, replaceableElement);\n }\n }\n }\n\n get newHead() {\n return this.newSnapshot.headSnapshot.element\n }\n\n get scriptElements() {\n return document.documentElement.querySelectorAll(\"script\")\n }\n}\n\nclass PageRenderer extends Renderer {\n static renderElement(currentElement, newElement) {\n if (document.body && newElement instanceof HTMLBodyElement) {\n document.body.replaceWith(newElement);\n } else {\n document.documentElement.appendChild(newElement);\n }\n }\n\n get shouldRender() {\n return this.newSnapshot.isVisitable && this.trackedElementsAreIdentical\n }\n\n get reloadReason() {\n if (!this.newSnapshot.isVisitable) {\n return {\n reason: \"turbo_visit_control_is_reload\"\n }\n }\n\n if (!this.trackedElementsAreIdentical) {\n return {\n reason: \"tracked_element_mismatch\"\n }\n }\n }\n\n async prepareToRender() {\n this.#setLanguage();\n await this.mergeHead();\n }\n\n async render() {\n if (this.willRender) {\n await this.replaceBody();\n }\n }\n\n finishRendering() {\n super.finishRendering();\n if (!this.isPreview) {\n this.focusFirstAutofocusableElement();\n }\n }\n\n get currentHeadSnapshot() {\n return this.currentSnapshot.headSnapshot\n }\n\n get newHeadSnapshot() {\n return this.newSnapshot.headSnapshot\n }\n\n get newElement() {\n return this.newSnapshot.element\n }\n\n #setLanguage() {\n const { documentElement } = this.currentSnapshot;\n const { lang } = this.newSnapshot;\n\n if (lang) {\n documentElement.setAttribute(\"lang\", lang);\n } else {\n documentElement.removeAttribute(\"lang\");\n }\n }\n\n async mergeHead() {\n const mergedHeadElements = this.mergeProvisionalElements();\n const newStylesheetElements = this.copyNewHeadStylesheetElements();\n this.copyNewHeadScriptElements();\n\n await mergedHeadElements;\n await newStylesheetElements;\n\n if (this.willRender) {\n this.removeUnusedDynamicStylesheetElements();\n }\n }\n\n async replaceBody() {\n await this.preservingPermanentElements(async () => {\n this.activateNewBody();\n await this.assignNewBody();\n });\n }\n\n get trackedElementsAreIdentical() {\n return this.currentHeadSnapshot.trackedElementSignature == this.newHeadSnapshot.trackedElementSignature\n }\n\n async copyNewHeadStylesheetElements() {\n const loadingElements = [];\n\n for (const element of this.newHeadStylesheetElements) {\n loadingElements.push(waitForLoad(element));\n\n document.head.appendChild(element);\n }\n\n await Promise.all(loadingElements);\n }\n\n copyNewHeadScriptElements() {\n for (const element of this.newHeadScriptElements) {\n document.head.appendChild(activateScriptElement(element));\n }\n }\n\n removeUnusedDynamicStylesheetElements() {\n for (const element of this.unusedDynamicStylesheetElements) {\n document.head.removeChild(element);\n }\n }\n\n async mergeProvisionalElements() {\n const newHeadElements = [...this.newHeadProvisionalElements];\n\n for (const element of this.currentHeadProvisionalElements) {\n if (!this.isCurrentElementInElementList(element, newHeadElements)) {\n document.head.removeChild(element);\n }\n }\n\n for (const element of newHeadElements) {\n document.head.appendChild(element);\n }\n }\n\n isCurrentElementInElementList(element, elementList) {\n for (const [index, newElement] of elementList.entries()) {\n // if title element...\n if (element.tagName == \"TITLE\") {\n if (newElement.tagName != \"TITLE\") {\n continue\n }\n if (element.innerHTML == newElement.innerHTML) {\n elementList.splice(index, 1);\n return true\n }\n }\n\n // if any other element...\n if (newElement.isEqualNode(element)) {\n elementList.splice(index, 1);\n return true\n }\n }\n\n return false\n }\n\n removeCurrentHeadProvisionalElements() {\n for (const element of this.currentHeadProvisionalElements) {\n document.head.removeChild(element);\n }\n }\n\n copyNewHeadProvisionalElements() {\n for (const element of this.newHeadProvisionalElements) {\n document.head.appendChild(element);\n }\n }\n\n activateNewBody() {\n document.adoptNode(this.newElement);\n this.activateNewBodyScriptElements();\n }\n\n activateNewBodyScriptElements() {\n for (const inertScriptElement of this.newBodyScriptElements) {\n const activatedScriptElement = activateScriptElement(inertScriptElement);\n inertScriptElement.replaceWith(activatedScriptElement);\n }\n }\n\n async assignNewBody() {\n await this.renderElement(this.currentElement, this.newElement);\n }\n\n get unusedDynamicStylesheetElements() {\n return this.oldHeadStylesheetElements.filter((element) => {\n return element.getAttribute(\"data-turbo-track\") === \"dynamic\"\n })\n }\n\n get oldHeadStylesheetElements() {\n return this.currentHeadSnapshot.getStylesheetElementsNotInSnapshot(this.newHeadSnapshot)\n }\n\n get newHeadStylesheetElements() {\n return this.newHeadSnapshot.getStylesheetElementsNotInSnapshot(this.currentHeadSnapshot)\n }\n\n get newHeadScriptElements() {\n return this.newHeadSnapshot.getScriptElementsNotInSnapshot(this.currentHeadSnapshot)\n }\n\n get currentHeadProvisionalElements() {\n return this.currentHeadSnapshot.provisionalElements\n }\n\n get newHeadProvisionalElements() {\n return this.newHeadSnapshot.provisionalElements\n }\n\n get newBodyScriptElements() {\n return this.newElement.querySelectorAll(\"script\")\n }\n}\n\nclass MorphingPageRenderer extends PageRenderer {\n static renderElement(currentElement, newElement) {\n morphElements(currentElement, newElement, {\n callbacks: {\n beforeNodeMorphed: element => !canRefreshFrame(element)\n }\n });\n\n for (const frame of currentElement.querySelectorAll(\"turbo-frame\")) {\n if (canRefreshFrame(frame)) frame.reload();\n }\n\n dispatch(\"turbo:morph\", { detail: { currentElement, newElement } });\n }\n\n async preservingPermanentElements(callback) {\n return await callback()\n }\n\n get renderMethod() {\n return \"morph\"\n }\n\n get shouldAutofocus() {\n return false\n }\n}\n\nfunction canRefreshFrame(frame) {\n return frame instanceof FrameElement &&\n frame.src &&\n frame.refresh === \"morph\" &&\n !frame.closest(\"[data-turbo-permanent]\")\n}\n\nclass SnapshotCache {\n keys = []\n snapshots = {}\n\n constructor(size) {\n this.size = size;\n }\n\n has(location) {\n return toCacheKey(location) in this.snapshots\n }\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\n put(location, snapshot) {\n this.write(location, snapshot);\n this.touch(location);\n return snapshot\n }\n\n clear() {\n this.snapshots = {};\n }\n\n // Private\n\n read(location) {\n return this.snapshots[toCacheKey(location)]\n }\n\n write(location, snapshot) {\n this.snapshots[toCacheKey(location)] = snapshot;\n }\n\n touch(location) {\n const key = toCacheKey(location);\n const index = this.keys.indexOf(key);\n if (index > -1) this.keys.splice(index, 1);\n this.keys.unshift(key);\n this.trim();\n }\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 snapshotCache = new SnapshotCache(10)\n lastRenderedLocation = new URL(location.href)\n forceReloaded = false\n\n shouldTransitionTo(newSnapshot) {\n return this.snapshot.prefersViewTransitions && newSnapshot.prefersViewTransitions\n }\n\n renderPage(snapshot, isPreview = false, willRender = true, visit) {\n const shouldMorphPage = this.isPageRefresh(visit) && this.snapshot.shouldMorphPage;\n const rendererClass = shouldMorphPage ? MorphingPageRenderer : PageRenderer;\n\n const renderer = new rendererClass(this.snapshot, snapshot, isPreview, willRender);\n\n if (!renderer.shouldRender) {\n this.forceReloaded = true;\n } else {\n visit?.changeHistory();\n }\n\n return this.render(renderer)\n }\n\n renderError(snapshot, visit) {\n visit?.changeHistory();\n const renderer = new ErrorRenderer(this.snapshot, snapshot, false);\n return this.render(renderer)\n }\n\n clearSnapshotCache() {\n this.snapshotCache.clear();\n }\n\n async cacheSnapshot(snapshot = this.snapshot) {\n if (snapshot.isCacheable) {\n this.delegate.viewWillCacheSnapshot();\n const { lastRenderedLocation: location } = this;\n await nextEventLoopTick();\n const cachedSnapshot = snapshot.clone();\n this.snapshotCache.put(location, cachedSnapshot);\n return cachedSnapshot\n }\n }\n\n getCachedSnapshotForLocation(location) {\n return this.snapshotCache.get(location)\n }\n\n isPageRefresh(visit) {\n return !visit || (this.lastRenderedLocation.pathname === visit.location.pathname && visit.action === \"replace\")\n }\n\n shouldPreserveScrollPosition(visit) {\n return this.isPageRefresh(visit) && this.snapshot.shouldPreserveScrollPosition\n }\n\n get snapshot() {\n return PageSnapshot.fromElement(this.element)\n }\n}\n\nclass Preloader {\n selector = \"a[data-turbo-preload]\"\n\n constructor(delegate, snapshotCache) {\n this.delegate = delegate;\n this.snapshotCache = snapshotCache;\n }\n\n start() {\n if (document.readyState === \"loading\") {\n document.addEventListener(\"DOMContentLoaded\", this.#preloadAll);\n } else {\n this.preloadOnLoadLinksForView(document.body);\n }\n }\n\n stop() {\n document.removeEventListener(\"DOMContentLoaded\", this.#preloadAll);\n }\n\n preloadOnLoadLinksForView(element) {\n for (const link of element.querySelectorAll(this.selector)) {\n if (this.delegate.shouldPreloadLink(link)) {\n this.preloadURL(link);\n }\n }\n }\n\n async preloadURL(link) {\n const location = new URL(link.href);\n\n if (this.snapshotCache.has(location)) {\n return\n }\n\n const fetchRequest = new FetchRequest(this, FetchMethod.get, location, new URLSearchParams(), link);\n await fetchRequest.perform();\n }\n\n // Fetch request delegate\n\n prepareRequest(fetchRequest) {\n fetchRequest.headers[\"X-Sec-Purpose\"] = \"prefetch\";\n }\n\n async requestSucceededWithResponse(fetchRequest, fetchResponse) {\n try {\n const responseHTML = await fetchResponse.responseHTML;\n const snapshot = PageSnapshot.fromHTMLString(responseHTML);\n\n this.snapshotCache.put(fetchRequest.url, snapshot);\n } catch (_) {\n // If we cannot preload that is ok!\n }\n }\n\n requestStarted(fetchRequest) {}\n\n requestErrored(fetchRequest) {}\n\n requestFinished(fetchRequest) {}\n\n requestPreventedHandlingResponse(fetchRequest, fetchResponse) {}\n\n requestFailedWithResponse(fetchRequest, fetchResponse) {}\n\n #preloadAll = () => {\n this.preloadOnLoadLinksForView(document.body);\n }\n}\n\nclass Cache {\n constructor(session) {\n this.session = session;\n }\n\n clear() {\n this.session.clearCache();\n }\n\n resetCacheControl() {\n this.#setCacheControl(\"\");\n }\n\n exemptPageFromCache() {\n this.#setCacheControl(\"no-cache\");\n }\n\n exemptPageFromPreview() {\n this.#setCacheControl(\"no-preview\");\n }\n\n #setCacheControl(value) {\n setMetaContent(\"turbo-cache-control\", value);\n }\n}\n\nclass Session {\n navigator = new Navigator(this)\n history = new History(this)\n view = new PageView(this, document.documentElement)\n adapter = new BrowserAdapter(this)\n\n pageObserver = new PageObserver(this)\n cacheObserver = new CacheObserver()\n linkPrefetchObserver = new LinkPrefetchObserver(this, document)\n linkClickObserver = new LinkClickObserver(this, window)\n formSubmitObserver = new FormSubmitObserver(this, document)\n scrollObserver = new ScrollObserver(this)\n streamObserver = new StreamObserver(this)\n formLinkClickObserver = new FormLinkClickObserver(this, document.documentElement)\n frameRedirector = new FrameRedirector(this, document.documentElement)\n streamMessageRenderer = new StreamMessageRenderer()\n cache = new Cache(this)\n\n enabled = true\n started = false\n #pageRefreshDebouncePeriod = 150\n\n constructor(recentRequests) {\n this.recentRequests = recentRequests;\n this.preloader = new Preloader(this, this.view.snapshotCache);\n this.debouncedRefresh = this.refresh;\n this.pageRefreshDebouncePeriod = this.pageRefreshDebouncePeriod;\n }\n\n start() {\n if (!this.started) {\n this.pageObserver.start();\n this.cacheObserver.start();\n this.linkPrefetchObserver.start();\n this.formLinkClickObserver.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.preloader.start();\n this.started = true;\n this.enabled = true;\n }\n }\n\n disable() {\n this.enabled = false;\n }\n\n stop() {\n if (this.started) {\n this.pageObserver.stop();\n this.cacheObserver.stop();\n this.linkPrefetchObserver.stop();\n this.formLinkClickObserver.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.preloader.stop();\n this.started = false;\n }\n }\n\n registerAdapter(adapter) {\n this.adapter = adapter;\n }\n\n visit(location, options = {}) {\n const frameElement = options.frame ? document.getElementById(options.frame) : null;\n\n if (frameElement instanceof FrameElement) {\n const action = options.action || getVisitAction(frameElement);\n\n frameElement.delegate.proposeVisitIfNavigatedWithAction(frameElement, action);\n frameElement.src = location.toString();\n } else {\n this.navigator.proposeVisit(expandURL(location), options);\n }\n }\n\n refresh(url, requestId) {\n const isRecentRequest = requestId && this.recentRequests.has(requestId);\n if (!isRecentRequest && !this.navigator.currentVisit) {\n this.visit(url, { action: \"replace\", shouldCacheSnapshot: false });\n }\n }\n\n connectStreamSource(source) {\n this.streamObserver.connectStreamSource(source);\n }\n\n disconnectStreamSource(source) {\n this.streamObserver.disconnectStreamSource(source);\n }\n\n renderStreamMessage(message) {\n this.streamMessageRenderer.render(StreamMessage.wrap(message));\n }\n\n clearCache() {\n this.view.clearSnapshotCache();\n }\n\n setProgressBarDelay(delay) {\n console.warn(\n \"Please replace `session.setProgressBarDelay(delay)` with `session.progressBarDelay = delay`. The function is deprecated and will be removed in a future version of Turbo.`\"\n );\n\n this.progressBarDelay = delay;\n }\n\n set progressBarDelay(delay) {\n config.drive.progressBarDelay = delay;\n }\n\n get progressBarDelay() {\n return config.drive.progressBarDelay\n }\n\n set drive(value) {\n config.drive.enabled = value;\n }\n\n get drive() {\n return config.drive.enabled\n }\n\n set formMode(value) {\n config.forms.mode = value;\n }\n\n get formMode() {\n return config.forms.mode\n }\n\n get location() {\n return this.history.location\n }\n\n get restorationIdentifier() {\n return this.history.restorationIdentifier\n }\n\n get pageRefreshDebouncePeriod() {\n return this.#pageRefreshDebouncePeriod\n }\n\n set pageRefreshDebouncePeriod(value) {\n this.refresh = debounce(this.debouncedRefresh.bind(this), value);\n this.#pageRefreshDebouncePeriod = value;\n }\n\n // Preloader delegate\n\n shouldPreloadLink(element) {\n const isUnsafe = element.hasAttribute(\"data-turbo-method\");\n const isStream = element.hasAttribute(\"data-turbo-stream\");\n const frameTarget = element.getAttribute(\"data-turbo-frame\");\n const frame = frameTarget == \"_top\" ?\n null :\n document.getElementById(frameTarget) || findClosestRecursively(element, \"turbo-frame:not([disabled])\");\n\n if (isUnsafe || isStream || frame instanceof FrameElement) {\n return false\n } else {\n const location = new URL(element.href);\n\n return this.elementIsNavigatable(element) && locationIsVisitable(location, this.snapshot.rootLocation)\n }\n }\n\n // History delegate\n\n historyPoppedToLocationWithRestorationIdentifierAndDirection(location, restorationIdentifier, direction) {\n if (this.enabled) {\n this.navigator.startVisit(location, restorationIdentifier, {\n action: \"restore\",\n historyChanged: true,\n direction\n });\n } else {\n this.adapter.pageInvalidated({\n reason: \"turbo_disabled\"\n });\n }\n }\n\n // Scroll observer delegate\n\n scrollPositionChanged(position) {\n this.history.updateRestorationData({ scrollPosition: position });\n }\n\n // Form click observer delegate\n\n willSubmitFormLinkToLocation(link, location) {\n return this.elementIsNavigatable(link) && locationIsVisitable(location, this.snapshot.rootLocation)\n }\n\n submittedFormLinkToLocation() {}\n\n // Link hover observer delegate\n\n canPrefetchRequestToLocation(link, location) {\n return (\n this.elementIsNavigatable(link) &&\n locationIsVisitable(location, this.snapshot.rootLocation)\n )\n }\n\n // Link click observer delegate\n\n willFollowLinkToLocation(link, location, event) {\n return (\n this.elementIsNavigatable(link) &&\n locationIsVisitable(location, this.snapshot.rootLocation) &&\n this.applicationAllowsFollowingLinkToLocation(link, location, event)\n )\n }\n\n followedLinkToLocation(link, location) {\n const action = this.getActionForLink(link);\n const acceptsStreamResponse = link.hasAttribute(\"data-turbo-stream\");\n\n this.visit(location.href, { action, acceptsStreamResponse });\n }\n\n // Navigator delegate\n\n allowsVisitingLocationWithAction(location, action) {\n return this.locationWithActionIsSamePage(location, action) || this.applicationAllowsVisitingLocation(location)\n }\n\n visitProposedToLocation(location, options) {\n extendURLWithDeprecatedProperties(location);\n this.adapter.visitProposedToLocation(location, options);\n }\n\n // Visit delegate\n\n visitStarted(visit) {\n if (!visit.acceptsStreamResponse) {\n markAsBusy(document.documentElement);\n this.view.markVisitDirection(visit.direction);\n }\n extendURLWithDeprecatedProperties(visit.location);\n if (!visit.silent) {\n this.notifyApplicationAfterVisitingLocation(visit.location, visit.action);\n }\n }\n\n visitCompleted(visit) {\n this.view.unmarkVisitDirection();\n clearBusyState(document.documentElement);\n this.notifyApplicationAfterPageLoad(visit.getTimingMetrics());\n }\n\n locationWithActionIsSamePage(location, action) {\n return this.navigator.locationWithActionIsSamePage(location, action)\n }\n\n visitScrolledToSamePageLocation(oldURL, newURL) {\n this.notifyApplicationAfterVisitingSamePageLocation(oldURL, newURL);\n }\n\n // Form submit observer delegate\n\n willSubmitForm(form, submitter) {\n const action = getAction$1(form, submitter);\n\n return (\n this.submissionIsNavigatable(form, submitter) &&\n locationIsVisitable(expandURL(action), this.snapshot.rootLocation)\n )\n }\n\n formSubmitted(form, submitter) {\n this.navigator.submitForm(form, submitter);\n }\n\n // Page observer delegate\n\n pageBecameInteractive() {\n this.view.lastRenderedLocation = this.location;\n this.notifyApplicationAfterPageLoad();\n }\n\n pageLoaded() {\n this.history.assumeControlOfScrollRestoration();\n }\n\n pageWillUnload() {\n this.history.relinquishControlOfScrollRestoration();\n }\n\n // Stream observer delegate\n\n receivedMessageFromStream(message) {\n this.renderStreamMessage(message);\n }\n\n // Page view delegate\n\n viewWillCacheSnapshot() {\n if (!this.navigator.currentVisit?.silent) {\n this.notifyApplicationBeforeCachingSnapshot();\n }\n }\n\n allowsImmediateRender({ element }, options) {\n const event = this.notifyApplicationBeforeRender(element, options);\n const {\n defaultPrevented,\n detail: { render }\n } = event;\n\n if (this.view.renderer && render) {\n this.view.renderer.renderElement = render;\n }\n\n return !defaultPrevented\n }\n\n viewRenderedSnapshot(_snapshot, _isPreview, renderMethod) {\n this.view.lastRenderedLocation = this.history.location;\n this.notifyApplicationAfterRender(renderMethod);\n }\n\n preloadOnLoadLinksForView(element) {\n this.preloader.preloadOnLoadLinksForView(element);\n }\n\n viewInvalidated(reason) {\n this.adapter.pageInvalidated(reason);\n }\n\n // Frame element\n\n frameLoaded(frame) {\n this.notifyApplicationAfterFrameLoad(frame);\n }\n\n frameRendered(fetchResponse, frame) {\n this.notifyApplicationAfterFrameRender(fetchResponse, frame);\n }\n\n // Application events\n\n applicationAllowsFollowingLinkToLocation(link, location, ev) {\n const event = this.notifyApplicationAfterClickingLinkToLocation(link, location, ev);\n return !event.defaultPrevented\n }\n\n applicationAllowsVisitingLocation(location) {\n const event = this.notifyApplicationBeforeVisitingLocation(location);\n return !event.defaultPrevented\n }\n\n notifyApplicationAfterClickingLinkToLocation(link, location, event) {\n return dispatch(\"turbo:click\", {\n target: link,\n detail: { url: location.href, originalEvent: event },\n cancelable: true\n })\n }\n\n notifyApplicationBeforeVisitingLocation(location) {\n return dispatch(\"turbo:before-visit\", {\n detail: { url: location.href },\n cancelable: true\n })\n }\n\n notifyApplicationAfterVisitingLocation(location, action) {\n return dispatch(\"turbo:visit\", { detail: { url: location.href, action } })\n }\n\n notifyApplicationBeforeCachingSnapshot() {\n return dispatch(\"turbo:before-cache\")\n }\n\n notifyApplicationBeforeRender(newBody, options) {\n return dispatch(\"turbo:before-render\", {\n detail: { newBody, ...options },\n cancelable: true\n })\n }\n\n notifyApplicationAfterRender(renderMethod) {\n return dispatch(\"turbo:render\", { detail: { renderMethod } })\n }\n\n notifyApplicationAfterPageLoad(timing = {}) {\n return dispatch(\"turbo:load\", {\n detail: { url: this.location.href, timing }\n })\n }\n\n notifyApplicationAfterVisitingSamePageLocation(oldURL, newURL) {\n dispatchEvent(\n new HashChangeEvent(\"hashchange\", {\n oldURL: oldURL.toString(),\n newURL: newURL.toString()\n })\n );\n }\n\n notifyApplicationAfterFrameLoad(frame) {\n return dispatch(\"turbo:frame-load\", { target: frame })\n }\n\n notifyApplicationAfterFrameRender(fetchResponse, frame) {\n return dispatch(\"turbo:frame-render\", {\n detail: { fetchResponse },\n target: frame,\n cancelable: true\n })\n }\n\n // Helpers\n\n submissionIsNavigatable(form, submitter) {\n if (config.forms.mode == \"off\") {\n return false\n } else {\n const submitterIsNavigatable = submitter ? this.elementIsNavigatable(submitter) : true;\n\n if (config.forms.mode == \"optin\") {\n return submitterIsNavigatable && form.closest('[data-turbo=\"true\"]') != null\n } else {\n return submitterIsNavigatable && this.elementIsNavigatable(form)\n }\n }\n }\n\n elementIsNavigatable(element) {\n const container = findClosestRecursively(element, \"[data-turbo]\");\n const withinFrame = findClosestRecursively(element, \"turbo-frame\");\n\n // Check if Drive is enabled on the session or we're within a Frame.\n if (config.drive.enabled || withinFrame) {\n // Element is navigatable by default, unless `data-turbo=\"false\"`.\n if (container) {\n return container.getAttribute(\"data-turbo\") != \"false\"\n } else {\n return true\n }\n } else {\n // Element isn't navigatable by default, unless `data-turbo=\"true\"`.\n if (container) {\n return container.getAttribute(\"data-turbo\") == \"true\"\n } else {\n return false\n }\n }\n }\n\n // Private\n\n getActionForLink(link) {\n return getVisitAction(link) || \"advance\"\n }\n\n get snapshot() {\n return this.view.snapshot\n }\n}\n\n// Older versions of the Turbo Native adapters referenced the\n// `Location#absoluteURL` property in their implementations of\n// the `Adapter#visitProposedToLocation()` and `#visitStarted()`\n// methods. The Location class has since been removed in favor\n// of the DOM URL API, and accordingly all Adapter methods now\n// receive URL objects.\n//\n// We alias #absoluteURL to #toString() here to avoid crashing\n// older adapters which do not expect URL objects. We should\n// consider removing this support at some point in the future.\n\nfunction extendURLWithDeprecatedProperties(url) {\n Object.defineProperties(url, deprecatedLocationPropertyDescriptors);\n}\n\nconst deprecatedLocationPropertyDescriptors = {\n absoluteURL: {\n get() {\n return this.toString()\n }\n }\n};\n\nconst session = new Session(recentRequests);\nconst { cache, navigator: navigator$1 } = session;\n\n/**\n * Starts the main session.\n * This initialises any necessary observers such as those to monitor\n * link interactions.\n */\nfunction start() {\n session.start();\n}\n\n/**\n * Registers an adapter for the main session.\n *\n * @param adapter Adapter to register\n */\nfunction registerAdapter(adapter) {\n session.registerAdapter(adapter);\n}\n\n/**\n * Performs an application visit to the given location.\n *\n * @param location Location to visit (a URL or path)\n * @param options Options to apply\n * @param options.action Type of history navigation to apply (\"restore\",\n * \"replace\" or \"advance\")\n * @param options.historyChanged Specifies whether the browser history has\n * already been changed for this visit or not\n * @param options.referrer Specifies the referrer of this visit such that\n * navigations to the same page will not result in a new history entry.\n * @param options.snapshotHTML Cached snapshot to render\n * @param options.response Response of the specified location\n */\nfunction visit(location, options) {\n session.visit(location, options);\n}\n\n/**\n * Connects a stream source to the main session.\n *\n * @param source Stream source to connect\n */\nfunction connectStreamSource(source) {\n session.connectStreamSource(source);\n}\n\n/**\n * Disconnects a stream source from the main session.\n *\n * @param source Stream source to disconnect\n */\nfunction disconnectStreamSource(source) {\n session.disconnectStreamSource(source);\n}\n\n/**\n * Renders a stream message to the main session by appending it to the\n * current document.\n *\n * @param message Message to render\n */\nfunction renderStreamMessage(message) {\n session.renderStreamMessage(message);\n}\n\n/**\n * Removes all entries from the Turbo Drive page cache.\n * Call this when state has changed on the server that may affect cached pages.\n *\n * @deprecated since version 7.2.0 in favor of `Turbo.cache.clear()`\n */\nfunction clearCache() {\n console.warn(\n \"Please replace `Turbo.clearCache()` with `Turbo.cache.clear()`. The top-level function is deprecated and will be removed in a future version of Turbo.`\"\n );\n session.clearCache();\n}\n\n/**\n * Sets the delay after which the progress bar will appear during navigation.\n *\n * The progress bar appears after 500ms by default.\n *\n * Note that this method has no effect when used with the iOS or Android\n * adapters.\n *\n * @param delay Time to delay in milliseconds\n */\nfunction setProgressBarDelay(delay) {\n console.warn(\n \"Please replace `Turbo.setProgressBarDelay(delay)` with `Turbo.config.drive.progressBarDelay = delay`. The top-level function is deprecated and will be removed in a future version of Turbo.`\"\n );\n config.drive.progressBarDelay = delay;\n}\n\nfunction setConfirmMethod(confirmMethod) {\n console.warn(\n \"Please replace `Turbo.setConfirmMethod(confirmMethod)` with `Turbo.config.forms.confirm = confirmMethod`. The top-level function is deprecated and will be removed in a future version of Turbo.`\"\n );\n config.forms.confirm = confirmMethod;\n}\n\nfunction setFormMode(mode) {\n console.warn(\n \"Please replace `Turbo.setFormMode(mode)` with `Turbo.config.forms.mode = mode`. The top-level function is deprecated and will be removed in a future version of Turbo.`\"\n );\n config.forms.mode = mode;\n}\n\nvar Turbo = /*#__PURE__*/Object.freeze({\n __proto__: null,\n navigator: navigator$1,\n session: session,\n cache: cache,\n PageRenderer: PageRenderer,\n PageSnapshot: PageSnapshot,\n FrameRenderer: FrameRenderer,\n fetch: fetchWithTurboHeaders,\n config: config,\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 setFormMode: setFormMode\n});\n\nclass TurboFrameMissingError extends Error {}\n\nclass FrameController {\n fetchResponseLoaded = (_fetchResponse) => Promise.resolve()\n #currentFetchRequest = null\n #resolveVisitPromise = () => {}\n #connected = false\n #hasBeenLoaded = false\n #ignoredAttributes = new Set()\n #shouldMorphFrame = false\n action = null\n\n constructor(element) {\n this.element = element;\n this.view = new FrameView(this, this.element);\n this.appearanceObserver = new AppearanceObserver(this, this.element);\n this.formLinkClickObserver = new FormLinkClickObserver(this, this.element);\n this.linkInterceptor = new LinkInterceptor(this, this.element);\n this.restorationIdentifier = uuid();\n this.formSubmitObserver = new FormSubmitObserver(this, this.element);\n }\n\n // Frame delegate\n\n connect() {\n if (!this.#connected) {\n this.#connected = true;\n if (this.loadingStyle == FrameLoadingStyle.lazy) {\n this.appearanceObserver.start();\n } else {\n this.#loadSourceURL();\n }\n this.formLinkClickObserver.start();\n this.linkInterceptor.start();\n this.formSubmitObserver.start();\n }\n }\n\n disconnect() {\n if (this.#connected) {\n this.#connected = false;\n this.appearanceObserver.stop();\n this.formLinkClickObserver.stop();\n this.linkInterceptor.stop();\n this.formSubmitObserver.stop();\n }\n }\n\n disabledChanged() {\n if (this.loadingStyle == FrameLoadingStyle.eager) {\n this.#loadSourceURL();\n }\n }\n\n sourceURLChanged() {\n if (this.#isIgnoringChangesTo(\"src\")) return\n\n if (this.element.isConnected) {\n this.complete = false;\n }\n\n if (this.loadingStyle == FrameLoadingStyle.eager || this.#hasBeenLoaded) {\n this.#loadSourceURL();\n }\n }\n\n sourceURLReloaded() {\n const { refresh, src } = this.element;\n\n this.#shouldMorphFrame = src && refresh === \"morph\";\n\n this.element.removeAttribute(\"complete\");\n this.element.src = null;\n this.element.src = src;\n return this.element.loaded\n }\n\n loadingStyleChanged() {\n if (this.loadingStyle == FrameLoadingStyle.lazy) {\n this.appearanceObserver.start();\n } else {\n this.appearanceObserver.stop();\n this.#loadSourceURL();\n }\n }\n\n async #loadSourceURL() {\n if (this.enabled && this.isActive && !this.complete && this.sourceURL) {\n this.element.loaded = this.#visit(expandURL(this.sourceURL));\n this.appearanceObserver.stop();\n await this.element.loaded;\n this.#hasBeenLoaded = true;\n }\n }\n\n async loadResponse(fetchResponse) {\n if (fetchResponse.redirected || (fetchResponse.succeeded && fetchResponse.isHTML)) {\n this.sourceURL = fetchResponse.response.url;\n }\n\n try {\n const html = await fetchResponse.responseHTML;\n if (html) {\n const document = parseHTMLDocument(html);\n const pageSnapshot = PageSnapshot.fromDocument(document);\n\n if (pageSnapshot.isVisitable) {\n await this.#loadFrameResponse(fetchResponse, document);\n } else {\n await this.#handleUnvisitableFrameResponse(fetchResponse);\n }\n }\n } finally {\n this.#shouldMorphFrame = false;\n this.fetchResponseLoaded = () => Promise.resolve();\n }\n }\n\n // Appearance observer delegate\n\n elementAppearedInViewport(element) {\n this.proposeVisitIfNavigatedWithAction(element, getVisitAction(element));\n this.#loadSourceURL();\n }\n\n // Form link click observer delegate\n\n willSubmitFormLinkToLocation(link) {\n return this.#shouldInterceptNavigation(link)\n }\n\n submittedFormLinkToLocation(link, _location, form) {\n const frame = this.#findFrameElement(link);\n if (frame) form.setAttribute(\"data-turbo-frame\", frame.id);\n }\n\n // Link interceptor delegate\n\n shouldInterceptLinkClick(element, _location, _event) {\n return this.#shouldInterceptNavigation(element)\n }\n\n linkClickIntercepted(element, location) {\n this.#navigateFrame(element, location);\n }\n\n // Form submit observer delegate\n\n willSubmitForm(element, submitter) {\n return element.closest(\"turbo-frame\") == this.element && this.#shouldInterceptNavigation(element, submitter)\n }\n\n formSubmitted(element, submitter) {\n if (this.formSubmission) {\n this.formSubmission.stop();\n }\n\n this.formSubmission = new FormSubmission(this, element, submitter);\n const { fetchRequest } = this.formSubmission;\n this.prepareRequest(fetchRequest);\n this.formSubmission.start();\n }\n\n // Fetch request delegate\n\n prepareRequest(request) {\n request.headers[\"Turbo-Frame\"] = this.id;\n\n if (this.currentNavigationElement?.hasAttribute(\"data-turbo-stream\")) {\n request.acceptResponseType(StreamMessage.contentType);\n }\n }\n\n requestStarted(_request) {\n markAsBusy(this.element);\n }\n\n requestPreventedHandlingResponse(_request, _response) {\n this.#resolveVisitPromise();\n }\n\n async requestSucceededWithResponse(request, response) {\n await this.loadResponse(response);\n this.#resolveVisitPromise();\n }\n\n async requestFailedWithResponse(request, response) {\n await this.loadResponse(response);\n this.#resolveVisitPromise();\n }\n\n requestErrored(request, error) {\n console.error(error);\n this.#resolveVisitPromise();\n }\n\n requestFinished(_request) {\n clearBusyState(this.element);\n }\n\n // Form submission delegate\n\n formSubmissionStarted({ formElement }) {\n markAsBusy(formElement, this.#findFrameElement(formElement));\n }\n\n formSubmissionSucceededWithResponse(formSubmission, response) {\n const frame = this.#findFrameElement(formSubmission.formElement, formSubmission.submitter);\n\n frame.delegate.proposeVisitIfNavigatedWithAction(frame, getVisitAction(formSubmission.submitter, formSubmission.formElement, frame));\n frame.delegate.loadResponse(response);\n\n if (!formSubmission.isSafe) {\n session.clearCache();\n }\n }\n\n formSubmissionFailedWithResponse(formSubmission, fetchResponse) {\n this.element.delegate.loadResponse(fetchResponse);\n session.clearCache();\n }\n\n formSubmissionErrored(formSubmission, error) {\n console.error(error);\n }\n\n formSubmissionFinished({ formElement }) {\n clearBusyState(formElement, this.#findFrameElement(formElement));\n }\n\n // View delegate\n\n allowsImmediateRender({ element: newFrame }, options) {\n const event = dispatch(\"turbo:before-frame-render\", {\n target: this.element,\n detail: { newFrame, ...options },\n cancelable: true\n });\n\n const {\n defaultPrevented,\n detail: { render }\n } = event;\n\n if (this.view.renderer && render) {\n this.view.renderer.renderElement = render;\n }\n\n return !defaultPrevented\n }\n\n viewRenderedSnapshot(_snapshot, _isPreview, _renderMethod) {}\n\n preloadOnLoadLinksForView(element) {\n session.preloadOnLoadLinksForView(element);\n }\n\n viewInvalidated() {}\n\n // Frame renderer delegate\n\n willRenderFrame(currentElement, _newElement) {\n this.previousFrameElement = currentElement.cloneNode(true);\n }\n\n visitCachedSnapshot = ({ element }) => {\n const frame = element.querySelector(\"#\" + this.element.id);\n\n if (frame && this.previousFrameElement) {\n frame.replaceChildren(...this.previousFrameElement.children);\n }\n\n delete this.previousFrameElement;\n }\n\n // Private\n\n async #loadFrameResponse(fetchResponse, document) {\n const newFrameElement = await this.extractForeignFrameElement(document.body);\n const rendererClass = this.#shouldMorphFrame ? MorphingFrameRenderer : FrameRenderer;\n\n if (newFrameElement) {\n const snapshot = new Snapshot(newFrameElement);\n const renderer = new rendererClass(this, this.view.snapshot, snapshot, false, false);\n if (this.view.renderPromise) await this.view.renderPromise;\n this.changeHistory();\n\n await this.view.render(renderer);\n this.complete = true;\n session.frameRendered(fetchResponse, this.element);\n session.frameLoaded(this.element);\n await this.fetchResponseLoaded(fetchResponse);\n } else if (this.#willHandleFrameMissingFromResponse(fetchResponse)) {\n this.#handleFrameMissingFromResponse(fetchResponse);\n }\n }\n\n async #visit(url) {\n const request = new FetchRequest(this, FetchMethod.get, url, new URLSearchParams(), this.element);\n\n this.#currentFetchRequest?.cancel();\n this.#currentFetchRequest = request;\n\n return new Promise((resolve) => {\n this.#resolveVisitPromise = () => {\n this.#resolveVisitPromise = () => {};\n this.#currentFetchRequest = null;\n resolve();\n };\n request.perform();\n })\n }\n\n #navigateFrame(element, url, submitter) {\n const frame = this.#findFrameElement(element, submitter);\n\n frame.delegate.proposeVisitIfNavigatedWithAction(frame, getVisitAction(submitter, element, frame));\n\n this.#withCurrentNavigationElement(element, () => {\n frame.src = url;\n });\n }\n\n proposeVisitIfNavigatedWithAction(frame, action = null) {\n this.action = action;\n\n if (this.action) {\n const pageSnapshot = PageSnapshot.fromElement(frame).clone();\n const { visitCachedSnapshot } = frame.delegate;\n\n frame.delegate.fetchResponseLoaded = async (fetchResponse) => {\n if (frame.src) {\n const { statusCode, redirected } = fetchResponse;\n const responseHTML = await fetchResponse.responseHTML;\n const response = { statusCode, redirected, responseHTML };\n const options = {\n response,\n visitCachedSnapshot,\n willRender: false,\n updateHistory: false,\n restorationIdentifier: this.restorationIdentifier,\n snapshot: pageSnapshot\n };\n\n if (this.action) options.action = this.action;\n\n session.visit(frame.src, options);\n }\n };\n }\n }\n\n changeHistory() {\n if (this.action) {\n const method = getHistoryMethodForAction(this.action);\n session.history.update(method, expandURL(this.element.src || \"\"), this.restorationIdentifier);\n }\n }\n\n async #handleUnvisitableFrameResponse(fetchResponse) {\n console.warn(\n `The response (${fetchResponse.statusCode}) from is performing a full page visit due to turbo-visit-control.`\n );\n\n await this.#visitResponse(fetchResponse.response);\n }\n\n #willHandleFrameMissingFromResponse(fetchResponse) {\n this.element.setAttribute(\"complete\", \"\");\n\n const response = fetchResponse.response;\n const visit = async (url, options) => {\n if (url instanceof Response) {\n this.#visitResponse(url);\n } else {\n session.visit(url, options);\n }\n };\n\n const event = dispatch(\"turbo:frame-missing\", {\n target: this.element,\n detail: { response, visit },\n cancelable: true\n });\n\n return !event.defaultPrevented\n }\n\n #handleFrameMissingFromResponse(fetchResponse) {\n this.view.missing();\n this.#throwFrameMissingError(fetchResponse);\n }\n\n #throwFrameMissingError(fetchResponse) {\n const message = `The response (${fetchResponse.statusCode}) did not contain the expected and will be ignored. To perform a full page visit instead, set turbo-visit-control to reload.`;\n throw new TurboFrameMissingError(message)\n }\n\n async #visitResponse(response) {\n const wrapped = new FetchResponse(response);\n const responseHTML = await wrapped.responseHTML;\n const { location, redirected, statusCode } = wrapped;\n\n return session.visit(location, { response: { redirected, statusCode, responseHTML } })\n }\n\n #findFrameElement(element, submitter) {\n const id = getAttribute(\"data-turbo-frame\", submitter, element) || this.element.getAttribute(\"target\");\n return getFrameElementById(id) ?? this.element\n }\n\n async extractForeignFrameElement(container) {\n let element;\n const id = CSS.escape(this.id);\n\n try {\n element = activateElement(container.querySelector(`turbo-frame#${id}`), this.sourceURL);\n if (element) {\n return element\n }\n\n element = activateElement(container.querySelector(`turbo-frame[src][recurse~=${id}]`), this.sourceURL);\n if (element) {\n await element.loaded;\n return await this.extractForeignFrameElement(element)\n }\n } catch (error) {\n console.error(error);\n return new FrameElement()\n }\n\n return null\n }\n\n #formActionIsVisitable(form, submitter) {\n const action = getAction$1(form, submitter);\n\n return locationIsVisitable(expandURL(action), this.rootLocation)\n }\n\n #shouldInterceptNavigation(element, submitter) {\n const id = getAttribute(\"data-turbo-frame\", submitter, element) || this.element.getAttribute(\"target\");\n\n if (element instanceof HTMLFormElement && !this.#formActionIsVisitable(element, submitter)) {\n return false\n }\n\n if (!this.enabled || id == \"_top\") {\n return false\n }\n\n if (id) {\n const frameElement = getFrameElementById(id);\n if (frameElement) {\n return !frameElement.disabled\n }\n }\n\n if (!session.elementIsNavigatable(element)) {\n return false\n }\n\n if (submitter && !session.elementIsNavigatable(submitter)) {\n return false\n }\n\n return true\n }\n\n // Computed properties\n\n get id() {\n return this.element.id\n }\n\n get enabled() {\n return !this.element.disabled\n }\n\n get sourceURL() {\n if (this.element.src) {\n return this.element.src\n }\n }\n\n set sourceURL(sourceURL) {\n this.#ignoringChangesToAttribute(\"src\", () => {\n this.element.src = sourceURL ?? null;\n });\n }\n\n get loadingStyle() {\n return this.element.loading\n }\n\n get isLoading() {\n return this.formSubmission !== undefined || this.#resolveVisitPromise() !== undefined\n }\n\n get complete() {\n return this.element.hasAttribute(\"complete\")\n }\n\n set complete(value) {\n if (value) {\n this.element.setAttribute(\"complete\", \"\");\n } else {\n this.element.removeAttribute(\"complete\");\n }\n }\n\n get isActive() {\n return this.element.isActive && this.#connected\n }\n\n get rootLocation() {\n const meta = this.element.ownerDocument.querySelector(`meta[name=\"turbo-root\"]`);\n const root = meta?.content ?? \"/\";\n return expandURL(root)\n }\n\n #isIgnoringChangesTo(attributeName) {\n return this.#ignoredAttributes.has(attributeName)\n }\n\n #ignoringChangesToAttribute(attributeName, callback) {\n this.#ignoredAttributes.add(attributeName);\n callback();\n this.#ignoredAttributes.delete(attributeName);\n }\n\n #withCurrentNavigationElement(element, callback) {\n this.currentNavigationElement = element;\n callback();\n delete this.currentNavigationElement;\n }\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}\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\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) => e.parentElement?.insertBefore(this.templateContent, e.nextSibling));\n },\n\n append() {\n this.removeDuplicateTargetChildren();\n this.targetElements.forEach((e) => e.append(this.templateContent));\n },\n\n before() {\n this.targetElements.forEach((e) => e.parentElement?.insertBefore(this.templateContent, e));\n },\n\n prepend() {\n this.removeDuplicateTargetChildren();\n this.targetElements.forEach((e) => e.prepend(this.templateContent));\n },\n\n remove() {\n this.targetElements.forEach((e) => e.remove());\n },\n\n replace() {\n const method = this.getAttribute(\"method\");\n\n this.targetElements.forEach((targetElement) => {\n if (method === \"morph\") {\n morphElements(targetElement, this.templateContent);\n } else {\n targetElement.replaceWith(this.templateContent);\n }\n });\n },\n\n update() {\n const method = this.getAttribute(\"method\");\n\n this.targetElements.forEach((targetElement) => {\n if (method === \"morph\") {\n morphChildren(targetElement, this.templateContent);\n } else {\n targetElement.innerHTML = \"\";\n targetElement.append(this.templateContent);\n }\n });\n },\n\n refresh() {\n session.refresh(this.baseURI, this.requestId);\n }\n};\n\n//