{ "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/filepond/dist/filepond.js", "../../../node_modules/filepond-plugin-file-validate-size/dist/filepond-plugin-file-validate-size.js", "../../../node_modules/filepond-plugin-image-preview/dist/filepond-plugin-image-preview.js", "../../../node_modules/@hotwired/stimulus/dist/stimulus.umd.js", "../../../node_modules/stimulus-reveal/dist/stimulus-reveal.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/@rails/activestorage/app/assets/javascripts/activestorage.esm.js", "../../javascript/application.js", "../../../node_modules/trix/src/trix/config/attachments.js", "../../../node_modules/trix/src/trix/config/block_attributes.js", "../../../node_modules/trix/src/trix/config/browser.js", "../../../node_modules/trix/src/trix/config/lang.js", "../../../node_modules/trix/src/trix/config/file_size_formatting.js", "../../../node_modules/trix/src/trix/constants.js", "../../../node_modules/trix/src/trix/core/helpers/extend.js", "../../../node_modules/trix/src/trix/core/helpers/dom.js", "../../../node_modules/trix/src/trix/config/input.js", "../../../node_modules/trix/src/trix/config/key_names.js", "../../../node_modules/trix/src/trix/config/parser.js", "../../../node_modules/trix/src/trix/config/text_attributes.js", "../../../node_modules/trix/src/trix/config/toolbar.js", "../../../node_modules/trix/src/trix/config/undo.js", "../../../node_modules/trix/src/trix/config/css.js", "../../../node_modules/trix/src/trix/core/basic_object.js", "../../../node_modules/trix/src/trix/core/utilities/utf16_string.js", "../../../node_modules/trix/src/trix/core/object.js", "../../../node_modules/trix/src/trix/core/helpers/arrays.js", "../../../node_modules/trix/src/trix/core/helpers/bidi.js", "../../../node_modules/trix/src/trix/core/helpers/config.js", "../../../node_modules/trix/src/trix/core/helpers/custom_elements.js", "../../../node_modules/trix/src/trix/core/helpers/events.js", "../../../node_modules/trix/src/trix/core/helpers/functions.js", "../../../node_modules/trix/src/trix/core/helpers/objects.js", "../../../node_modules/trix/src/trix/core/helpers/ranges.js", "../../../node_modules/trix/src/trix/observers/selection_change_observer.js", "../../../node_modules/trix/src/trix/core/helpers/strings.js", "../../../node_modules/trix/src/trix/core/collections/hash.js", "../../../node_modules/trix/src/trix/core/collections/object_group.js", "../../../node_modules/trix/src/trix/core/collections/object_map.js", "../../../node_modules/trix/src/trix/core/collections/element_store.js", "../../../node_modules/trix/src/trix/core/utilities/operation.js", "../../../node_modules/trix/src/trix/views/object_view.js", "../../../node_modules/trix/src/trix/views/attachment_view.js", "../../../node_modules/trix/src/trix/views/previewable_attachment_view.js", "../../../node_modules/trix/src/trix/views/piece_view.js", "../../../node_modules/trix/src/trix/views/text_view.js", "../../../node_modules/trix/src/trix/views/block_view.js", "../../../node_modules/trix/src/trix/views/document_view.js", "../../../node_modules/trix/src/trix/models/piece.js", "../../../node_modules/trix/src/trix/operations/image_preload_operation.js", "../../../node_modules/trix/src/trix/models/attachment.js", "../../../node_modules/trix/src/trix/models/attachment_piece.js", "../../../node_modules/trix/src/trix/models/string_piece.js", "../../../node_modules/trix/src/trix/models/splittable_list.js", "../../../node_modules/trix/src/trix/models/text.js", "../../../node_modules/trix/src/trix/models/block.js", "../../../node_modules/trix/src/trix/models/document.js", "../../../node_modules/trix/src/trix/models/html_sanitizer.js", "../../../node_modules/trix/src/trix/models/html_parser.js", "../../../node_modules/trix/src/trix/core/serialization.js", "../../../node_modules/trix/src/trix/models/managed_attachment.js", "../../../node_modules/trix/src/trix/models/attachment_manager.js", "../../../node_modules/trix/src/trix/models/line_break_insertion.js", "../../../node_modules/trix/src/trix/models/composition.js", "../../../node_modules/trix/src/trix/models/undo_manager.js", "../../../node_modules/trix/src/trix/filters/filter.js", "../../../node_modules/trix/src/trix/filters/attachment_gallery_filter.js", "../../../node_modules/trix/src/trix/models/editor.js", "../../../node_modules/trix/src/trix/models/location_mapper.js", "../../../node_modules/trix/src/trix/models/point_mapper.js", "../../../node_modules/trix/src/trix/models/selection_manager.js", "../../../node_modules/trix/src/trix/controllers/attachment_editor_controller.js", "../../../node_modules/trix/src/trix/controllers/composition_controller.js", "../../../node_modules/trix/src/trix/controllers/controller.js", "../../../node_modules/trix/src/trix/observers/mutation_observer.js", "../../../node_modules/trix/src/trix/operations/file_verification_operation.js", "../../../node_modules/trix/src/trix/models/flaky_android_keyboard_detector.js", "../../../node_modules/trix/src/trix/controllers/input_controller.js", "../../../node_modules/trix/src/trix/controllers/level_0_input_controller.js", "../../../node_modules/trix/src/trix/controllers/level_2_input_controller.js", "../../../node_modules/trix/src/trix/controllers/toolbar_controller.js", "../../../node_modules/trix/src/trix/controllers/editor_controller.js", "../../../node_modules/trix/src/trix/elements/trix_toolbar_element.js", "../../../node_modules/trix/src/trix/elements/trix_editor_element.js", "../../../node_modules/trix/src/trix/trix.js", "../../../node_modules/@rails/actiontext/app/assets/javascripts/actiontext.esm.js", "../../javascript/controllers/index.js", "../../../node_modules/@josefarias/hotwire_combobox/app/assets/javascripts/hotwire_combobox.esm.js", "../../javascript/controllers/dropdown_controller.js", "../../../node_modules/stimulus-use/dist/index.js", "../../../node_modules/hotkeys-js/dist/hotkeys.esm.js", "../../javascript/controllers/dark_mode_controller.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 recordPing() {\n this.pingedAt = now()\n }\n\n recordConnect() {\n this.reconnectAttempts = 0\n this.recordPing()\n delete this.disconnectedAt\n logger.log(\"ConnectionMonitor recorded connect\")\n }\n\n recordDisconnect() {\n this.disconnectedAt = now()\n logger.log(\"ConnectionMonitor recorded disconnect\")\n }\n\n // Private\n\n startPolling() {\n this.stopPolling()\n this.poll()\n }\n\n stopPolling() {\n clearTimeout(this.pollTimeout)\n }\n\n poll() {\n this.pollTimeout = setTimeout(() => {\n this.reconnectIfStale()\n this.poll()\n }\n , this.getPollInterval())\n }\n\n getPollInterval() {\n const { staleThreshold, reconnectionBackoffRate } = this.constructor\n const backoff = Math.pow(1 + reconnectionBackoffRate, Math.min(this.reconnectAttempts, 10))\n const jitterMax = this.reconnectAttempts === 0 ? 1.0 : reconnectionBackoffRate\n const jitter = jitterMax * Math.random()\n return staleThreshold * 1000 * backoff * (1 + jitter)\n }\n\n reconnectIfStale() {\n if (this.connectionIsStale()) {\n logger.log(`ConnectionMonitor detected stale connection. reconnectAttempts = ${this.reconnectAttempts}, time stale = ${secondsSince(this.refreshedAt)} s, stale threshold = ${this.constructor.staleThreshold} s`)\n this.reconnectAttempts++\n if (this.disconnectedRecently()) {\n logger.log(`ConnectionMonitor skipping reopening recent disconnect. time disconnected = ${secondsSince(this.disconnectedAt)} s`)\n } else {\n logger.log(\"ConnectionMonitor reopening\")\n this.connection.reopen()\n }\n }\n }\n\n get refreshedAt() {\n return this.pingedAt ? this.pingedAt : this.startedAt\n }\n\n connectionIsStale() {\n return secondsSince(this.refreshedAt) > this.constructor.staleThreshold\n }\n\n disconnectedRecently() {\n return this.disconnectedAt && (secondsSince(this.disconnectedAt) < this.constructor.staleThreshold)\n }\n\n visibilityDidChange() {\n if (document.visibilityState === \"visible\") {\n setTimeout(() => {\n if (this.connectionIsStale() || !this.connection.isOpen()) {\n logger.log(`ConnectionMonitor reopening stale connection on visibilitychange. visibilityState = ${document.visibilityState}`)\n this.connection.reopen()\n }\n }\n , 200)\n }\n }\n\n}\n\nConnectionMonitor.staleThreshold = 6 // Server::Connections::BEAT_INTERVAL * 2 (missed two pings)\nConnectionMonitor.reconnectionBackoffRate = 0.15\n\nexport default ConnectionMonitor\n", "export default {\n \"message_types\": {\n \"welcome\": \"welcome\",\n \"disconnect\": \"disconnect\",\n \"ping\": \"ping\",\n \"confirmation\": \"confirm_subscription\",\n \"rejection\": \"reject_subscription\"\n },\n \"disconnect_reasons\": {\n \"unauthorized\": \"unauthorized\",\n \"invalid_request\": \"invalid_request\",\n \"server_restart\": \"server_restart\",\n \"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 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 this.monitor.recordPing()\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", "/*!\n * FilePond 4.30.6\n * Licensed under MIT, https://opensource.org/licenses/MIT/\n * Please visit https://pqina.nl/filepond/ for details.\n */\n\n/* eslint-disable */\n\n(function(global, factory) {\n typeof exports === 'object' && typeof module !== 'undefined'\n ? factory(exports)\n : typeof define === 'function' && define.amd\n ? define(['exports'], factory)\n : ((global = global || self), factory((global.FilePond = {})));\n})(this, function(exports) {\n 'use strict';\n\n var isNode = function isNode(value) {\n return value instanceof HTMLElement;\n };\n\n var createStore = function createStore(initialState) {\n var queries = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : [];\n var actions = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : [];\n // internal state\n var state = Object.assign({}, initialState);\n\n // contains all actions for next frame, is clear when actions are requested\n var actionQueue = [];\n var dispatchQueue = [];\n\n // returns a duplicate of the current state\n var getState = function getState() {\n return Object.assign({}, state);\n };\n\n // returns a duplicate of the actions array and clears the actions array\n var processActionQueue = function processActionQueue() {\n // create copy of actions queue\n var queue = [].concat(actionQueue);\n\n // clear actions queue (we don't want no double actions)\n actionQueue.length = 0;\n\n return queue;\n };\n\n // processes actions that might block the main UI thread\n var processDispatchQueue = function processDispatchQueue() {\n // create copy of actions queue\n var queue = [].concat(dispatchQueue);\n\n // clear actions queue (we don't want no double actions)\n dispatchQueue.length = 0;\n\n // now dispatch these actions\n queue.forEach(function(_ref) {\n var type = _ref.type,\n data = _ref.data;\n dispatch(type, data);\n });\n };\n\n // adds a new action, calls its handler and\n var dispatch = function dispatch(type, data, isBlocking) {\n // is blocking action (should never block if document is hidden)\n if (isBlocking && !document.hidden) {\n dispatchQueue.push({ type: type, data: data });\n return;\n }\n\n // if this action has a handler, handle the action\n if (actionHandlers[type]) {\n actionHandlers[type](data);\n }\n\n // now add action\n actionQueue.push({\n type: type,\n data: data,\n });\n };\n\n var query = function query(str) {\n var _queryHandles;\n for (\n var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1;\n _key < _len;\n _key++\n ) {\n args[_key - 1] = arguments[_key];\n }\n return queryHandles[str]\n ? (_queryHandles = queryHandles)[str].apply(_queryHandles, args)\n : null;\n };\n\n var api = {\n getState: getState,\n processActionQueue: processActionQueue,\n processDispatchQueue: processDispatchQueue,\n dispatch: dispatch,\n query: query,\n };\n\n var queryHandles = {};\n queries.forEach(function(query) {\n queryHandles = Object.assign({}, query(state), {}, queryHandles);\n });\n\n var actionHandlers = {};\n actions.forEach(function(action) {\n actionHandlers = Object.assign({}, action(dispatch, query, state), {}, actionHandlers);\n });\n\n return api;\n };\n\n var defineProperty = function defineProperty(obj, property, definition) {\n if (typeof definition === 'function') {\n obj[property] = definition;\n return;\n }\n Object.defineProperty(obj, property, Object.assign({}, definition));\n };\n\n var forin = function forin(obj, cb) {\n for (var key in obj) {\n if (!obj.hasOwnProperty(key)) {\n continue;\n }\n\n cb(key, obj[key]);\n }\n };\n\n var createObject = function createObject(definition) {\n var obj = {};\n forin(definition, function(property) {\n defineProperty(obj, property, definition[property]);\n });\n return obj;\n };\n\n var attr = function attr(node, name) {\n var value = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null;\n if (value === null) {\n return node.getAttribute(name) || node.hasAttribute(name);\n }\n node.setAttribute(name, value);\n };\n\n var ns = 'http://www.w3.org/2000/svg';\n var svgElements = ['svg', 'path']; // only svg elements used\n\n var isSVGElement = function isSVGElement(tag) {\n return svgElements.includes(tag);\n };\n\n var createElement = function createElement(tag, className) {\n var attributes = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};\n if (typeof className === 'object') {\n attributes = className;\n className = null;\n }\n var element = isSVGElement(tag)\n ? document.createElementNS(ns, tag)\n : document.createElement(tag);\n if (className) {\n if (isSVGElement(tag)) {\n attr(element, 'class', className);\n } else {\n element.className = className;\n }\n }\n forin(attributes, function(name, value) {\n attr(element, name, value);\n });\n return element;\n };\n\n var appendChild = function appendChild(parent) {\n return function(child, index) {\n if (typeof index !== 'undefined' && parent.children[index]) {\n parent.insertBefore(child, parent.children[index]);\n } else {\n parent.appendChild(child);\n }\n };\n };\n\n var appendChildView = function appendChildView(parent, childViews) {\n return function(view, index) {\n if (typeof index !== 'undefined') {\n childViews.splice(index, 0, view);\n } else {\n childViews.push(view);\n }\n\n return view;\n };\n };\n\n var removeChildView = function removeChildView(parent, childViews) {\n return function(view) {\n // remove from child views\n childViews.splice(childViews.indexOf(view), 1);\n\n // remove the element\n if (view.element.parentNode) {\n parent.removeChild(view.element);\n }\n\n return view;\n };\n };\n\n var IS_BROWSER = (function() {\n return typeof window !== 'undefined' && typeof window.document !== 'undefined';\n })();\n var isBrowser = function isBrowser() {\n return IS_BROWSER;\n };\n\n var testElement = isBrowser() ? createElement('svg') : {};\n var getChildCount =\n 'children' in testElement\n ? function(el) {\n return el.children.length;\n }\n : function(el) {\n return el.childNodes.length;\n };\n\n var getViewRect = function getViewRect(elementRect, childViews, offset, scale) {\n var left = offset[0] || elementRect.left;\n var top = offset[1] || elementRect.top;\n var right = left + elementRect.width;\n var bottom = top + elementRect.height * (scale[1] || 1);\n\n var rect = {\n // the rectangle of the element itself\n element: Object.assign({}, elementRect),\n\n // the rectangle of the element expanded to contain its children, does not include any margins\n inner: {\n left: elementRect.left,\n top: elementRect.top,\n right: elementRect.right,\n bottom: elementRect.bottom,\n },\n\n // the rectangle of the element expanded to contain its children including own margin and child margins\n // margins will be added after we've recalculated the size\n outer: {\n left: left,\n top: top,\n right: right,\n bottom: bottom,\n },\n };\n\n // expand rect to fit all child rectangles\n childViews\n .filter(function(childView) {\n return !childView.isRectIgnored();\n })\n .map(function(childView) {\n return childView.rect;\n })\n .forEach(function(childViewRect) {\n expandRect(rect.inner, Object.assign({}, childViewRect.inner));\n expandRect(rect.outer, Object.assign({}, childViewRect.outer));\n });\n\n // calculate inner width and height\n calculateRectSize(rect.inner);\n\n // append additional margin (top and left margins are included in top and left automatically)\n rect.outer.bottom += rect.element.marginBottom;\n rect.outer.right += rect.element.marginRight;\n\n // calculate outer width and height\n calculateRectSize(rect.outer);\n\n return rect;\n };\n\n var expandRect = function expandRect(parent, child) {\n // adjust for parent offset\n child.top += parent.top;\n child.right += parent.left;\n child.bottom += parent.top;\n child.left += parent.left;\n\n if (child.bottom > parent.bottom) {\n parent.bottom = child.bottom;\n }\n\n if (child.right > parent.right) {\n parent.right = child.right;\n }\n };\n\n var calculateRectSize = function calculateRectSize(rect) {\n rect.width = rect.right - rect.left;\n rect.height = rect.bottom - rect.top;\n };\n\n var isNumber = function isNumber(value) {\n return typeof value === 'number';\n };\n\n /**\n * Determines if position is at destination\n * @param position\n * @param destination\n * @param velocity\n * @param errorMargin\n * @returns {boolean}\n */\n var thereYet = function thereYet(position, destination, velocity) {\n var errorMargin = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 0.001;\n return Math.abs(position - destination) < errorMargin && Math.abs(velocity) < errorMargin;\n };\n\n /**\n * Spring animation\n */\n var spring =\n // default options\n function spring() // method definition\n {\n var _ref = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {},\n _ref$stiffness = _ref.stiffness,\n stiffness = _ref$stiffness === void 0 ? 0.5 : _ref$stiffness,\n _ref$damping = _ref.damping,\n damping = _ref$damping === void 0 ? 0.75 : _ref$damping,\n _ref$mass = _ref.mass,\n mass = _ref$mass === void 0 ? 10 : _ref$mass;\n var target = null;\n var position = null;\n var velocity = 0;\n var resting = false;\n\n // updates spring state\n var interpolate = function interpolate(ts, skipToEndState) {\n // in rest, don't animate\n if (resting) return;\n\n // need at least a target or position to do springy things\n if (!(isNumber(target) && isNumber(position))) {\n resting = true;\n velocity = 0;\n return;\n }\n\n // calculate spring force\n var f = -(position - target) * stiffness;\n\n // update velocity by adding force based on mass\n velocity += f / mass;\n\n // update position by adding velocity\n position += velocity;\n\n // slow down based on amount of damping\n velocity *= damping;\n\n // we've arrived if we're near target and our velocity is near zero\n if (thereYet(position, target, velocity) || skipToEndState) {\n position = target;\n velocity = 0;\n resting = true;\n\n // we done\n api.onupdate(position);\n api.oncomplete(position);\n } else {\n // progress update\n api.onupdate(position);\n }\n };\n\n /**\n * Set new target value\n * @param value\n */\n var setTarget = function setTarget(value) {\n // if currently has no position, set target and position to this value\n if (isNumber(value) && !isNumber(position)) {\n position = value;\n }\n\n // next target value will not be animated to\n if (target === null) {\n target = value;\n position = value;\n }\n\n // let start moving to target\n target = value;\n\n // already at target\n if (position === target || typeof target === 'undefined') {\n // now resting as target is current position, stop moving\n resting = true;\n velocity = 0;\n\n // done!\n api.onupdate(position);\n api.oncomplete(position);\n\n return;\n }\n\n resting = false;\n };\n\n // need 'api' to call onupdate callback\n var api = createObject({\n interpolate: interpolate,\n target: {\n set: setTarget,\n get: function get() {\n return target;\n },\n },\n\n resting: {\n get: function get() {\n return resting;\n },\n },\n\n onupdate: function onupdate(value) {},\n oncomplete: function oncomplete(value) {},\n });\n\n return api;\n };\n\n var easeLinear = function easeLinear(t) {\n return t;\n };\n var easeInOutQuad = function easeInOutQuad(t) {\n return t < 0.5 ? 2 * t * t : -1 + (4 - 2 * t) * t;\n };\n\n var tween =\n // default values\n function tween() // method definition\n {\n var _ref = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {},\n _ref$duration = _ref.duration,\n duration = _ref$duration === void 0 ? 500 : _ref$duration,\n _ref$easing = _ref.easing,\n easing = _ref$easing === void 0 ? easeInOutQuad : _ref$easing,\n _ref$delay = _ref.delay,\n delay = _ref$delay === void 0 ? 0 : _ref$delay;\n var start = null;\n var t;\n var p;\n var resting = true;\n var reverse = false;\n var target = null;\n\n var interpolate = function interpolate(ts, skipToEndState) {\n if (resting || target === null) return;\n\n if (start === null) {\n start = ts;\n }\n\n if (ts - start < delay) return;\n\n t = ts - start - delay;\n\n if (t >= duration || skipToEndState) {\n t = 1;\n p = reverse ? 0 : 1;\n api.onupdate(p * target);\n api.oncomplete(p * target);\n resting = true;\n } else {\n p = t / duration;\n api.onupdate((t >= 0 ? easing(reverse ? 1 - p : p) : 0) * target);\n }\n };\n\n // need 'api' to call onupdate callback\n var api = createObject({\n interpolate: interpolate,\n target: {\n get: function get() {\n return reverse ? 0 : target;\n },\n set: function set(value) {\n // is initial value\n if (target === null) {\n target = value;\n api.onupdate(value);\n api.oncomplete(value);\n return;\n }\n\n // want to tween to a smaller value and have a current value\n if (value < target) {\n target = 1;\n reverse = true;\n } else {\n // not tweening to a smaller value\n reverse = false;\n target = value;\n }\n\n // let's go!\n resting = false;\n start = null;\n },\n },\n\n resting: {\n get: function get() {\n return resting;\n },\n },\n\n onupdate: function onupdate(value) {},\n oncomplete: function oncomplete(value) {},\n });\n\n return api;\n };\n\n var animator = {\n spring: spring,\n tween: tween,\n };\n\n /*\n { type: 'spring', stiffness: .5, damping: .75, mass: 10 };\n { translation: { type: 'spring', ... }, ... }\n { translation: { x: { type: 'spring', ... } } }\n */\n var createAnimator = function createAnimator(definition, category, property) {\n // default is single definition\n // we check if transform is set, if so, we check if property is set\n var def =\n definition[category] && typeof definition[category][property] === 'object'\n ? definition[category][property]\n : definition[category] || definition;\n\n var type = typeof def === 'string' ? def : def.type;\n var props = typeof def === 'object' ? Object.assign({}, def) : {};\n\n return animator[type] ? animator[type](props) : null;\n };\n\n var addGetSet = function addGetSet(keys, obj, props) {\n var overwrite = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : false;\n obj = Array.isArray(obj) ? obj : [obj];\n obj.forEach(function(o) {\n keys.forEach(function(key) {\n var name = key;\n var getter = function getter() {\n return props[key];\n };\n var setter = function setter(value) {\n return (props[key] = value);\n };\n\n if (typeof key === 'object') {\n name = key.key;\n getter = key.getter || getter;\n setter = key.setter || setter;\n }\n\n if (o[name] && !overwrite) {\n return;\n }\n\n o[name] = {\n get: getter,\n set: setter,\n };\n });\n });\n };\n\n // add to state,\n // add getters and setters to internal and external api (if not set)\n // setup animators\n\n var animations = function animations(_ref) {\n var mixinConfig = _ref.mixinConfig,\n viewProps = _ref.viewProps,\n viewInternalAPI = _ref.viewInternalAPI,\n viewExternalAPI = _ref.viewExternalAPI;\n // initial properties\n var initialProps = Object.assign({}, viewProps);\n\n // list of all active animations\n var animations = [];\n\n // setup animators\n forin(mixinConfig, function(property, animation) {\n var animator = createAnimator(animation);\n if (!animator) {\n return;\n }\n\n // when the animator updates, update the view state value\n animator.onupdate = function(value) {\n viewProps[property] = value;\n };\n\n // set animator target\n animator.target = initialProps[property];\n\n // when value is set, set the animator target value\n var prop = {\n key: property,\n setter: function setter(value) {\n // if already at target, we done!\n if (animator.target === value) {\n return;\n }\n\n animator.target = value;\n },\n getter: function getter() {\n return viewProps[property];\n },\n };\n\n // add getters and setters\n addGetSet([prop], [viewInternalAPI, viewExternalAPI], viewProps, true);\n\n // add it to the list for easy updating from the _write method\n animations.push(animator);\n });\n\n // expose internal write api\n return {\n write: function write(ts) {\n var skipToEndState = document.hidden;\n var resting = true;\n animations.forEach(function(animation) {\n if (!animation.resting) resting = false;\n animation.interpolate(ts, skipToEndState);\n });\n return resting;\n },\n destroy: function destroy() {},\n };\n };\n\n var addEvent = function addEvent(element) {\n return function(type, fn) {\n element.addEventListener(type, fn);\n };\n };\n\n var removeEvent = function removeEvent(element) {\n return function(type, fn) {\n element.removeEventListener(type, fn);\n };\n };\n\n // mixin\n var listeners = function listeners(_ref) {\n var mixinConfig = _ref.mixinConfig,\n viewProps = _ref.viewProps,\n viewInternalAPI = _ref.viewInternalAPI,\n viewExternalAPI = _ref.viewExternalAPI,\n viewState = _ref.viewState,\n view = _ref.view;\n var events = [];\n\n var add = addEvent(view.element);\n var remove = removeEvent(view.element);\n\n viewExternalAPI.on = function(type, fn) {\n events.push({\n type: type,\n fn: fn,\n });\n\n add(type, fn);\n };\n\n viewExternalAPI.off = function(type, fn) {\n events.splice(\n events.findIndex(function(event) {\n return event.type === type && event.fn === fn;\n }),\n 1\n );\n\n remove(type, fn);\n };\n\n return {\n write: function write() {\n // not busy\n return true;\n },\n destroy: function destroy() {\n events.forEach(function(event) {\n remove(event.type, event.fn);\n });\n },\n };\n };\n\n // add to external api and link to props\n\n var apis = function apis(_ref) {\n var mixinConfig = _ref.mixinConfig,\n viewProps = _ref.viewProps,\n viewExternalAPI = _ref.viewExternalAPI;\n addGetSet(mixinConfig, viewExternalAPI, viewProps);\n };\n\n var isDefined = function isDefined(value) {\n return value != null;\n };\n\n // add to state,\n // add getters and setters to internal and external api (if not set)\n // set initial state based on props in viewProps\n // apply as transforms each frame\n\n var defaults = {\n opacity: 1,\n scaleX: 1,\n scaleY: 1,\n translateX: 0,\n translateY: 0,\n rotateX: 0,\n rotateY: 0,\n rotateZ: 0,\n originX: 0,\n originY: 0,\n };\n\n var styles = function styles(_ref) {\n var mixinConfig = _ref.mixinConfig,\n viewProps = _ref.viewProps,\n viewInternalAPI = _ref.viewInternalAPI,\n viewExternalAPI = _ref.viewExternalAPI,\n view = _ref.view;\n // initial props\n var initialProps = Object.assign({}, viewProps);\n\n // current props\n var currentProps = {};\n\n // we will add those properties to the external API and link them to the viewState\n addGetSet(mixinConfig, [viewInternalAPI, viewExternalAPI], viewProps);\n\n // override rect on internal and external rect getter so it takes in account transforms\n var getOffset = function getOffset() {\n return [viewProps['translateX'] || 0, viewProps['translateY'] || 0];\n };\n\n var getScale = function getScale() {\n return [viewProps['scaleX'] || 0, viewProps['scaleY'] || 0];\n };\n var getRect = function getRect() {\n return view.rect\n ? getViewRect(view.rect, view.childViews, getOffset(), getScale())\n : null;\n };\n viewInternalAPI.rect = { get: getRect };\n viewExternalAPI.rect = { get: getRect };\n\n // apply view props\n mixinConfig.forEach(function(key) {\n viewProps[key] =\n typeof initialProps[key] === 'undefined' ? defaults[key] : initialProps[key];\n });\n\n // expose api\n return {\n write: function write() {\n // see if props have changed\n if (!propsHaveChanged(currentProps, viewProps)) {\n return;\n }\n\n // moves element to correct position on screen\n applyStyles(view.element, viewProps);\n\n // store new transforms\n Object.assign(currentProps, Object.assign({}, viewProps));\n\n // no longer busy\n return true;\n },\n destroy: function destroy() {},\n };\n };\n\n var propsHaveChanged = function propsHaveChanged(currentProps, newProps) {\n // different amount of keys\n if (Object.keys(currentProps).length !== Object.keys(newProps).length) {\n return true;\n }\n\n // lets analyze the individual props\n for (var prop in newProps) {\n if (newProps[prop] !== currentProps[prop]) {\n return true;\n }\n }\n\n return false;\n };\n\n var applyStyles = function applyStyles(element, _ref2) {\n var opacity = _ref2.opacity,\n perspective = _ref2.perspective,\n translateX = _ref2.translateX,\n translateY = _ref2.translateY,\n scaleX = _ref2.scaleX,\n scaleY = _ref2.scaleY,\n rotateX = _ref2.rotateX,\n rotateY = _ref2.rotateY,\n rotateZ = _ref2.rotateZ,\n originX = _ref2.originX,\n originY = _ref2.originY,\n width = _ref2.width,\n height = _ref2.height;\n\n var transforms = '';\n var styles = '';\n\n // handle transform origin\n if (isDefined(originX) || isDefined(originY)) {\n styles += 'transform-origin: ' + (originX || 0) + 'px ' + (originY || 0) + 'px;';\n }\n\n // transform order is relevant\n // 0. perspective\n if (isDefined(perspective)) {\n transforms += 'perspective(' + perspective + 'px) ';\n }\n\n // 1. translate\n if (isDefined(translateX) || isDefined(translateY)) {\n transforms +=\n 'translate3d(' + (translateX || 0) + 'px, ' + (translateY || 0) + 'px, 0) ';\n }\n\n // 2. scale\n if (isDefined(scaleX) || isDefined(scaleY)) {\n transforms +=\n 'scale3d(' +\n (isDefined(scaleX) ? scaleX : 1) +\n ', ' +\n (isDefined(scaleY) ? scaleY : 1) +\n ', 1) ';\n }\n\n // 3. rotate\n if (isDefined(rotateZ)) {\n transforms += 'rotateZ(' + rotateZ + 'rad) ';\n }\n\n if (isDefined(rotateX)) {\n transforms += 'rotateX(' + rotateX + 'rad) ';\n }\n\n if (isDefined(rotateY)) {\n transforms += 'rotateY(' + rotateY + 'rad) ';\n }\n\n // add transforms\n if (transforms.length) {\n styles += 'transform:' + transforms + ';';\n }\n\n // add opacity\n if (isDefined(opacity)) {\n styles += 'opacity:' + opacity + ';';\n\n // if we reach zero, we make the element inaccessible\n if (opacity === 0) {\n styles += 'visibility:hidden;';\n }\n\n // if we're below 100% opacity this element can't be clicked\n if (opacity < 1) {\n styles += 'pointer-events:none;';\n }\n }\n\n // add height\n if (isDefined(height)) {\n styles += 'height:' + height + 'px;';\n }\n\n // add width\n if (isDefined(width)) {\n styles += 'width:' + width + 'px;';\n }\n\n // apply styles\n var elementCurrentStyle = element.elementCurrentStyle || '';\n\n // if new styles does not match current styles, lets update!\n if (styles.length !== elementCurrentStyle.length || styles !== elementCurrentStyle) {\n element.style.cssText = styles;\n // store current styles so we can compare them to new styles later on\n // _not_ getting the style value is faster\n element.elementCurrentStyle = styles;\n }\n };\n\n var Mixins = {\n styles: styles,\n listeners: listeners,\n animations: animations,\n apis: apis,\n };\n\n var updateRect = function updateRect() {\n var rect = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};\n var element = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};\n var style = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};\n\n if (!element.layoutCalculated) {\n rect.paddingTop = parseInt(style.paddingTop, 10) || 0;\n rect.marginTop = parseInt(style.marginTop, 10) || 0;\n rect.marginRight = parseInt(style.marginRight, 10) || 0;\n rect.marginBottom = parseInt(style.marginBottom, 10) || 0;\n rect.marginLeft = parseInt(style.marginLeft, 10) || 0;\n element.layoutCalculated = true;\n }\n\n rect.left = element.offsetLeft || 0;\n rect.top = element.offsetTop || 0;\n rect.width = element.offsetWidth || 0;\n rect.height = element.offsetHeight || 0;\n\n rect.right = rect.left + rect.width;\n rect.bottom = rect.top + rect.height;\n\n rect.scrollTop = element.scrollTop;\n\n rect.hidden = element.offsetParent === null;\n\n return rect;\n };\n\n var createView =\n // default view definition\n function createView() {\n var _ref = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {},\n _ref$tag = _ref.tag,\n tag = _ref$tag === void 0 ? 'div' : _ref$tag,\n _ref$name = _ref.name,\n name = _ref$name === void 0 ? null : _ref$name,\n _ref$attributes = _ref.attributes,\n attributes = _ref$attributes === void 0 ? {} : _ref$attributes,\n _ref$read = _ref.read,\n read = _ref$read === void 0 ? function() {} : _ref$read,\n _ref$write = _ref.write,\n write = _ref$write === void 0 ? function() {} : _ref$write,\n _ref$create = _ref.create,\n create = _ref$create === void 0 ? function() {} : _ref$create,\n _ref$destroy = _ref.destroy,\n destroy = _ref$destroy === void 0 ? function() {} : _ref$destroy,\n _ref$filterFrameActio = _ref.filterFrameActionsForChild,\n filterFrameActionsForChild =\n _ref$filterFrameActio === void 0\n ? function(child, actions) {\n return actions;\n }\n : _ref$filterFrameActio,\n _ref$didCreateView = _ref.didCreateView,\n didCreateView = _ref$didCreateView === void 0 ? function() {} : _ref$didCreateView,\n _ref$didWriteView = _ref.didWriteView,\n didWriteView = _ref$didWriteView === void 0 ? function() {} : _ref$didWriteView,\n _ref$ignoreRect = _ref.ignoreRect,\n ignoreRect = _ref$ignoreRect === void 0 ? false : _ref$ignoreRect,\n _ref$ignoreRectUpdate = _ref.ignoreRectUpdate,\n ignoreRectUpdate = _ref$ignoreRectUpdate === void 0 ? false : _ref$ignoreRectUpdate,\n _ref$mixins = _ref.mixins,\n mixins = _ref$mixins === void 0 ? [] : _ref$mixins;\n return function(\n // each view requires reference to store\n store\n ) {\n var props = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};\n // root element should not be changed\n var element = createElement(tag, 'filepond--' + name, attributes);\n\n // style reference should also not be changed\n var style = window.getComputedStyle(element, null);\n\n // element rectangle\n var rect = updateRect();\n var frameRect = null;\n\n // rest state\n var isResting = false;\n\n // pretty self explanatory\n var childViews = [];\n\n // loaded mixins\n var activeMixins = [];\n\n // references to created children\n var ref = {};\n\n // state used for each instance\n var state = {};\n\n // list of writers that will be called to update this view\n var writers = [\n write, // default writer\n ];\n\n var readers = [\n read, // default reader\n ];\n\n var destroyers = [\n destroy, // default destroy\n ];\n\n // core view methods\n var getElement = function getElement() {\n return element;\n };\n var getChildViews = function getChildViews() {\n return childViews.concat();\n };\n var getReference = function getReference() {\n return ref;\n };\n var createChildView = function createChildView(store) {\n return function(view, props) {\n return view(store, props);\n };\n };\n var getRect = function getRect() {\n if (frameRect) {\n return frameRect;\n }\n frameRect = getViewRect(rect, childViews, [0, 0], [1, 1]);\n return frameRect;\n };\n var getStyle = function getStyle() {\n return style;\n };\n\n /**\n * Read data from DOM\n * @private\n */\n var _read = function _read() {\n frameRect = null;\n\n // read child views\n childViews.forEach(function(child) {\n return child._read();\n });\n\n var shouldUpdate = !(ignoreRectUpdate && rect.width && rect.height);\n if (shouldUpdate) {\n updateRect(rect, element, style);\n }\n\n // readers\n var api = { root: internalAPI, props: props, rect: rect };\n readers.forEach(function(reader) {\n return reader(api);\n });\n };\n\n /**\n * Write data to DOM\n * @private\n */\n var _write = function _write(ts, frameActions, shouldOptimize) {\n // if no actions, we assume that the view is resting\n var resting = frameActions.length === 0;\n\n // writers\n writers.forEach(function(writer) {\n var writerResting = writer({\n props: props,\n root: internalAPI,\n actions: frameActions,\n timestamp: ts,\n shouldOptimize: shouldOptimize,\n });\n\n if (writerResting === false) {\n resting = false;\n }\n });\n\n // run mixins\n activeMixins.forEach(function(mixin) {\n // if one of the mixins is still busy after write operation, we are not resting\n var mixinResting = mixin.write(ts);\n if (mixinResting === false) {\n resting = false;\n }\n });\n\n // updates child views that are currently attached to the DOM\n childViews\n .filter(function(child) {\n return !!child.element.parentNode;\n })\n .forEach(function(child) {\n // if a child view is not resting, we are not resting\n var childResting = child._write(\n ts,\n filterFrameActionsForChild(child, frameActions),\n shouldOptimize\n );\n\n if (!childResting) {\n resting = false;\n }\n });\n\n // append new elements to DOM and update those\n childViews\n //.filter(child => !child.element.parentNode)\n .forEach(function(child, index) {\n // skip\n if (child.element.parentNode) {\n return;\n }\n\n // append to DOM\n internalAPI.appendChild(child.element, index);\n\n // call read (need to know the size of these elements)\n child._read();\n\n // re-call write\n child._write(\n ts,\n filterFrameActionsForChild(child, frameActions),\n shouldOptimize\n );\n\n // we just added somthing to the dom, no rest\n resting = false;\n });\n\n // update resting state\n isResting = resting;\n\n didWriteView({\n props: props,\n root: internalAPI,\n actions: frameActions,\n timestamp: ts,\n });\n\n // let parent know if we are resting\n return resting;\n };\n\n var _destroy = function _destroy() {\n activeMixins.forEach(function(mixin) {\n return mixin.destroy();\n });\n destroyers.forEach(function(destroyer) {\n destroyer({ root: internalAPI, props: props });\n });\n childViews.forEach(function(child) {\n return child._destroy();\n });\n };\n\n // sharedAPI\n var sharedAPIDefinition = {\n element: {\n get: getElement,\n },\n\n style: {\n get: getStyle,\n },\n\n childViews: {\n get: getChildViews,\n },\n };\n\n // private API definition\n var internalAPIDefinition = Object.assign({}, sharedAPIDefinition, {\n rect: {\n get: getRect,\n },\n\n // access to custom children references\n ref: {\n get: getReference,\n },\n\n // dom modifiers\n is: function is(needle) {\n return name === needle;\n },\n appendChild: appendChild(element),\n createChildView: createChildView(store),\n linkView: function linkView(view) {\n childViews.push(view);\n return view;\n },\n unlinkView: function unlinkView(view) {\n childViews.splice(childViews.indexOf(view), 1);\n },\n appendChildView: appendChildView(element, childViews),\n removeChildView: removeChildView(element, childViews),\n registerWriter: function registerWriter(writer) {\n return writers.push(writer);\n },\n registerReader: function registerReader(reader) {\n return readers.push(reader);\n },\n registerDestroyer: function registerDestroyer(destroyer) {\n return destroyers.push(destroyer);\n },\n invalidateLayout: function invalidateLayout() {\n return (element.layoutCalculated = false);\n },\n\n // access to data store\n dispatch: store.dispatch,\n query: store.query,\n });\n\n // public view API methods\n var externalAPIDefinition = {\n element: {\n get: getElement,\n },\n\n childViews: {\n get: getChildViews,\n },\n\n rect: {\n get: getRect,\n },\n\n resting: {\n get: function get() {\n return isResting;\n },\n },\n\n isRectIgnored: function isRectIgnored() {\n return ignoreRect;\n },\n _read: _read,\n _write: _write,\n _destroy: _destroy,\n };\n\n // mixin API methods\n var mixinAPIDefinition = Object.assign({}, sharedAPIDefinition, {\n rect: {\n get: function get() {\n return rect;\n },\n },\n });\n\n // add mixin functionality\n Object.keys(mixins)\n .sort(function(a, b) {\n // move styles to the back of the mixin list (so adjustments of other mixins are applied to the props correctly)\n if (a === 'styles') {\n return 1;\n } else if (b === 'styles') {\n return -1;\n }\n return 0;\n })\n .forEach(function(key) {\n var mixinAPI = Mixins[key]({\n mixinConfig: mixins[key],\n viewProps: props,\n viewState: state,\n viewInternalAPI: internalAPIDefinition,\n viewExternalAPI: externalAPIDefinition,\n view: createObject(mixinAPIDefinition),\n });\n\n if (mixinAPI) {\n activeMixins.push(mixinAPI);\n }\n });\n\n // construct private api\n var internalAPI = createObject(internalAPIDefinition);\n\n // create the view\n create({\n root: internalAPI,\n props: props,\n });\n\n // append created child views to root node\n var childCount = getChildCount(element); // need to know the current child count so appending happens in correct order\n childViews.forEach(function(child, index) {\n internalAPI.appendChild(child.element, childCount + index);\n });\n\n // call did create\n didCreateView(internalAPI);\n\n // expose public api\n return createObject(externalAPIDefinition);\n };\n };\n\n var createPainter = function createPainter(read, write) {\n var fps = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 60;\n\n var name = '__framePainter';\n\n // set global painter\n if (window[name]) {\n window[name].readers.push(read);\n window[name].writers.push(write);\n return;\n }\n\n window[name] = {\n readers: [read],\n writers: [write],\n };\n\n var painter = window[name];\n\n var interval = 1000 / fps;\n var last = null;\n var id = null;\n var requestTick = null;\n var cancelTick = null;\n\n var setTimerType = function setTimerType() {\n if (document.hidden) {\n requestTick = function requestTick() {\n return window.setTimeout(function() {\n return tick(performance.now());\n }, interval);\n };\n cancelTick = function cancelTick() {\n return window.clearTimeout(id);\n };\n } else {\n requestTick = function requestTick() {\n return window.requestAnimationFrame(tick);\n };\n cancelTick = function cancelTick() {\n return window.cancelAnimationFrame(id);\n };\n }\n };\n\n document.addEventListener('visibilitychange', function() {\n if (cancelTick) cancelTick();\n setTimerType();\n tick(performance.now());\n });\n\n var tick = function tick(ts) {\n // queue next tick\n id = requestTick(tick);\n\n // limit fps\n if (!last) {\n last = ts;\n }\n\n var delta = ts - last;\n\n if (delta <= interval) {\n // skip frame\n return;\n }\n\n // align next frame\n last = ts - (delta % interval);\n\n // update view\n painter.readers.forEach(function(read) {\n return read();\n });\n painter.writers.forEach(function(write) {\n return write(ts);\n });\n };\n\n setTimerType();\n tick(performance.now());\n\n return {\n pause: function pause() {\n cancelTick(id);\n },\n };\n };\n\n var createRoute = function createRoute(routes, fn) {\n return function(_ref) {\n var root = _ref.root,\n props = _ref.props,\n _ref$actions = _ref.actions,\n actions = _ref$actions === void 0 ? [] : _ref$actions,\n timestamp = _ref.timestamp,\n shouldOptimize = _ref.shouldOptimize;\n actions\n .filter(function(action) {\n return routes[action.type];\n })\n .forEach(function(action) {\n return routes[action.type]({\n root: root,\n props: props,\n action: action.data,\n timestamp: timestamp,\n shouldOptimize: shouldOptimize,\n });\n });\n\n if (fn) {\n fn({\n root: root,\n props: props,\n actions: actions,\n timestamp: timestamp,\n shouldOptimize: shouldOptimize,\n });\n }\n };\n };\n\n var insertBefore = function insertBefore(newNode, referenceNode) {\n return referenceNode.parentNode.insertBefore(newNode, referenceNode);\n };\n\n var insertAfter = function insertAfter(newNode, referenceNode) {\n return referenceNode.parentNode.insertBefore(newNode, referenceNode.nextSibling);\n };\n\n var isArray = function isArray(value) {\n return Array.isArray(value);\n };\n\n var isEmpty = function isEmpty(value) {\n return value == null;\n };\n\n var trim = function trim(str) {\n return str.trim();\n };\n\n var toString = function toString(value) {\n return '' + value;\n };\n\n var toArray = function toArray(value) {\n var splitter = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : ',';\n if (isEmpty(value)) {\n return [];\n }\n if (isArray(value)) {\n return value;\n }\n return toString(value)\n .split(splitter)\n .map(trim)\n .filter(function(str) {\n return str.length;\n });\n };\n\n var isBoolean = function isBoolean(value) {\n return typeof value === 'boolean';\n };\n\n var toBoolean = function toBoolean(value) {\n return isBoolean(value) ? value : value === 'true';\n };\n\n var isString = function isString(value) {\n return typeof value === 'string';\n };\n\n var toNumber = function toNumber(value) {\n return isNumber(value)\n ? value\n : isString(value)\n ? toString(value).replace(/[a-z]+/gi, '')\n : 0;\n };\n\n var toInt = function toInt(value) {\n return parseInt(toNumber(value), 10);\n };\n\n var toFloat = function toFloat(value) {\n return parseFloat(toNumber(value));\n };\n\n var isInt = function isInt(value) {\n return isNumber(value) && isFinite(value) && Math.floor(value) === value;\n };\n\n var toBytes = function toBytes(value) {\n var base = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 1000;\n // is in bytes\n if (isInt(value)) {\n return value;\n }\n\n // is natural file size\n var naturalFileSize = toString(value).trim();\n\n // if is value in megabytes\n if (/MB$/i.test(naturalFileSize)) {\n naturalFileSize = naturalFileSize.replace(/MB$i/, '').trim();\n return toInt(naturalFileSize) * base * base;\n }\n\n // if is value in kilobytes\n if (/KB/i.test(naturalFileSize)) {\n naturalFileSize = naturalFileSize.replace(/KB$i/, '').trim();\n return toInt(naturalFileSize) * base;\n }\n\n return toInt(naturalFileSize);\n };\n\n var isFunction = function isFunction(value) {\n return typeof value === 'function';\n };\n\n var toFunctionReference = function toFunctionReference(string) {\n var ref = self;\n var levels = string.split('.');\n var level = null;\n while ((level = levels.shift())) {\n ref = ref[level];\n if (!ref) {\n return null;\n }\n }\n return ref;\n };\n\n var methods = {\n process: 'POST',\n patch: 'PATCH',\n revert: 'DELETE',\n fetch: 'GET',\n restore: 'GET',\n load: 'GET',\n };\n\n var createServerAPI = function createServerAPI(outline) {\n var api = {};\n\n api.url = isString(outline) ? outline : outline.url || '';\n api.timeout = outline.timeout ? parseInt(outline.timeout, 10) : 0;\n api.headers = outline.headers ? outline.headers : {};\n\n forin(methods, function(key) {\n api[key] = createAction(key, outline[key], methods[key], api.timeout, api.headers);\n });\n\n // remove process if no url or process on outline\n api.process = outline.process || isString(outline) || outline.url ? api.process : null;\n\n // special treatment for remove\n api.remove = outline.remove || null;\n\n // remove generic headers from api object\n delete api.headers;\n\n return api;\n };\n\n var createAction = function createAction(name, outline, method, timeout, headers) {\n // is explicitely set to null so disable\n if (outline === null) {\n return null;\n }\n\n // if is custom function, done! Dev handles everything.\n if (typeof outline === 'function') {\n return outline;\n }\n\n // build action object\n var action = {\n url: method === 'GET' || method === 'PATCH' ? '?' + name + '=' : '',\n method: method,\n headers: headers,\n withCredentials: false,\n timeout: timeout,\n onload: null,\n ondata: null,\n onerror: null,\n };\n\n // is a single url\n if (isString(outline)) {\n action.url = outline;\n return action;\n }\n\n // overwrite\n Object.assign(action, outline);\n\n // see if should reformat headers;\n if (isString(action.headers)) {\n var parts = action.headers.split(/:(.+)/);\n action.headers = {\n header: parts[0],\n value: parts[1],\n };\n }\n\n // if is bool withCredentials\n action.withCredentials = toBoolean(action.withCredentials);\n\n return action;\n };\n\n var toServerAPI = function toServerAPI(value) {\n return createServerAPI(value);\n };\n\n var isNull = function isNull(value) {\n return value === null;\n };\n\n var isObject = function isObject(value) {\n return typeof value === 'object' && value !== null;\n };\n\n var isAPI = function isAPI(value) {\n return (\n isObject(value) &&\n isString(value.url) &&\n isObject(value.process) &&\n isObject(value.revert) &&\n isObject(value.restore) &&\n isObject(value.fetch)\n );\n };\n\n var getType = function getType(value) {\n if (isArray(value)) {\n return 'array';\n }\n\n if (isNull(value)) {\n return 'null';\n }\n\n if (isInt(value)) {\n return 'int';\n }\n\n if (/^[0-9]+ ?(?:GB|MB|KB)$/gi.test(value)) {\n return 'bytes';\n }\n\n if (isAPI(value)) {\n return 'api';\n }\n\n return typeof value;\n };\n\n var replaceSingleQuotes = function replaceSingleQuotes(str) {\n return str\n .replace(/{\\s*'/g, '{\"')\n .replace(/'\\s*}/g, '\"}')\n .replace(/'\\s*:/g, '\":')\n .replace(/:\\s*'/g, ':\"')\n .replace(/,\\s*'/g, ',\"')\n .replace(/'\\s*,/g, '\",');\n };\n\n var conversionTable = {\n array: toArray,\n boolean: toBoolean,\n int: function int(value) {\n return getType(value) === 'bytes' ? toBytes(value) : toInt(value);\n },\n number: toFloat,\n float: toFloat,\n bytes: toBytes,\n string: function string(value) {\n return isFunction(value) ? value : toString(value);\n },\n function: function _function(value) {\n return toFunctionReference(value);\n },\n serverapi: toServerAPI,\n object: function object(value) {\n try {\n return JSON.parse(replaceSingleQuotes(value));\n } catch (e) {\n return null;\n }\n },\n };\n\n var convertTo = function convertTo(value, type) {\n return conversionTable[type](value);\n };\n\n var getValueByType = function getValueByType(newValue, defaultValue, valueType) {\n // can always assign default value\n if (newValue === defaultValue) {\n return newValue;\n }\n\n // get the type of the new value\n var newValueType = getType(newValue);\n\n // is valid type?\n if (newValueType !== valueType) {\n // is string input, let's attempt to convert\n var convertedValue = convertTo(newValue, valueType);\n\n // what is the type now\n newValueType = getType(convertedValue);\n\n // no valid conversions found\n if (convertedValue === null) {\n throw 'Trying to assign value with incorrect type to \"' +\n option +\n '\", allowed type: \"' +\n valueType +\n '\"';\n } else {\n newValue = convertedValue;\n }\n }\n\n // assign new value\n return newValue;\n };\n\n var createOption = function createOption(defaultValue, valueType) {\n var currentValue = defaultValue;\n return {\n enumerable: true,\n get: function get() {\n return currentValue;\n },\n set: function set(newValue) {\n currentValue = getValueByType(newValue, defaultValue, valueType);\n },\n };\n };\n\n var createOptions = function createOptions(options) {\n var obj = {};\n forin(options, function(prop) {\n var optionDefinition = options[prop];\n obj[prop] = createOption(optionDefinition[0], optionDefinition[1]);\n });\n return createObject(obj);\n };\n\n var createInitialState = function createInitialState(options) {\n return {\n // model\n items: [],\n\n // timeout used for calling update items\n listUpdateTimeout: null,\n\n // timeout used for stacking metadata updates\n itemUpdateTimeout: null,\n\n // queue of items waiting to be processed\n processingQueue: [],\n\n // options\n options: createOptions(options),\n };\n };\n\n var fromCamels = function fromCamels(string) {\n var separator = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : '-';\n return string\n .split(/(?=[A-Z])/)\n .map(function(part) {\n return part.toLowerCase();\n })\n .join(separator);\n };\n\n var createOptionAPI = function createOptionAPI(store, options) {\n var obj = {};\n forin(options, function(key) {\n obj[key] = {\n get: function get() {\n return store.getState().options[key];\n },\n set: function set(value) {\n store.dispatch('SET_' + fromCamels(key, '_').toUpperCase(), {\n value: value,\n });\n },\n };\n });\n return obj;\n };\n\n var createOptionActions = function createOptionActions(options) {\n return function(dispatch, query, state) {\n var obj = {};\n forin(options, function(key) {\n var name = fromCamels(key, '_').toUpperCase();\n\n obj['SET_' + name] = function(action) {\n try {\n state.options[key] = action.value;\n } catch (e) {} // nope, failed\n\n // we successfully set the value of this option\n dispatch('DID_SET_' + name, { value: state.options[key] });\n };\n });\n return obj;\n };\n };\n\n var createOptionQueries = function createOptionQueries(options) {\n return function(state) {\n var obj = {};\n forin(options, function(key) {\n obj['GET_' + fromCamels(key, '_').toUpperCase()] = function(action) {\n return state.options[key];\n };\n });\n return obj;\n };\n };\n\n var InteractionMethod = {\n API: 1,\n DROP: 2,\n BROWSE: 3,\n PASTE: 4,\n NONE: 5,\n };\n\n var getUniqueId = function getUniqueId() {\n return Math.random()\n .toString(36)\n .substring(2, 11);\n };\n\n function _typeof(obj) {\n if (typeof Symbol === 'function' && typeof Symbol.iterator === 'symbol') {\n _typeof = function(obj) {\n return typeof obj;\n };\n } else {\n _typeof = function(obj) {\n return obj &&\n typeof Symbol === 'function' &&\n obj.constructor === Symbol &&\n obj !== Symbol.prototype\n ? 'symbol'\n : typeof obj;\n };\n }\n\n return _typeof(obj);\n }\n\n var REACT_ELEMENT_TYPE;\n\n function _jsx(type, props, key, children) {\n if (!REACT_ELEMENT_TYPE) {\n REACT_ELEMENT_TYPE =\n (typeof Symbol === 'function' && Symbol['for'] && Symbol['for']('react.element')) ||\n 0xeac7;\n }\n\n var defaultProps = type && type.defaultProps;\n var childrenLength = arguments.length - 3;\n\n if (!props && childrenLength !== 0) {\n props = {\n children: void 0,\n };\n }\n\n if (props && defaultProps) {\n for (var propName in defaultProps) {\n if (props[propName] === void 0) {\n props[propName] = defaultProps[propName];\n }\n }\n } else if (!props) {\n props = defaultProps || {};\n }\n\n if (childrenLength === 1) {\n props.children = children;\n } else if (childrenLength > 1) {\n var childArray = new Array(childrenLength);\n\n for (var i = 0; i < childrenLength; i++) {\n childArray[i] = arguments[i + 3];\n }\n\n props.children = childArray;\n }\n\n return {\n $$typeof: REACT_ELEMENT_TYPE,\n type: type,\n key: key === undefined ? null : '' + key,\n ref: null,\n props: props,\n _owner: null,\n };\n }\n\n function _asyncIterator(iterable) {\n var method;\n\n if (typeof Symbol !== 'undefined') {\n if (Symbol.asyncIterator) {\n method = iterable[Symbol.asyncIterator];\n if (method != null) return method.call(iterable);\n }\n\n if (Symbol.iterator) {\n method = iterable[Symbol.iterator];\n if (method != null) return method.call(iterable);\n }\n }\n\n throw new TypeError('Object is not async iterable');\n }\n\n function _AwaitValue(value) {\n this.wrapped = value;\n }\n\n function _AsyncGenerator(gen) {\n var front, back;\n\n function send(key, arg) {\n return new Promise(function(resolve, reject) {\n var request = {\n key: key,\n arg: arg,\n resolve: resolve,\n reject: reject,\n next: null,\n };\n\n if (back) {\n back = back.next = request;\n } else {\n front = back = request;\n resume(key, arg);\n }\n });\n }\n\n function resume(key, arg) {\n try {\n var result = gen[key](arg);\n var value = result.value;\n var wrappedAwait = value instanceof _AwaitValue;\n Promise.resolve(wrappedAwait ? value.wrapped : value).then(\n function(arg) {\n if (wrappedAwait) {\n resume('next', arg);\n return;\n }\n\n settle(result.done ? 'return' : 'normal', arg);\n },\n function(err) {\n resume('throw', err);\n }\n );\n } catch (err) {\n settle('throw', err);\n }\n }\n\n function settle(type, value) {\n switch (type) {\n case 'return':\n front.resolve({\n value: value,\n done: true,\n });\n break;\n\n case 'throw':\n front.reject(value);\n break;\n\n default:\n front.resolve({\n value: value,\n done: false,\n });\n break;\n }\n\n front = front.next;\n\n if (front) {\n resume(front.key, front.arg);\n } else {\n back = null;\n }\n }\n\n this._invoke = send;\n\n if (typeof gen.return !== 'function') {\n this.return = undefined;\n }\n }\n\n if (typeof Symbol === 'function' && Symbol.asyncIterator) {\n _AsyncGenerator.prototype[Symbol.asyncIterator] = function() {\n return this;\n };\n }\n\n _AsyncGenerator.prototype.next = function(arg) {\n return this._invoke('next', arg);\n };\n\n _AsyncGenerator.prototype.throw = function(arg) {\n return this._invoke('throw', arg);\n };\n\n _AsyncGenerator.prototype.return = function(arg) {\n return this._invoke('return', arg);\n };\n\n function _wrapAsyncGenerator(fn) {\n return function() {\n return new _AsyncGenerator(fn.apply(this, arguments));\n };\n }\n\n function _awaitAsyncGenerator(value) {\n return new _AwaitValue(value);\n }\n\n function _asyncGeneratorDelegate(inner, awaitWrap) {\n var iter = {},\n waiting = false;\n\n function pump(key, value) {\n waiting = true;\n value = new Promise(function(resolve) {\n resolve(inner[key](value));\n });\n return {\n done: false,\n value: awaitWrap(value),\n };\n }\n\n if (typeof Symbol === 'function' && Symbol.iterator) {\n iter[Symbol.iterator] = function() {\n return this;\n };\n }\n\n iter.next = function(value) {\n if (waiting) {\n waiting = false;\n return value;\n }\n\n return pump('next', value);\n };\n\n if (typeof inner.throw === 'function') {\n iter.throw = function(value) {\n if (waiting) {\n waiting = false;\n throw value;\n }\n\n return pump('throw', value);\n };\n }\n\n if (typeof inner.return === 'function') {\n iter.return = function(value) {\n return pump('return', value);\n };\n }\n\n return iter;\n }\n\n function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {\n try {\n var info = gen[key](arg);\n var value = info.value;\n } catch (error) {\n reject(error);\n return;\n }\n\n if (info.done) {\n resolve(value);\n } else {\n Promise.resolve(value).then(_next, _throw);\n }\n }\n\n function _asyncToGenerator(fn) {\n return function() {\n var self = this,\n args = arguments;\n return new Promise(function(resolve, reject) {\n var gen = fn.apply(self, args);\n\n function _next(value) {\n asyncGeneratorStep(gen, resolve, reject, _next, _throw, 'next', value);\n }\n\n function _throw(err) {\n asyncGeneratorStep(gen, resolve, reject, _next, _throw, 'throw', err);\n }\n\n _next(undefined);\n });\n };\n }\n\n function _classCallCheck(instance, Constructor) {\n if (!(instance instanceof Constructor)) {\n throw new TypeError('Cannot call a class as a function');\n }\n }\n\n function _defineProperties(target, props) {\n for (var i = 0; i < props.length; i++) {\n var descriptor = props[i];\n descriptor.enumerable = descriptor.enumerable || false;\n descriptor.configurable = true;\n if ('value' in descriptor) descriptor.writable = true;\n Object.defineProperty(target, descriptor.key, descriptor);\n }\n }\n\n function _createClass(Constructor, protoProps, staticProps) {\n if (protoProps) _defineProperties(Constructor.prototype, protoProps);\n if (staticProps) _defineProperties(Constructor, staticProps);\n return Constructor;\n }\n\n function _defineEnumerableProperties(obj, descs) {\n for (var key in descs) {\n var desc = descs[key];\n desc.configurable = desc.enumerable = true;\n if ('value' in desc) desc.writable = true;\n Object.defineProperty(obj, key, desc);\n }\n\n if (Object.getOwnPropertySymbols) {\n var objectSymbols = Object.getOwnPropertySymbols(descs);\n\n for (var i = 0; i < objectSymbols.length; i++) {\n var sym = objectSymbols[i];\n var desc = descs[sym];\n desc.configurable = desc.enumerable = true;\n if ('value' in desc) desc.writable = true;\n Object.defineProperty(obj, sym, desc);\n }\n }\n\n return obj;\n }\n\n function _defaults(obj, defaults) {\n var keys = Object.getOwnPropertyNames(defaults);\n\n for (var i = 0; i < keys.length; i++) {\n var key = keys[i];\n var value = Object.getOwnPropertyDescriptor(defaults, key);\n\n if (value && value.configurable && obj[key] === undefined) {\n Object.defineProperty(obj, key, value);\n }\n }\n\n return obj;\n }\n\n function _defineProperty(obj, key, value) {\n if (key in obj) {\n Object.defineProperty(obj, key, {\n value: value,\n enumerable: true,\n configurable: true,\n writable: true,\n });\n } else {\n obj[key] = value;\n }\n\n return obj;\n }\n\n function _extends() {\n _extends =\n Object.assign ||\n function(target) {\n for (var i = 1; i < arguments.length; i++) {\n var source = arguments[i];\n\n for (var key in source) {\n if (Object.prototype.hasOwnProperty.call(source, key)) {\n target[key] = source[key];\n }\n }\n }\n\n return target;\n };\n\n return _extends.apply(this, arguments);\n }\n\n function _objectSpread(target) {\n for (var i = 1; i < arguments.length; i++) {\n var source = arguments[i] != null ? arguments[i] : {};\n var ownKeys = Object.keys(source);\n\n if (typeof Object.getOwnPropertySymbols === 'function') {\n ownKeys = ownKeys.concat(\n Object.getOwnPropertySymbols(source).filter(function(sym) {\n return Object.getOwnPropertyDescriptor(source, sym).enumerable;\n })\n );\n }\n\n ownKeys.forEach(function(key) {\n _defineProperty(target, key, source[key]);\n });\n }\n\n return target;\n }\n\n function ownKeys(object, enumerableOnly) {\n var keys = Object.keys(object);\n\n if (Object.getOwnPropertySymbols) {\n var symbols = Object.getOwnPropertySymbols(object);\n if (enumerableOnly)\n symbols = symbols.filter(function(sym) {\n return Object.getOwnPropertyDescriptor(object, sym).enumerable;\n });\n keys.push.apply(keys, symbols);\n }\n\n return keys;\n }\n\n function _objectSpread2(target) {\n for (var i = 1; i < arguments.length; i++) {\n var source = arguments[i] != null ? arguments[i] : {};\n\n if (i % 2) {\n ownKeys(source, true).forEach(function(key) {\n _defineProperty(target, key, source[key]);\n });\n } else if (Object.getOwnPropertyDescriptors) {\n Object.defineProperties(target, Object.getOwnPropertyDescriptors(source));\n } else {\n ownKeys(source).forEach(function(key) {\n Object.defineProperty(\n target,\n key,\n Object.getOwnPropertyDescriptor(source, key)\n );\n });\n }\n }\n\n return target;\n }\n\n function _inherits(subClass, superClass) {\n if (typeof superClass !== 'function' && superClass !== null) {\n throw new TypeError('Super expression must either be null or a function');\n }\n\n subClass.prototype = Object.create(superClass && superClass.prototype, {\n constructor: {\n value: subClass,\n writable: true,\n configurable: true,\n },\n });\n if (superClass) _setPrototypeOf(subClass, superClass);\n }\n\n function _inheritsLoose(subClass, superClass) {\n subClass.prototype = Object.create(superClass.prototype);\n subClass.prototype.constructor = subClass;\n subClass.__proto__ = superClass;\n }\n\n function _getPrototypeOf(o) {\n _getPrototypeOf = Object.setPrototypeOf\n ? Object.getPrototypeOf\n : function _getPrototypeOf(o) {\n return o.__proto__ || Object.getPrototypeOf(o);\n };\n return _getPrototypeOf(o);\n }\n\n function _setPrototypeOf(o, p) {\n _setPrototypeOf =\n Object.setPrototypeOf ||\n function _setPrototypeOf(o, p) {\n o.__proto__ = p;\n return o;\n };\n\n return _setPrototypeOf(o, p);\n }\n\n function isNativeReflectConstruct() {\n if (typeof Reflect === 'undefined' || !Reflect.construct) return false;\n if (Reflect.construct.sham) return false;\n if (typeof Proxy === 'function') return true;\n\n try {\n Date.prototype.toString.call(Reflect.construct(Date, [], function() {}));\n return true;\n } catch (e) {\n return false;\n }\n }\n\n function _construct(Parent, args, Class) {\n if (isNativeReflectConstruct()) {\n _construct = Reflect.construct;\n } else {\n _construct = function _construct(Parent, args, Class) {\n var a = [null];\n a.push.apply(a, args);\n var Constructor = Function.bind.apply(Parent, a);\n var instance = new Constructor();\n if (Class) _setPrototypeOf(instance, Class.prototype);\n return instance;\n };\n }\n\n return _construct.apply(null, arguments);\n }\n\n function _isNativeFunction(fn) {\n return Function.toString.call(fn).indexOf('[native code]') !== -1;\n }\n\n function _wrapNativeSuper(Class) {\n var _cache = typeof Map === 'function' ? new Map() : undefined;\n\n _wrapNativeSuper = function _wrapNativeSuper(Class) {\n if (Class === null || !_isNativeFunction(Class)) return Class;\n\n if (typeof Class !== 'function') {\n throw new TypeError('Super expression must either be null or a function');\n }\n\n if (typeof _cache !== 'undefined') {\n if (_cache.has(Class)) return _cache.get(Class);\n\n _cache.set(Class, Wrapper);\n }\n\n function Wrapper() {\n return _construct(Class, arguments, _getPrototypeOf(this).constructor);\n }\n\n Wrapper.prototype = Object.create(Class.prototype, {\n constructor: {\n value: Wrapper,\n enumerable: false,\n writable: true,\n configurable: true,\n },\n });\n return _setPrototypeOf(Wrapper, Class);\n };\n\n return _wrapNativeSuper(Class);\n }\n\n function _instanceof(left, right) {\n if (right != null && typeof Symbol !== 'undefined' && right[Symbol.hasInstance]) {\n return !!right[Symbol.hasInstance](left);\n } else {\n return left instanceof right;\n }\n }\n\n function _interopRequireDefault(obj) {\n return obj && obj.__esModule\n ? obj\n : {\n default: obj,\n };\n }\n\n function _interopRequireWildcard(obj) {\n if (obj && obj.__esModule) {\n return obj;\n } else {\n var newObj = {};\n\n if (obj != null) {\n for (var key in obj) {\n if (Object.prototype.hasOwnProperty.call(obj, key)) {\n var desc =\n Object.defineProperty && Object.getOwnPropertyDescriptor\n ? Object.getOwnPropertyDescriptor(obj, key)\n : {};\n\n if (desc.get || desc.set) {\n Object.defineProperty(newObj, key, desc);\n } else {\n newObj[key] = obj[key];\n }\n }\n }\n }\n\n newObj.default = obj;\n return newObj;\n }\n }\n\n function _newArrowCheck(innerThis, boundThis) {\n if (innerThis !== boundThis) {\n throw new TypeError('Cannot instantiate an arrow function');\n }\n }\n\n function _objectDestructuringEmpty(obj) {\n if (obj == null) throw new TypeError('Cannot destructure undefined');\n }\n\n function _objectWithoutPropertiesLoose(source, excluded) {\n if (source == null) return {};\n var target = {};\n var sourceKeys = Object.keys(source);\n var key, i;\n\n for (i = 0; i < sourceKeys.length; i++) {\n key = sourceKeys[i];\n if (excluded.indexOf(key) >= 0) continue;\n target[key] = source[key];\n }\n\n return target;\n }\n\n function _objectWithoutProperties(source, excluded) {\n if (source == null) return {};\n\n var target = _objectWithoutPropertiesLoose(source, excluded);\n\n var key, i;\n\n if (Object.getOwnPropertySymbols) {\n var sourceSymbolKeys = Object.getOwnPropertySymbols(source);\n\n for (i = 0; i < sourceSymbolKeys.length; i++) {\n key = sourceSymbolKeys[i];\n if (excluded.indexOf(key) >= 0) continue;\n if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue;\n target[key] = source[key];\n }\n }\n\n return target;\n }\n\n function _assertThisInitialized(self) {\n if (self === void 0) {\n throw new ReferenceError(\"this hasn't been initialised - super() hasn't been called\");\n }\n\n return self;\n }\n\n function _possibleConstructorReturn(self, call) {\n if (call && (typeof call === 'object' || typeof call === 'function')) {\n return call;\n }\n\n return _assertThisInitialized(self);\n }\n\n function _superPropBase(object, property) {\n while (!Object.prototype.hasOwnProperty.call(object, property)) {\n object = _getPrototypeOf(object);\n if (object === null) break;\n }\n\n return object;\n }\n\n function _get(target, property, receiver) {\n if (typeof Reflect !== 'undefined' && Reflect.get) {\n _get = Reflect.get;\n } else {\n _get = function _get(target, property, receiver) {\n var base = _superPropBase(target, property);\n\n if (!base) return;\n var desc = Object.getOwnPropertyDescriptor(base, property);\n\n if (desc.get) {\n return desc.get.call(receiver);\n }\n\n return desc.value;\n };\n }\n\n return _get(target, property, receiver || target);\n }\n\n function set(target, property, value, receiver) {\n if (typeof Reflect !== 'undefined' && Reflect.set) {\n set = Reflect.set;\n } else {\n set = function set(target, property, value, receiver) {\n var base = _superPropBase(target, property);\n\n var desc;\n\n if (base) {\n desc = Object.getOwnPropertyDescriptor(base, property);\n\n if (desc.set) {\n desc.set.call(receiver, value);\n return true;\n } else if (!desc.writable) {\n return false;\n }\n }\n\n desc = Object.getOwnPropertyDescriptor(receiver, property);\n\n if (desc) {\n if (!desc.writable) {\n return false;\n }\n\n desc.value = value;\n Object.defineProperty(receiver, property, desc);\n } else {\n _defineProperty(receiver, property, value);\n }\n\n return true;\n };\n }\n\n return set(target, property, value, receiver);\n }\n\n function _set(target, property, value, receiver, isStrict) {\n var s = set(target, property, value, receiver || target);\n\n if (!s && isStrict) {\n throw new Error('failed to set property');\n }\n\n return value;\n }\n\n function _taggedTemplateLiteral(strings, raw) {\n if (!raw) {\n raw = strings.slice(0);\n }\n\n return Object.freeze(\n Object.defineProperties(strings, {\n raw: {\n value: Object.freeze(raw),\n },\n })\n );\n }\n\n function _taggedTemplateLiteralLoose(strings, raw) {\n if (!raw) {\n raw = strings.slice(0);\n }\n\n strings.raw = raw;\n return strings;\n }\n\n function _temporalRef(val, name) {\n if (val === _temporalUndefined) {\n throw new ReferenceError(name + ' is not defined - temporal dead zone');\n } else {\n return val;\n }\n }\n\n function _readOnlyError(name) {\n throw new Error('\"' + name + '\" is read-only');\n }\n\n function _classNameTDZError(name) {\n throw new Error('Class \"' + name + '\" cannot be referenced in computed property keys.');\n }\n\n var _temporalUndefined = {};\n\n function _slicedToArray(arr, i) {\n return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _nonIterableRest();\n }\n\n function _slicedToArrayLoose(arr, i) {\n return _arrayWithHoles(arr) || _iterableToArrayLimitLoose(arr, i) || _nonIterableRest();\n }\n\n function _toArray(arr) {\n return _arrayWithHoles(arr) || _iterableToArray(arr) || _nonIterableRest();\n }\n\n function _toConsumableArray(arr) {\n return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _nonIterableSpread();\n }\n\n function _arrayWithoutHoles(arr) {\n if (Array.isArray(arr)) {\n for (var i = 0, arr2 = new Array(arr.length); i < arr.length; i++) arr2[i] = arr[i];\n\n return arr2;\n }\n }\n\n function _arrayWithHoles(arr) {\n if (Array.isArray(arr)) return arr;\n }\n\n function _iterableToArray(iter) {\n if (\n Symbol.iterator in Object(iter) ||\n Object.prototype.toString.call(iter) === '[object Arguments]'\n )\n return Array.from(iter);\n }\n\n function _iterableToArrayLimit(arr, i) {\n var _arr = [];\n var _n = true;\n var _d = false;\n var _e = undefined;\n\n try {\n for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) {\n _arr.push(_s.value);\n\n if (i && _arr.length === i) break;\n }\n } catch (err) {\n _d = true;\n _e = err;\n } finally {\n try {\n if (!_n && _i['return'] != null) _i['return']();\n } finally {\n if (_d) throw _e;\n }\n }\n\n return _arr;\n }\n\n function _iterableToArrayLimitLoose(arr, i) {\n var _arr = [];\n\n for (var _iterator = arr[Symbol.iterator](), _step; !(_step = _iterator.next()).done; ) {\n _arr.push(_step.value);\n\n if (i && _arr.length === i) break;\n }\n\n return _arr;\n }\n\n function _nonIterableSpread() {\n throw new TypeError('Invalid attempt to spread non-iterable instance');\n }\n\n function _nonIterableRest() {\n throw new TypeError('Invalid attempt to destructure non-iterable instance');\n }\n\n function _skipFirstGeneratorNext(fn) {\n return function() {\n var it = fn.apply(this, arguments);\n it.next();\n return it;\n };\n }\n\n function _toPrimitive(input, hint) {\n if (typeof input !== 'object' || input === null) return input;\n var prim = input[Symbol.toPrimitive];\n\n if (prim !== undefined) {\n var res = prim.call(input, hint || 'default');\n if (typeof res !== 'object') return res;\n throw new TypeError('@@toPrimitive must return a primitive value.');\n }\n\n return (hint === 'string' ? String : Number)(input);\n }\n\n function _toPropertyKey(arg) {\n var key = _toPrimitive(arg, 'string');\n\n return typeof key === 'symbol' ? key : String(key);\n }\n\n function _initializerWarningHelper(descriptor, context) {\n throw new Error(\n 'Decorating class property failed. Please ensure that ' +\n 'proposal-class-properties is enabled and set to use loose mode. ' +\n 'To use proposal-class-properties in spec mode with decorators, wait for ' +\n 'the next major version of decorators in stage 2.'\n );\n }\n\n function _initializerDefineProperty(target, property, descriptor, context) {\n if (!descriptor) return;\n Object.defineProperty(target, property, {\n enumerable: descriptor.enumerable,\n configurable: descriptor.configurable,\n writable: descriptor.writable,\n value: descriptor.initializer ? descriptor.initializer.call(context) : void 0,\n });\n }\n\n function _applyDecoratedDescriptor(target, property, decorators, descriptor, context) {\n var desc = {};\n Object.keys(descriptor).forEach(function(key) {\n desc[key] = descriptor[key];\n });\n desc.enumerable = !!desc.enumerable;\n desc.configurable = !!desc.configurable;\n\n if ('value' in desc || desc.initializer) {\n desc.writable = true;\n }\n\n desc = decorators\n .slice()\n .reverse()\n .reduce(function(desc, decorator) {\n return decorator(target, property, desc) || desc;\n }, desc);\n\n if (context && desc.initializer !== void 0) {\n desc.value = desc.initializer ? desc.initializer.call(context) : void 0;\n desc.initializer = undefined;\n }\n\n if (desc.initializer === void 0) {\n Object.defineProperty(target, property, desc);\n desc = null;\n }\n\n return desc;\n }\n\n var id = 0;\n\n function _classPrivateFieldLooseKey(name) {\n return '__private_' + id++ + '_' + name;\n }\n\n function _classPrivateFieldLooseBase(receiver, privateKey) {\n if (!Object.prototype.hasOwnProperty.call(receiver, privateKey)) {\n throw new TypeError('attempted to use private field on non-instance');\n }\n\n return receiver;\n }\n\n function _classPrivateFieldGet(receiver, privateMap) {\n var descriptor = privateMap.get(receiver);\n\n if (!descriptor) {\n throw new TypeError('attempted to get private field on non-instance');\n }\n\n if (descriptor.get) {\n return descriptor.get.call(receiver);\n }\n\n return descriptor.value;\n }\n\n function _classPrivateFieldSet(receiver, privateMap, value) {\n var descriptor = privateMap.get(receiver);\n\n if (!descriptor) {\n throw new TypeError('attempted to set private field on non-instance');\n }\n\n if (descriptor.set) {\n descriptor.set.call(receiver, value);\n } else {\n if (!descriptor.writable) {\n throw new TypeError('attempted to set read only private field');\n }\n\n descriptor.value = value;\n }\n\n return value;\n }\n\n function _classPrivateFieldDestructureSet(receiver, privateMap) {\n if (!privateMap.has(receiver)) {\n throw new TypeError('attempted to set private field on non-instance');\n }\n\n var descriptor = privateMap.get(receiver);\n\n if (descriptor.set) {\n if (!('__destrObj' in descriptor)) {\n descriptor.__destrObj = {\n set value(v) {\n descriptor.set.call(receiver, v);\n },\n };\n }\n\n return descriptor.__destrObj;\n } else {\n if (!descriptor.writable) {\n throw new TypeError('attempted to set read only private field');\n }\n\n return descriptor;\n }\n }\n\n function _classStaticPrivateFieldSpecGet(receiver, classConstructor, descriptor) {\n if (receiver !== classConstructor) {\n throw new TypeError('Private static access of wrong provenance');\n }\n\n return descriptor.value;\n }\n\n function _classStaticPrivateFieldSpecSet(receiver, classConstructor, descriptor, value) {\n if (receiver !== classConstructor) {\n throw new TypeError('Private static access of wrong provenance');\n }\n\n if (!descriptor.writable) {\n throw new TypeError('attempted to set read only private field');\n }\n\n descriptor.value = value;\n return value;\n }\n\n function _classStaticPrivateMethodGet(receiver, classConstructor, method) {\n if (receiver !== classConstructor) {\n throw new TypeError('Private static access of wrong provenance');\n }\n\n return method;\n }\n\n function _classStaticPrivateMethodSet() {\n throw new TypeError('attempted to set read only static private field');\n }\n\n function _decorate(decorators, factory, superClass, mixins) {\n var api = _getDecoratorsApi();\n\n if (mixins) {\n for (var i = 0; i < mixins.length; i++) {\n api = mixins[i](api);\n }\n }\n\n var r = factory(function initialize(O) {\n api.initializeInstanceElements(O, decorated.elements);\n }, superClass);\n var decorated = api.decorateClass(\n _coalesceClassElements(r.d.map(_createElementDescriptor)),\n decorators\n );\n api.initializeClassElements(r.F, decorated.elements);\n return api.runClassFinishers(r.F, decorated.finishers);\n }\n\n function _getDecoratorsApi() {\n _getDecoratorsApi = function() {\n return api;\n };\n\n var api = {\n elementsDefinitionOrder: [['method'], ['field']],\n initializeInstanceElements: function(O, elements) {\n ['method', 'field'].forEach(function(kind) {\n elements.forEach(function(element) {\n if (element.kind === kind && element.placement === 'own') {\n this.defineClassElement(O, element);\n }\n }, this);\n }, this);\n },\n initializeClassElements: function(F, elements) {\n var proto = F.prototype;\n ['method', 'field'].forEach(function(kind) {\n elements.forEach(function(element) {\n var placement = element.placement;\n\n if (\n element.kind === kind &&\n (placement === 'static' || placement === 'prototype')\n ) {\n var receiver = placement === 'static' ? F : proto;\n this.defineClassElement(receiver, element);\n }\n }, this);\n }, this);\n },\n defineClassElement: function(receiver, element) {\n var descriptor = element.descriptor;\n\n if (element.kind === 'field') {\n var initializer = element.initializer;\n descriptor = {\n enumerable: descriptor.enumerable,\n writable: descriptor.writable,\n configurable: descriptor.configurable,\n value: initializer === void 0 ? void 0 : initializer.call(receiver),\n };\n }\n\n Object.defineProperty(receiver, element.key, descriptor);\n },\n decorateClass: function(elements, decorators) {\n var newElements = [];\n var finishers = [];\n var placements = {\n static: [],\n prototype: [],\n own: [],\n };\n elements.forEach(function(element) {\n this.addElementPlacement(element, placements);\n }, this);\n elements.forEach(function(element) {\n if (!_hasDecorators(element)) return newElements.push(element);\n var elementFinishersExtras = this.decorateElement(element, placements);\n newElements.push(elementFinishersExtras.element);\n newElements.push.apply(newElements, elementFinishersExtras.extras);\n finishers.push.apply(finishers, elementFinishersExtras.finishers);\n }, this);\n\n if (!decorators) {\n return {\n elements: newElements,\n finishers: finishers,\n };\n }\n\n var result = this.decorateConstructor(newElements, decorators);\n finishers.push.apply(finishers, result.finishers);\n result.finishers = finishers;\n return result;\n },\n addElementPlacement: function(element, placements, silent) {\n var keys = placements[element.placement];\n\n if (!silent && keys.indexOf(element.key) !== -1) {\n throw new TypeError('Duplicated element (' + element.key + ')');\n }\n\n keys.push(element.key);\n },\n decorateElement: function(element, placements) {\n var extras = [];\n var finishers = [];\n\n for (var decorators = element.decorators, i = decorators.length - 1; i >= 0; i--) {\n var keys = placements[element.placement];\n keys.splice(keys.indexOf(element.key), 1);\n var elementObject = this.fromElementDescriptor(element);\n var elementFinisherExtras = this.toElementFinisherExtras(\n (0, decorators[i])(elementObject) || elementObject\n );\n element = elementFinisherExtras.element;\n this.addElementPlacement(element, placements);\n\n if (elementFinisherExtras.finisher) {\n finishers.push(elementFinisherExtras.finisher);\n }\n\n var newExtras = elementFinisherExtras.extras;\n\n if (newExtras) {\n for (var j = 0; j < newExtras.length; j++) {\n this.addElementPlacement(newExtras[j], placements);\n }\n\n extras.push.apply(extras, newExtras);\n }\n }\n\n return {\n element: element,\n finishers: finishers,\n extras: extras,\n };\n },\n decorateConstructor: function(elements, decorators) {\n var finishers = [];\n\n for (var i = decorators.length - 1; i >= 0; i--) {\n var obj = this.fromClassDescriptor(elements);\n var elementsAndFinisher = this.toClassDescriptor(\n (0, decorators[i])(obj) || obj\n );\n\n if (elementsAndFinisher.finisher !== undefined) {\n finishers.push(elementsAndFinisher.finisher);\n }\n\n if (elementsAndFinisher.elements !== undefined) {\n elements = elementsAndFinisher.elements;\n\n for (var j = 0; j < elements.length - 1; j++) {\n for (var k = j + 1; k < elements.length; k++) {\n if (\n elements[j].key === elements[k].key &&\n elements[j].placement === elements[k].placement\n ) {\n throw new TypeError(\n 'Duplicated element (' + elements[j].key + ')'\n );\n }\n }\n }\n }\n }\n\n return {\n elements: elements,\n finishers: finishers,\n };\n },\n fromElementDescriptor: function(element) {\n var obj = {\n kind: element.kind,\n key: element.key,\n placement: element.placement,\n descriptor: element.descriptor,\n };\n var desc = {\n value: 'Descriptor',\n configurable: true,\n };\n Object.defineProperty(obj, Symbol.toStringTag, desc);\n if (element.kind === 'field') obj.initializer = element.initializer;\n return obj;\n },\n toElementDescriptors: function(elementObjects) {\n if (elementObjects === undefined) return;\n return _toArray(elementObjects).map(function(elementObject) {\n var element = this.toElementDescriptor(elementObject);\n this.disallowProperty(elementObject, 'finisher', 'An element descriptor');\n this.disallowProperty(elementObject, 'extras', 'An element descriptor');\n return element;\n }, this);\n },\n toElementDescriptor: function(elementObject) {\n var kind = String(elementObject.kind);\n\n if (kind !== 'method' && kind !== 'field') {\n throw new TypeError(\n 'An element descriptor\\'s .kind property must be either \"method\" or' +\n ' \"field\", but a decorator created an element descriptor with' +\n ' .kind \"' +\n kind +\n '\"'\n );\n }\n\n var key = _toPropertyKey(elementObject.key);\n\n var placement = String(elementObject.placement);\n\n if (placement !== 'static' && placement !== 'prototype' && placement !== 'own') {\n throw new TypeError(\n 'An element descriptor\\'s .placement property must be one of \"static\",' +\n ' \"prototype\" or \"own\", but a decorator created an element descriptor' +\n ' with .placement \"' +\n placement +\n '\"'\n );\n }\n\n var descriptor = elementObject.descriptor;\n this.disallowProperty(elementObject, 'elements', 'An element descriptor');\n var element = {\n kind: kind,\n key: key,\n placement: placement,\n descriptor: Object.assign({}, descriptor),\n };\n\n if (kind !== 'field') {\n this.disallowProperty(elementObject, 'initializer', 'A method descriptor');\n } else {\n this.disallowProperty(\n descriptor,\n 'get',\n 'The property descriptor of a field descriptor'\n );\n this.disallowProperty(\n descriptor,\n 'set',\n 'The property descriptor of a field descriptor'\n );\n this.disallowProperty(\n descriptor,\n 'value',\n 'The property descriptor of a field descriptor'\n );\n element.initializer = elementObject.initializer;\n }\n\n return element;\n },\n toElementFinisherExtras: function(elementObject) {\n var element = this.toElementDescriptor(elementObject);\n\n var finisher = _optionalCallableProperty(elementObject, 'finisher');\n\n var extras = this.toElementDescriptors(elementObject.extras);\n return {\n element: element,\n finisher: finisher,\n extras: extras,\n };\n },\n fromClassDescriptor: function(elements) {\n var obj = {\n kind: 'class',\n elements: elements.map(this.fromElementDescriptor, this),\n };\n var desc = {\n value: 'Descriptor',\n configurable: true,\n };\n Object.defineProperty(obj, Symbol.toStringTag, desc);\n return obj;\n },\n toClassDescriptor: function(obj) {\n var kind = String(obj.kind);\n\n if (kind !== 'class') {\n throw new TypeError(\n 'A class descriptor\\'s .kind property must be \"class\", but a decorator' +\n ' created a class descriptor with .kind \"' +\n kind +\n '\"'\n );\n }\n\n this.disallowProperty(obj, 'key', 'A class descriptor');\n this.disallowProperty(obj, 'placement', 'A class descriptor');\n this.disallowProperty(obj, 'descriptor', 'A class descriptor');\n this.disallowProperty(obj, 'initializer', 'A class descriptor');\n this.disallowProperty(obj, 'extras', 'A class descriptor');\n\n var finisher = _optionalCallableProperty(obj, 'finisher');\n\n var elements = this.toElementDescriptors(obj.elements);\n return {\n elements: elements,\n finisher: finisher,\n };\n },\n runClassFinishers: function(constructor, finishers) {\n for (var i = 0; i < finishers.length; i++) {\n var newConstructor = (0, finishers[i])(constructor);\n\n if (newConstructor !== undefined) {\n if (typeof newConstructor !== 'function') {\n throw new TypeError('Finishers must return a constructor.');\n }\n\n constructor = newConstructor;\n }\n }\n\n return constructor;\n },\n disallowProperty: function(obj, name, objectType) {\n if (obj[name] !== undefined) {\n throw new TypeError(objectType + \" can't have a .\" + name + ' property.');\n }\n },\n };\n return api;\n }\n\n function _createElementDescriptor(def) {\n var key = _toPropertyKey(def.key);\n\n var descriptor;\n\n if (def.kind === 'method') {\n descriptor = {\n value: def.value,\n writable: true,\n configurable: true,\n enumerable: false,\n };\n } else if (def.kind === 'get') {\n descriptor = {\n get: def.value,\n configurable: true,\n enumerable: false,\n };\n } else if (def.kind === 'set') {\n descriptor = {\n set: def.value,\n configurable: true,\n enumerable: false,\n };\n } else if (def.kind === 'field') {\n descriptor = {\n configurable: true,\n writable: true,\n enumerable: true,\n };\n }\n\n var element = {\n kind: def.kind === 'field' ? 'field' : 'method',\n key: key,\n placement: def.static ? 'static' : def.kind === 'field' ? 'own' : 'prototype',\n descriptor: descriptor,\n };\n if (def.decorators) element.decorators = def.decorators;\n if (def.kind === 'field') element.initializer = def.value;\n return element;\n }\n\n function _coalesceGetterSetter(element, other) {\n if (element.descriptor.get !== undefined) {\n other.descriptor.get = element.descriptor.get;\n } else {\n other.descriptor.set = element.descriptor.set;\n }\n }\n\n function _coalesceClassElements(elements) {\n var newElements = [];\n\n var isSameElement = function(other) {\n return (\n other.kind === 'method' &&\n other.key === element.key &&\n other.placement === element.placement\n );\n };\n\n for (var i = 0; i < elements.length; i++) {\n var element = elements[i];\n var other;\n\n if (element.kind === 'method' && (other = newElements.find(isSameElement))) {\n if (_isDataDescriptor(element.descriptor) || _isDataDescriptor(other.descriptor)) {\n if (_hasDecorators(element) || _hasDecorators(other)) {\n throw new ReferenceError(\n 'Duplicated methods (' + element.key + \") can't be decorated.\"\n );\n }\n\n other.descriptor = element.descriptor;\n } else {\n if (_hasDecorators(element)) {\n if (_hasDecorators(other)) {\n throw new ReferenceError(\n \"Decorators can't be placed on different accessors with for \" +\n 'the same property (' +\n element.key +\n ').'\n );\n }\n\n other.decorators = element.decorators;\n }\n\n _coalesceGetterSetter(element, other);\n }\n } else {\n newElements.push(element);\n }\n }\n\n return newElements;\n }\n\n function _hasDecorators(element) {\n return element.decorators && element.decorators.length;\n }\n\n function _isDataDescriptor(desc) {\n return desc !== undefined && !(desc.value === undefined && desc.writable === undefined);\n }\n\n function _optionalCallableProperty(obj, name) {\n var value = obj[name];\n\n if (value !== undefined && typeof value !== 'function') {\n throw new TypeError(\"Expected '\" + name + \"' to be a function\");\n }\n\n return value;\n }\n\n function _classPrivateMethodGet(receiver, privateSet, fn) {\n if (!privateSet.has(receiver)) {\n throw new TypeError('attempted to get private field on non-instance');\n }\n\n return fn;\n }\n\n function _classPrivateMethodSet() {\n throw new TypeError('attempted to reassign private method');\n }\n\n function _wrapRegExp(re, groups) {\n _wrapRegExp = function(re, groups) {\n return new BabelRegExp(re, groups);\n };\n\n var _RegExp = _wrapNativeSuper(RegExp);\n\n var _super = RegExp.prototype;\n\n var _groups = new WeakMap();\n\n function BabelRegExp(re, groups) {\n var _this = _RegExp.call(this, re);\n\n _groups.set(_this, groups);\n\n return _this;\n }\n\n _inherits(BabelRegExp, _RegExp);\n\n BabelRegExp.prototype.exec = function(str) {\n var result = _super.exec.call(this, str);\n\n if (result) result.groups = buildGroups(result, this);\n return result;\n };\n\n BabelRegExp.prototype[Symbol.replace] = function(str, substitution) {\n if (typeof substitution === 'string') {\n var groups = _groups.get(this);\n\n return _super[Symbol.replace].call(\n this,\n str,\n substitution.replace(/\\$<([^>]+)>/g, function(_, name) {\n return '$' + groups[name];\n })\n );\n } else if (typeof substitution === 'function') {\n var _this = this;\n\n return _super[Symbol.replace].call(this, str, function() {\n var args = [];\n args.push.apply(args, arguments);\n\n if (typeof args[args.length - 1] !== 'object') {\n args.push(buildGroups(args, _this));\n }\n\n return substitution.apply(this, args);\n });\n } else {\n return _super[Symbol.replace].call(this, str, substitution);\n }\n };\n\n function buildGroups(result, re) {\n var g = _groups.get(re);\n\n return Object.keys(g).reduce(function(groups, name) {\n groups[name] = result[g[name]];\n return groups;\n }, Object.create(null));\n }\n\n return _wrapRegExp.apply(this, arguments);\n }\n\n var arrayRemove = function arrayRemove(arr, index) {\n return arr.splice(index, 1);\n };\n\n var run = function run(cb, sync) {\n if (sync) {\n cb();\n } else if (document.hidden) {\n Promise.resolve(1).then(cb);\n } else {\n setTimeout(cb, 0);\n }\n };\n\n var on = function on() {\n var listeners = [];\n var off = function off(event, cb) {\n arrayRemove(\n listeners,\n listeners.findIndex(function(listener) {\n return listener.event === event && (listener.cb === cb || !cb);\n })\n );\n };\n var _fire = function fire(event, args, sync) {\n listeners\n .filter(function(listener) {\n return listener.event === event;\n })\n .map(function(listener) {\n return listener.cb;\n })\n .forEach(function(cb) {\n return run(function() {\n return cb.apply(void 0, _toConsumableArray(args));\n }, sync);\n });\n };\n return {\n fireSync: function fireSync(event) {\n for (\n var _len = arguments.length,\n args = new Array(_len > 1 ? _len - 1 : 0),\n _key = 1;\n _key < _len;\n _key++\n ) {\n args[_key - 1] = arguments[_key];\n }\n _fire(event, args, true);\n },\n fire: function fire(event) {\n for (\n var _len2 = arguments.length,\n args = new Array(_len2 > 1 ? _len2 - 1 : 0),\n _key2 = 1;\n _key2 < _len2;\n _key2++\n ) {\n args[_key2 - 1] = arguments[_key2];\n }\n _fire(event, args, false);\n },\n on: function on(event, cb) {\n listeners.push({ event: event, cb: cb });\n },\n onOnce: function onOnce(event, _cb) {\n listeners.push({\n event: event,\n cb: function cb() {\n off(event, _cb);\n _cb.apply(void 0, arguments);\n },\n });\n },\n off: off,\n };\n };\n\n var copyObjectPropertiesToObject = function copyObjectPropertiesToObject(\n src,\n target,\n excluded\n ) {\n Object.getOwnPropertyNames(src)\n .filter(function(property) {\n return !excluded.includes(property);\n })\n .forEach(function(key) {\n return Object.defineProperty(\n target,\n key,\n Object.getOwnPropertyDescriptor(src, key)\n );\n });\n };\n\n var PRIVATE = [\n 'fire',\n 'process',\n 'revert',\n 'load',\n 'on',\n 'off',\n 'onOnce',\n 'retryLoad',\n 'extend',\n 'archive',\n 'archived',\n 'release',\n 'released',\n 'requestProcessing',\n 'freeze',\n ];\n\n var createItemAPI = function createItemAPI(item) {\n var api = {};\n copyObjectPropertiesToObject(item, api, PRIVATE);\n return api;\n };\n\n var removeReleasedItems = function removeReleasedItems(items) {\n items.forEach(function(item, index) {\n if (item.released) {\n arrayRemove(items, index);\n }\n });\n };\n\n var ItemStatus = {\n INIT: 1,\n IDLE: 2,\n PROCESSING_QUEUED: 9,\n PROCESSING: 3,\n PROCESSING_COMPLETE: 5,\n PROCESSING_ERROR: 6,\n PROCESSING_REVERT_ERROR: 10,\n LOADING: 7,\n LOAD_ERROR: 8,\n };\n\n var FileOrigin = {\n INPUT: 1,\n LIMBO: 2,\n LOCAL: 3,\n };\n\n var getNonNumeric = function getNonNumeric(str) {\n return /[^0-9]+/.exec(str);\n };\n\n var getDecimalSeparator = function getDecimalSeparator() {\n return getNonNumeric((1.1).toLocaleString())[0];\n };\n\n var getThousandsSeparator = function getThousandsSeparator() {\n // Added for browsers that do not return the thousands separator (happend on native browser Android 4.4.4)\n // We check against the normal toString output and if they're the same return a comma when decimal separator is a dot\n var decimalSeparator = getDecimalSeparator();\n var thousandsStringWithSeparator = (1000.0).toLocaleString();\n var thousandsStringWithoutSeparator = (1000.0).toString();\n if (thousandsStringWithSeparator !== thousandsStringWithoutSeparator) {\n return getNonNumeric(thousandsStringWithSeparator)[0];\n }\n return decimalSeparator === '.' ? ',' : '.';\n };\n\n var Type = {\n BOOLEAN: 'boolean',\n INT: 'int',\n NUMBER: 'number',\n STRING: 'string',\n ARRAY: 'array',\n OBJECT: 'object',\n FUNCTION: 'function',\n ACTION: 'action',\n SERVER_API: 'serverapi',\n REGEX: 'regex',\n };\n\n // all registered filters\n var filters = [];\n\n // loops over matching filters and passes options to each filter, returning the mapped results\n var applyFilterChain = function applyFilterChain(key, value, utils) {\n return new Promise(function(resolve, reject) {\n // find matching filters for this key\n var matchingFilters = filters\n .filter(function(f) {\n return f.key === key;\n })\n .map(function(f) {\n return f.cb;\n });\n\n // resolve now\n if (matchingFilters.length === 0) {\n resolve(value);\n return;\n }\n\n // first filter to kick things of\n var initialFilter = matchingFilters.shift();\n\n // chain filters\n matchingFilters\n .reduce(\n // loop over promises passing value to next promise\n function(current, next) {\n return current.then(function(value) {\n return next(value, utils);\n });\n },\n\n // call initial filter, will return a promise\n initialFilter(value, utils)\n\n // all executed\n )\n .then(function(value) {\n return resolve(value);\n })\n .catch(function(error) {\n return reject(error);\n });\n });\n };\n\n var applyFilters = function applyFilters(key, value, utils) {\n return filters\n .filter(function(f) {\n return f.key === key;\n })\n .map(function(f) {\n return f.cb(value, utils);\n });\n };\n\n // adds a new filter to the list\n var addFilter = function addFilter(key, cb) {\n return filters.push({ key: key, cb: cb });\n };\n\n var extendDefaultOptions = function extendDefaultOptions(additionalOptions) {\n return Object.assign(defaultOptions, additionalOptions);\n };\n\n var getOptions = function getOptions() {\n return Object.assign({}, defaultOptions);\n };\n\n var setOptions = function setOptions(opts) {\n forin(opts, function(key, value) {\n // key does not exist, so this option cannot be set\n if (!defaultOptions[key]) {\n return;\n }\n defaultOptions[key][0] = getValueByType(\n value,\n defaultOptions[key][0],\n defaultOptions[key][1]\n );\n });\n };\n\n // default options on app\n var defaultOptions = {\n // the id to add to the root element\n id: [null, Type.STRING],\n\n // input field name to use\n name: ['filepond', Type.STRING],\n\n // disable the field\n disabled: [false, Type.BOOLEAN],\n\n // classname to put on wrapper\n className: [null, Type.STRING],\n\n // is the field required\n required: [false, Type.BOOLEAN],\n\n // Allow media capture when value is set\n captureMethod: [null, Type.STRING],\n // - \"camera\", \"microphone\" or \"camcorder\",\n // - Does not work with multiple on apple devices\n // - If set, acceptedFileTypes must be made to match with media wildcard \"image/*\", \"audio/*\" or \"video/*\"\n\n // sync `acceptedFileTypes` property with `accept` attribute\n allowSyncAcceptAttribute: [true, Type.BOOLEAN],\n\n // Feature toggles\n allowDrop: [true, Type.BOOLEAN], // Allow dropping of files\n allowBrowse: [true, Type.BOOLEAN], // Allow browsing the file system\n allowPaste: [true, Type.BOOLEAN], // Allow pasting files\n allowMultiple: [false, Type.BOOLEAN], // Allow multiple files (disabled by default, as multiple attribute is also required on input to allow multiple)\n allowReplace: [true, Type.BOOLEAN], // Allow dropping a file on other file to replace it (only works when multiple is set to false)\n allowRevert: [true, Type.BOOLEAN], // Allows user to revert file upload\n allowRemove: [true, Type.BOOLEAN], // Allow user to remove a file\n allowProcess: [true, Type.BOOLEAN], // Allows user to process a file, when set to false, this removes the file upload button\n allowReorder: [false, Type.BOOLEAN], // Allow reordering of files\n allowDirectoriesOnly: [false, Type.BOOLEAN], // Allow only selecting directories with browse (no support for filtering dnd at this point)\n\n // Try store file if `server` not set\n storeAsFile: [false, Type.BOOLEAN],\n\n // Revert mode\n forceRevert: [false, Type.BOOLEAN], // Set to 'force' to require the file to be reverted before removal\n\n // Input requirements\n maxFiles: [null, Type.INT], // Max number of files\n checkValidity: [false, Type.BOOLEAN], // Enables custom validity messages\n\n // Where to put file\n itemInsertLocationFreedom: [true, Type.BOOLEAN], // Set to false to always add items to begin or end of list\n itemInsertLocation: ['before', Type.STRING], // Default index in list to add items that have been dropped at the top of the list\n itemInsertInterval: [75, Type.INT],\n\n // Drag 'n Drop related\n dropOnPage: [false, Type.BOOLEAN], // Allow dropping of files anywhere on page (prevents browser from opening file if dropped outside of Up)\n dropOnElement: [true, Type.BOOLEAN], // Drop needs to happen on element (set to false to also load drops outside of Up)\n dropValidation: [false, Type.BOOLEAN], // Enable or disable validating files on drop\n ignoredFiles: [['.ds_store', 'thumbs.db', 'desktop.ini'], Type.ARRAY],\n\n // Upload related\n instantUpload: [true, Type.BOOLEAN], // Should upload files immediately on drop\n maxParallelUploads: [2, Type.INT], // Maximum files to upload in parallel\n allowMinimumUploadDuration: [true, Type.BOOLEAN], // if true uploads take at least 750 ms, this ensures the user sees the upload progress giving trust the upload actually happened\n\n // Chunks\n chunkUploads: [false, Type.BOOLEAN], // Enable chunked uploads\n chunkForce: [false, Type.BOOLEAN], // Force use of chunk uploads even for files smaller than chunk size\n chunkSize: [5000000, Type.INT], // Size of chunks (5MB default)\n chunkRetryDelays: [[500, 1000, 3000], Type.ARRAY], // Amount of times to retry upload of a chunk when it fails\n\n // The server api end points to use for uploading (see docs)\n server: [null, Type.SERVER_API],\n\n // File size calculations, can set to 1024, this is only used for display, properties use file size base 1000\n fileSizeBase: [1000, Type.INT],\n\n // Labels and status messages\n labelFileSizeBytes: ['bytes', Type.STRING],\n labelFileSizeKilobytes: ['KB', Type.STRING],\n labelFileSizeMegabytes: ['MB', Type.STRING],\n labelFileSizeGigabytes: ['GB', Type.STRING],\n\n labelDecimalSeparator: [getDecimalSeparator(), Type.STRING], // Default is locale separator\n labelThousandsSeparator: [getThousandsSeparator(), Type.STRING], // Default is locale separator\n\n labelIdle: [\n 'Drag & Drop your files or Browse',\n Type.STRING,\n ],\n\n labelInvalidField: ['Field contains invalid files', Type.STRING],\n labelFileWaitingForSize: ['Waiting for size', Type.STRING],\n labelFileSizeNotAvailable: ['Size not available', Type.STRING],\n labelFileCountSingular: ['file in list', Type.STRING],\n labelFileCountPlural: ['files in list', Type.STRING],\n labelFileLoading: ['Loading', Type.STRING],\n labelFileAdded: ['Added', Type.STRING], // assistive only\n labelFileLoadError: ['Error during load', Type.STRING],\n labelFileRemoved: ['Removed', Type.STRING], // assistive only\n labelFileRemoveError: ['Error during remove', Type.STRING],\n labelFileProcessing: ['Uploading', Type.STRING],\n labelFileProcessingComplete: ['Upload complete', Type.STRING],\n labelFileProcessingAborted: ['Upload cancelled', Type.STRING],\n labelFileProcessingError: ['Error during upload', Type.STRING],\n labelFileProcessingRevertError: ['Error during revert', Type.STRING],\n\n labelTapToCancel: ['tap to cancel', Type.STRING],\n labelTapToRetry: ['tap to retry', Type.STRING],\n labelTapToUndo: ['tap to undo', Type.STRING],\n\n labelButtonRemoveItem: ['Remove', Type.STRING],\n labelButtonAbortItemLoad: ['Abort', Type.STRING],\n labelButtonRetryItemLoad: ['Retry', Type.STRING],\n labelButtonAbortItemProcessing: ['Cancel', Type.STRING],\n labelButtonUndoItemProcessing: ['Undo', Type.STRING],\n labelButtonRetryItemProcessing: ['Retry', Type.STRING],\n labelButtonProcessItem: ['Upload', Type.STRING],\n\n // make sure width and height plus viewpox are even numbers so icons are nicely centered\n iconRemove: [\n '',\n Type.STRING,\n ],\n\n iconProcess: [\n '',\n Type.STRING,\n ],\n\n iconRetry: [\n '',\n Type.STRING,\n ],\n\n iconUndo: [\n '',\n Type.STRING,\n ],\n\n iconDone: [\n '',\n Type.STRING,\n ],\n\n // event handlers\n oninit: [null, Type.FUNCTION],\n onwarning: [null, Type.FUNCTION],\n onerror: [null, Type.FUNCTION],\n onactivatefile: [null, Type.FUNCTION],\n oninitfile: [null, Type.FUNCTION],\n onaddfilestart: [null, Type.FUNCTION],\n onaddfileprogress: [null, Type.FUNCTION],\n onaddfile: [null, Type.FUNCTION],\n onprocessfilestart: [null, Type.FUNCTION],\n onprocessfileprogress: [null, Type.FUNCTION],\n onprocessfileabort: [null, Type.FUNCTION],\n onprocessfilerevert: [null, Type.FUNCTION],\n onprocessfile: [null, Type.FUNCTION],\n onprocessfiles: [null, Type.FUNCTION],\n onremovefile: [null, Type.FUNCTION],\n onpreparefile: [null, Type.FUNCTION],\n onupdatefiles: [null, Type.FUNCTION],\n onreorderfiles: [null, Type.FUNCTION],\n\n // hooks\n beforeDropFile: [null, Type.FUNCTION],\n beforeAddFile: [null, Type.FUNCTION],\n beforeRemoveFile: [null, Type.FUNCTION],\n beforePrepareFile: [null, Type.FUNCTION],\n\n // styles\n stylePanelLayout: [null, Type.STRING], // null 'integrated', 'compact', 'circle'\n stylePanelAspectRatio: [null, Type.STRING], // null or '3:2' or 1\n styleItemPanelAspectRatio: [null, Type.STRING],\n styleButtonRemoveItemPosition: ['left', Type.STRING],\n styleButtonProcessItemPosition: ['right', Type.STRING],\n styleLoadIndicatorPosition: ['right', Type.STRING],\n styleProgressIndicatorPosition: ['right', Type.STRING],\n styleButtonRemoveItemAlign: [false, Type.BOOLEAN],\n\n // custom initial files array\n files: [[], Type.ARRAY],\n\n // show support by displaying credits\n credits: [['https://pqina.nl/', 'Powered by PQINA'], Type.ARRAY],\n };\n\n var getItemByQuery = function getItemByQuery(items, query) {\n // just return first index\n if (isEmpty(query)) {\n return items[0] || null;\n }\n\n // query is index\n if (isInt(query)) {\n return items[query] || null;\n }\n\n // if query is item, get the id\n if (typeof query === 'object') {\n query = query.id;\n }\n\n // assume query is a string and return item by id\n return (\n items.find(function(item) {\n return item.id === query;\n }) || null\n );\n };\n\n var getNumericAspectRatioFromString = function getNumericAspectRatioFromString(aspectRatio) {\n if (isEmpty(aspectRatio)) {\n return aspectRatio;\n }\n if (/:/.test(aspectRatio)) {\n var parts = aspectRatio.split(':');\n return parts[1] / parts[0];\n }\n return parseFloat(aspectRatio);\n };\n\n var getActiveItems = function getActiveItems(items) {\n return items.filter(function(item) {\n return !item.archived;\n });\n };\n\n var Status = {\n EMPTY: 0,\n IDLE: 1, // waiting\n ERROR: 2, // a file is in error state\n BUSY: 3, // busy processing or loading\n READY: 4, // all files uploaded\n };\n\n var res = null;\n var canUpdateFileInput = function canUpdateFileInput() {\n if (res === null) {\n try {\n var dataTransfer = new DataTransfer();\n dataTransfer.items.add(new File(['hello world'], 'This_Works.txt'));\n var el = document.createElement('input');\n el.setAttribute('type', 'file');\n el.files = dataTransfer.files;\n res = el.files.length === 1;\n } catch (err) {\n res = false;\n }\n }\n return res;\n };\n\n var ITEM_ERROR = [\n ItemStatus.LOAD_ERROR,\n ItemStatus.PROCESSING_ERROR,\n ItemStatus.PROCESSING_REVERT_ERROR,\n ];\n\n var ITEM_BUSY = [\n ItemStatus.LOADING,\n ItemStatus.PROCESSING,\n ItemStatus.PROCESSING_QUEUED,\n ItemStatus.INIT,\n ];\n\n var ITEM_READY = [ItemStatus.PROCESSING_COMPLETE];\n\n var isItemInErrorState = function isItemInErrorState(item) {\n return ITEM_ERROR.includes(item.status);\n };\n var isItemInBusyState = function isItemInBusyState(item) {\n return ITEM_BUSY.includes(item.status);\n };\n var isItemInReadyState = function isItemInReadyState(item) {\n return ITEM_READY.includes(item.status);\n };\n\n var isAsync = function isAsync(state) {\n return (\n isObject(state.options.server) &&\n (isObject(state.options.server.process) || isFunction(state.options.server.process))\n );\n };\n\n var queries = function queries(state) {\n return {\n GET_STATUS: function GET_STATUS() {\n var items = getActiveItems(state.items);\n var EMPTY = Status.EMPTY,\n ERROR = Status.ERROR,\n BUSY = Status.BUSY,\n IDLE = Status.IDLE,\n READY = Status.READY;\n\n if (items.length === 0) return EMPTY;\n\n if (items.some(isItemInErrorState)) return ERROR;\n\n if (items.some(isItemInBusyState)) return BUSY;\n\n if (items.some(isItemInReadyState)) return READY;\n\n return IDLE;\n },\n\n GET_ITEM: function GET_ITEM(query) {\n return getItemByQuery(state.items, query);\n },\n\n GET_ACTIVE_ITEM: function GET_ACTIVE_ITEM(query) {\n return getItemByQuery(getActiveItems(state.items), query);\n },\n\n GET_ACTIVE_ITEMS: function GET_ACTIVE_ITEMS() {\n return getActiveItems(state.items);\n },\n\n GET_ITEMS: function GET_ITEMS() {\n return state.items;\n },\n\n GET_ITEM_NAME: function GET_ITEM_NAME(query) {\n var item = getItemByQuery(state.items, query);\n return item ? item.filename : null;\n },\n\n GET_ITEM_SIZE: function GET_ITEM_SIZE(query) {\n var item = getItemByQuery(state.items, query);\n return item ? item.fileSize : null;\n },\n\n GET_STYLES: function GET_STYLES() {\n return Object.keys(state.options)\n .filter(function(key) {\n return /^style/.test(key);\n })\n .map(function(option) {\n return {\n name: option,\n value: state.options[option],\n };\n });\n },\n\n GET_PANEL_ASPECT_RATIO: function GET_PANEL_ASPECT_RATIO() {\n var isShapeCircle = /circle/.test(state.options.stylePanelLayout);\n var aspectRatio = isShapeCircle\n ? 1\n : getNumericAspectRatioFromString(state.options.stylePanelAspectRatio);\n return aspectRatio;\n },\n\n GET_ITEM_PANEL_ASPECT_RATIO: function GET_ITEM_PANEL_ASPECT_RATIO() {\n return state.options.styleItemPanelAspectRatio;\n },\n\n GET_ITEMS_BY_STATUS: function GET_ITEMS_BY_STATUS(status) {\n return getActiveItems(state.items).filter(function(item) {\n return item.status === status;\n });\n },\n\n GET_TOTAL_ITEMS: function GET_TOTAL_ITEMS() {\n return getActiveItems(state.items).length;\n },\n\n SHOULD_UPDATE_FILE_INPUT: function SHOULD_UPDATE_FILE_INPUT() {\n return state.options.storeAsFile && canUpdateFileInput() && !isAsync(state);\n },\n\n IS_ASYNC: function IS_ASYNC() {\n return isAsync(state);\n },\n\n GET_FILE_SIZE_LABELS: function GET_FILE_SIZE_LABELS(query) {\n return {\n labelBytes: query('GET_LABEL_FILE_SIZE_BYTES') || undefined,\n labelKilobytes: query('GET_LABEL_FILE_SIZE_KILOBYTES') || undefined,\n labelMegabytes: query('GET_LABEL_FILE_SIZE_MEGABYTES') || undefined,\n labelGigabytes: query('GET_LABEL_FILE_SIZE_GIGABYTES') || undefined,\n };\n },\n };\n };\n\n var hasRoomForItem = function hasRoomForItem(state) {\n var count = getActiveItems(state.items).length;\n\n // if cannot have multiple items, to add one item it should currently not contain items\n if (!state.options.allowMultiple) {\n return count === 0;\n }\n\n // if allows multiple items, we check if a max item count has been set, if not, there's no limit\n var maxFileCount = state.options.maxFiles;\n if (maxFileCount === null) {\n return true;\n }\n\n // we check if the current count is smaller than the max count, if so, another file can still be added\n if (count < maxFileCount) {\n return true;\n }\n\n // no more room for another file\n return false;\n };\n\n var limit = function limit(value, min, max) {\n return Math.max(Math.min(max, value), min);\n };\n\n var arrayInsert = function arrayInsert(arr, index, item) {\n return arr.splice(index, 0, item);\n };\n\n var insertItem = function insertItem(items, item, index) {\n if (isEmpty(item)) {\n return null;\n }\n\n // if index is undefined, append\n if (typeof index === 'undefined') {\n items.push(item);\n return item;\n }\n\n // limit the index to the size of the items array\n index = limit(index, 0, items.length);\n\n // add item to array\n arrayInsert(items, index, item);\n\n // expose\n return item;\n };\n\n var isBase64DataURI = function isBase64DataURI(str) {\n return /^\\s*data:([a-z]+\\/[a-z0-9-+.]+(;[a-z-]+=[a-z0-9-]+)?)?(;base64)?,([a-z0-9!$&',()*+;=\\-._~:@\\/?%\\s]*)\\s*$/i.test(\n str\n );\n };\n\n var getFilenameFromURL = function getFilenameFromURL(url) {\n return ('' + url)\n .split('/')\n .pop()\n .split('?')\n .shift();\n };\n\n var getExtensionFromFilename = function getExtensionFromFilename(name) {\n return name.split('.').pop();\n };\n\n var guesstimateExtension = function guesstimateExtension(type) {\n // if no extension supplied, exit here\n if (typeof type !== 'string') {\n return '';\n }\n\n // get subtype\n var subtype = type.split('/').pop();\n\n // is svg subtype\n if (/svg/.test(subtype)) {\n return 'svg';\n }\n\n if (/zip|compressed/.test(subtype)) {\n return 'zip';\n }\n\n if (/plain/.test(subtype)) {\n return 'txt';\n }\n\n if (/msword/.test(subtype)) {\n return 'doc';\n }\n\n // if is valid subtype\n if (/[a-z]+/.test(subtype)) {\n // always use jpg extension\n if (subtype === 'jpeg') {\n return 'jpg';\n }\n\n // return subtype\n return subtype;\n }\n\n return '';\n };\n\n var leftPad = function leftPad(value) {\n var padding = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : '';\n return (padding + value).slice(-padding.length);\n };\n\n var getDateString = function getDateString() {\n var date = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : new Date();\n return (\n date.getFullYear() +\n '-' +\n leftPad(date.getMonth() + 1, '00') +\n '-' +\n leftPad(date.getDate(), '00') +\n '_' +\n leftPad(date.getHours(), '00') +\n '-' +\n leftPad(date.getMinutes(), '00') +\n '-' +\n leftPad(date.getSeconds(), '00')\n );\n };\n\n var getFileFromBlob = function getFileFromBlob(blob, filename) {\n var type = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null;\n var extension = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : null;\n var file =\n typeof type === 'string'\n ? blob.slice(0, blob.size, type)\n : blob.slice(0, blob.size, blob.type);\n file.lastModifiedDate = new Date();\n\n // copy relative path\n if (blob._relativePath) file._relativePath = blob._relativePath;\n\n // if blob has name property, use as filename if no filename supplied\n if (!isString(filename)) {\n filename = getDateString();\n }\n\n // if filename supplied but no extension and filename has extension\n if (filename && extension === null && getExtensionFromFilename(filename)) {\n file.name = filename;\n } else {\n extension = extension || guesstimateExtension(file.type);\n file.name = filename + (extension ? '.' + extension : '');\n }\n\n return file;\n };\n\n var getBlobBuilder = function getBlobBuilder() {\n return (window.BlobBuilder =\n window.BlobBuilder ||\n window.WebKitBlobBuilder ||\n window.MozBlobBuilder ||\n window.MSBlobBuilder);\n };\n\n var createBlob = function createBlob(arrayBuffer, mimeType) {\n var BB = getBlobBuilder();\n\n if (BB) {\n var bb = new BB();\n bb.append(arrayBuffer);\n return bb.getBlob(mimeType);\n }\n\n return new Blob([arrayBuffer], {\n type: mimeType,\n });\n };\n\n var getBlobFromByteStringWithMimeType = function getBlobFromByteStringWithMimeType(\n byteString,\n mimeType\n ) {\n var ab = new ArrayBuffer(byteString.length);\n var ia = new Uint8Array(ab);\n\n for (var i = 0; i < byteString.length; i++) {\n ia[i] = byteString.charCodeAt(i);\n }\n\n return createBlob(ab, mimeType);\n };\n\n var getMimeTypeFromBase64DataURI = function getMimeTypeFromBase64DataURI(dataURI) {\n return (/^data:(.+);/.exec(dataURI) || [])[1] || null;\n };\n\n var getBase64DataFromBase64DataURI = function getBase64DataFromBase64DataURI(dataURI) {\n // get data part of string (remove data:image/jpeg...,)\n var data = dataURI.split(',')[1];\n\n // remove any whitespace as that causes InvalidCharacterError in IE\n return data.replace(/\\s/g, '');\n };\n\n var getByteStringFromBase64DataURI = function getByteStringFromBase64DataURI(dataURI) {\n return atob(getBase64DataFromBase64DataURI(dataURI));\n };\n\n var getBlobFromBase64DataURI = function getBlobFromBase64DataURI(dataURI) {\n var mimeType = getMimeTypeFromBase64DataURI(dataURI);\n var byteString = getByteStringFromBase64DataURI(dataURI);\n\n return getBlobFromByteStringWithMimeType(byteString, mimeType);\n };\n\n var getFileFromBase64DataURI = function getFileFromBase64DataURI(dataURI, filename, extension) {\n return getFileFromBlob(getBlobFromBase64DataURI(dataURI), filename, null, extension);\n };\n\n var getFileNameFromHeader = function getFileNameFromHeader(header) {\n // test if is content disposition header, if not exit\n if (!/^content-disposition:/i.test(header)) return null;\n\n // get filename parts\n var matches = header\n .split(/filename=|filename\\*=.+''/)\n .splice(1)\n .map(function(name) {\n return name.trim().replace(/^[\"']|[;\"']{0,2}$/g, '');\n })\n .filter(function(name) {\n return name.length;\n });\n\n return matches.length ? decodeURI(matches[matches.length - 1]) : null;\n };\n\n var getFileSizeFromHeader = function getFileSizeFromHeader(header) {\n if (/content-length:/i.test(header)) {\n var size = header.match(/[0-9]+/)[0];\n return size ? parseInt(size, 10) : null;\n }\n return null;\n };\n\n var getTranfserIdFromHeader = function getTranfserIdFromHeader(header) {\n if (/x-content-transfer-id:/i.test(header)) {\n var id = (header.split(':')[1] || '').trim();\n return id || null;\n }\n return null;\n };\n\n var getFileInfoFromHeaders = function getFileInfoFromHeaders(headers) {\n var info = {\n source: null,\n name: null,\n size: null,\n };\n\n var rows = headers.split('\\n');\n var _iteratorNormalCompletion = true;\n var _didIteratorError = false;\n var _iteratorError = undefined;\n try {\n for (\n var _iterator = rows[Symbol.iterator](), _step;\n !(_iteratorNormalCompletion = (_step = _iterator.next()).done);\n _iteratorNormalCompletion = true\n ) {\n var header = _step.value;\n\n var name = getFileNameFromHeader(header);\n if (name) {\n info.name = name;\n continue;\n }\n\n var size = getFileSizeFromHeader(header);\n if (size) {\n info.size = size;\n continue;\n }\n\n var source = getTranfserIdFromHeader(header);\n if (source) {\n info.source = source;\n continue;\n }\n }\n } catch (err) {\n _didIteratorError = true;\n _iteratorError = err;\n } finally {\n try {\n if (!_iteratorNormalCompletion && _iterator.return != null) {\n _iterator.return();\n }\n } finally {\n if (_didIteratorError) {\n throw _iteratorError;\n }\n }\n }\n\n return info;\n };\n\n var createFileLoader = function createFileLoader(fetchFn) {\n var state = {\n source: null,\n complete: false,\n progress: 0,\n size: null,\n timestamp: null,\n duration: 0,\n request: null,\n };\n\n var getProgress = function getProgress() {\n return state.progress;\n };\n var abort = function abort() {\n if (state.request && state.request.abort) {\n state.request.abort();\n }\n };\n\n // load source\n var load = function load() {\n // get quick reference\n var source = state.source;\n\n api.fire('init', source);\n\n // Load Files\n if (source instanceof File) {\n api.fire('load', source);\n } else if (source instanceof Blob) {\n // Load blobs, set default name to current date\n api.fire('load', getFileFromBlob(source, source.name));\n } else if (isBase64DataURI(source)) {\n // Load base 64, set default name to current date\n api.fire('load', getFileFromBase64DataURI(source));\n } else {\n // Deal as if is external URL, let's load it!\n loadURL(source);\n }\n };\n\n // loads a url\n var loadURL = function loadURL(url) {\n // is remote url and no fetch method supplied\n if (!fetchFn) {\n api.fire('error', {\n type: 'error',\n body: \"Can't load URL\",\n code: 400,\n });\n\n return;\n }\n\n // set request start\n state.timestamp = Date.now();\n\n // load file\n state.request = fetchFn(\n url,\n function(response) {\n // update duration\n state.duration = Date.now() - state.timestamp;\n\n // done!\n state.complete = true;\n\n // turn blob response into a file\n if (response instanceof Blob) {\n response = getFileFromBlob(\n response,\n response.name || getFilenameFromURL(url)\n );\n }\n\n api.fire(\n 'load',\n // if has received blob, we go with blob, if no response, we return null\n response instanceof Blob ? response : response ? response.body : null\n );\n },\n function(error) {\n api.fire(\n 'error',\n typeof error === 'string'\n ? {\n type: 'error',\n code: 0,\n body: error,\n }\n : error\n );\n },\n function(computable, current, total) {\n // collected some meta data already\n if (total) {\n state.size = total;\n }\n\n // update duration\n state.duration = Date.now() - state.timestamp;\n\n // if we can't compute progress, we're not going to fire progress events\n if (!computable) {\n state.progress = null;\n return;\n }\n\n // update progress percentage\n state.progress = current / total;\n\n // expose\n api.fire('progress', state.progress);\n },\n function() {\n api.fire('abort');\n },\n function(response) {\n var fileinfo = getFileInfoFromHeaders(\n typeof response === 'string' ? response : response.headers\n );\n api.fire('meta', {\n size: state.size || fileinfo.size,\n filename: fileinfo.name,\n source: fileinfo.source,\n });\n }\n );\n };\n\n var api = Object.assign({}, on(), {\n setSource: function setSource(source) {\n return (state.source = source);\n },\n getProgress: getProgress, // file load progress\n abort: abort, // abort file load\n load: load, // start load\n });\n\n return api;\n };\n\n var isGet = function isGet(method) {\n return /GET|HEAD/.test(method);\n };\n\n var sendRequest = function sendRequest(data, url, options) {\n var api = {\n onheaders: function onheaders() {},\n onprogress: function onprogress() {},\n onload: function onload() {},\n ontimeout: function ontimeout() {},\n onerror: function onerror() {},\n onabort: function onabort() {},\n abort: function abort() {\n aborted = true;\n xhr.abort();\n },\n };\n\n // timeout identifier, only used when timeout is defined\n var aborted = false;\n var headersReceived = false;\n\n // set default options\n options = Object.assign(\n {\n method: 'POST',\n headers: {},\n withCredentials: false,\n },\n options\n );\n\n // encode url\n url = encodeURI(url);\n\n // if method is GET, add any received data to url\n\n if (isGet(options.method) && data) {\n url =\n '' +\n url +\n encodeURIComponent(typeof data === 'string' ? data : JSON.stringify(data));\n }\n\n // create request\n var xhr = new XMLHttpRequest();\n\n // progress of load\n var process = isGet(options.method) ? xhr : xhr.upload;\n process.onprogress = function(e) {\n // no progress event when aborted ( onprogress is called once after abort() )\n if (aborted) {\n return;\n }\n\n api.onprogress(e.lengthComputable, e.loaded, e.total);\n };\n\n // tries to get header info to the app as fast as possible\n xhr.onreadystatechange = function() {\n // not interesting in these states ('unsent' and 'openend' as they don't give us any additional info)\n if (xhr.readyState < 2) {\n return;\n }\n\n // no server response\n if (xhr.readyState === 4 && xhr.status === 0) {\n return;\n }\n\n if (headersReceived) {\n return;\n }\n\n headersReceived = true;\n\n // we've probably received some useful data in response headers\n api.onheaders(xhr);\n };\n\n // load successful\n xhr.onload = function() {\n // is classified as valid response\n if (xhr.status >= 200 && xhr.status < 300) {\n api.onload(xhr);\n } else {\n api.onerror(xhr);\n }\n };\n\n // error during load\n xhr.onerror = function() {\n return api.onerror(xhr);\n };\n\n // request aborted\n xhr.onabort = function() {\n aborted = true;\n api.onabort();\n };\n\n // request timeout\n xhr.ontimeout = function() {\n return api.ontimeout(xhr);\n };\n\n // open up open up!\n xhr.open(options.method, url, true);\n\n // set timeout if defined (do it after open so IE11 plays ball)\n if (isInt(options.timeout)) {\n xhr.timeout = options.timeout;\n }\n\n // add headers\n Object.keys(options.headers).forEach(function(key) {\n var value = unescape(encodeURIComponent(options.headers[key]));\n xhr.setRequestHeader(key, value);\n });\n\n // set type of response\n if (options.responseType) {\n xhr.responseType = options.responseType;\n }\n\n // set credentials\n if (options.withCredentials) {\n xhr.withCredentials = true;\n }\n\n // let's send our data\n xhr.send(data);\n\n return api;\n };\n\n var createResponse = function createResponse(type, code, body, headers) {\n return {\n type: type,\n code: code,\n body: body,\n headers: headers,\n };\n };\n\n var createTimeoutResponse = function createTimeoutResponse(cb) {\n return function(xhr) {\n cb(createResponse('error', 0, 'Timeout', xhr.getAllResponseHeaders()));\n };\n };\n\n var hasQS = function hasQS(str) {\n return /\\?/.test(str);\n };\n var buildURL = function buildURL() {\n var url = '';\n for (var _len = arguments.length, parts = new Array(_len), _key = 0; _key < _len; _key++) {\n parts[_key] = arguments[_key];\n }\n parts.forEach(function(part) {\n url += hasQS(url) && hasQS(part) ? part.replace(/\\?/, '&') : part;\n });\n return url;\n };\n\n var createFetchFunction = function createFetchFunction() {\n var apiUrl = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : '';\n var action = arguments.length > 1 ? arguments[1] : undefined;\n // custom handler (should also handle file, load, error, progress and abort)\n if (typeof action === 'function') {\n return action;\n }\n\n // no action supplied\n if (!action || !isString(action.url)) {\n return null;\n }\n\n // set onload hanlder\n var onload =\n action.onload ||\n function(res) {\n return res;\n };\n var onerror =\n action.onerror ||\n function(res) {\n return null;\n };\n\n // internal handler\n return function(url, load, error, progress, abort, headers) {\n // do local or remote request based on if the url is external\n var request = sendRequest(\n url,\n buildURL(apiUrl, action.url),\n Object.assign({}, action, {\n responseType: 'blob',\n })\n );\n\n request.onload = function(xhr) {\n // get headers\n var headers = xhr.getAllResponseHeaders();\n\n // get filename\n var filename = getFileInfoFromHeaders(headers).name || getFilenameFromURL(url);\n\n // create response\n load(\n createResponse(\n 'load',\n xhr.status,\n action.method === 'HEAD'\n ? null\n : getFileFromBlob(onload(xhr.response), filename),\n headers\n )\n );\n };\n\n request.onerror = function(xhr) {\n error(\n createResponse(\n 'error',\n xhr.status,\n onerror(xhr.response) || xhr.statusText,\n xhr.getAllResponseHeaders()\n )\n );\n };\n\n request.onheaders = function(xhr) {\n headers(createResponse('headers', xhr.status, null, xhr.getAllResponseHeaders()));\n };\n\n request.ontimeout = createTimeoutResponse(error);\n request.onprogress = progress;\n request.onabort = abort;\n\n // should return request\n return request;\n };\n };\n\n var ChunkStatus = {\n QUEUED: 0,\n COMPLETE: 1,\n PROCESSING: 2,\n ERROR: 3,\n WAITING: 4,\n };\n\n /*\n function signature:\n (file, metadata, load, error, progress, abort, transfer, options) => {\n return {\n abort:() => {}\n }\n }\n */\n\n // apiUrl, action, name, file, metadata, load, error, progress, abort, transfer, options\n var processFileChunked = function processFileChunked(\n apiUrl,\n action,\n name,\n file,\n metadata,\n load,\n error,\n progress,\n abort,\n transfer,\n options\n ) {\n // all chunks\n var chunks = [];\n var chunkTransferId = options.chunkTransferId,\n chunkServer = options.chunkServer,\n chunkSize = options.chunkSize,\n chunkRetryDelays = options.chunkRetryDelays;\n\n // default state\n var state = {\n serverId: chunkTransferId,\n aborted: false,\n };\n\n // set onload handlers\n var ondata =\n action.ondata ||\n function(fd) {\n return fd;\n };\n var onload =\n action.onload ||\n function(xhr, method) {\n return method === 'HEAD' ? xhr.getResponseHeader('Upload-Offset') : xhr.response;\n };\n var onerror =\n action.onerror ||\n function(res) {\n return null;\n };\n\n // create server hook\n var requestTransferId = function requestTransferId(cb) {\n var formData = new FormData();\n\n // add metadata under same name\n if (isObject(metadata)) formData.append(name, JSON.stringify(metadata));\n\n var headers =\n typeof action.headers === 'function'\n ? action.headers(file, metadata)\n : Object.assign({}, action.headers, {\n 'Upload-Length': file.size,\n });\n\n var requestParams = Object.assign({}, action, {\n headers: headers,\n });\n\n // send request object\n var request = sendRequest(\n ondata(formData),\n buildURL(apiUrl, action.url),\n requestParams\n );\n\n request.onload = function(xhr) {\n return cb(onload(xhr, requestParams.method));\n };\n\n request.onerror = function(xhr) {\n return error(\n createResponse(\n 'error',\n xhr.status,\n onerror(xhr.response) || xhr.statusText,\n xhr.getAllResponseHeaders()\n )\n );\n };\n\n request.ontimeout = createTimeoutResponse(error);\n };\n\n var requestTransferOffset = function requestTransferOffset(cb) {\n var requestUrl = buildURL(apiUrl, chunkServer.url, state.serverId);\n\n var headers =\n typeof action.headers === 'function'\n ? action.headers(state.serverId)\n : Object.assign({}, action.headers);\n\n var requestParams = {\n headers: headers,\n method: 'HEAD',\n };\n\n var request = sendRequest(null, requestUrl, requestParams);\n\n request.onload = function(xhr) {\n return cb(onload(xhr, requestParams.method));\n };\n\n request.onerror = function(xhr) {\n return error(\n createResponse(\n 'error',\n xhr.status,\n onerror(xhr.response) || xhr.statusText,\n xhr.getAllResponseHeaders()\n )\n );\n };\n\n request.ontimeout = createTimeoutResponse(error);\n };\n\n // create chunks\n var lastChunkIndex = Math.floor(file.size / chunkSize);\n for (var i = 0; i <= lastChunkIndex; i++) {\n var offset = i * chunkSize;\n var data = file.slice(offset, offset + chunkSize, 'application/offset+octet-stream');\n chunks[i] = {\n index: i,\n size: data.size,\n offset: offset,\n data: data,\n file: file,\n progress: 0,\n retries: _toConsumableArray(chunkRetryDelays),\n status: ChunkStatus.QUEUED,\n error: null,\n request: null,\n timeout: null,\n };\n }\n\n var completeProcessingChunks = function completeProcessingChunks() {\n return load(state.serverId);\n };\n\n var canProcessChunk = function canProcessChunk(chunk) {\n return chunk.status === ChunkStatus.QUEUED || chunk.status === ChunkStatus.ERROR;\n };\n\n var processChunk = function processChunk(chunk) {\n // processing is paused, wait here\n if (state.aborted) return;\n\n // get next chunk to process\n chunk = chunk || chunks.find(canProcessChunk);\n\n // no more chunks to process\n if (!chunk) {\n // all done?\n if (\n chunks.every(function(chunk) {\n return chunk.status === ChunkStatus.COMPLETE;\n })\n ) {\n completeProcessingChunks();\n }\n\n // no chunk to handle\n return;\n }\n\n // now processing this chunk\n chunk.status = ChunkStatus.PROCESSING;\n chunk.progress = null;\n\n // allow parsing of formdata\n var ondata =\n chunkServer.ondata ||\n function(fd) {\n return fd;\n };\n var onerror =\n chunkServer.onerror ||\n function(res) {\n return null;\n };\n\n // send request object\n var requestUrl = buildURL(apiUrl, chunkServer.url, state.serverId);\n\n var headers =\n typeof chunkServer.headers === 'function'\n ? chunkServer.headers(chunk)\n : Object.assign({}, chunkServer.headers, {\n 'Content-Type': 'application/offset+octet-stream',\n 'Upload-Offset': chunk.offset,\n 'Upload-Length': file.size,\n 'Upload-Name': file.name,\n });\n\n var request = (chunk.request = sendRequest(\n ondata(chunk.data),\n requestUrl,\n Object.assign({}, chunkServer, {\n headers: headers,\n })\n ));\n\n request.onload = function() {\n // done!\n chunk.status = ChunkStatus.COMPLETE;\n\n // remove request reference\n chunk.request = null;\n\n // start processing more chunks\n processChunks();\n };\n\n request.onprogress = function(lengthComputable, loaded, total) {\n chunk.progress = lengthComputable ? loaded : null;\n updateTotalProgress();\n };\n\n request.onerror = function(xhr) {\n chunk.status = ChunkStatus.ERROR;\n chunk.request = null;\n chunk.error = onerror(xhr.response) || xhr.statusText;\n if (!retryProcessChunk(chunk)) {\n error(\n createResponse(\n 'error',\n xhr.status,\n onerror(xhr.response) || xhr.statusText,\n xhr.getAllResponseHeaders()\n )\n );\n }\n };\n\n request.ontimeout = function(xhr) {\n chunk.status = ChunkStatus.ERROR;\n chunk.request = null;\n if (!retryProcessChunk(chunk)) {\n createTimeoutResponse(error)(xhr);\n }\n };\n\n request.onabort = function() {\n chunk.status = ChunkStatus.QUEUED;\n chunk.request = null;\n abort();\n };\n };\n\n var retryProcessChunk = function retryProcessChunk(chunk) {\n // no more retries left\n if (chunk.retries.length === 0) return false;\n\n // new retry\n chunk.status = ChunkStatus.WAITING;\n clearTimeout(chunk.timeout);\n chunk.timeout = setTimeout(function() {\n processChunk(chunk);\n }, chunk.retries.shift());\n\n // we're going to retry\n return true;\n };\n\n var updateTotalProgress = function updateTotalProgress() {\n // calculate total progress fraction\n var totalBytesTransfered = chunks.reduce(function(p, chunk) {\n if (p === null || chunk.progress === null) return null;\n return p + chunk.progress;\n }, 0);\n\n // can't compute progress\n if (totalBytesTransfered === null) return progress(false, 0, 0);\n\n // calculate progress values\n var totalSize = chunks.reduce(function(total, chunk) {\n return total + chunk.size;\n }, 0);\n\n // can update progress indicator\n progress(true, totalBytesTransfered, totalSize);\n };\n\n // process new chunks\n var processChunks = function processChunks() {\n var totalProcessing = chunks.filter(function(chunk) {\n return chunk.status === ChunkStatus.PROCESSING;\n }).length;\n if (totalProcessing >= 1) return;\n processChunk();\n };\n\n var abortChunks = function abortChunks() {\n chunks.forEach(function(chunk) {\n clearTimeout(chunk.timeout);\n if (chunk.request) {\n chunk.request.abort();\n }\n });\n };\n\n // let's go!\n if (!state.serverId) {\n requestTransferId(function(serverId) {\n // stop here if aborted, might have happened in between request and callback\n if (state.aborted) return;\n\n // pass back to item so we can use it if something goes wrong\n transfer(serverId);\n\n // store internally\n state.serverId = serverId;\n processChunks();\n });\n } else {\n requestTransferOffset(function(offset) {\n // stop here if aborted, might have happened in between request and callback\n if (state.aborted) return;\n\n // mark chunks with lower offset as complete\n chunks\n .filter(function(chunk) {\n return chunk.offset < offset;\n })\n .forEach(function(chunk) {\n chunk.status = ChunkStatus.COMPLETE;\n chunk.progress = chunk.size;\n });\n\n // continue processing\n processChunks();\n });\n }\n\n return {\n abort: function abort() {\n state.aborted = true;\n abortChunks();\n },\n };\n };\n\n /*\n function signature:\n (file, metadata, load, error, progress, abort) => {\n return {\n abort:() => {}\n }\n }\n */\n var createFileProcessorFunction = function createFileProcessorFunction(\n apiUrl,\n action,\n name,\n options\n ) {\n return function(file, metadata, load, error, progress, abort, transfer) {\n // no file received\n if (!file) return;\n\n // if was passed a file, and we can chunk it, exit here\n var canChunkUpload = options.chunkUploads;\n var shouldChunkUpload = canChunkUpload && file.size > options.chunkSize;\n var willChunkUpload = canChunkUpload && (shouldChunkUpload || options.chunkForce);\n if (file instanceof Blob && willChunkUpload)\n return processFileChunked(\n apiUrl,\n action,\n name,\n file,\n metadata,\n load,\n error,\n progress,\n abort,\n transfer,\n options\n );\n\n // set handlers\n var ondata =\n action.ondata ||\n function(fd) {\n return fd;\n };\n var onload =\n action.onload ||\n function(res) {\n return res;\n };\n var onerror =\n action.onerror ||\n function(res) {\n return null;\n };\n\n var headers =\n typeof action.headers === 'function'\n ? action.headers(file, metadata) || {}\n : Object.assign(\n {},\n\n action.headers\n );\n\n var requestParams = Object.assign({}, action, {\n headers: headers,\n });\n\n // create formdata object\n var formData = new FormData();\n\n // add metadata under same name\n if (isObject(metadata)) {\n formData.append(name, JSON.stringify(metadata));\n }\n\n // Turn into an array of objects so no matter what the input, we can handle it the same way\n (file instanceof Blob ? [{ name: null, file: file }] : file).forEach(function(item) {\n formData.append(\n name,\n item.file,\n item.name === null ? item.file.name : '' + item.name + item.file.name\n );\n });\n\n // send request object\n var request = sendRequest(\n ondata(formData),\n buildURL(apiUrl, action.url),\n requestParams\n );\n request.onload = function(xhr) {\n load(\n createResponse(\n 'load',\n xhr.status,\n onload(xhr.response),\n xhr.getAllResponseHeaders()\n )\n );\n };\n\n request.onerror = function(xhr) {\n error(\n createResponse(\n 'error',\n xhr.status,\n onerror(xhr.response) || xhr.statusText,\n xhr.getAllResponseHeaders()\n )\n );\n };\n\n request.ontimeout = createTimeoutResponse(error);\n request.onprogress = progress;\n request.onabort = abort;\n\n // should return request\n return request;\n };\n };\n\n var createProcessorFunction = function createProcessorFunction() {\n var apiUrl = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : '';\n var action = arguments.length > 1 ? arguments[1] : undefined;\n var name = arguments.length > 2 ? arguments[2] : undefined;\n var options = arguments.length > 3 ? arguments[3] : undefined;\n\n // custom handler (should also handle file, load, error, progress and abort)\n if (typeof action === 'function')\n return function() {\n for (\n var _len = arguments.length, params = new Array(_len), _key = 0;\n _key < _len;\n _key++\n ) {\n params[_key] = arguments[_key];\n }\n return action.apply(void 0, [name].concat(params, [options]));\n };\n\n // no action supplied\n if (!action || !isString(action.url)) return null;\n\n // internal handler\n return createFileProcessorFunction(apiUrl, action, name, options);\n };\n\n /*\n function signature:\n (uniqueFileId, load, error) => { }\n */\n var createRevertFunction = function createRevertFunction() {\n var apiUrl = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : '';\n var action = arguments.length > 1 ? arguments[1] : undefined;\n // is custom implementation\n if (typeof action === 'function') {\n return action;\n }\n\n // no action supplied, return stub function, interface will work, but file won't be removed\n if (!action || !isString(action.url)) {\n return function(uniqueFileId, load) {\n return load();\n };\n }\n\n // set onload hanlder\n var onload =\n action.onload ||\n function(res) {\n return res;\n };\n var onerror =\n action.onerror ||\n function(res) {\n return null;\n };\n\n // internal implementation\n return function(uniqueFileId, load, error) {\n var request = sendRequest(\n uniqueFileId,\n apiUrl + action.url,\n action // contains method, headers and withCredentials properties\n );\n request.onload = function(xhr) {\n load(\n createResponse(\n 'load',\n xhr.status,\n onload(xhr.response),\n xhr.getAllResponseHeaders()\n )\n );\n };\n\n request.onerror = function(xhr) {\n error(\n createResponse(\n 'error',\n xhr.status,\n onerror(xhr.response) || xhr.statusText,\n xhr.getAllResponseHeaders()\n )\n );\n };\n\n request.ontimeout = createTimeoutResponse(error);\n\n return request;\n };\n };\n\n var getRandomNumber = function getRandomNumber() {\n var min = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0;\n var max = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 1;\n return min + Math.random() * (max - min);\n };\n\n var createPerceivedPerformanceUpdater = function createPerceivedPerformanceUpdater(cb) {\n var duration = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 1000;\n var offset = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 0;\n var tickMin = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 25;\n var tickMax = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : 250;\n var timeout = null;\n var start = Date.now();\n\n var tick = function tick() {\n var runtime = Date.now() - start;\n var delay = getRandomNumber(tickMin, tickMax);\n\n if (runtime + delay > duration) {\n delay = runtime + delay - duration;\n }\n\n var progress = runtime / duration;\n if (progress >= 1 || document.hidden) {\n cb(1);\n return;\n }\n\n cb(progress);\n\n timeout = setTimeout(tick, delay);\n };\n\n if (duration > 0) tick();\n\n return {\n clear: function clear() {\n clearTimeout(timeout);\n },\n };\n };\n\n var createFileProcessor = function createFileProcessor(processFn, options) {\n var state = {\n complete: false,\n perceivedProgress: 0,\n perceivedPerformanceUpdater: null,\n progress: null,\n timestamp: null,\n perceivedDuration: 0,\n duration: 0,\n request: null,\n response: null,\n };\n var allowMinimumUploadDuration = options.allowMinimumUploadDuration;\n\n var process = function process(file, metadata) {\n var progressFn = function progressFn() {\n // we've not yet started the real download, stop here\n // the request might not go through, for instance, there might be some server trouble\n // if state.progress is null, the server does not allow computing progress and we show the spinner instead\n if (state.duration === 0 || state.progress === null) return;\n\n // as we're now processing, fire the progress event\n api.fire('progress', api.getProgress());\n };\n\n var completeFn = function completeFn() {\n state.complete = true;\n api.fire('load-perceived', state.response.body);\n };\n\n // let's start processing\n api.fire('start');\n\n // set request start\n state.timestamp = Date.now();\n\n // create perceived performance progress indicator\n state.perceivedPerformanceUpdater = createPerceivedPerformanceUpdater(\n function(progress) {\n state.perceivedProgress = progress;\n state.perceivedDuration = Date.now() - state.timestamp;\n\n progressFn();\n\n // if fake progress is done, and a response has been received,\n // and we've not yet called the complete method\n if (state.response && state.perceivedProgress === 1 && !state.complete) {\n // we done!\n completeFn();\n }\n },\n // random delay as in a list of files you start noticing\n // files uploading at the exact same speed\n allowMinimumUploadDuration ? getRandomNumber(750, 1500) : 0\n );\n\n // remember request so we can abort it later\n state.request = processFn(\n // the file to process\n file,\n\n // the metadata to send along\n metadata,\n\n // callbacks (load, error, progress, abort, transfer)\n // load expects the body to be a server id if\n // you want to make use of revert\n function(response) {\n // we put the response in state so we can access\n // it outside of this method\n state.response = isObject(response)\n ? response\n : {\n type: 'load',\n code: 200,\n body: '' + response,\n headers: {},\n };\n\n // update duration\n state.duration = Date.now() - state.timestamp;\n\n // force progress to 1 as we're now done\n state.progress = 1;\n\n // actual load is done let's share results\n api.fire('load', state.response.body);\n\n // we are really done\n // if perceived progress is 1 ( wait for perceived progress to complete )\n // or if server does not support progress ( null )\n if (\n !allowMinimumUploadDuration ||\n (allowMinimumUploadDuration && state.perceivedProgress === 1)\n ) {\n completeFn();\n }\n },\n\n // error is expected to be an object with type, code, body\n function(error) {\n // cancel updater\n state.perceivedPerformanceUpdater.clear();\n\n // update others about this error\n api.fire(\n 'error',\n isObject(error)\n ? error\n : {\n type: 'error',\n code: 0,\n body: '' + error,\n }\n );\n },\n\n // actual processing progress\n function(computable, current, total) {\n // update actual duration\n state.duration = Date.now() - state.timestamp;\n\n // update actual progress\n state.progress = computable ? current / total : null;\n\n progressFn();\n },\n\n // abort does not expect a value\n function() {\n // stop updater\n state.perceivedPerformanceUpdater.clear();\n\n // fire the abort event so we can switch visuals\n api.fire('abort', state.response ? state.response.body : null);\n },\n\n // register the id for this transfer\n function(transferId) {\n api.fire('transfer', transferId);\n }\n );\n };\n\n var abort = function abort() {\n // no request running, can't abort\n if (!state.request) return;\n\n // stop updater\n state.perceivedPerformanceUpdater.clear();\n\n // abort actual request\n if (state.request.abort) state.request.abort();\n\n // if has response object, we've completed the request\n state.complete = true;\n };\n\n var reset = function reset() {\n abort();\n state.complete = false;\n state.perceivedProgress = 0;\n state.progress = 0;\n state.timestamp = null;\n state.perceivedDuration = 0;\n state.duration = 0;\n state.request = null;\n state.response = null;\n };\n\n var getProgress = allowMinimumUploadDuration\n ? function() {\n return state.progress ? Math.min(state.progress, state.perceivedProgress) : null;\n }\n : function() {\n return state.progress || null;\n };\n\n var getDuration = allowMinimumUploadDuration\n ? function() {\n return Math.min(state.duration, state.perceivedDuration);\n }\n : function() {\n return state.duration;\n };\n\n var api = Object.assign({}, on(), {\n process: process, // start processing file\n abort: abort, // abort active process request\n getProgress: getProgress,\n getDuration: getDuration,\n reset: reset,\n });\n\n return api;\n };\n\n var getFilenameWithoutExtension = function getFilenameWithoutExtension(name) {\n return name.substring(0, name.lastIndexOf('.')) || name;\n };\n\n var createFileStub = function createFileStub(source) {\n var data = [source.name, source.size, source.type];\n\n // is blob or base64, then we need to set the name\n if (source instanceof Blob || isBase64DataURI(source)) {\n data[0] = source.name || getDateString();\n } else if (isBase64DataURI(source)) {\n // if is base64 data uri we need to determine the average size and type\n data[1] = source.length;\n data[2] = getMimeTypeFromBase64DataURI(source);\n } else if (isString(source)) {\n // url\n data[0] = getFilenameFromURL(source);\n data[1] = 0;\n data[2] = 'application/octet-stream';\n }\n\n return {\n name: data[0],\n size: data[1],\n type: data[2],\n };\n };\n\n var isFile = function isFile(value) {\n return !!(value instanceof File || (value instanceof Blob && value.name));\n };\n\n var deepCloneObject = function deepCloneObject(src) {\n if (!isObject(src)) return src;\n var target = isArray(src) ? [] : {};\n for (var key in src) {\n if (!src.hasOwnProperty(key)) continue;\n var v = src[key];\n target[key] = v && isObject(v) ? deepCloneObject(v) : v;\n }\n return target;\n };\n\n var createItem = function createItem() {\n var origin = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null;\n var serverFileReference =\n arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null;\n var file = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null;\n // unique id for this item, is used to identify the item across views\n var id = getUniqueId();\n\n /**\n * Internal item state\n */\n var state = {\n // is archived\n archived: false,\n\n // if is frozen, no longer fires events\n frozen: false,\n\n // removed from view\n released: false,\n\n // original source\n source: null,\n\n // file model reference\n file: file,\n\n // id of file on server\n serverFileReference: serverFileReference,\n\n // id of file transfer on server\n transferId: null,\n\n // is aborted\n processingAborted: false,\n\n // current item status\n status: serverFileReference ? ItemStatus.PROCESSING_COMPLETE : ItemStatus.INIT,\n\n // active processes\n activeLoader: null,\n activeProcessor: null,\n };\n\n // callback used when abort processing is called to link back to the resolve method\n var abortProcessingRequestComplete = null;\n\n /**\n * Externally added item metadata\n */\n var metadata = {};\n\n // item data\n var setStatus = function setStatus(status) {\n return (state.status = status);\n };\n\n // fire event unless the item has been archived\n var fire = function fire(event) {\n if (state.released || state.frozen) return;\n for (\n var _len = arguments.length, params = new Array(_len > 1 ? _len - 1 : 0), _key = 1;\n _key < _len;\n _key++\n ) {\n params[_key - 1] = arguments[_key];\n }\n api.fire.apply(api, [event].concat(params));\n };\n\n // file data\n var getFileExtension = function getFileExtension() {\n return getExtensionFromFilename(state.file.name);\n };\n var getFileType = function getFileType() {\n return state.file.type;\n };\n var getFileSize = function getFileSize() {\n return state.file.size;\n };\n var getFile = function getFile() {\n return state.file;\n };\n\n //\n // logic to load a file\n //\n var load = function load(source, loader, onload) {\n // remember the original item source\n state.source = source;\n\n // source is known\n api.fireSync('init');\n\n // file stub is already there\n if (state.file) {\n api.fireSync('load-skip');\n return;\n }\n\n // set a stub file object while loading the actual data\n state.file = createFileStub(source);\n\n // starts loading\n loader.on('init', function() {\n fire('load-init');\n });\n\n // we'eve received a size indication, let's update the stub\n loader.on('meta', function(meta) {\n // set size of file stub\n state.file.size = meta.size;\n\n // set name of file stub\n state.file.filename = meta.filename;\n\n // if has received source, we done\n if (meta.source) {\n origin = FileOrigin.LIMBO;\n state.serverFileReference = meta.source;\n state.status = ItemStatus.PROCESSING_COMPLETE;\n }\n\n // size has been updated\n fire('load-meta');\n });\n\n // the file is now loading we need to update the progress indicators\n loader.on('progress', function(progress) {\n setStatus(ItemStatus.LOADING);\n\n fire('load-progress', progress);\n });\n\n // an error was thrown while loading the file, we need to switch to error state\n loader.on('error', function(error) {\n setStatus(ItemStatus.LOAD_ERROR);\n\n fire('load-request-error', error);\n });\n\n // user or another process aborted the file load (cannot retry)\n loader.on('abort', function() {\n setStatus(ItemStatus.INIT);\n fire('load-abort');\n });\n\n // done loading\n loader.on('load', function(file) {\n // as we've now loaded the file the loader is no longer required\n state.activeLoader = null;\n\n // called when file has loaded succesfully\n var success = function success(result) {\n // set (possibly) transformed file\n state.file = isFile(result) ? result : state.file;\n\n // file received\n if (origin === FileOrigin.LIMBO && state.serverFileReference) {\n setStatus(ItemStatus.PROCESSING_COMPLETE);\n } else {\n setStatus(ItemStatus.IDLE);\n }\n\n fire('load');\n };\n\n var error = function error(result) {\n // set original file\n state.file = file;\n fire('load-meta');\n\n setStatus(ItemStatus.LOAD_ERROR);\n fire('load-file-error', result);\n };\n\n // if we already have a server file reference, we don't need to call the onload method\n if (state.serverFileReference) {\n success(file);\n return;\n }\n\n // no server id, let's give this file the full treatment\n onload(file, success, error);\n });\n\n // set loader source data\n loader.setSource(source);\n\n // set as active loader\n state.activeLoader = loader;\n\n // load the source data\n loader.load();\n };\n\n var retryLoad = function retryLoad() {\n if (!state.activeLoader) {\n return;\n }\n state.activeLoader.load();\n };\n\n var abortLoad = function abortLoad() {\n if (state.activeLoader) {\n state.activeLoader.abort();\n return;\n }\n setStatus(ItemStatus.INIT);\n fire('load-abort');\n };\n\n //\n // logic to process a file\n //\n var process = function process(processor, onprocess) {\n // processing was aborted\n if (state.processingAborted) {\n state.processingAborted = false;\n return;\n }\n\n // now processing\n setStatus(ItemStatus.PROCESSING);\n\n // reset abort callback\n abortProcessingRequestComplete = null;\n\n // if no file loaded we'll wait for the load event\n if (!(state.file instanceof Blob)) {\n api.on('load', function() {\n process(processor, onprocess);\n });\n return;\n }\n\n // setup processor\n processor.on('load', function(serverFileReference) {\n // need this id to be able to revert the upload\n state.transferId = null;\n state.serverFileReference = serverFileReference;\n });\n\n // register transfer id\n processor.on('transfer', function(transferId) {\n // need this id to be able to revert the upload\n state.transferId = transferId;\n });\n\n processor.on('load-perceived', function(serverFileReference) {\n // no longer required\n state.activeProcessor = null;\n\n // need this id to be able to rever the upload\n state.transferId = null;\n state.serverFileReference = serverFileReference;\n\n setStatus(ItemStatus.PROCESSING_COMPLETE);\n fire('process-complete', serverFileReference);\n });\n\n processor.on('start', function() {\n fire('process-start');\n });\n\n processor.on('error', function(error) {\n state.activeProcessor = null;\n setStatus(ItemStatus.PROCESSING_ERROR);\n fire('process-error', error);\n });\n\n processor.on('abort', function(serverFileReference) {\n state.activeProcessor = null;\n\n // if file was uploaded but processing was cancelled during perceived processor time store file reference\n state.serverFileReference = serverFileReference;\n\n setStatus(ItemStatus.IDLE);\n fire('process-abort');\n\n // has timeout so doesn't interfere with remove action\n if (abortProcessingRequestComplete) {\n abortProcessingRequestComplete();\n }\n });\n\n processor.on('progress', function(progress) {\n fire('process-progress', progress);\n });\n\n // when successfully transformed\n var success = function success(file) {\n // if was archived in the mean time, don't process\n if (state.archived) return;\n\n // process file!\n processor.process(file, Object.assign({}, metadata));\n };\n\n // something went wrong during transform phase\n var error = console.error;\n\n // start processing the file\n onprocess(state.file, success, error);\n\n // set as active processor\n state.activeProcessor = processor;\n };\n\n var requestProcessing = function requestProcessing() {\n state.processingAborted = false;\n setStatus(ItemStatus.PROCESSING_QUEUED);\n };\n\n var abortProcessing = function abortProcessing() {\n return new Promise(function(resolve) {\n if (!state.activeProcessor) {\n state.processingAborted = true;\n\n setStatus(ItemStatus.IDLE);\n fire('process-abort');\n\n resolve();\n return;\n }\n\n abortProcessingRequestComplete = function abortProcessingRequestComplete() {\n resolve();\n };\n\n state.activeProcessor.abort();\n });\n };\n\n //\n // logic to revert a processed file\n //\n var revert = function revert(revertFileUpload, forceRevert) {\n return new Promise(function(resolve, reject) {\n // a completed upload will have a serverFileReference, a failed chunked upload where\n // getting a serverId succeeded but >=0 chunks have been uploaded will have transferId set\n var serverTransferId =\n state.serverFileReference !== null\n ? state.serverFileReference\n : state.transferId;\n\n // cannot revert without a server id for this process\n if (serverTransferId === null) {\n resolve();\n return;\n }\n\n // revert the upload (fire and forget)\n revertFileUpload(\n serverTransferId,\n function() {\n // reset file server id and transfer id as now it's not available on the server\n state.serverFileReference = null;\n state.transferId = null;\n resolve();\n },\n function(error) {\n // don't set error state when reverting is optional, it will always resolve\n if (!forceRevert) {\n resolve();\n return;\n }\n\n // oh no errors\n setStatus(ItemStatus.PROCESSING_REVERT_ERROR);\n fire('process-revert-error');\n reject(error);\n }\n );\n\n // fire event\n setStatus(ItemStatus.IDLE);\n fire('process-revert');\n });\n };\n\n // exposed methods\n var _setMetadata = function setMetadata(key, value, silent) {\n var keys = key.split('.');\n var root = keys[0];\n var last = keys.pop();\n var data = metadata;\n keys.forEach(function(key) {\n return (data = data[key]);\n });\n\n // compare old value against new value, if they're the same, we're not updating\n if (JSON.stringify(data[last]) === JSON.stringify(value)) return;\n\n // update value\n data[last] = value;\n\n // fire update\n fire('metadata-update', {\n key: root,\n value: metadata[root],\n silent: silent,\n });\n };\n\n var getMetadata = function getMetadata(key) {\n return deepCloneObject(key ? metadata[key] : metadata);\n };\n\n var api = Object.assign(\n {\n id: {\n get: function get() {\n return id;\n },\n },\n origin: {\n get: function get() {\n return origin;\n },\n set: function set(value) {\n return (origin = value);\n },\n },\n serverId: {\n get: function get() {\n return state.serverFileReference;\n },\n },\n transferId: {\n get: function get() {\n return state.transferId;\n },\n },\n status: {\n get: function get() {\n return state.status;\n },\n },\n filename: {\n get: function get() {\n return state.file.name;\n },\n },\n filenameWithoutExtension: {\n get: function get() {\n return getFilenameWithoutExtension(state.file.name);\n },\n },\n fileExtension: { get: getFileExtension },\n fileType: { get: getFileType },\n fileSize: { get: getFileSize },\n file: { get: getFile },\n relativePath: {\n get: function get() {\n return state.file._relativePath;\n },\n },\n\n source: {\n get: function get() {\n return state.source;\n },\n },\n\n getMetadata: getMetadata,\n setMetadata: function setMetadata(key, value, silent) {\n if (isObject(key)) {\n var data = key;\n Object.keys(data).forEach(function(key) {\n _setMetadata(key, data[key], value);\n });\n return key;\n }\n _setMetadata(key, value, silent);\n return value;\n },\n\n extend: function extend(name, handler) {\n return (itemAPI[name] = handler);\n },\n\n abortLoad: abortLoad,\n retryLoad: retryLoad,\n requestProcessing: requestProcessing,\n abortProcessing: abortProcessing,\n\n load: load,\n process: process,\n revert: revert,\n },\n\n on(),\n {\n freeze: function freeze() {\n return (state.frozen = true);\n },\n\n release: function release() {\n return (state.released = true);\n },\n released: {\n get: function get() {\n return state.released;\n },\n },\n\n archive: function archive() {\n return (state.archived = true);\n },\n archived: {\n get: function get() {\n return state.archived;\n },\n },\n }\n );\n\n // create it here instead of returning it instantly so we can extend it later\n var itemAPI = createObject(api);\n\n return itemAPI;\n };\n\n var getItemIndexByQuery = function getItemIndexByQuery(items, query) {\n // just return first index\n if (isEmpty(query)) {\n return 0;\n }\n\n // invalid queries\n if (!isString(query)) {\n return -1;\n }\n\n // return item by id (or -1 if not found)\n return items.findIndex(function(item) {\n return item.id === query;\n });\n };\n\n var getItemById = function getItemById(items, itemId) {\n var index = getItemIndexByQuery(items, itemId);\n if (index < 0) {\n return;\n }\n return items[index] || null;\n };\n\n var fetchBlob = function fetchBlob(url, load, error, progress, abort, headers) {\n var request = sendRequest(null, url, {\n method: 'GET',\n responseType: 'blob',\n });\n\n request.onload = function(xhr) {\n // get headers\n var headers = xhr.getAllResponseHeaders();\n\n // get filename\n var filename = getFileInfoFromHeaders(headers).name || getFilenameFromURL(url);\n\n // create response\n load(\n createResponse('load', xhr.status, getFileFromBlob(xhr.response, filename), headers)\n );\n };\n\n request.onerror = function(xhr) {\n error(createResponse('error', xhr.status, xhr.statusText, xhr.getAllResponseHeaders()));\n };\n\n request.onheaders = function(xhr) {\n headers(createResponse('headers', xhr.status, null, xhr.getAllResponseHeaders()));\n };\n\n request.ontimeout = createTimeoutResponse(error);\n request.onprogress = progress;\n request.onabort = abort;\n\n // should return request\n return request;\n };\n\n var getDomainFromURL = function getDomainFromURL(url) {\n if (url.indexOf('//') === 0) {\n url = location.protocol + url;\n }\n return url\n .toLowerCase()\n .replace('blob:', '')\n .replace(/([a-z])?:\\/\\//, '$1')\n .split('/')[0];\n };\n\n var isExternalURL = function isExternalURL(url) {\n return (\n (url.indexOf(':') > -1 || url.indexOf('//') > -1) &&\n getDomainFromURL(location.href) !== getDomainFromURL(url)\n );\n };\n\n var dynamicLabel = function dynamicLabel(label) {\n return function() {\n return isFunction(label) ? label.apply(void 0, arguments) : label;\n };\n };\n\n var isMockItem = function isMockItem(item) {\n return !isFile(item.file);\n };\n\n var listUpdated = function listUpdated(dispatch, state) {\n clearTimeout(state.listUpdateTimeout);\n state.listUpdateTimeout = setTimeout(function() {\n dispatch('DID_UPDATE_ITEMS', { items: getActiveItems(state.items) });\n }, 0);\n };\n\n var optionalPromise = function optionalPromise(fn) {\n for (\n var _len = arguments.length, params = new Array(_len > 1 ? _len - 1 : 0), _key = 1;\n _key < _len;\n _key++\n ) {\n params[_key - 1] = arguments[_key];\n }\n return new Promise(function(resolve) {\n if (!fn) {\n return resolve(true);\n }\n\n var result = fn.apply(void 0, params);\n\n if (result == null) {\n return resolve(true);\n }\n\n if (typeof result === 'boolean') {\n return resolve(result);\n }\n\n if (typeof result.then === 'function') {\n result.then(resolve);\n }\n });\n };\n\n var sortItems = function sortItems(state, compare) {\n state.items.sort(function(a, b) {\n return compare(createItemAPI(a), createItemAPI(b));\n });\n };\n\n // returns item based on state\n var getItemByQueryFromState = function getItemByQueryFromState(state, itemHandler) {\n return function() {\n var _ref = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};\n var query = _ref.query,\n _ref$success = _ref.success,\n success = _ref$success === void 0 ? function() {} : _ref$success,\n _ref$failure = _ref.failure,\n failure = _ref$failure === void 0 ? function() {} : _ref$failure,\n options = _objectWithoutProperties(_ref, ['query', 'success', 'failure']);\n var item = getItemByQuery(state.items, query);\n if (!item) {\n failure({\n error: createResponse('error', 0, 'Item not found'),\n file: null,\n });\n\n return;\n }\n itemHandler(item, success, failure, options || {});\n };\n };\n\n var actions = function actions(dispatch, query, state) {\n return {\n /**\n * Aborts all ongoing processes\n */\n ABORT_ALL: function ABORT_ALL() {\n getActiveItems(state.items).forEach(function(item) {\n item.freeze();\n item.abortLoad();\n item.abortProcessing();\n });\n },\n\n /**\n * Sets initial files\n */\n DID_SET_FILES: function DID_SET_FILES(_ref2) {\n var _ref2$value = _ref2.value,\n value = _ref2$value === void 0 ? [] : _ref2$value;\n // map values to file objects\n var files = value.map(function(file) {\n return {\n source: file.source ? file.source : file,\n options: file.options,\n };\n });\n\n // loop over files, if file is in list, leave it be, if not, remove\n // test if items should be moved\n var activeItems = getActiveItems(state.items);\n\n activeItems.forEach(function(item) {\n // if item not is in new value, remove\n if (\n !files.find(function(file) {\n return file.source === item.source || file.source === item.file;\n })\n ) {\n dispatch('REMOVE_ITEM', { query: item, remove: false });\n }\n });\n\n // add new files\n activeItems = getActiveItems(state.items);\n files.forEach(function(file, index) {\n // if file is already in list\n if (\n activeItems.find(function(item) {\n return item.source === file.source || item.file === file.source;\n })\n )\n return;\n\n // not in list, add\n dispatch(\n 'ADD_ITEM',\n Object.assign({}, file, {\n interactionMethod: InteractionMethod.NONE,\n index: index,\n })\n );\n });\n },\n\n DID_UPDATE_ITEM_METADATA: function DID_UPDATE_ITEM_METADATA(_ref3) {\n var id = _ref3.id,\n action = _ref3.action,\n change = _ref3.change;\n // don't do anything\n if (change.silent) return;\n\n // if is called multiple times in close succession we combined all calls together to save resources\n clearTimeout(state.itemUpdateTimeout);\n state.itemUpdateTimeout = setTimeout(function() {\n var item = getItemById(state.items, id);\n\n // only revert and attempt to upload when we're uploading to a server\n if (!query('IS_ASYNC')) {\n // should we update the output data\n applyFilterChain('SHOULD_PREPARE_OUTPUT', false, {\n item: item,\n query: query,\n action: action,\n change: change,\n }).then(function(shouldPrepareOutput) {\n // plugins determined the output data should be prepared (or not), can be adjusted with beforePrepareOutput hook\n var beforePrepareFile = query('GET_BEFORE_PREPARE_FILE');\n if (beforePrepareFile)\n shouldPrepareOutput = beforePrepareFile(item, shouldPrepareOutput);\n\n if (!shouldPrepareOutput) return;\n\n dispatch(\n 'REQUEST_PREPARE_OUTPUT',\n {\n query: id,\n item: item,\n success: function success(file) {\n dispatch('DID_PREPARE_OUTPUT', { id: id, file: file });\n },\n },\n\n true\n );\n });\n\n return;\n }\n\n // if is local item we need to enable upload button so change can be propagated to server\n if (item.origin === FileOrigin.LOCAL) {\n dispatch('DID_LOAD_ITEM', {\n id: item.id,\n error: null,\n serverFileReference: item.source,\n });\n }\n\n // for async scenarios\n var upload = function upload() {\n // we push this forward a bit so the interface is updated correctly\n setTimeout(function() {\n dispatch('REQUEST_ITEM_PROCESSING', { query: id });\n }, 32);\n };\n\n var revert = function revert(doUpload) {\n item.revert(\n createRevertFunction(\n state.options.server.url,\n state.options.server.revert\n ),\n query('GET_FORCE_REVERT')\n )\n .then(doUpload ? upload : function() {})\n .catch(function() {});\n };\n\n var abort = function abort(doUpload) {\n item.abortProcessing().then(doUpload ? upload : function() {});\n };\n\n // if we should re-upload the file immediately\n if (item.status === ItemStatus.PROCESSING_COMPLETE) {\n return revert(state.options.instantUpload);\n }\n\n // if currently uploading, cancel upload\n if (item.status === ItemStatus.PROCESSING) {\n return abort(state.options.instantUpload);\n }\n\n if (state.options.instantUpload) {\n upload();\n }\n }, 0);\n },\n\n MOVE_ITEM: function MOVE_ITEM(_ref4) {\n var query = _ref4.query,\n index = _ref4.index;\n var item = getItemByQuery(state.items, query);\n if (!item) return;\n var currentIndex = state.items.indexOf(item);\n index = limit(index, 0, state.items.length - 1);\n if (currentIndex === index) return;\n state.items.splice(index, 0, state.items.splice(currentIndex, 1)[0]);\n },\n\n SORT: function SORT(_ref5) {\n var compare = _ref5.compare;\n sortItems(state, compare);\n dispatch('DID_SORT_ITEMS', {\n items: query('GET_ACTIVE_ITEMS'),\n });\n },\n\n ADD_ITEMS: function ADD_ITEMS(_ref6) {\n var items = _ref6.items,\n index = _ref6.index,\n interactionMethod = _ref6.interactionMethod,\n _ref6$success = _ref6.success,\n success = _ref6$success === void 0 ? function() {} : _ref6$success,\n _ref6$failure = _ref6.failure,\n failure = _ref6$failure === void 0 ? function() {} : _ref6$failure;\n var currentIndex = index;\n\n if (index === -1 || typeof index === 'undefined') {\n var insertLocation = query('GET_ITEM_INSERT_LOCATION');\n var totalItems = query('GET_TOTAL_ITEMS');\n currentIndex = insertLocation === 'before' ? 0 : totalItems;\n }\n\n var ignoredFiles = query('GET_IGNORED_FILES');\n var isValidFile = function isValidFile(source) {\n return isFile(source)\n ? !ignoredFiles.includes(source.name.toLowerCase())\n : !isEmpty(source);\n };\n var validItems = items.filter(isValidFile);\n\n var promises = validItems.map(function(source) {\n return new Promise(function(resolve, reject) {\n dispatch('ADD_ITEM', {\n interactionMethod: interactionMethod,\n source: source.source || source,\n success: resolve,\n failure: reject,\n index: currentIndex++,\n options: source.options || {},\n });\n });\n });\n\n Promise.all(promises)\n .then(success)\n .catch(failure);\n },\n\n /**\n * @param source\n * @param index\n * @param interactionMethod\n */\n ADD_ITEM: function ADD_ITEM(_ref7) {\n var source = _ref7.source,\n _ref7$index = _ref7.index,\n index = _ref7$index === void 0 ? -1 : _ref7$index,\n interactionMethod = _ref7.interactionMethod,\n _ref7$success = _ref7.success,\n success = _ref7$success === void 0 ? function() {} : _ref7$success,\n _ref7$failure = _ref7.failure,\n failure = _ref7$failure === void 0 ? function() {} : _ref7$failure,\n _ref7$options = _ref7.options,\n options = _ref7$options === void 0 ? {} : _ref7$options;\n // if no source supplied\n if (isEmpty(source)) {\n failure({\n error: createResponse('error', 0, 'No source'),\n file: null,\n });\n\n return;\n }\n\n // filter out invalid file items, used to filter dropped directory contents\n if (\n isFile(source) &&\n state.options.ignoredFiles.includes(source.name.toLowerCase())\n ) {\n // fail silently\n return;\n }\n\n // test if there's still room in the list of files\n if (!hasRoomForItem(state)) {\n // if multiple allowed, we can't replace\n // or if only a single item is allowed but we're not allowed to replace it we exit\n if (\n state.options.allowMultiple ||\n (!state.options.allowMultiple && !state.options.allowReplace)\n ) {\n var error = createResponse('warning', 0, 'Max files');\n\n dispatch('DID_THROW_MAX_FILES', {\n source: source,\n error: error,\n });\n\n failure({ error: error, file: null });\n\n return;\n }\n\n // let's replace the item\n // id of first item we're about to remove\n var _item = getActiveItems(state.items)[0];\n\n // if has been processed remove it from the server as well\n if (\n _item.status === ItemStatus.PROCESSING_COMPLETE ||\n _item.status === ItemStatus.PROCESSING_REVERT_ERROR\n ) {\n var forceRevert = query('GET_FORCE_REVERT');\n _item\n .revert(\n createRevertFunction(\n state.options.server.url,\n state.options.server.revert\n ),\n forceRevert\n )\n .then(function() {\n if (!forceRevert) return;\n\n // try to add now\n dispatch('ADD_ITEM', {\n source: source,\n index: index,\n interactionMethod: interactionMethod,\n success: success,\n failure: failure,\n options: options,\n });\n })\n .catch(function() {}); // no need to handle this catch state for now\n\n if (forceRevert) return;\n }\n\n // remove first item as it will be replaced by this item\n dispatch('REMOVE_ITEM', { query: _item.id });\n }\n\n // where did the file originate\n var origin =\n options.type === 'local'\n ? FileOrigin.LOCAL\n : options.type === 'limbo'\n ? FileOrigin.LIMBO\n : FileOrigin.INPUT;\n\n // create a new blank item\n var item = createItem(\n // where did this file come from\n origin,\n\n // an input file never has a server file reference\n origin === FileOrigin.INPUT ? null : source,\n\n // file mock data, if defined\n options.file\n );\n\n // set initial meta data\n Object.keys(options.metadata || {}).forEach(function(key) {\n item.setMetadata(key, options.metadata[key]);\n });\n\n // created the item, let plugins add methods\n applyFilters('DID_CREATE_ITEM', item, { query: query, dispatch: dispatch });\n\n // where to insert new items\n var itemInsertLocation = query('GET_ITEM_INSERT_LOCATION');\n\n // adjust index if is not allowed to pick location\n if (!state.options.itemInsertLocationFreedom) {\n index = itemInsertLocation === 'before' ? -1 : state.items.length;\n }\n\n // add item to list\n insertItem(state.items, item, index);\n\n // sort items in list\n if (isFunction(itemInsertLocation) && source) {\n sortItems(state, itemInsertLocation);\n }\n\n // get a quick reference to the item id\n var id = item.id;\n\n // observe item events\n item.on('init', function() {\n dispatch('DID_INIT_ITEM', { id: id });\n });\n\n item.on('load-init', function() {\n dispatch('DID_START_ITEM_LOAD', { id: id });\n });\n\n item.on('load-meta', function() {\n dispatch('DID_UPDATE_ITEM_META', { id: id });\n });\n\n item.on('load-progress', function(progress) {\n dispatch('DID_UPDATE_ITEM_LOAD_PROGRESS', { id: id, progress: progress });\n });\n\n item.on('load-request-error', function(error) {\n var mainStatus = dynamicLabel(state.options.labelFileLoadError)(error);\n\n // is client error, no way to recover\n if (error.code >= 400 && error.code < 500) {\n dispatch('DID_THROW_ITEM_INVALID', {\n id: id,\n error: error,\n status: {\n main: mainStatus,\n sub: error.code + ' (' + error.body + ')',\n },\n });\n\n // reject the file so can be dealt with through API\n failure({ error: error, file: createItemAPI(item) });\n return;\n }\n\n // is possible server error, so might be possible to retry\n dispatch('DID_THROW_ITEM_LOAD_ERROR', {\n id: id,\n error: error,\n status: {\n main: mainStatus,\n sub: state.options.labelTapToRetry,\n },\n });\n });\n\n item.on('load-file-error', function(error) {\n dispatch('DID_THROW_ITEM_INVALID', {\n id: id,\n error: error.status,\n status: error.status,\n });\n\n failure({ error: error.status, file: createItemAPI(item) });\n });\n\n item.on('load-abort', function() {\n dispatch('REMOVE_ITEM', { query: id });\n });\n\n item.on('load-skip', function() {\n dispatch('COMPLETE_LOAD_ITEM', {\n query: id,\n item: item,\n data: {\n source: source,\n success: success,\n },\n });\n });\n\n item.on('load', function() {\n var handleAdd = function handleAdd(shouldAdd) {\n // no should not add this file\n if (!shouldAdd) {\n dispatch('REMOVE_ITEM', {\n query: id,\n });\n\n return;\n }\n\n // now interested in metadata updates\n item.on('metadata-update', function(change) {\n dispatch('DID_UPDATE_ITEM_METADATA', { id: id, change: change });\n });\n\n // let plugins decide if the output data should be prepared at this point\n // means we'll do this and wait for idle state\n applyFilterChain('SHOULD_PREPARE_OUTPUT', false, {\n item: item,\n query: query,\n }).then(function(shouldPrepareOutput) {\n // plugins determined the output data should be prepared (or not), can be adjusted with beforePrepareOutput hook\n var beforePrepareFile = query('GET_BEFORE_PREPARE_FILE');\n if (beforePrepareFile)\n shouldPrepareOutput = beforePrepareFile(item, shouldPrepareOutput);\n\n var loadComplete = function loadComplete() {\n dispatch('COMPLETE_LOAD_ITEM', {\n query: id,\n item: item,\n data: {\n source: source,\n success: success,\n },\n });\n\n listUpdated(dispatch, state);\n };\n\n // exit\n if (shouldPrepareOutput) {\n // wait for idle state and then run PREPARE_OUTPUT\n dispatch(\n 'REQUEST_PREPARE_OUTPUT',\n {\n query: id,\n item: item,\n success: function success(file) {\n dispatch('DID_PREPARE_OUTPUT', { id: id, file: file });\n loadComplete();\n },\n },\n\n true\n );\n\n return;\n }\n\n loadComplete();\n });\n };\n\n // item loaded, allow plugins to\n // - read data (quickly)\n // - add metadata\n applyFilterChain('DID_LOAD_ITEM', item, { query: query, dispatch: dispatch })\n .then(function() {\n optionalPromise(query('GET_BEFORE_ADD_FILE'), createItemAPI(item)).then(\n handleAdd\n );\n })\n .catch(function(e) {\n if (!e || !e.error || !e.status) return handleAdd(false);\n dispatch('DID_THROW_ITEM_INVALID', {\n id: id,\n error: e.error,\n status: e.status,\n });\n });\n });\n\n item.on('process-start', function() {\n dispatch('DID_START_ITEM_PROCESSING', { id: id });\n });\n\n item.on('process-progress', function(progress) {\n dispatch('DID_UPDATE_ITEM_PROCESS_PROGRESS', { id: id, progress: progress });\n });\n\n item.on('process-error', function(error) {\n dispatch('DID_THROW_ITEM_PROCESSING_ERROR', {\n id: id,\n error: error,\n status: {\n main: dynamicLabel(state.options.labelFileProcessingError)(error),\n sub: state.options.labelTapToRetry,\n },\n });\n });\n\n item.on('process-revert-error', function(error) {\n dispatch('DID_THROW_ITEM_PROCESSING_REVERT_ERROR', {\n id: id,\n error: error,\n status: {\n main: dynamicLabel(state.options.labelFileProcessingRevertError)(error),\n sub: state.options.labelTapToRetry,\n },\n });\n });\n\n item.on('process-complete', function(serverFileReference) {\n dispatch('DID_COMPLETE_ITEM_PROCESSING', {\n id: id,\n error: null,\n serverFileReference: serverFileReference,\n });\n\n dispatch('DID_DEFINE_VALUE', { id: id, value: serverFileReference });\n });\n\n item.on('process-abort', function() {\n dispatch('DID_ABORT_ITEM_PROCESSING', { id: id });\n });\n\n item.on('process-revert', function() {\n dispatch('DID_REVERT_ITEM_PROCESSING', { id: id });\n dispatch('DID_DEFINE_VALUE', { id: id, value: null });\n });\n\n // let view know the item has been inserted\n dispatch('DID_ADD_ITEM', {\n id: id,\n index: index,\n interactionMethod: interactionMethod,\n });\n\n listUpdated(dispatch, state);\n\n // start loading the source\n var _ref8 = state.options.server || {},\n url = _ref8.url,\n load = _ref8.load,\n restore = _ref8.restore,\n fetch = _ref8.fetch;\n\n item.load(\n source,\n\n // this creates a function that loads the file based on the type of file (string, base64, blob, file) and location of file (local, remote, limbo)\n createFileLoader(\n origin === FileOrigin.INPUT\n ? // input, if is remote, see if should use custom fetch, else use default fetchBlob\n isString(source) && isExternalURL(source)\n ? fetch\n ? createFetchFunction(url, fetch)\n : fetchBlob // remote url\n : fetchBlob // try to fetch url\n : // limbo or local\n origin === FileOrigin.LIMBO\n ? createFetchFunction(url, restore) // limbo\n : createFetchFunction(url, load) // local\n ),\n\n // called when the file is loaded so it can be piped through the filters\n function(file, success, error) {\n // let's process the file\n applyFilterChain('LOAD_FILE', file, { query: query })\n .then(success)\n .catch(error);\n }\n );\n },\n\n REQUEST_PREPARE_OUTPUT: function REQUEST_PREPARE_OUTPUT(_ref9) {\n var item = _ref9.item,\n success = _ref9.success,\n _ref9$failure = _ref9.failure,\n failure = _ref9$failure === void 0 ? function() {} : _ref9$failure;\n // error response if item archived\n var err = {\n error: createResponse('error', 0, 'Item not found'),\n file: null,\n };\n\n // don't handle archived items, an item could have been archived (load aborted) while waiting to be prepared\n if (item.archived) return failure(err);\n\n // allow plugins to alter the file data\n applyFilterChain('PREPARE_OUTPUT', item.file, { query: query, item: item }).then(\n function(result) {\n applyFilterChain('COMPLETE_PREPARE_OUTPUT', result, {\n query: query,\n item: item,\n }).then(function(result) {\n // don't handle archived items, an item could have been archived (load aborted) while being prepared\n if (item.archived) return failure(err);\n\n // we done!\n success(result);\n });\n }\n );\n },\n\n COMPLETE_LOAD_ITEM: function COMPLETE_LOAD_ITEM(_ref10) {\n var item = _ref10.item,\n data = _ref10.data;\n var success = data.success,\n source = data.source;\n\n // sort items in list\n var itemInsertLocation = query('GET_ITEM_INSERT_LOCATION');\n if (isFunction(itemInsertLocation) && source) {\n sortItems(state, itemInsertLocation);\n }\n\n // let interface know the item has loaded\n dispatch('DID_LOAD_ITEM', {\n id: item.id,\n error: null,\n serverFileReference: item.origin === FileOrigin.INPUT ? null : source,\n });\n\n // item has been successfully loaded and added to the\n // list of items so can now be safely returned for use\n success(createItemAPI(item));\n\n // if this is a local server file we need to show a different state\n if (item.origin === FileOrigin.LOCAL) {\n dispatch('DID_LOAD_LOCAL_ITEM', { id: item.id });\n return;\n }\n\n // if is a temp server file we prevent async upload call here (as the file is already on the server)\n if (item.origin === FileOrigin.LIMBO) {\n dispatch('DID_COMPLETE_ITEM_PROCESSING', {\n id: item.id,\n error: null,\n serverFileReference: source,\n });\n\n dispatch('DID_DEFINE_VALUE', {\n id: item.id,\n value: item.serverId || source,\n });\n\n return;\n }\n\n // id we are allowed to upload the file immediately, lets do it\n if (query('IS_ASYNC') && state.options.instantUpload) {\n dispatch('REQUEST_ITEM_PROCESSING', { query: item.id });\n }\n },\n\n RETRY_ITEM_LOAD: getItemByQueryFromState(state, function(item) {\n // try loading the source one more time\n item.retryLoad();\n }),\n\n REQUEST_ITEM_PREPARE: getItemByQueryFromState(state, function(item, _success, failure) {\n dispatch(\n 'REQUEST_PREPARE_OUTPUT',\n {\n query: item.id,\n item: item,\n success: function success(file) {\n dispatch('DID_PREPARE_OUTPUT', { id: item.id, file: file });\n _success({\n file: item,\n output: file,\n });\n },\n failure: failure,\n },\n\n true\n );\n }),\n\n REQUEST_ITEM_PROCESSING: getItemByQueryFromState(state, function(\n item,\n success,\n failure\n ) {\n // cannot be queued (or is already queued)\n var itemCanBeQueuedForProcessing =\n // waiting for something\n item.status === ItemStatus.IDLE ||\n // processing went wrong earlier\n item.status === ItemStatus.PROCESSING_ERROR;\n\n // not ready to be processed\n if (!itemCanBeQueuedForProcessing) {\n var processNow = function processNow() {\n return dispatch('REQUEST_ITEM_PROCESSING', {\n query: item,\n success: success,\n failure: failure,\n });\n };\n\n var process = function process() {\n return document.hidden ? processNow() : setTimeout(processNow, 32);\n };\n\n // if already done processing or tried to revert but didn't work, try again\n if (\n item.status === ItemStatus.PROCESSING_COMPLETE ||\n item.status === ItemStatus.PROCESSING_REVERT_ERROR\n ) {\n item.revert(\n createRevertFunction(\n state.options.server.url,\n state.options.server.revert\n ),\n query('GET_FORCE_REVERT')\n )\n .then(process)\n .catch(function() {}); // don't continue with processing if something went wrong\n } else if (item.status === ItemStatus.PROCESSING) {\n item.abortProcessing().then(process);\n }\n\n return;\n }\n\n // already queued for processing\n if (item.status === ItemStatus.PROCESSING_QUEUED) return;\n\n item.requestProcessing();\n\n dispatch('DID_REQUEST_ITEM_PROCESSING', { id: item.id });\n\n dispatch('PROCESS_ITEM', { query: item, success: success, failure: failure }, true);\n }),\n\n PROCESS_ITEM: getItemByQueryFromState(state, function(item, success, failure) {\n var maxParallelUploads = query('GET_MAX_PARALLEL_UPLOADS');\n var totalCurrentUploads = query('GET_ITEMS_BY_STATUS', ItemStatus.PROCESSING)\n .length;\n\n // queue and wait till queue is freed up\n if (totalCurrentUploads === maxParallelUploads) {\n // queue for later processing\n state.processingQueue.push({\n id: item.id,\n success: success,\n failure: failure,\n });\n\n // stop it!\n return;\n }\n\n // if was not queued or is already processing exit here\n if (item.status === ItemStatus.PROCESSING) return;\n\n var processNext = function processNext() {\n // process queueud items\n var queueEntry = state.processingQueue.shift();\n\n // no items left\n if (!queueEntry) return;\n\n // get item reference\n var id = queueEntry.id,\n success = queueEntry.success,\n failure = queueEntry.failure;\n var itemReference = getItemByQuery(state.items, id);\n\n // if item was archived while in queue, jump to next\n if (!itemReference || itemReference.archived) {\n processNext();\n return;\n }\n\n // process queued item\n dispatch(\n 'PROCESS_ITEM',\n { query: id, success: success, failure: failure },\n true\n );\n };\n\n // we done function\n item.onOnce('process-complete', function() {\n success(createItemAPI(item));\n processNext();\n\n // if origin is local, and we're instant uploading, trigger remove of original\n // as revert will remove file from list\n var server = state.options.server;\n var instantUpload = state.options.instantUpload;\n if (\n instantUpload &&\n item.origin === FileOrigin.LOCAL &&\n isFunction(server.remove)\n ) {\n var noop = function noop() {};\n item.origin = FileOrigin.LIMBO;\n state.options.server.remove(item.source, noop, noop);\n }\n\n // All items processed? No errors?\n var allItemsProcessed =\n query('GET_ITEMS_BY_STATUS', ItemStatus.PROCESSING_COMPLETE).length ===\n state.items.length;\n if (allItemsProcessed) {\n dispatch('DID_COMPLETE_ITEM_PROCESSING_ALL');\n }\n });\n\n // we error function\n item.onOnce('process-error', function(error) {\n failure({ error: error, file: createItemAPI(item) });\n processNext();\n });\n\n // start file processing\n var options = state.options;\n item.process(\n createFileProcessor(\n createProcessorFunction(\n options.server.url,\n options.server.process,\n options.name,\n {\n chunkTransferId: item.transferId,\n chunkServer: options.server.patch,\n chunkUploads: options.chunkUploads,\n chunkForce: options.chunkForce,\n chunkSize: options.chunkSize,\n chunkRetryDelays: options.chunkRetryDelays,\n }\n ),\n\n {\n allowMinimumUploadDuration: query('GET_ALLOW_MINIMUM_UPLOAD_DURATION'),\n }\n ),\n\n // called when the file is about to be processed so it can be piped through the transform filters\n function(file, success, error) {\n // allow plugins to alter the file data\n applyFilterChain('PREPARE_OUTPUT', file, { query: query, item: item })\n .then(function(file) {\n dispatch('DID_PREPARE_OUTPUT', { id: item.id, file: file });\n\n success(file);\n })\n .catch(error);\n }\n );\n }),\n\n RETRY_ITEM_PROCESSING: getItemByQueryFromState(state, function(item) {\n dispatch('REQUEST_ITEM_PROCESSING', { query: item });\n }),\n\n REQUEST_REMOVE_ITEM: getItemByQueryFromState(state, function(item) {\n optionalPromise(query('GET_BEFORE_REMOVE_FILE'), createItemAPI(item)).then(function(\n shouldRemove\n ) {\n if (!shouldRemove) {\n return;\n }\n dispatch('REMOVE_ITEM', { query: item });\n });\n }),\n\n RELEASE_ITEM: getItemByQueryFromState(state, function(item) {\n item.release();\n }),\n\n REMOVE_ITEM: getItemByQueryFromState(state, function(item, success, failure, options) {\n var removeFromView = function removeFromView() {\n // get id reference\n var id = item.id;\n\n // archive the item, this does not remove it from the list\n getItemById(state.items, id).archive();\n\n // tell the view the item has been removed\n dispatch('DID_REMOVE_ITEM', { error: null, id: id, item: item });\n\n // now the list has been modified\n listUpdated(dispatch, state);\n\n // correctly removed\n success(createItemAPI(item));\n };\n\n // if this is a local file and the `server.remove` function has been configured,\n // send source there so dev can remove file from server\n var server = state.options.server;\n if (\n item.origin === FileOrigin.LOCAL &&\n server &&\n isFunction(server.remove) &&\n options.remove !== false\n ) {\n dispatch('DID_START_ITEM_REMOVE', { id: item.id });\n\n server.remove(\n item.source,\n function() {\n return removeFromView();\n },\n function(status) {\n dispatch('DID_THROW_ITEM_REMOVE_ERROR', {\n id: item.id,\n error: createResponse('error', 0, status, null),\n status: {\n main: dynamicLabel(state.options.labelFileRemoveError)(status),\n sub: state.options.labelTapToRetry,\n },\n });\n }\n );\n } else {\n // if is requesting revert and can revert need to call revert handler (not calling request_ because that would also trigger beforeRemoveHook)\n if (\n (options.revert &&\n item.origin !== FileOrigin.LOCAL &&\n item.serverId !== null) ||\n // if chunked uploads are enabled and we're uploading in chunks for this specific file\n // or if the file isn't big enough for chunked uploads but chunkForce is set then call\n // revert before removing from the view...\n (state.options.chunkUploads && item.file.size > state.options.chunkSize) ||\n (state.options.chunkUploads && state.options.chunkForce)\n ) {\n item.revert(\n createRevertFunction(\n state.options.server.url,\n state.options.server.revert\n ),\n query('GET_FORCE_REVERT')\n );\n }\n\n // can now safely remove from view\n removeFromView();\n }\n }),\n\n ABORT_ITEM_LOAD: getItemByQueryFromState(state, function(item) {\n item.abortLoad();\n }),\n\n ABORT_ITEM_PROCESSING: getItemByQueryFromState(state, function(item) {\n // test if is already processed\n if (item.serverId) {\n dispatch('REVERT_ITEM_PROCESSING', { id: item.id });\n return;\n }\n\n // abort\n item.abortProcessing().then(function() {\n var shouldRemove = state.options.instantUpload;\n if (shouldRemove) {\n dispatch('REMOVE_ITEM', { query: item.id });\n }\n });\n }),\n\n REQUEST_REVERT_ITEM_PROCESSING: getItemByQueryFromState(state, function(item) {\n // not instant uploading, revert immediately\n if (!state.options.instantUpload) {\n dispatch('REVERT_ITEM_PROCESSING', { query: item });\n return;\n }\n\n // if we're instant uploading the file will also be removed if we revert,\n // so if a before remove file hook is defined we need to run it now\n var handleRevert = function handleRevert(shouldRevert) {\n if (!shouldRevert) return;\n dispatch('REVERT_ITEM_PROCESSING', { query: item });\n };\n\n var fn = query('GET_BEFORE_REMOVE_FILE');\n if (!fn) {\n return handleRevert(true);\n }\n\n var requestRemoveResult = fn(createItemAPI(item));\n if (requestRemoveResult == null) {\n // undefined or null\n return handleRevert(true);\n }\n\n if (typeof requestRemoveResult === 'boolean') {\n return handleRevert(requestRemoveResult);\n }\n\n if (typeof requestRemoveResult.then === 'function') {\n requestRemoveResult.then(handleRevert);\n }\n }),\n\n REVERT_ITEM_PROCESSING: getItemByQueryFromState(state, function(item) {\n item.revert(\n createRevertFunction(state.options.server.url, state.options.server.revert),\n query('GET_FORCE_REVERT')\n )\n .then(function() {\n var shouldRemove = state.options.instantUpload || isMockItem(item);\n if (shouldRemove) {\n dispatch('REMOVE_ITEM', { query: item.id });\n }\n })\n .catch(function() {});\n }),\n\n SET_OPTIONS: function SET_OPTIONS(_ref11) {\n var options = _ref11.options;\n // get all keys passed\n var optionKeys = Object.keys(options);\n\n // get prioritized keyed to include (remove once not in options object)\n var prioritizedOptionKeys = PrioritizedOptions.filter(function(key) {\n return optionKeys.includes(key);\n });\n\n // order the keys, prioritized first, then rest\n var orderedOptionKeys = [].concat(\n _toConsumableArray(prioritizedOptionKeys),\n _toConsumableArray(\n Object.keys(options).filter(function(key) {\n return !prioritizedOptionKeys.includes(key);\n })\n )\n );\n\n // dispatch set event for each option\n orderedOptionKeys.forEach(function(key) {\n dispatch('SET_' + fromCamels(key, '_').toUpperCase(), {\n value: options[key],\n });\n });\n },\n };\n };\n\n var PrioritizedOptions = ['server'];\n\n var formatFilename = function formatFilename(name) {\n return name;\n };\n\n var createElement$1 = function createElement(tagName) {\n return document.createElement(tagName);\n };\n\n var text = function text(node, value) {\n var textNode = node.childNodes[0];\n if (!textNode) {\n textNode = document.createTextNode(value);\n node.appendChild(textNode);\n } else if (value !== textNode.nodeValue) {\n textNode.nodeValue = value;\n }\n };\n\n var polarToCartesian = function polarToCartesian(centerX, centerY, radius, angleInDegrees) {\n var angleInRadians = (((angleInDegrees % 360) - 90) * Math.PI) / 180.0;\n return {\n x: centerX + radius * Math.cos(angleInRadians),\n y: centerY + radius * Math.sin(angleInRadians),\n };\n };\n\n var describeArc = function describeArc(x, y, radius, startAngle, endAngle, arcSweep) {\n var start = polarToCartesian(x, y, radius, endAngle);\n var end = polarToCartesian(x, y, radius, startAngle);\n return ['M', start.x, start.y, 'A', radius, radius, 0, arcSweep, 0, end.x, end.y].join(' ');\n };\n\n var percentageArc = function percentageArc(x, y, radius, from, to) {\n var arcSweep = 1;\n if (to > from && to - from <= 0.5) {\n arcSweep = 0;\n }\n if (from > to && from - to >= 0.5) {\n arcSweep = 0;\n }\n return describeArc(\n x,\n y,\n radius,\n Math.min(0.9999, from) * 360,\n Math.min(0.9999, to) * 360,\n arcSweep\n );\n };\n\n var create = function create(_ref) {\n var root = _ref.root,\n props = _ref.props;\n // start at 0\n props.spin = false;\n props.progress = 0;\n props.opacity = 0;\n\n // svg\n var svg = createElement('svg');\n root.ref.path = createElement('path', {\n 'stroke-width': 2,\n 'stroke-linecap': 'round',\n });\n\n svg.appendChild(root.ref.path);\n\n root.ref.svg = svg;\n\n root.appendChild(svg);\n };\n\n var write = function write(_ref2) {\n var root = _ref2.root,\n props = _ref2.props;\n if (props.opacity === 0) {\n return;\n }\n\n if (props.align) {\n root.element.dataset.align = props.align;\n }\n\n // get width of stroke\n var ringStrokeWidth = parseInt(attr(root.ref.path, 'stroke-width'), 10);\n\n // calculate size of ring\n var size = root.rect.element.width * 0.5;\n\n // ring state\n var ringFrom = 0;\n var ringTo = 0;\n\n // now in busy mode\n if (props.spin) {\n ringFrom = 0;\n ringTo = 0.5;\n } else {\n ringFrom = 0;\n ringTo = props.progress;\n }\n\n // get arc path\n var coordinates = percentageArc(size, size, size - ringStrokeWidth, ringFrom, ringTo);\n\n // update progress bar\n attr(root.ref.path, 'd', coordinates);\n\n // hide while contains 0 value\n attr(root.ref.path, 'stroke-opacity', props.spin || props.progress > 0 ? 1 : 0);\n };\n\n var progressIndicator = createView({\n tag: 'div',\n name: 'progress-indicator',\n ignoreRectUpdate: true,\n ignoreRect: true,\n create: create,\n write: write,\n mixins: {\n apis: ['progress', 'spin', 'align'],\n styles: ['opacity'],\n animations: {\n opacity: { type: 'tween', duration: 500 },\n progress: {\n type: 'spring',\n stiffness: 0.95,\n damping: 0.65,\n mass: 10,\n },\n },\n },\n });\n\n var create$1 = function create(_ref) {\n var root = _ref.root,\n props = _ref.props;\n root.element.innerHTML = (props.icon || '') + ('' + props.label + '');\n\n props.isDisabled = false;\n };\n\n var write$1 = function write(_ref2) {\n var root = _ref2.root,\n props = _ref2.props;\n var isDisabled = props.isDisabled;\n var shouldDisable = root.query('GET_DISABLED') || props.opacity === 0;\n\n if (shouldDisable && !isDisabled) {\n props.isDisabled = true;\n attr(root.element, 'disabled', 'disabled');\n } else if (!shouldDisable && isDisabled) {\n props.isDisabled = false;\n root.element.removeAttribute('disabled');\n }\n };\n\n var fileActionButton = createView({\n tag: 'button',\n attributes: {\n type: 'button',\n },\n\n ignoreRect: true,\n ignoreRectUpdate: true,\n name: 'file-action-button',\n mixins: {\n apis: ['label'],\n styles: ['translateX', 'translateY', 'scaleX', 'scaleY', 'opacity'],\n animations: {\n scaleX: 'spring',\n scaleY: 'spring',\n translateX: 'spring',\n translateY: 'spring',\n opacity: { type: 'tween', duration: 250 },\n },\n\n listeners: true,\n },\n\n create: create$1,\n write: write$1,\n });\n\n var toNaturalFileSize = function toNaturalFileSize(bytes) {\n var decimalSeparator =\n arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : '.';\n var base = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 1000;\n var options = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {};\n var _options$labelBytes = options.labelBytes,\n labelBytes = _options$labelBytes === void 0 ? 'bytes' : _options$labelBytes,\n _options$labelKilobyt = options.labelKilobytes,\n labelKilobytes = _options$labelKilobyt === void 0 ? 'KB' : _options$labelKilobyt,\n _options$labelMegabyt = options.labelMegabytes,\n labelMegabytes = _options$labelMegabyt === void 0 ? 'MB' : _options$labelMegabyt,\n _options$labelGigabyt = options.labelGigabytes,\n labelGigabytes = _options$labelGigabyt === void 0 ? 'GB' : _options$labelGigabyt;\n\n // no negative byte sizes\n bytes = Math.round(Math.abs(bytes));\n\n var KB = base;\n var MB = base * base;\n var GB = base * base * base;\n\n // just bytes\n if (bytes < KB) {\n return bytes + ' ' + labelBytes;\n }\n\n // kilobytes\n if (bytes < MB) {\n return Math.floor(bytes / KB) + ' ' + labelKilobytes;\n }\n\n // megabytes\n if (bytes < GB) {\n return removeDecimalsWhenZero(bytes / MB, 1, decimalSeparator) + ' ' + labelMegabytes;\n }\n\n // gigabytes\n return removeDecimalsWhenZero(bytes / GB, 2, decimalSeparator) + ' ' + labelGigabytes;\n };\n\n var removeDecimalsWhenZero = function removeDecimalsWhenZero(value, decimalCount, separator) {\n return value\n .toFixed(decimalCount)\n .split('.')\n .filter(function(part) {\n return part !== '0';\n })\n .join(separator);\n };\n\n var create$2 = function create(_ref) {\n var root = _ref.root,\n props = _ref.props;\n // filename\n var fileName = createElement$1('span');\n fileName.className = 'filepond--file-info-main';\n // hide for screenreaders\n // the file is contained in a fieldset with legend that contains the filename\n // no need to read it twice\n attr(fileName, 'aria-hidden', 'true');\n root.appendChild(fileName);\n root.ref.fileName = fileName;\n\n // filesize\n var fileSize = createElement$1('span');\n fileSize.className = 'filepond--file-info-sub';\n root.appendChild(fileSize);\n root.ref.fileSize = fileSize;\n\n // set initial values\n text(fileSize, root.query('GET_LABEL_FILE_WAITING_FOR_SIZE'));\n text(fileName, formatFilename(root.query('GET_ITEM_NAME', props.id)));\n };\n\n var updateFile = function updateFile(_ref2) {\n var root = _ref2.root,\n props = _ref2.props;\n text(\n root.ref.fileSize,\n toNaturalFileSize(\n root.query('GET_ITEM_SIZE', props.id),\n '.',\n root.query('GET_FILE_SIZE_BASE'),\n root.query('GET_FILE_SIZE_LABELS', root.query)\n )\n );\n\n text(root.ref.fileName, formatFilename(root.query('GET_ITEM_NAME', props.id)));\n };\n\n var updateFileSizeOnError = function updateFileSizeOnError(_ref3) {\n var root = _ref3.root,\n props = _ref3.props;\n // if size is available don't fallback to unknown size message\n if (isInt(root.query('GET_ITEM_SIZE', props.id))) {\n updateFile({ root: root, props: props });\n return;\n }\n\n text(root.ref.fileSize, root.query('GET_LABEL_FILE_SIZE_NOT_AVAILABLE'));\n };\n\n var fileInfo = createView({\n name: 'file-info',\n ignoreRect: true,\n ignoreRectUpdate: true,\n write: createRoute({\n DID_LOAD_ITEM: updateFile,\n DID_UPDATE_ITEM_META: updateFile,\n DID_THROW_ITEM_LOAD_ERROR: updateFileSizeOnError,\n DID_THROW_ITEM_INVALID: updateFileSizeOnError,\n }),\n\n didCreateView: function didCreateView(root) {\n applyFilters('CREATE_VIEW', Object.assign({}, root, { view: root }));\n },\n create: create$2,\n mixins: {\n styles: ['translateX', 'translateY'],\n animations: {\n translateX: 'spring',\n translateY: 'spring',\n },\n },\n });\n\n var toPercentage = function toPercentage(value) {\n return Math.round(value * 100);\n };\n\n var create$3 = function create(_ref) {\n var root = _ref.root;\n\n // main status\n var main = createElement$1('span');\n main.className = 'filepond--file-status-main';\n root.appendChild(main);\n root.ref.main = main;\n\n // sub status\n var sub = createElement$1('span');\n sub.className = 'filepond--file-status-sub';\n root.appendChild(sub);\n root.ref.sub = sub;\n\n didSetItemLoadProgress({ root: root, action: { progress: null } });\n };\n\n var didSetItemLoadProgress = function didSetItemLoadProgress(_ref2) {\n var root = _ref2.root,\n action = _ref2.action;\n var title =\n action.progress === null\n ? root.query('GET_LABEL_FILE_LOADING')\n : root.query('GET_LABEL_FILE_LOADING') + ' ' + toPercentage(action.progress) + '%';\n\n text(root.ref.main, title);\n text(root.ref.sub, root.query('GET_LABEL_TAP_TO_CANCEL'));\n };\n\n var didSetItemProcessProgress = function didSetItemProcessProgress(_ref3) {\n var root = _ref3.root,\n action = _ref3.action;\n var title =\n action.progress === null\n ? root.query('GET_LABEL_FILE_PROCESSING')\n : root.query('GET_LABEL_FILE_PROCESSING') +\n ' ' +\n toPercentage(action.progress) +\n '%';\n\n text(root.ref.main, title);\n text(root.ref.sub, root.query('GET_LABEL_TAP_TO_CANCEL'));\n };\n\n var didRequestItemProcessing = function didRequestItemProcessing(_ref4) {\n var root = _ref4.root;\n text(root.ref.main, root.query('GET_LABEL_FILE_PROCESSING'));\n text(root.ref.sub, root.query('GET_LABEL_TAP_TO_CANCEL'));\n };\n\n var didAbortItemProcessing = function didAbortItemProcessing(_ref5) {\n var root = _ref5.root;\n text(root.ref.main, root.query('GET_LABEL_FILE_PROCESSING_ABORTED'));\n text(root.ref.sub, root.query('GET_LABEL_TAP_TO_RETRY'));\n };\n\n var didCompleteItemProcessing = function didCompleteItemProcessing(_ref6) {\n var root = _ref6.root;\n text(root.ref.main, root.query('GET_LABEL_FILE_PROCESSING_COMPLETE'));\n text(root.ref.sub, root.query('GET_LABEL_TAP_TO_UNDO'));\n };\n\n var clear = function clear(_ref7) {\n var root = _ref7.root;\n text(root.ref.main, '');\n text(root.ref.sub, '');\n };\n\n var error = function error(_ref8) {\n var root = _ref8.root,\n action = _ref8.action;\n text(root.ref.main, action.status.main);\n text(root.ref.sub, action.status.sub);\n };\n\n var fileStatus = createView({\n name: 'file-status',\n ignoreRect: true,\n ignoreRectUpdate: true,\n write: createRoute({\n DID_LOAD_ITEM: clear,\n DID_REVERT_ITEM_PROCESSING: clear,\n DID_REQUEST_ITEM_PROCESSING: didRequestItemProcessing,\n DID_ABORT_ITEM_PROCESSING: didAbortItemProcessing,\n DID_COMPLETE_ITEM_PROCESSING: didCompleteItemProcessing,\n DID_UPDATE_ITEM_PROCESS_PROGRESS: didSetItemProcessProgress,\n DID_UPDATE_ITEM_LOAD_PROGRESS: didSetItemLoadProgress,\n DID_THROW_ITEM_LOAD_ERROR: error,\n DID_THROW_ITEM_INVALID: error,\n DID_THROW_ITEM_PROCESSING_ERROR: error,\n DID_THROW_ITEM_PROCESSING_REVERT_ERROR: error,\n DID_THROW_ITEM_REMOVE_ERROR: error,\n }),\n\n didCreateView: function didCreateView(root) {\n applyFilters('CREATE_VIEW', Object.assign({}, root, { view: root }));\n },\n create: create$3,\n mixins: {\n styles: ['translateX', 'translateY', 'opacity'],\n animations: {\n opacity: { type: 'tween', duration: 250 },\n translateX: 'spring',\n translateY: 'spring',\n },\n },\n });\n\n /**\n * Button definitions for the file view\n */\n\n var Buttons = {\n AbortItemLoad: {\n label: 'GET_LABEL_BUTTON_ABORT_ITEM_LOAD',\n action: 'ABORT_ITEM_LOAD',\n className: 'filepond--action-abort-item-load',\n align: 'LOAD_INDICATOR_POSITION', // right\n },\n RetryItemLoad: {\n label: 'GET_LABEL_BUTTON_RETRY_ITEM_LOAD',\n action: 'RETRY_ITEM_LOAD',\n icon: 'GET_ICON_RETRY',\n className: 'filepond--action-retry-item-load',\n align: 'BUTTON_PROCESS_ITEM_POSITION', // right\n },\n RemoveItem: {\n label: 'GET_LABEL_BUTTON_REMOVE_ITEM',\n action: 'REQUEST_REMOVE_ITEM',\n icon: 'GET_ICON_REMOVE',\n className: 'filepond--action-remove-item',\n align: 'BUTTON_REMOVE_ITEM_POSITION', // left\n },\n ProcessItem: {\n label: 'GET_LABEL_BUTTON_PROCESS_ITEM',\n action: 'REQUEST_ITEM_PROCESSING',\n icon: 'GET_ICON_PROCESS',\n className: 'filepond--action-process-item',\n align: 'BUTTON_PROCESS_ITEM_POSITION', // right\n },\n AbortItemProcessing: {\n label: 'GET_LABEL_BUTTON_ABORT_ITEM_PROCESSING',\n action: 'ABORT_ITEM_PROCESSING',\n className: 'filepond--action-abort-item-processing',\n align: 'BUTTON_PROCESS_ITEM_POSITION', // right\n },\n RetryItemProcessing: {\n label: 'GET_LABEL_BUTTON_RETRY_ITEM_PROCESSING',\n action: 'RETRY_ITEM_PROCESSING',\n icon: 'GET_ICON_RETRY',\n className: 'filepond--action-retry-item-processing',\n align: 'BUTTON_PROCESS_ITEM_POSITION', // right\n },\n RevertItemProcessing: {\n label: 'GET_LABEL_BUTTON_UNDO_ITEM_PROCESSING',\n action: 'REQUEST_REVERT_ITEM_PROCESSING',\n icon: 'GET_ICON_UNDO',\n className: 'filepond--action-revert-item-processing',\n align: 'BUTTON_PROCESS_ITEM_POSITION', // right\n },\n };\n\n // make a list of buttons, we can then remove buttons from this list if they're disabled\n var ButtonKeys = [];\n forin(Buttons, function(key) {\n ButtonKeys.push(key);\n });\n\n var calculateFileInfoOffset = function calculateFileInfoOffset(root) {\n if (getRemoveIndicatorAligment(root) === 'right') return 0;\n var buttonRect = root.ref.buttonRemoveItem.rect.element;\n return buttonRect.hidden ? null : buttonRect.width + buttonRect.left;\n };\n\n var calculateButtonWidth = function calculateButtonWidth(root) {\n var buttonRect = root.ref.buttonAbortItemLoad.rect.element;\n return buttonRect.width;\n };\n\n // Force on full pixels so text stays crips\n var calculateFileVerticalCenterOffset = function calculateFileVerticalCenterOffset(root) {\n return Math.floor(root.ref.buttonRemoveItem.rect.element.height / 4);\n };\n var calculateFileHorizontalCenterOffset = function calculateFileHorizontalCenterOffset(root) {\n return Math.floor(root.ref.buttonRemoveItem.rect.element.left / 2);\n };\n\n var getLoadIndicatorAlignment = function getLoadIndicatorAlignment(root) {\n return root.query('GET_STYLE_LOAD_INDICATOR_POSITION');\n };\n var getProcessIndicatorAlignment = function getProcessIndicatorAlignment(root) {\n return root.query('GET_STYLE_PROGRESS_INDICATOR_POSITION');\n };\n var getRemoveIndicatorAligment = function getRemoveIndicatorAligment(root) {\n return root.query('GET_STYLE_BUTTON_REMOVE_ITEM_POSITION');\n };\n\n var DefaultStyle = {\n buttonAbortItemLoad: { opacity: 0 },\n buttonRetryItemLoad: { opacity: 0 },\n buttonRemoveItem: { opacity: 0 },\n buttonProcessItem: { opacity: 0 },\n buttonAbortItemProcessing: { opacity: 0 },\n buttonRetryItemProcessing: { opacity: 0 },\n buttonRevertItemProcessing: { opacity: 0 },\n loadProgressIndicator: { opacity: 0, align: getLoadIndicatorAlignment },\n processProgressIndicator: { opacity: 0, align: getProcessIndicatorAlignment },\n processingCompleteIndicator: { opacity: 0, scaleX: 0.75, scaleY: 0.75 },\n info: { translateX: 0, translateY: 0, opacity: 0 },\n status: { translateX: 0, translateY: 0, opacity: 0 },\n };\n\n var IdleStyle = {\n buttonRemoveItem: { opacity: 1 },\n buttonProcessItem: { opacity: 1 },\n info: { translateX: calculateFileInfoOffset },\n status: { translateX: calculateFileInfoOffset },\n };\n\n var ProcessingStyle = {\n buttonAbortItemProcessing: { opacity: 1 },\n processProgressIndicator: { opacity: 1 },\n status: { opacity: 1 },\n };\n\n var StyleMap = {\n DID_THROW_ITEM_INVALID: {\n buttonRemoveItem: { opacity: 1 },\n info: { translateX: calculateFileInfoOffset },\n status: { translateX: calculateFileInfoOffset, opacity: 1 },\n },\n\n DID_START_ITEM_LOAD: {\n buttonAbortItemLoad: { opacity: 1 },\n loadProgressIndicator: { opacity: 1 },\n status: { opacity: 1 },\n },\n\n DID_THROW_ITEM_LOAD_ERROR: {\n buttonRetryItemLoad: { opacity: 1 },\n buttonRemoveItem: { opacity: 1 },\n info: { translateX: calculateFileInfoOffset },\n status: { opacity: 1 },\n },\n\n DID_START_ITEM_REMOVE: {\n processProgressIndicator: { opacity: 1, align: getRemoveIndicatorAligment },\n info: { translateX: calculateFileInfoOffset },\n status: { opacity: 0 },\n },\n\n DID_THROW_ITEM_REMOVE_ERROR: {\n processProgressIndicator: { opacity: 0, align: getRemoveIndicatorAligment },\n buttonRemoveItem: { opacity: 1 },\n info: { translateX: calculateFileInfoOffset },\n status: { opacity: 1, translateX: calculateFileInfoOffset },\n },\n\n DID_LOAD_ITEM: IdleStyle,\n DID_LOAD_LOCAL_ITEM: {\n buttonRemoveItem: { opacity: 1 },\n info: { translateX: calculateFileInfoOffset },\n status: { translateX: calculateFileInfoOffset },\n },\n\n DID_START_ITEM_PROCESSING: ProcessingStyle,\n DID_REQUEST_ITEM_PROCESSING: ProcessingStyle,\n DID_UPDATE_ITEM_PROCESS_PROGRESS: ProcessingStyle,\n DID_COMPLETE_ITEM_PROCESSING: {\n buttonRevertItemProcessing: { opacity: 1 },\n info: { opacity: 1 },\n status: { opacity: 1 },\n },\n\n DID_THROW_ITEM_PROCESSING_ERROR: {\n buttonRemoveItem: { opacity: 1 },\n buttonRetryItemProcessing: { opacity: 1 },\n status: { opacity: 1 },\n info: { translateX: calculateFileInfoOffset },\n },\n\n DID_THROW_ITEM_PROCESSING_REVERT_ERROR: {\n buttonRevertItemProcessing: { opacity: 1 },\n status: { opacity: 1 },\n info: { opacity: 1 },\n },\n\n DID_ABORT_ITEM_PROCESSING: {\n buttonRemoveItem: { opacity: 1 },\n buttonProcessItem: { opacity: 1 },\n info: { translateX: calculateFileInfoOffset },\n status: { opacity: 1 },\n },\n\n DID_REVERT_ITEM_PROCESSING: IdleStyle,\n };\n\n // complete indicator view\n var processingCompleteIndicatorView = createView({\n create: function create(_ref) {\n var root = _ref.root;\n root.element.innerHTML = root.query('GET_ICON_DONE');\n },\n name: 'processing-complete-indicator',\n ignoreRect: true,\n mixins: {\n styles: ['scaleX', 'scaleY', 'opacity'],\n animations: {\n scaleX: 'spring',\n scaleY: 'spring',\n opacity: { type: 'tween', duration: 250 },\n },\n },\n });\n\n /**\n * Creates the file view\n */\n var create$4 = function create(_ref2) {\n var root = _ref2.root,\n props = _ref2.props;\n // copy Buttons object\n var LocalButtons = Object.keys(Buttons).reduce(function(prev, curr) {\n prev[curr] = Object.assign({}, Buttons[curr]);\n return prev;\n }, {});\n var id = props.id;\n\n // allow reverting upload\n var allowRevert = root.query('GET_ALLOW_REVERT');\n\n // allow remove file\n var allowRemove = root.query('GET_ALLOW_REMOVE');\n\n // allow processing upload\n var allowProcess = root.query('GET_ALLOW_PROCESS');\n\n // is instant uploading, need this to determine the icon of the undo button\n var instantUpload = root.query('GET_INSTANT_UPLOAD');\n\n // is async set up\n var isAsync = root.query('IS_ASYNC');\n\n // should align remove item buttons\n var alignRemoveItemButton = root.query('GET_STYLE_BUTTON_REMOVE_ITEM_ALIGN');\n\n // enabled buttons array\n var buttonFilter;\n if (isAsync) {\n if (allowProcess && !allowRevert) {\n // only remove revert button\n buttonFilter = function buttonFilter(key) {\n return !/RevertItemProcessing/.test(key);\n };\n } else if (!allowProcess && allowRevert) {\n // only remove process button\n buttonFilter = function buttonFilter(key) {\n return !/ProcessItem|RetryItemProcessing|AbortItemProcessing/.test(key);\n };\n } else if (!allowProcess && !allowRevert) {\n // remove all process buttons\n buttonFilter = function buttonFilter(key) {\n return !/Process/.test(key);\n };\n }\n } else {\n // no process controls available\n buttonFilter = function buttonFilter(key) {\n return !/Process/.test(key);\n };\n }\n\n var enabledButtons = buttonFilter ? ButtonKeys.filter(buttonFilter) : ButtonKeys.concat();\n\n // update icon and label for revert button when instant uploading\n if (instantUpload && allowRevert) {\n LocalButtons['RevertItemProcessing'].label = 'GET_LABEL_BUTTON_REMOVE_ITEM';\n LocalButtons['RevertItemProcessing'].icon = 'GET_ICON_REMOVE';\n }\n\n // remove last button (revert) if not allowed\n if (isAsync && !allowRevert) {\n var map = StyleMap['DID_COMPLETE_ITEM_PROCESSING'];\n map.info.translateX = calculateFileHorizontalCenterOffset;\n map.info.translateY = calculateFileVerticalCenterOffset;\n map.status.translateY = calculateFileVerticalCenterOffset;\n map.processingCompleteIndicator = { opacity: 1, scaleX: 1, scaleY: 1 };\n }\n\n // should align center\n if (isAsync && !allowProcess) {\n [\n 'DID_START_ITEM_PROCESSING',\n 'DID_REQUEST_ITEM_PROCESSING',\n 'DID_UPDATE_ITEM_PROCESS_PROGRESS',\n 'DID_THROW_ITEM_PROCESSING_ERROR',\n ].forEach(function(key) {\n StyleMap[key].status.translateY = calculateFileVerticalCenterOffset;\n });\n StyleMap['DID_THROW_ITEM_PROCESSING_ERROR'].status.translateX = calculateButtonWidth;\n }\n\n // move remove button to right\n if (alignRemoveItemButton && allowRevert) {\n LocalButtons['RevertItemProcessing'].align = 'BUTTON_REMOVE_ITEM_POSITION';\n var _map = StyleMap['DID_COMPLETE_ITEM_PROCESSING'];\n _map.info.translateX = calculateFileInfoOffset;\n _map.status.translateY = calculateFileVerticalCenterOffset;\n _map.processingCompleteIndicator = { opacity: 1, scaleX: 1, scaleY: 1 };\n }\n\n // show/hide RemoveItem button\n if (!allowRemove) {\n LocalButtons['RemoveItem'].disabled = true;\n }\n\n // create the button views\n forin(LocalButtons, function(key, definition) {\n // create button\n var buttonView = root.createChildView(fileActionButton, {\n label: root.query(definition.label),\n icon: root.query(definition.icon),\n opacity: 0,\n });\n\n // should be appended?\n if (enabledButtons.includes(key)) {\n root.appendChildView(buttonView);\n }\n\n // toggle\n if (definition.disabled) {\n buttonView.element.setAttribute('disabled', 'disabled');\n buttonView.element.setAttribute('hidden', 'hidden');\n }\n\n // add position attribute\n buttonView.element.dataset.align = root.query('GET_STYLE_' + definition.align);\n\n // add class\n buttonView.element.classList.add(definition.className);\n\n // handle interactions\n buttonView.on('click', function(e) {\n e.stopPropagation();\n if (definition.disabled) return;\n root.dispatch(definition.action, { query: id });\n });\n\n // set reference\n root.ref['button' + key] = buttonView;\n });\n\n // checkmark\n root.ref.processingCompleteIndicator = root.appendChildView(\n root.createChildView(processingCompleteIndicatorView)\n );\n\n root.ref.processingCompleteIndicator.element.dataset.align = root.query(\n 'GET_STYLE_BUTTON_PROCESS_ITEM_POSITION'\n );\n\n // create file info view\n root.ref.info = root.appendChildView(root.createChildView(fileInfo, { id: id }));\n\n // create file status view\n root.ref.status = root.appendChildView(root.createChildView(fileStatus, { id: id }));\n\n // add progress indicators\n var loadIndicatorView = root.appendChildView(\n root.createChildView(progressIndicator, {\n opacity: 0,\n align: root.query('GET_STYLE_LOAD_INDICATOR_POSITION'),\n })\n );\n\n loadIndicatorView.element.classList.add('filepond--load-indicator');\n root.ref.loadProgressIndicator = loadIndicatorView;\n\n var progressIndicatorView = root.appendChildView(\n root.createChildView(progressIndicator, {\n opacity: 0,\n align: root.query('GET_STYLE_PROGRESS_INDICATOR_POSITION'),\n })\n );\n\n progressIndicatorView.element.classList.add('filepond--process-indicator');\n root.ref.processProgressIndicator = progressIndicatorView;\n\n // current active styles\n root.ref.activeStyles = [];\n };\n\n var write$2 = function write(_ref3) {\n var root = _ref3.root,\n actions = _ref3.actions,\n props = _ref3.props;\n // route actions\n route({ root: root, actions: actions, props: props });\n\n // select last state change action\n var action = actions\n .concat()\n .filter(function(action) {\n return /^DID_/.test(action.type);\n })\n .reverse()\n .find(function(action) {\n return StyleMap[action.type];\n });\n\n // a new action happened, let's get the matching styles\n if (action) {\n // define new active styles\n root.ref.activeStyles = [];\n\n var stylesToApply = StyleMap[action.type];\n forin(DefaultStyle, function(name, defaultStyles) {\n // get reference to control\n var control = root.ref[name];\n\n // loop over all styles for this control\n forin(defaultStyles, function(key, defaultValue) {\n var value =\n stylesToApply[name] && typeof stylesToApply[name][key] !== 'undefined'\n ? stylesToApply[name][key]\n : defaultValue;\n root.ref.activeStyles.push({ control: control, key: key, value: value });\n });\n });\n }\n\n // apply active styles to element\n root.ref.activeStyles.forEach(function(_ref4) {\n var control = _ref4.control,\n key = _ref4.key,\n value = _ref4.value;\n control[key] = typeof value === 'function' ? value(root) : value;\n });\n };\n\n var route = createRoute({\n DID_SET_LABEL_BUTTON_ABORT_ITEM_PROCESSING: function DID_SET_LABEL_BUTTON_ABORT_ITEM_PROCESSING(\n _ref5\n ) {\n var root = _ref5.root,\n action = _ref5.action;\n root.ref.buttonAbortItemProcessing.label = action.value;\n },\n DID_SET_LABEL_BUTTON_ABORT_ITEM_LOAD: function DID_SET_LABEL_BUTTON_ABORT_ITEM_LOAD(_ref6) {\n var root = _ref6.root,\n action = _ref6.action;\n root.ref.buttonAbortItemLoad.label = action.value;\n },\n DID_SET_LABEL_BUTTON_ABORT_ITEM_REMOVAL: function DID_SET_LABEL_BUTTON_ABORT_ITEM_REMOVAL(\n _ref7\n ) {\n var root = _ref7.root,\n action = _ref7.action;\n root.ref.buttonAbortItemRemoval.label = action.value;\n },\n DID_REQUEST_ITEM_PROCESSING: function DID_REQUEST_ITEM_PROCESSING(_ref8) {\n var root = _ref8.root;\n root.ref.processProgressIndicator.spin = true;\n root.ref.processProgressIndicator.progress = 0;\n },\n DID_START_ITEM_LOAD: function DID_START_ITEM_LOAD(_ref9) {\n var root = _ref9.root;\n root.ref.loadProgressIndicator.spin = true;\n root.ref.loadProgressIndicator.progress = 0;\n },\n DID_START_ITEM_REMOVE: function DID_START_ITEM_REMOVE(_ref10) {\n var root = _ref10.root;\n root.ref.processProgressIndicator.spin = true;\n root.ref.processProgressIndicator.progress = 0;\n },\n DID_UPDATE_ITEM_LOAD_PROGRESS: function DID_UPDATE_ITEM_LOAD_PROGRESS(_ref11) {\n var root = _ref11.root,\n action = _ref11.action;\n root.ref.loadProgressIndicator.spin = false;\n root.ref.loadProgressIndicator.progress = action.progress;\n },\n DID_UPDATE_ITEM_PROCESS_PROGRESS: function DID_UPDATE_ITEM_PROCESS_PROGRESS(_ref12) {\n var root = _ref12.root,\n action = _ref12.action;\n root.ref.processProgressIndicator.spin = false;\n root.ref.processProgressIndicator.progress = action.progress;\n },\n });\n\n var file = createView({\n create: create$4,\n write: write$2,\n didCreateView: function didCreateView(root) {\n applyFilters('CREATE_VIEW', Object.assign({}, root, { view: root }));\n },\n name: 'file',\n });\n\n /**\n * Creates the file view\n */\n var create$5 = function create(_ref) {\n var root = _ref.root,\n props = _ref.props;\n\n // filename\n root.ref.fileName = createElement$1('legend');\n root.appendChild(root.ref.fileName);\n\n // file appended\n root.ref.file = root.appendChildView(root.createChildView(file, { id: props.id }));\n\n // data has moved to data.js\n root.ref.data = false;\n };\n\n /**\n * Data storage\n */\n var didLoadItem = function didLoadItem(_ref2) {\n var root = _ref2.root,\n props = _ref2.props;\n // updates the legend of the fieldset so screenreaders can better group buttons\n text(root.ref.fileName, formatFilename(root.query('GET_ITEM_NAME', props.id)));\n };\n\n var fileWrapper = createView({\n create: create$5,\n ignoreRect: true,\n write: createRoute({\n DID_LOAD_ITEM: didLoadItem,\n }),\n\n didCreateView: function didCreateView(root) {\n applyFilters('CREATE_VIEW', Object.assign({}, root, { view: root }));\n },\n tag: 'fieldset',\n name: 'file-wrapper',\n });\n\n var PANEL_SPRING_PROPS = { type: 'spring', damping: 0.6, mass: 7 };\n\n var create$6 = function create(_ref) {\n var root = _ref.root,\n props = _ref.props;\n [\n {\n name: 'top',\n },\n\n {\n name: 'center',\n props: {\n translateY: null,\n scaleY: null,\n },\n\n mixins: {\n animations: {\n scaleY: PANEL_SPRING_PROPS,\n },\n\n styles: ['translateY', 'scaleY'],\n },\n },\n\n {\n name: 'bottom',\n props: {\n translateY: null,\n },\n\n mixins: {\n animations: {\n translateY: PANEL_SPRING_PROPS,\n },\n\n styles: ['translateY'],\n },\n },\n ].forEach(function(section) {\n createSection(root, section, props.name);\n });\n\n root.element.classList.add('filepond--' + props.name);\n\n root.ref.scalable = null;\n };\n\n var createSection = function createSection(root, section, className) {\n var viewConstructor = createView({\n name: 'panel-' + section.name + ' filepond--' + className,\n mixins: section.mixins,\n ignoreRectUpdate: true,\n });\n\n var view = root.createChildView(viewConstructor, section.props);\n\n root.ref[section.name] = root.appendChildView(view);\n };\n\n var write$3 = function write(_ref2) {\n var root = _ref2.root,\n props = _ref2.props;\n\n // update scalable state\n if (root.ref.scalable === null || props.scalable !== root.ref.scalable) {\n root.ref.scalable = isBoolean(props.scalable) ? props.scalable : true;\n root.element.dataset.scalable = root.ref.scalable;\n }\n\n // no height, can't set\n if (!props.height) return;\n\n // get child rects\n var topRect = root.ref.top.rect.element;\n var bottomRect = root.ref.bottom.rect.element;\n\n // make sure height never is smaller than bottom and top seciton heights combined (will probably never happen, but who knows)\n var height = Math.max(topRect.height + bottomRect.height, props.height);\n\n // offset center part\n root.ref.center.translateY = topRect.height;\n\n // scale center part\n // use math ceil to prevent transparent lines because of rounding errors\n root.ref.center.scaleY = (height - topRect.height - bottomRect.height) / 100;\n\n // offset bottom part\n root.ref.bottom.translateY = height - bottomRect.height;\n };\n\n var panel = createView({\n name: 'panel',\n read: function read(_ref3) {\n var root = _ref3.root,\n props = _ref3.props;\n return (props.heightCurrent = root.ref.bottom.translateY);\n },\n write: write$3,\n create: create$6,\n ignoreRect: true,\n mixins: {\n apis: ['height', 'heightCurrent', 'scalable'],\n },\n });\n\n var createDragHelper = function createDragHelper(items) {\n var itemIds = items.map(function(item) {\n return item.id;\n });\n var prevIndex = undefined;\n return {\n setIndex: function setIndex(index) {\n prevIndex = index;\n },\n getIndex: function getIndex() {\n return prevIndex;\n },\n getItemIndex: function getItemIndex(item) {\n return itemIds.indexOf(item.id);\n },\n };\n };\n\n var ITEM_TRANSLATE_SPRING = {\n type: 'spring',\n stiffness: 0.75,\n damping: 0.45,\n mass: 10,\n };\n\n var ITEM_SCALE_SPRING = 'spring';\n\n var StateMap = {\n DID_START_ITEM_LOAD: 'busy',\n DID_UPDATE_ITEM_LOAD_PROGRESS: 'loading',\n DID_THROW_ITEM_INVALID: 'load-invalid',\n DID_THROW_ITEM_LOAD_ERROR: 'load-error',\n DID_LOAD_ITEM: 'idle',\n DID_THROW_ITEM_REMOVE_ERROR: 'remove-error',\n DID_START_ITEM_REMOVE: 'busy',\n DID_START_ITEM_PROCESSING: 'busy processing',\n DID_REQUEST_ITEM_PROCESSING: 'busy processing',\n DID_UPDATE_ITEM_PROCESS_PROGRESS: 'processing',\n DID_COMPLETE_ITEM_PROCESSING: 'processing-complete',\n DID_THROW_ITEM_PROCESSING_ERROR: 'processing-error',\n DID_THROW_ITEM_PROCESSING_REVERT_ERROR: 'processing-revert-error',\n DID_ABORT_ITEM_PROCESSING: 'cancelled',\n DID_REVERT_ITEM_PROCESSING: 'idle',\n };\n\n /**\n * Creates the file view\n */\n var create$7 = function create(_ref) {\n var root = _ref.root,\n props = _ref.props;\n\n // select\n root.ref.handleClick = function(e) {\n return root.dispatch('DID_ACTIVATE_ITEM', { id: props.id });\n };\n\n // set id\n root.element.id = 'filepond--item-' + props.id;\n root.element.addEventListener('click', root.ref.handleClick);\n\n // file view\n root.ref.container = root.appendChildView(\n root.createChildView(fileWrapper, { id: props.id })\n );\n\n // file panel\n root.ref.panel = root.appendChildView(root.createChildView(panel, { name: 'item-panel' }));\n\n // default start height\n root.ref.panel.height = null;\n\n // by default not marked for removal\n props.markedForRemoval = false;\n\n // if not allowed to reorder file items, exit here\n if (!root.query('GET_ALLOW_REORDER')) return;\n\n // set to idle so shows grab cursor\n root.element.dataset.dragState = 'idle';\n\n var grab = function grab(e) {\n if (!e.isPrimary) return;\n\n var removedActivateListener = false;\n\n var origin = {\n x: e.pageX,\n y: e.pageY,\n };\n\n props.dragOrigin = {\n x: root.translateX,\n y: root.translateY,\n };\n\n props.dragCenter = {\n x: e.offsetX,\n y: e.offsetY,\n };\n\n var dragState = createDragHelper(root.query('GET_ACTIVE_ITEMS'));\n\n root.dispatch('DID_GRAB_ITEM', { id: props.id, dragState: dragState });\n\n var drag = function drag(e) {\n if (!e.isPrimary) return;\n\n e.stopPropagation();\n e.preventDefault();\n\n props.dragOffset = {\n x: e.pageX - origin.x,\n y: e.pageY - origin.y,\n };\n\n // if dragged stop listening to clicks, will re-add when done dragging\n var dist =\n props.dragOffset.x * props.dragOffset.x +\n props.dragOffset.y * props.dragOffset.y;\n if (dist > 16 && !removedActivateListener) {\n removedActivateListener = true;\n root.element.removeEventListener('click', root.ref.handleClick);\n }\n\n root.dispatch('DID_DRAG_ITEM', { id: props.id, dragState: dragState });\n };\n\n var drop = function drop(e) {\n if (!e.isPrimary) return;\n\n document.removeEventListener('pointermove', drag);\n document.removeEventListener('pointerup', drop);\n\n props.dragOffset = {\n x: e.pageX - origin.x,\n y: e.pageY - origin.y,\n };\n\n root.dispatch('DID_DROP_ITEM', { id: props.id, dragState: dragState });\n\n // start listening to clicks again\n if (removedActivateListener) {\n setTimeout(function() {\n return root.element.addEventListener('click', root.ref.handleClick);\n }, 0);\n }\n };\n\n document.addEventListener('pointermove', drag);\n document.addEventListener('pointerup', drop);\n };\n\n root.element.addEventListener('pointerdown', grab);\n };\n\n var route$1 = createRoute({\n DID_UPDATE_PANEL_HEIGHT: function DID_UPDATE_PANEL_HEIGHT(_ref2) {\n var root = _ref2.root,\n action = _ref2.action;\n root.height = action.height;\n },\n });\n\n var write$4 = createRoute(\n {\n DID_GRAB_ITEM: function DID_GRAB_ITEM(_ref3) {\n var root = _ref3.root,\n props = _ref3.props;\n props.dragOrigin = {\n x: root.translateX,\n y: root.translateY,\n };\n },\n DID_DRAG_ITEM: function DID_DRAG_ITEM(_ref4) {\n var root = _ref4.root;\n root.element.dataset.dragState = 'drag';\n },\n DID_DROP_ITEM: function DID_DROP_ITEM(_ref5) {\n var root = _ref5.root,\n props = _ref5.props;\n props.dragOffset = null;\n props.dragOrigin = null;\n root.element.dataset.dragState = 'drop';\n },\n },\n function(_ref6) {\n var root = _ref6.root,\n actions = _ref6.actions,\n props = _ref6.props,\n shouldOptimize = _ref6.shouldOptimize;\n\n if (root.element.dataset.dragState === 'drop') {\n if (root.scaleX <= 1) {\n root.element.dataset.dragState = 'idle';\n }\n }\n\n // select last state change action\n var action = actions\n .concat()\n .filter(function(action) {\n return /^DID_/.test(action.type);\n })\n .reverse()\n .find(function(action) {\n return StateMap[action.type];\n });\n\n // no need to set same state twice\n if (action && action.type !== props.currentState) {\n // set current state\n props.currentState = action.type;\n\n // set state\n root.element.dataset.filepondItemState = StateMap[props.currentState] || '';\n }\n\n // route actions\n var aspectRatio =\n root.query('GET_ITEM_PANEL_ASPECT_RATIO') || root.query('GET_PANEL_ASPECT_RATIO');\n if (!aspectRatio) {\n route$1({ root: root, actions: actions, props: props });\n if (!root.height && root.ref.container.rect.element.height > 0) {\n root.height = root.ref.container.rect.element.height;\n }\n } else if (!shouldOptimize) {\n root.height = root.rect.element.width * aspectRatio;\n }\n\n // sync panel height with item height\n if (shouldOptimize) {\n root.ref.panel.height = null;\n }\n\n root.ref.panel.height = root.height;\n }\n );\n\n var item = createView({\n create: create$7,\n write: write$4,\n destroy: function destroy(_ref7) {\n var root = _ref7.root,\n props = _ref7.props;\n root.element.removeEventListener('click', root.ref.handleClick);\n root.dispatch('RELEASE_ITEM', { query: props.id });\n },\n tag: 'li',\n name: 'item',\n mixins: {\n apis: [\n 'id',\n 'interactionMethod',\n 'markedForRemoval',\n 'spawnDate',\n 'dragCenter',\n 'dragOrigin',\n 'dragOffset',\n ],\n styles: ['translateX', 'translateY', 'scaleX', 'scaleY', 'opacity', 'height'],\n\n animations: {\n scaleX: ITEM_SCALE_SPRING,\n scaleY: ITEM_SCALE_SPRING,\n translateX: ITEM_TRANSLATE_SPRING,\n translateY: ITEM_TRANSLATE_SPRING,\n opacity: { type: 'tween', duration: 150 },\n },\n },\n });\n\n var getItemsPerRow = function(horizontalSpace, itemWidth) {\n // add one pixel leeway, when using percentages for item width total items can be 1.99 per row\n\n return Math.max(1, Math.floor((horizontalSpace + 1) / itemWidth));\n };\n\n var getItemIndexByPosition = function getItemIndexByPosition(view, children, positionInView) {\n if (!positionInView) return;\n\n var horizontalSpace = view.rect.element.width;\n // const children = view.childViews;\n var l = children.length;\n var last = null;\n\n // -1, don't move items to accomodate (either add to top or bottom)\n if (l === 0 || positionInView.top < children[0].rect.element.top) return -1;\n\n // let's get the item width\n var item = children[0];\n var itemRect = item.rect.element;\n var itemHorizontalMargin = itemRect.marginLeft + itemRect.marginRight;\n var itemWidth = itemRect.width + itemHorizontalMargin;\n var itemsPerRow = getItemsPerRow(horizontalSpace, itemWidth);\n\n // stack\n if (itemsPerRow === 1) {\n for (var index = 0; index < l; index++) {\n var child = children[index];\n var childMid = child.rect.outer.top + child.rect.element.height * 0.5;\n if (positionInView.top < childMid) {\n return index;\n }\n }\n return l;\n }\n\n // grid\n var itemVerticalMargin = itemRect.marginTop + itemRect.marginBottom;\n var itemHeight = itemRect.height + itemVerticalMargin;\n for (var _index = 0; _index < l; _index++) {\n var indexX = _index % itemsPerRow;\n var indexY = Math.floor(_index / itemsPerRow);\n\n var offsetX = indexX * itemWidth;\n var offsetY = indexY * itemHeight;\n\n var itemTop = offsetY - itemRect.marginTop;\n var itemRight = offsetX + itemWidth;\n var itemBottom = offsetY + itemHeight + itemRect.marginBottom;\n\n if (positionInView.top < itemBottom && positionInView.top > itemTop) {\n if (positionInView.left < itemRight) {\n return _index;\n } else if (_index !== l - 1) {\n last = _index;\n } else {\n last = null;\n }\n }\n }\n\n if (last !== null) {\n return last;\n }\n\n return l;\n };\n\n var dropAreaDimensions = {\n height: 0,\n width: 0,\n get getHeight() {\n return this.height;\n },\n set setHeight(val) {\n if (this.height === 0 || val === 0) this.height = val;\n },\n get getWidth() {\n return this.width;\n },\n set setWidth(val) {\n if (this.width === 0 || val === 0) this.width = val;\n },\n setDimensions: function setDimensions(height, width) {\n if (this.height === 0 || height === 0) this.height = height;\n if (this.width === 0 || width === 0) this.width = width;\n },\n };\n\n var create$8 = function create(_ref) {\n var root = _ref.root;\n // need to set role to list as otherwise it won't be read as a list by VoiceOver\n attr(root.element, 'role', 'list');\n\n root.ref.lastItemSpanwDate = Date.now();\n };\n\n /**\n * Inserts a new item\n * @param root\n * @param action\n */\n var addItemView = function addItemView(_ref2) {\n var root = _ref2.root,\n action = _ref2.action;\n var id = action.id,\n index = action.index,\n interactionMethod = action.interactionMethod;\n\n root.ref.addIndex = index;\n\n var now = Date.now();\n var spawnDate = now;\n var opacity = 1;\n\n if (interactionMethod !== InteractionMethod.NONE) {\n opacity = 0;\n var cooldown = root.query('GET_ITEM_INSERT_INTERVAL');\n var dist = now - root.ref.lastItemSpanwDate;\n spawnDate = dist < cooldown ? now + (cooldown - dist) : now;\n }\n\n root.ref.lastItemSpanwDate = spawnDate;\n\n root.appendChildView(\n root.createChildView(\n // view type\n item,\n\n // props\n {\n spawnDate: spawnDate,\n id: id,\n opacity: opacity,\n interactionMethod: interactionMethod,\n }\n ),\n\n index\n );\n };\n\n var moveItem = function moveItem(item, x, y) {\n var vx = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 0;\n var vy = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : 1;\n // set to null to remove animation while dragging\n if (item.dragOffset) {\n item.translateX = null;\n item.translateY = null;\n item.translateX = item.dragOrigin.x + item.dragOffset.x;\n item.translateY = item.dragOrigin.y + item.dragOffset.y;\n item.scaleX = 1.025;\n item.scaleY = 1.025;\n } else {\n item.translateX = x;\n item.translateY = y;\n\n if (Date.now() > item.spawnDate) {\n // reveal element\n if (item.opacity === 0) {\n introItemView(item, x, y, vx, vy);\n }\n\n // make sure is default scale every frame\n item.scaleX = 1;\n item.scaleY = 1;\n item.opacity = 1;\n }\n }\n };\n\n var introItemView = function introItemView(item, x, y, vx, vy) {\n if (item.interactionMethod === InteractionMethod.NONE) {\n item.translateX = null;\n item.translateX = x;\n item.translateY = null;\n item.translateY = y;\n } else if (item.interactionMethod === InteractionMethod.DROP) {\n item.translateX = null;\n item.translateX = x - vx * 20;\n\n item.translateY = null;\n item.translateY = y - vy * 10;\n\n item.scaleX = 0.8;\n item.scaleY = 0.8;\n } else if (item.interactionMethod === InteractionMethod.BROWSE) {\n item.translateY = null;\n item.translateY = y - 30;\n } else if (item.interactionMethod === InteractionMethod.API) {\n item.translateX = null;\n item.translateX = x - 30;\n item.translateY = null;\n }\n };\n\n /**\n * Removes an existing item\n * @param root\n * @param action\n */\n var removeItemView = function removeItemView(_ref3) {\n var root = _ref3.root,\n action = _ref3.action;\n var id = action.id;\n\n // get the view matching the given id\n var view = root.childViews.find(function(child) {\n return child.id === id;\n });\n\n // if no view found, exit\n if (!view) {\n return;\n }\n\n // animate view out of view\n view.scaleX = 0.9;\n view.scaleY = 0.9;\n view.opacity = 0;\n\n // mark for removal\n view.markedForRemoval = true;\n };\n\n var getItemHeight = function getItemHeight(child) {\n return (\n child.rect.element.height +\n child.rect.element.marginBottom * 0.5 +\n child.rect.element.marginTop * 0.5\n );\n };\n var getItemWidth = function getItemWidth(child) {\n return (\n child.rect.element.width +\n child.rect.element.marginLeft * 0.5 +\n child.rect.element.marginRight * 0.5\n );\n };\n\n var dragItem = function dragItem(_ref4) {\n var root = _ref4.root,\n action = _ref4.action;\n var id = action.id,\n dragState = action.dragState;\n\n // reference to item\n var item = root.query('GET_ITEM', { id: id });\n\n // get the view matching the given id\n var view = root.childViews.find(function(child) {\n return child.id === id;\n });\n\n var numItems = root.childViews.length;\n var oldIndex = dragState.getItemIndex(item);\n\n // if no view found, exit\n if (!view) return;\n\n var dragPosition = {\n x: view.dragOrigin.x + view.dragOffset.x + view.dragCenter.x,\n y: view.dragOrigin.y + view.dragOffset.y + view.dragCenter.y,\n };\n\n // get drag area dimensions\n var dragHeight = getItemHeight(view);\n var dragWidth = getItemWidth(view);\n\n // get rows and columns (There will always be at least one row and one column if a file is present)\n var cols = Math.floor(root.rect.outer.width / dragWidth);\n if (cols > numItems) cols = numItems;\n\n // rows are used to find when we have left the preview area bounding box\n var rows = Math.floor(numItems / cols + 1);\n\n dropAreaDimensions.setHeight = dragHeight * rows;\n dropAreaDimensions.setWidth = dragWidth * cols;\n\n // get new index of dragged item\n var location = {\n y: Math.floor(dragPosition.y / dragHeight),\n x: Math.floor(dragPosition.x / dragWidth),\n getGridIndex: function getGridIndex() {\n if (\n dragPosition.y > dropAreaDimensions.getHeight ||\n dragPosition.y < 0 ||\n dragPosition.x > dropAreaDimensions.getWidth ||\n dragPosition.x < 0\n )\n return oldIndex;\n return this.y * cols + this.x;\n },\n getColIndex: function getColIndex() {\n var items = root.query('GET_ACTIVE_ITEMS');\n var visibleChildren = root.childViews.filter(function(child) {\n return child.rect.element.height;\n });\n var children = items.map(function(item) {\n return visibleChildren.find(function(childView) {\n return childView.id === item.id;\n });\n });\n\n var currentIndex = children.findIndex(function(child) {\n return child === view;\n });\n var dragHeight = getItemHeight(view);\n var l = children.length;\n var idx = l;\n var childHeight = 0;\n var childBottom = 0;\n var childTop = 0;\n for (var i = 0; i < l; i++) {\n childHeight = getItemHeight(children[i]);\n childTop = childBottom;\n childBottom = childTop + childHeight;\n if (dragPosition.y < childBottom) {\n if (currentIndex > i) {\n if (dragPosition.y < childTop + dragHeight) {\n idx = i;\n break;\n }\n continue;\n }\n idx = i;\n break;\n }\n }\n return idx;\n },\n };\n\n // get new index\n var index = cols > 1 ? location.getGridIndex() : location.getColIndex();\n root.dispatch('MOVE_ITEM', { query: view, index: index });\n\n // if the index of the item changed, dispatch reorder action\n var currentIndex = dragState.getIndex();\n\n if (currentIndex === undefined || currentIndex !== index) {\n dragState.setIndex(index);\n\n if (currentIndex === undefined) return;\n\n root.dispatch('DID_REORDER_ITEMS', {\n items: root.query('GET_ACTIVE_ITEMS'),\n origin: oldIndex,\n target: index,\n });\n }\n };\n\n /**\n * Setup action routes\n */\n var route$2 = createRoute({\n DID_ADD_ITEM: addItemView,\n DID_REMOVE_ITEM: removeItemView,\n DID_DRAG_ITEM: dragItem,\n });\n\n /**\n * Write to view\n * @param root\n * @param actions\n * @param props\n */\n var write$5 = function write(_ref5) {\n var root = _ref5.root,\n props = _ref5.props,\n actions = _ref5.actions,\n shouldOptimize = _ref5.shouldOptimize;\n // route actions\n route$2({ root: root, props: props, actions: actions });\n var dragCoordinates = props.dragCoordinates;\n\n // available space on horizontal axis\n var horizontalSpace = root.rect.element.width;\n\n // only draw children that have dimensions\n var visibleChildren = root.childViews.filter(function(child) {\n return child.rect.element.height;\n });\n\n // sort based on current active items\n var children = root\n .query('GET_ACTIVE_ITEMS')\n .map(function(item) {\n return visibleChildren.find(function(child) {\n return child.id === item.id;\n });\n })\n .filter(function(item) {\n return item;\n });\n\n // get index\n var dragIndex = dragCoordinates\n ? getItemIndexByPosition(root, children, dragCoordinates)\n : null;\n\n // add index is used to reserve the dropped/added item index till the actual item is rendered\n var addIndex = root.ref.addIndex || null;\n\n // add index no longer needed till possibly next draw\n root.ref.addIndex = null;\n\n var dragIndexOffset = 0;\n var removeIndexOffset = 0;\n var addIndexOffset = 0;\n\n if (children.length === 0) return;\n\n var childRect = children[0].rect.element;\n var itemVerticalMargin = childRect.marginTop + childRect.marginBottom;\n var itemHorizontalMargin = childRect.marginLeft + childRect.marginRight;\n var itemWidth = childRect.width + itemHorizontalMargin;\n var itemHeight = childRect.height + itemVerticalMargin;\n var itemsPerRow = getItemsPerRow(horizontalSpace, itemWidth);\n\n // stack\n if (itemsPerRow === 1) {\n var offsetY = 0;\n var dragOffset = 0;\n\n children.forEach(function(child, index) {\n if (dragIndex) {\n var dist = index - dragIndex;\n if (dist === -2) {\n dragOffset = -itemVerticalMargin * 0.25;\n } else if (dist === -1) {\n dragOffset = -itemVerticalMargin * 0.75;\n } else if (dist === 0) {\n dragOffset = itemVerticalMargin * 0.75;\n } else if (dist === 1) {\n dragOffset = itemVerticalMargin * 0.25;\n } else {\n dragOffset = 0;\n }\n }\n\n if (shouldOptimize) {\n child.translateX = null;\n child.translateY = null;\n }\n\n if (!child.markedForRemoval) {\n moveItem(child, 0, offsetY + dragOffset);\n }\n\n var itemHeight = child.rect.element.height + itemVerticalMargin;\n\n var visualHeight = itemHeight * (child.markedForRemoval ? child.opacity : 1);\n\n offsetY += visualHeight;\n });\n }\n // grid\n else {\n var prevX = 0;\n var prevY = 0;\n\n children.forEach(function(child, index) {\n if (index === dragIndex) {\n dragIndexOffset = 1;\n }\n\n if (index === addIndex) {\n addIndexOffset += 1;\n }\n\n if (child.markedForRemoval && child.opacity < 0.5) {\n removeIndexOffset -= 1;\n }\n\n var visualIndex = index + addIndexOffset + dragIndexOffset + removeIndexOffset;\n\n var indexX = visualIndex % itemsPerRow;\n var indexY = Math.floor(visualIndex / itemsPerRow);\n\n var offsetX = indexX * itemWidth;\n var offsetY = indexY * itemHeight;\n\n var vectorX = Math.sign(offsetX - prevX);\n var vectorY = Math.sign(offsetY - prevY);\n\n prevX = offsetX;\n prevY = offsetY;\n\n if (child.markedForRemoval) return;\n\n if (shouldOptimize) {\n child.translateX = null;\n child.translateY = null;\n }\n\n moveItem(child, offsetX, offsetY, vectorX, vectorY);\n });\n }\n };\n\n /**\n * Filters actions that are meant specifically for a certain child of the list\n * @param child\n * @param actions\n */\n var filterSetItemActions = function filterSetItemActions(child, actions) {\n return actions.filter(function(action) {\n // if action has an id, filter out actions that don't have this child id\n if (action.data && action.data.id) {\n return child.id === action.data.id;\n }\n\n // allow all other actions\n return true;\n });\n };\n\n var list = createView({\n create: create$8,\n write: write$5,\n tag: 'ul',\n name: 'list',\n didWriteView: function didWriteView(_ref6) {\n var root = _ref6.root;\n root.childViews\n .filter(function(view) {\n return view.markedForRemoval && view.opacity === 0 && view.resting;\n })\n .forEach(function(view) {\n view._destroy();\n root.removeChildView(view);\n });\n },\n filterFrameActionsForChild: filterSetItemActions,\n mixins: {\n apis: ['dragCoordinates'],\n },\n });\n\n var create$9 = function create(_ref) {\n var root = _ref.root,\n props = _ref.props;\n root.ref.list = root.appendChildView(root.createChildView(list));\n props.dragCoordinates = null;\n props.overflowing = false;\n };\n\n var storeDragCoordinates = function storeDragCoordinates(_ref2) {\n var root = _ref2.root,\n props = _ref2.props,\n action = _ref2.action;\n if (!root.query('GET_ITEM_INSERT_LOCATION_FREEDOM')) return;\n props.dragCoordinates = {\n left: action.position.scopeLeft - root.ref.list.rect.element.left,\n top:\n action.position.scopeTop -\n (root.rect.outer.top + root.rect.element.marginTop + root.rect.element.scrollTop),\n };\n };\n\n var clearDragCoordinates = function clearDragCoordinates(_ref3) {\n var props = _ref3.props;\n props.dragCoordinates = null;\n };\n\n var route$3 = createRoute({\n DID_DRAG: storeDragCoordinates,\n DID_END_DRAG: clearDragCoordinates,\n });\n\n var write$6 = function write(_ref4) {\n var root = _ref4.root,\n props = _ref4.props,\n actions = _ref4.actions;\n\n // route actions\n route$3({ root: root, props: props, actions: actions });\n\n // current drag position\n root.ref.list.dragCoordinates = props.dragCoordinates;\n\n // if currently overflowing but no longer received overflow\n if (props.overflowing && !props.overflow) {\n props.overflowing = false;\n\n // reset overflow state\n root.element.dataset.state = '';\n root.height = null;\n }\n\n // if is not overflowing currently but does receive overflow value\n if (props.overflow) {\n var newHeight = Math.round(props.overflow);\n if (newHeight !== root.height) {\n props.overflowing = true;\n root.element.dataset.state = 'overflow';\n root.height = newHeight;\n }\n }\n };\n\n var listScroller = createView({\n create: create$9,\n write: write$6,\n name: 'list-scroller',\n mixins: {\n apis: ['overflow', 'dragCoordinates'],\n styles: ['height', 'translateY'],\n animations: {\n translateY: 'spring',\n },\n },\n });\n\n var attrToggle = function attrToggle(element, name, state) {\n var enabledValue = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : '';\n if (state) {\n attr(element, name, enabledValue);\n } else {\n element.removeAttribute(name);\n }\n };\n\n var resetFileInput = function resetFileInput(input) {\n // no value, no need to reset\n if (!input || input.value === '') {\n return;\n }\n\n try {\n // for modern browsers\n input.value = '';\n } catch (err) {}\n\n // for IE10\n if (input.value) {\n // quickly append input to temp form and reset form\n var form = createElement$1('form');\n var parentNode = input.parentNode;\n var ref = input.nextSibling;\n form.appendChild(input);\n form.reset();\n\n // re-inject input where it originally was\n if (ref) {\n parentNode.insertBefore(input, ref);\n } else {\n parentNode.appendChild(input);\n }\n }\n };\n\n var create$a = function create(_ref) {\n var root = _ref.root,\n props = _ref.props;\n\n // set id so can be referenced from outside labels\n root.element.id = 'filepond--browser-' + props.id;\n\n // set name of element (is removed when a value is set)\n attr(root.element, 'name', root.query('GET_NAME'));\n\n // we have to link this element to the status element\n attr(root.element, 'aria-controls', 'filepond--assistant-' + props.id);\n\n // set label, we use labelled by as otherwise the screenreader does not read the \"browse\" text in the label (as it has tabindex: 0)\n attr(root.element, 'aria-labelledby', 'filepond--drop-label-' + props.id);\n\n // set configurable props\n setAcceptedFileTypes({\n root: root,\n action: { value: root.query('GET_ACCEPTED_FILE_TYPES') },\n });\n toggleAllowMultiple({ root: root, action: { value: root.query('GET_ALLOW_MULTIPLE') } });\n toggleDirectoryFilter({\n root: root,\n action: { value: root.query('GET_ALLOW_DIRECTORIES_ONLY') },\n });\n toggleDisabled({ root: root });\n toggleRequired({ root: root, action: { value: root.query('GET_REQUIRED') } });\n setCaptureMethod({ root: root, action: { value: root.query('GET_CAPTURE_METHOD') } });\n\n // handle changes to the input field\n root.ref.handleChange = function(e) {\n if (!root.element.value) {\n return;\n }\n\n // extract files and move value of webkitRelativePath path to _relativePath\n var files = Array.from(root.element.files).map(function(file) {\n file._relativePath = file.webkitRelativePath;\n return file;\n });\n\n // we add a little delay so the OS file select window can move out of the way before we add our file\n setTimeout(function() {\n // load files\n props.onload(files);\n\n // reset input, it's just for exposing a method to drop files, should not retain any state\n resetFileInput(root.element);\n }, 250);\n };\n\n root.element.addEventListener('change', root.ref.handleChange);\n };\n\n var setAcceptedFileTypes = function setAcceptedFileTypes(_ref2) {\n var root = _ref2.root,\n action = _ref2.action;\n if (!root.query('GET_ALLOW_SYNC_ACCEPT_ATTRIBUTE')) return;\n attrToggle(\n root.element,\n 'accept',\n !!action.value,\n action.value ? action.value.join(',') : ''\n );\n };\n\n var toggleAllowMultiple = function toggleAllowMultiple(_ref3) {\n var root = _ref3.root,\n action = _ref3.action;\n attrToggle(root.element, 'multiple', action.value);\n };\n\n var toggleDirectoryFilter = function toggleDirectoryFilter(_ref4) {\n var root = _ref4.root,\n action = _ref4.action;\n attrToggle(root.element, 'webkitdirectory', action.value);\n };\n\n var toggleDisabled = function toggleDisabled(_ref5) {\n var root = _ref5.root;\n var isDisabled = root.query('GET_DISABLED');\n var doesAllowBrowse = root.query('GET_ALLOW_BROWSE');\n var disableField = isDisabled || !doesAllowBrowse;\n attrToggle(root.element, 'disabled', disableField);\n };\n\n var toggleRequired = function toggleRequired(_ref6) {\n var root = _ref6.root,\n action = _ref6.action;\n // want to remove required, always possible\n if (!action.value) {\n attrToggle(root.element, 'required', false);\n }\n // if want to make required, only possible when zero items\n else if (root.query('GET_TOTAL_ITEMS') === 0) {\n attrToggle(root.element, 'required', true);\n }\n };\n\n var setCaptureMethod = function setCaptureMethod(_ref7) {\n var root = _ref7.root,\n action = _ref7.action;\n attrToggle(\n root.element,\n 'capture',\n !!action.value,\n action.value === true ? '' : action.value\n );\n };\n\n var updateRequiredStatus = function updateRequiredStatus(_ref8) {\n var root = _ref8.root;\n var element = root.element;\n // always remove the required attribute when more than zero items\n if (root.query('GET_TOTAL_ITEMS') > 0) {\n attrToggle(element, 'required', false);\n attrToggle(element, 'name', false);\n } else {\n // add name attribute\n attrToggle(element, 'name', true, root.query('GET_NAME'));\n\n // remove any validation messages\n var shouldCheckValidity = root.query('GET_CHECK_VALIDITY');\n if (shouldCheckValidity) {\n element.setCustomValidity('');\n }\n\n // we only add required if the field has been deemed required\n if (root.query('GET_REQUIRED')) {\n attrToggle(element, 'required', true);\n }\n }\n };\n\n var updateFieldValidityStatus = function updateFieldValidityStatus(_ref9) {\n var root = _ref9.root;\n var shouldCheckValidity = root.query('GET_CHECK_VALIDITY');\n if (!shouldCheckValidity) return;\n root.element.setCustomValidity(root.query('GET_LABEL_INVALID_FIELD'));\n };\n\n var browser = createView({\n tag: 'input',\n name: 'browser',\n ignoreRect: true,\n ignoreRectUpdate: true,\n attributes: {\n type: 'file',\n },\n\n create: create$a,\n destroy: function destroy(_ref10) {\n var root = _ref10.root;\n root.element.removeEventListener('change', root.ref.handleChange);\n },\n write: createRoute({\n DID_LOAD_ITEM: updateRequiredStatus,\n DID_REMOVE_ITEM: updateRequiredStatus,\n DID_THROW_ITEM_INVALID: updateFieldValidityStatus,\n\n DID_SET_DISABLED: toggleDisabled,\n DID_SET_ALLOW_BROWSE: toggleDisabled,\n DID_SET_ALLOW_DIRECTORIES_ONLY: toggleDirectoryFilter,\n DID_SET_ALLOW_MULTIPLE: toggleAllowMultiple,\n DID_SET_ACCEPTED_FILE_TYPES: setAcceptedFileTypes,\n DID_SET_CAPTURE_METHOD: setCaptureMethod,\n DID_SET_REQUIRED: toggleRequired,\n }),\n });\n\n var Key = {\n ENTER: 13,\n SPACE: 32,\n };\n\n var create$b = function create(_ref) {\n var root = _ref.root,\n props = _ref.props;\n\n // create the label and link it to the file browser\n var label = createElement$1('label');\n attr(label, 'for', 'filepond--browser-' + props.id);\n\n // use for labeling file input (aria-labelledby on file input)\n attr(label, 'id', 'filepond--drop-label-' + props.id);\n\n // hide the label for screenreaders, the input element will read the contents of the label when it's focussed. If we don't set aria-hidden the screenreader will also navigate the contents of the label separately from the input.\n attr(label, 'aria-hidden', 'true');\n\n // handle keys\n root.ref.handleKeyDown = function(e) {\n var isActivationKey = e.keyCode === Key.ENTER || e.keyCode === Key.SPACE;\n if (!isActivationKey) return;\n // stops from triggering the element a second time\n e.preventDefault();\n\n // click link (will then in turn activate file input)\n root.ref.label.click();\n };\n\n root.ref.handleClick = function(e) {\n var isLabelClick = e.target === label || label.contains(e.target);\n\n // don't want to click twice\n if (isLabelClick) return;\n\n // click link (will then in turn activate file input)\n root.ref.label.click();\n };\n\n // attach events\n label.addEventListener('keydown', root.ref.handleKeyDown);\n root.element.addEventListener('click', root.ref.handleClick);\n\n // update\n updateLabelValue(label, props.caption);\n\n // add!\n root.appendChild(label);\n root.ref.label = label;\n };\n\n var updateLabelValue = function updateLabelValue(label, value) {\n label.innerHTML = value;\n var clickable = label.querySelector('.filepond--label-action');\n if (clickable) {\n attr(clickable, 'tabindex', '0');\n }\n return value;\n };\n\n var dropLabel = createView({\n name: 'drop-label',\n ignoreRect: true,\n create: create$b,\n destroy: function destroy(_ref2) {\n var root = _ref2.root;\n root.ref.label.addEventListener('keydown', root.ref.handleKeyDown);\n root.element.removeEventListener('click', root.ref.handleClick);\n },\n write: createRoute({\n DID_SET_LABEL_IDLE: function DID_SET_LABEL_IDLE(_ref3) {\n var root = _ref3.root,\n action = _ref3.action;\n updateLabelValue(root.ref.label, action.value);\n },\n }),\n\n mixins: {\n styles: ['opacity', 'translateX', 'translateY'],\n animations: {\n opacity: { type: 'tween', duration: 150 },\n translateX: 'spring',\n translateY: 'spring',\n },\n },\n });\n\n var blob = createView({\n name: 'drip-blob',\n ignoreRect: true,\n mixins: {\n styles: ['translateX', 'translateY', 'scaleX', 'scaleY', 'opacity'],\n animations: {\n scaleX: 'spring',\n scaleY: 'spring',\n translateX: 'spring',\n translateY: 'spring',\n opacity: { type: 'tween', duration: 250 },\n },\n },\n });\n\n var addBlob = function addBlob(_ref) {\n var root = _ref.root;\n var centerX = root.rect.element.width * 0.5;\n var centerY = root.rect.element.height * 0.5;\n\n root.ref.blob = root.appendChildView(\n root.createChildView(blob, {\n opacity: 0,\n scaleX: 2.5,\n scaleY: 2.5,\n translateX: centerX,\n translateY: centerY,\n })\n );\n };\n\n var moveBlob = function moveBlob(_ref2) {\n var root = _ref2.root,\n action = _ref2.action;\n if (!root.ref.blob) {\n addBlob({ root: root });\n return;\n }\n\n root.ref.blob.translateX = action.position.scopeLeft;\n root.ref.blob.translateY = action.position.scopeTop;\n root.ref.blob.scaleX = 1;\n root.ref.blob.scaleY = 1;\n root.ref.blob.opacity = 1;\n };\n\n var hideBlob = function hideBlob(_ref3) {\n var root = _ref3.root;\n if (!root.ref.blob) {\n return;\n }\n root.ref.blob.opacity = 0;\n };\n\n var explodeBlob = function explodeBlob(_ref4) {\n var root = _ref4.root;\n if (!root.ref.blob) {\n return;\n }\n root.ref.blob.scaleX = 2.5;\n root.ref.blob.scaleY = 2.5;\n root.ref.blob.opacity = 0;\n };\n\n var write$7 = function write(_ref5) {\n var root = _ref5.root,\n props = _ref5.props,\n actions = _ref5.actions;\n route$4({ root: root, props: props, actions: actions });\n var blob = root.ref.blob;\n\n if (actions.length === 0 && blob && blob.opacity === 0) {\n root.removeChildView(blob);\n root.ref.blob = null;\n }\n };\n\n var route$4 = createRoute({\n DID_DRAG: moveBlob,\n DID_DROP: explodeBlob,\n DID_END_DRAG: hideBlob,\n });\n\n var drip = createView({\n ignoreRect: true,\n ignoreRectUpdate: true,\n name: 'drip',\n write: write$7,\n });\n\n var setInputFiles = function setInputFiles(element, files) {\n try {\n // Create a DataTransfer instance and add a newly created file\n var dataTransfer = new DataTransfer();\n files.forEach(function(file) {\n if (file instanceof File) {\n dataTransfer.items.add(file);\n } else {\n dataTransfer.items.add(\n new File([file], file.name, {\n type: file.type,\n })\n );\n }\n });\n\n // Assign the DataTransfer files list to the file input\n element.files = dataTransfer.files;\n } catch (err) {\n return false;\n }\n return true;\n };\n\n var create$c = function create(_ref) {\n var root = _ref.root;\n return (root.ref.fields = {});\n };\n\n var getField = function getField(root, id) {\n return root.ref.fields[id];\n };\n\n var syncFieldPositionsWithItems = function syncFieldPositionsWithItems(root) {\n root.query('GET_ACTIVE_ITEMS').forEach(function(item) {\n if (!root.ref.fields[item.id]) return;\n root.element.appendChild(root.ref.fields[item.id]);\n });\n };\n\n var didReorderItems = function didReorderItems(_ref2) {\n var root = _ref2.root;\n return syncFieldPositionsWithItems(root);\n };\n\n var didAddItem = function didAddItem(_ref3) {\n var root = _ref3.root,\n action = _ref3.action;\n var fileItem = root.query('GET_ITEM', action.id);\n var isLocalFile = fileItem.origin === FileOrigin.LOCAL;\n var shouldUseFileInput = !isLocalFile && root.query('SHOULD_UPDATE_FILE_INPUT');\n var dataContainer = createElement$1('input');\n dataContainer.type = shouldUseFileInput ? 'file' : 'hidden';\n dataContainer.name = root.query('GET_NAME');\n dataContainer.disabled = root.query('GET_DISABLED');\n root.ref.fields[action.id] = dataContainer;\n syncFieldPositionsWithItems(root);\n };\n\n var didLoadItem$1 = function didLoadItem(_ref4) {\n var root = _ref4.root,\n action = _ref4.action;\n var field = getField(root, action.id);\n if (!field) return;\n\n // store server ref in hidden input\n if (action.serverFileReference !== null) field.value = action.serverFileReference;\n\n // store file item in file input\n if (!root.query('SHOULD_UPDATE_FILE_INPUT')) return;\n\n var fileItem = root.query('GET_ITEM', action.id);\n setInputFiles(field, [fileItem.file]);\n };\n\n var didPrepareOutput = function didPrepareOutput(_ref5) {\n var root = _ref5.root,\n action = _ref5.action;\n // this timeout pushes the handler after 'load'\n if (!root.query('SHOULD_UPDATE_FILE_INPUT')) return;\n setTimeout(function() {\n var field = getField(root, action.id);\n if (!field) return;\n setInputFiles(field, [action.file]);\n }, 0);\n };\n\n var didSetDisabled = function didSetDisabled(_ref6) {\n var root = _ref6.root;\n root.element.disabled = root.query('GET_DISABLED');\n };\n\n var didRemoveItem = function didRemoveItem(_ref7) {\n var root = _ref7.root,\n action = _ref7.action;\n var field = getField(root, action.id);\n if (!field) return;\n if (field.parentNode) field.parentNode.removeChild(field);\n delete root.ref.fields[action.id];\n };\n\n // only runs for server files. will refuse to update the value if the field\n // is a file field\n var didDefineValue = function didDefineValue(_ref8) {\n var root = _ref8.root,\n action = _ref8.action;\n var field = getField(root, action.id);\n if (!field) return;\n if (action.value === null) {\n // clear field value\n field.removeAttribute('value');\n } else {\n // set field value\n if (field.type != 'file') {\n field.value = action.value;\n }\n }\n syncFieldPositionsWithItems(root);\n };\n\n var write$8 = createRoute({\n DID_SET_DISABLED: didSetDisabled,\n DID_ADD_ITEM: didAddItem,\n DID_LOAD_ITEM: didLoadItem$1,\n DID_REMOVE_ITEM: didRemoveItem,\n DID_DEFINE_VALUE: didDefineValue,\n DID_PREPARE_OUTPUT: didPrepareOutput,\n DID_REORDER_ITEMS: didReorderItems,\n DID_SORT_ITEMS: didReorderItems,\n });\n\n var data = createView({\n tag: 'fieldset',\n name: 'data',\n create: create$c,\n write: write$8,\n ignoreRect: true,\n });\n\n var getRootNode = function getRootNode(element) {\n return 'getRootNode' in element ? element.getRootNode() : document;\n };\n\n var images = ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp', 'svg', 'tiff'];\n var text$1 = ['css', 'csv', 'html', 'txt'];\n var map = {\n zip: 'zip|compressed',\n epub: 'application/epub+zip',\n };\n\n var guesstimateMimeType = function guesstimateMimeType() {\n var extension = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : '';\n extension = extension.toLowerCase();\n if (images.includes(extension)) {\n return (\n 'image/' +\n (extension === 'jpg' ? 'jpeg' : extension === 'svg' ? 'svg+xml' : extension)\n );\n }\n if (text$1.includes(extension)) {\n return 'text/' + extension;\n }\n\n return map[extension] || '';\n };\n\n var requestDataTransferItems = function requestDataTransferItems(dataTransfer) {\n return new Promise(function(resolve, reject) {\n // try to get links from transfer, if found we'll exit immediately (unless a file is in the dataTransfer as well, this is because Firefox could represent the file as a URL and a file object at the same time)\n var links = getLinks(dataTransfer);\n if (links.length && !hasFiles(dataTransfer)) {\n return resolve(links);\n }\n // try to get files from the transfer\n getFiles(dataTransfer).then(resolve);\n });\n };\n\n /**\n * Test if datatransfer has files\n */\n var hasFiles = function hasFiles(dataTransfer) {\n if (dataTransfer.files) return dataTransfer.files.length > 0;\n return false;\n };\n\n /**\n * Extracts files from a DataTransfer object\n */\n var getFiles = function getFiles(dataTransfer) {\n return new Promise(function(resolve, reject) {\n // get the transfer items as promises\n var promisedFiles = (dataTransfer.items ? Array.from(dataTransfer.items) : [])\n // only keep file system items (files and directories)\n .filter(function(item) {\n return isFileSystemItem(item);\n })\n\n // map each item to promise\n .map(function(item) {\n return getFilesFromItem(item);\n });\n\n // if is empty, see if we can extract some info from the files property as a fallback\n if (!promisedFiles.length) {\n // TODO: test for directories (should not be allowed)\n // Use FileReader, problem is that the files property gets lost in the process\n resolve(dataTransfer.files ? Array.from(dataTransfer.files) : []);\n return;\n }\n\n // done!\n Promise.all(promisedFiles)\n .then(function(returnedFileGroups) {\n // flatten groups\n var files = [];\n returnedFileGroups.forEach(function(group) {\n files.push.apply(files, group);\n });\n\n // done (filter out empty files)!\n resolve(\n files\n .filter(function(file) {\n return file;\n })\n .map(function(file) {\n if (!file._relativePath)\n file._relativePath = file.webkitRelativePath;\n return file;\n })\n );\n })\n .catch(console.error);\n });\n };\n\n var isFileSystemItem = function isFileSystemItem(item) {\n if (isEntry(item)) {\n var entry = getAsEntry(item);\n if (entry) {\n return entry.isFile || entry.isDirectory;\n }\n }\n return item.kind === 'file';\n };\n\n var getFilesFromItem = function getFilesFromItem(item) {\n return new Promise(function(resolve, reject) {\n if (isDirectoryEntry(item)) {\n getFilesInDirectory(getAsEntry(item))\n .then(resolve)\n .catch(reject);\n return;\n }\n\n resolve([item.getAsFile()]);\n });\n };\n\n var getFilesInDirectory = function getFilesInDirectory(entry) {\n return new Promise(function(resolve, reject) {\n var files = [];\n\n // the total entries to read\n var dirCounter = 0;\n var fileCounter = 0;\n\n var resolveIfDone = function resolveIfDone() {\n if (fileCounter === 0 && dirCounter === 0) {\n resolve(files);\n }\n };\n\n // the recursive function\n var readEntries = function readEntries(dirEntry) {\n dirCounter++;\n\n var directoryReader = dirEntry.createReader();\n\n // directories are returned in batches, we need to process all batches before we're done\n var readBatch = function readBatch() {\n directoryReader.readEntries(function(entries) {\n if (entries.length === 0) {\n dirCounter--;\n resolveIfDone();\n return;\n }\n\n entries.forEach(function(entry) {\n // recursively read more directories\n if (entry.isDirectory) {\n readEntries(entry);\n } else {\n // read as file\n fileCounter++;\n\n entry.file(function(file) {\n var correctedFile = correctMissingFileType(file);\n if (entry.fullPath)\n correctedFile._relativePath = entry.fullPath;\n files.push(correctedFile);\n fileCounter--;\n resolveIfDone();\n });\n }\n });\n\n // try to get next batch of files\n readBatch();\n }, reject);\n };\n\n // read first batch of files\n readBatch();\n };\n\n // go!\n readEntries(entry);\n });\n };\n\n var correctMissingFileType = function correctMissingFileType(file) {\n if (file.type.length) return file;\n var date = file.lastModifiedDate;\n var name = file.name;\n var type = guesstimateMimeType(getExtensionFromFilename(file.name));\n if (!type.length) return file;\n file = file.slice(0, file.size, type);\n file.name = name;\n file.lastModifiedDate = date;\n return file;\n };\n\n var isDirectoryEntry = function isDirectoryEntry(item) {\n return isEntry(item) && (getAsEntry(item) || {}).isDirectory;\n };\n\n var isEntry = function isEntry(item) {\n return 'webkitGetAsEntry' in item;\n };\n\n var getAsEntry = function getAsEntry(item) {\n return item.webkitGetAsEntry();\n };\n\n /**\n * Extracts links from a DataTransfer object\n */\n var getLinks = function getLinks(dataTransfer) {\n var links = [];\n try {\n // look in meta data property\n links = getLinksFromTransferMetaData(dataTransfer);\n if (links.length) {\n return links;\n }\n links = getLinksFromTransferURLData(dataTransfer);\n } catch (e) {\n // nope nope nope (probably IE trouble)\n }\n return links;\n };\n\n var getLinksFromTransferURLData = function getLinksFromTransferURLData(dataTransfer) {\n var data = dataTransfer.getData('url');\n if (typeof data === 'string' && data.length) {\n return [data];\n }\n return [];\n };\n\n var getLinksFromTransferMetaData = function getLinksFromTransferMetaData(dataTransfer) {\n var data = dataTransfer.getData('text/html');\n if (typeof data === 'string' && data.length) {\n var matches = data.match(/src\\s*=\\s*\"(.+?)\"/);\n if (matches) {\n return [matches[1]];\n }\n }\n return [];\n };\n\n var dragNDropObservers = [];\n\n var eventPosition = function eventPosition(e) {\n return {\n pageLeft: e.pageX,\n pageTop: e.pageY,\n scopeLeft: e.offsetX || e.layerX,\n scopeTop: e.offsetY || e.layerY,\n };\n };\n\n var createDragNDropClient = function createDragNDropClient(\n element,\n scopeToObserve,\n filterElement\n ) {\n var observer = getDragNDropObserver(scopeToObserve);\n\n var client = {\n element: element,\n filterElement: filterElement,\n state: null,\n ondrop: function ondrop() {},\n onenter: function onenter() {},\n ondrag: function ondrag() {},\n onexit: function onexit() {},\n onload: function onload() {},\n allowdrop: function allowdrop() {},\n };\n\n client.destroy = observer.addListener(client);\n\n return client;\n };\n\n var getDragNDropObserver = function getDragNDropObserver(element) {\n // see if already exists, if so, return\n var observer = dragNDropObservers.find(function(item) {\n return item.element === element;\n });\n if (observer) {\n return observer;\n }\n\n // create new observer, does not yet exist for this element\n var newObserver = createDragNDropObserver(element);\n dragNDropObservers.push(newObserver);\n return newObserver;\n };\n\n var createDragNDropObserver = function createDragNDropObserver(element) {\n var clients = [];\n\n var routes = {\n dragenter: dragenter,\n dragover: dragover,\n dragleave: dragleave,\n drop: drop,\n };\n\n var handlers = {};\n\n forin(routes, function(event, createHandler) {\n handlers[event] = createHandler(element, clients);\n element.addEventListener(event, handlers[event], false);\n });\n\n var observer = {\n element: element,\n addListener: function addListener(client) {\n // add as client\n clients.push(client);\n\n // return removeListener function\n return function() {\n // remove client\n clients.splice(clients.indexOf(client), 1);\n\n // if no more clients, clean up observer\n if (clients.length === 0) {\n dragNDropObservers.splice(dragNDropObservers.indexOf(observer), 1);\n\n forin(routes, function(event) {\n element.removeEventListener(event, handlers[event], false);\n });\n }\n };\n },\n };\n\n return observer;\n };\n\n var elementFromPoint = function elementFromPoint(root, point) {\n if (!('elementFromPoint' in root)) {\n root = document;\n }\n return root.elementFromPoint(point.x, point.y);\n };\n\n var isEventTarget = function isEventTarget(e, target) {\n // get root\n var root = getRootNode(target);\n\n // get element at position\n // if root is not actual shadow DOM and does not have elementFromPoint method, use the one on document\n var elementAtPosition = elementFromPoint(root, {\n x: e.pageX - window.pageXOffset,\n y: e.pageY - window.pageYOffset,\n });\n\n // test if target is the element or if one of its children is\n return elementAtPosition === target || target.contains(elementAtPosition);\n };\n\n var initialTarget = null;\n\n var setDropEffect = function setDropEffect(dataTransfer, effect) {\n // is in try catch as IE11 will throw error if not\n try {\n dataTransfer.dropEffect = effect;\n } catch (e) {}\n };\n\n var dragenter = function dragenter(root, clients) {\n return function(e) {\n e.preventDefault();\n\n initialTarget = e.target;\n\n clients.forEach(function(client) {\n var element = client.element,\n onenter = client.onenter;\n\n if (isEventTarget(e, element)) {\n client.state = 'enter';\n\n // fire enter event\n onenter(eventPosition(e));\n }\n });\n };\n };\n\n var dragover = function dragover(root, clients) {\n return function(e) {\n e.preventDefault();\n\n var dataTransfer = e.dataTransfer;\n\n requestDataTransferItems(dataTransfer).then(function(items) {\n var overDropTarget = false;\n\n clients.some(function(client) {\n var filterElement = client.filterElement,\n element = client.element,\n onenter = client.onenter,\n onexit = client.onexit,\n ondrag = client.ondrag,\n allowdrop = client.allowdrop;\n\n // by default we can drop\n setDropEffect(dataTransfer, 'copy');\n\n // allow transfer of these items\n var allowsTransfer = allowdrop(items);\n\n // only used when can be dropped on page\n if (!allowsTransfer) {\n setDropEffect(dataTransfer, 'none');\n return;\n }\n\n // targetting this client\n if (isEventTarget(e, element)) {\n overDropTarget = true;\n\n // had no previous state, means we are entering this client\n if (client.state === null) {\n client.state = 'enter';\n onenter(eventPosition(e));\n return;\n }\n\n // now over element (no matter if it allows the drop or not)\n client.state = 'over';\n\n // needs to allow transfer\n if (filterElement && !allowsTransfer) {\n setDropEffect(dataTransfer, 'none');\n return;\n }\n\n // dragging\n ondrag(eventPosition(e));\n } else {\n // should be over an element to drop\n if (filterElement && !overDropTarget) {\n setDropEffect(dataTransfer, 'none');\n }\n\n // might have just left this client?\n if (client.state) {\n client.state = null;\n onexit(eventPosition(e));\n }\n }\n });\n });\n };\n };\n\n var drop = function drop(root, clients) {\n return function(e) {\n e.preventDefault();\n\n var dataTransfer = e.dataTransfer;\n\n requestDataTransferItems(dataTransfer).then(function(items) {\n clients.forEach(function(client) {\n var filterElement = client.filterElement,\n element = client.element,\n ondrop = client.ondrop,\n onexit = client.onexit,\n allowdrop = client.allowdrop;\n\n client.state = null;\n\n // if we're filtering on element we need to be over the element to drop\n if (filterElement && !isEventTarget(e, element)) return;\n\n // no transfer for this client\n if (!allowdrop(items)) return onexit(eventPosition(e));\n\n // we can drop these items on this client\n ondrop(eventPosition(e), items);\n });\n });\n };\n };\n\n var dragleave = function dragleave(root, clients) {\n return function(e) {\n if (initialTarget !== e.target) {\n return;\n }\n\n clients.forEach(function(client) {\n var onexit = client.onexit;\n\n client.state = null;\n\n onexit(eventPosition(e));\n });\n };\n };\n\n var createHopper = function createHopper(scope, validateItems, options) {\n // is now hopper scope\n scope.classList.add('filepond--hopper');\n\n // shortcuts\n var catchesDropsOnPage = options.catchesDropsOnPage,\n requiresDropOnElement = options.requiresDropOnElement,\n _options$filterItems = options.filterItems,\n filterItems =\n _options$filterItems === void 0\n ? function(items) {\n return items;\n }\n : _options$filterItems;\n\n // create a dnd client\n var client = createDragNDropClient(\n scope,\n catchesDropsOnPage ? document.documentElement : scope,\n requiresDropOnElement\n );\n\n // current client state\n var lastState = '';\n var currentState = '';\n\n // determines if a file may be dropped\n client.allowdrop = function(items) {\n // TODO: if we can, throw error to indicate the items cannot by dropped\n\n return validateItems(filterItems(items));\n };\n\n client.ondrop = function(position, items) {\n var filteredItems = filterItems(items);\n\n if (!validateItems(filteredItems)) {\n api.ondragend(position);\n return;\n }\n\n currentState = 'drag-drop';\n\n api.onload(filteredItems, position);\n };\n\n client.ondrag = function(position) {\n api.ondrag(position);\n };\n\n client.onenter = function(position) {\n currentState = 'drag-over';\n\n api.ondragstart(position);\n };\n\n client.onexit = function(position) {\n currentState = 'drag-exit';\n\n api.ondragend(position);\n };\n\n var api = {\n updateHopperState: function updateHopperState() {\n if (lastState !== currentState) {\n scope.dataset.hopperState = currentState;\n lastState = currentState;\n }\n },\n onload: function onload() {},\n ondragstart: function ondragstart() {},\n ondrag: function ondrag() {},\n ondragend: function ondragend() {},\n destroy: function destroy() {\n // destroy client\n client.destroy();\n },\n };\n\n return api;\n };\n\n var listening = false;\n var listeners$1 = [];\n\n var handlePaste = function handlePaste(e) {\n // if is pasting in input or textarea and the target is outside of a filepond scope, ignore\n var activeEl = document.activeElement;\n if (activeEl && /textarea|input/i.test(activeEl.nodeName)) {\n // test textarea or input is contained in filepond root\n var inScope = false;\n var element = activeEl;\n while (element !== document.body) {\n if (element.classList.contains('filepond--root')) {\n inScope = true;\n break;\n }\n element = element.parentNode;\n }\n\n if (!inScope) return;\n }\n\n requestDataTransferItems(e.clipboardData).then(function(files) {\n // no files received\n if (!files.length) {\n return;\n }\n\n // notify listeners of received files\n listeners$1.forEach(function(listener) {\n return listener(files);\n });\n });\n };\n\n var listen = function listen(cb) {\n // can't add twice\n if (listeners$1.includes(cb)) {\n return;\n }\n\n // add initial listener\n listeners$1.push(cb);\n\n // setup paste listener for entire page\n if (listening) {\n return;\n }\n\n listening = true;\n document.addEventListener('paste', handlePaste);\n };\n\n var unlisten = function unlisten(listener) {\n arrayRemove(listeners$1, listeners$1.indexOf(listener));\n\n // clean up\n if (listeners$1.length === 0) {\n document.removeEventListener('paste', handlePaste);\n listening = false;\n }\n };\n\n var createPaster = function createPaster() {\n var cb = function cb(files) {\n api.onload(files);\n };\n\n var api = {\n destroy: function destroy() {\n unlisten(cb);\n },\n onload: function onload() {},\n };\n\n listen(cb);\n\n return api;\n };\n\n /**\n * Creates the file view\n */\n var create$d = function create(_ref) {\n var root = _ref.root,\n props = _ref.props;\n root.element.id = 'filepond--assistant-' + props.id;\n attr(root.element, 'role', 'status');\n attr(root.element, 'aria-live', 'polite');\n attr(root.element, 'aria-relevant', 'additions');\n };\n\n var addFilesNotificationTimeout = null;\n var notificationClearTimeout = null;\n\n var filenames = [];\n\n var assist = function assist(root, message) {\n root.element.textContent = message;\n };\n\n var clear$1 = function clear(root) {\n root.element.textContent = '';\n };\n\n var listModified = function listModified(root, filename, label) {\n var total = root.query('GET_TOTAL_ITEMS');\n assist(\n root,\n label +\n ' ' +\n filename +\n ', ' +\n total +\n ' ' +\n (total === 1\n ? root.query('GET_LABEL_FILE_COUNT_SINGULAR')\n : root.query('GET_LABEL_FILE_COUNT_PLURAL'))\n );\n\n // clear group after set amount of time so the status is not read twice\n clearTimeout(notificationClearTimeout);\n notificationClearTimeout = setTimeout(function() {\n clear$1(root);\n }, 1500);\n };\n\n var isUsingFilePond = function isUsingFilePond(root) {\n return root.element.parentNode.contains(document.activeElement);\n };\n\n var itemAdded = function itemAdded(_ref2) {\n var root = _ref2.root,\n action = _ref2.action;\n if (!isUsingFilePond(root)) {\n return;\n }\n\n root.element.textContent = '';\n var item = root.query('GET_ITEM', action.id);\n filenames.push(item.filename);\n\n clearTimeout(addFilesNotificationTimeout);\n addFilesNotificationTimeout = setTimeout(function() {\n listModified(root, filenames.join(', '), root.query('GET_LABEL_FILE_ADDED'));\n\n filenames.length = 0;\n }, 750);\n };\n\n var itemRemoved = function itemRemoved(_ref3) {\n var root = _ref3.root,\n action = _ref3.action;\n if (!isUsingFilePond(root)) {\n return;\n }\n\n var item = action.item;\n listModified(root, item.filename, root.query('GET_LABEL_FILE_REMOVED'));\n };\n\n var itemProcessed = function itemProcessed(_ref4) {\n var root = _ref4.root,\n action = _ref4.action;\n // will also notify the user when FilePond is not being used, as the user might be occupied with other activities while uploading a file\n\n var item = root.query('GET_ITEM', action.id);\n var filename = item.filename;\n var label = root.query('GET_LABEL_FILE_PROCESSING_COMPLETE');\n\n assist(root, filename + ' ' + label);\n };\n\n var itemProcessedUndo = function itemProcessedUndo(_ref5) {\n var root = _ref5.root,\n action = _ref5.action;\n var item = root.query('GET_ITEM', action.id);\n var filename = item.filename;\n var label = root.query('GET_LABEL_FILE_PROCESSING_ABORTED');\n\n assist(root, filename + ' ' + label);\n };\n\n var itemError = function itemError(_ref6) {\n var root = _ref6.root,\n action = _ref6.action;\n var item = root.query('GET_ITEM', action.id);\n var filename = item.filename;\n\n // will also notify the user when FilePond is not being used, as the user might be occupied with other activities while uploading a file\n\n assist(root, action.status.main + ' ' + filename + ' ' + action.status.sub);\n };\n\n var assistant = createView({\n create: create$d,\n ignoreRect: true,\n ignoreRectUpdate: true,\n write: createRoute({\n DID_LOAD_ITEM: itemAdded,\n DID_REMOVE_ITEM: itemRemoved,\n DID_COMPLETE_ITEM_PROCESSING: itemProcessed,\n\n DID_ABORT_ITEM_PROCESSING: itemProcessedUndo,\n DID_REVERT_ITEM_PROCESSING: itemProcessedUndo,\n\n DID_THROW_ITEM_REMOVE_ERROR: itemError,\n DID_THROW_ITEM_LOAD_ERROR: itemError,\n DID_THROW_ITEM_INVALID: itemError,\n DID_THROW_ITEM_PROCESSING_ERROR: itemError,\n }),\n\n tag: 'span',\n name: 'assistant',\n });\n\n var toCamels = function toCamels(string) {\n var separator = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : '-';\n return string.replace(new RegExp(separator + '.', 'g'), function(sub) {\n return sub.charAt(1).toUpperCase();\n });\n };\n\n var debounce = function debounce(func) {\n var interval = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 16;\n var immidiateOnly =\n arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : true;\n var last = Date.now();\n var timeout = null;\n\n return function() {\n for (\n var _len = arguments.length, args = new Array(_len), _key = 0;\n _key < _len;\n _key++\n ) {\n args[_key] = arguments[_key];\n }\n clearTimeout(timeout);\n\n var dist = Date.now() - last;\n\n var fn = function fn() {\n last = Date.now();\n func.apply(void 0, args);\n };\n\n if (dist < interval) {\n // we need to delay by the difference between interval and dist\n // for example: if distance is 10 ms and interval is 16 ms,\n // we need to wait an additional 6ms before calling the function)\n if (!immidiateOnly) {\n timeout = setTimeout(fn, interval - dist);\n }\n } else {\n // go!\n fn();\n }\n };\n };\n\n var MAX_FILES_LIMIT = 1000000;\n\n var prevent = function prevent(e) {\n return e.preventDefault();\n };\n\n var create$e = function create(_ref) {\n var root = _ref.root,\n props = _ref.props;\n // Add id\n var id = root.query('GET_ID');\n if (id) {\n root.element.id = id;\n }\n\n // Add className\n var className = root.query('GET_CLASS_NAME');\n if (className) {\n className\n .split(' ')\n .filter(function(name) {\n return name.length;\n })\n .forEach(function(name) {\n root.element.classList.add(name);\n });\n }\n\n // Field label\n root.ref.label = root.appendChildView(\n root.createChildView(\n dropLabel,\n Object.assign({}, props, {\n translateY: null,\n caption: root.query('GET_LABEL_IDLE'),\n })\n )\n );\n\n // List of items\n root.ref.list = root.appendChildView(\n root.createChildView(listScroller, { translateY: null })\n );\n\n // Background panel\n root.ref.panel = root.appendChildView(root.createChildView(panel, { name: 'panel-root' }));\n\n // Assistant notifies assistive tech when content changes\n root.ref.assistant = root.appendChildView(\n root.createChildView(assistant, Object.assign({}, props))\n );\n\n // Data\n root.ref.data = root.appendChildView(root.createChildView(data, Object.assign({}, props)));\n\n // Measure (tests if fixed height was set)\n // DOCTYPE needs to be set for this to work\n root.ref.measure = createElement$1('div');\n root.ref.measure.style.height = '100%';\n root.element.appendChild(root.ref.measure);\n\n // information on the root height or fixed height status\n root.ref.bounds = null;\n\n // apply initial style properties\n root.query('GET_STYLES')\n .filter(function(style) {\n return !isEmpty(style.value);\n })\n .map(function(_ref2) {\n var name = _ref2.name,\n value = _ref2.value;\n root.element.dataset[name] = value;\n });\n\n // determine if width changed\n root.ref.widthPrevious = null;\n root.ref.widthUpdated = debounce(function() {\n root.ref.updateHistory = [];\n root.dispatch('DID_RESIZE_ROOT');\n }, 250);\n\n // history of updates\n root.ref.previousAspectRatio = null;\n root.ref.updateHistory = [];\n\n // prevent scrolling and zooming on iOS (only if supports pointer events, for then we can enable reorder)\n var canHover = window.matchMedia('(pointer: fine) and (hover: hover)').matches;\n var hasPointerEvents = 'PointerEvent' in window;\n if (root.query('GET_ALLOW_REORDER') && hasPointerEvents && !canHover) {\n root.element.addEventListener('touchmove', prevent, { passive: false });\n root.element.addEventListener('gesturestart', prevent);\n }\n\n // add credits\n var credits = root.query('GET_CREDITS');\n var hasCredits = credits.length === 2;\n if (hasCredits) {\n var frag = document.createElement('a');\n frag.className = 'filepond--credits';\n frag.setAttribute('aria-hidden', 'true');\n frag.href = credits[0];\n frag.tabindex = -1;\n frag.target = '_blank';\n frag.rel = 'noopener noreferrer';\n frag.textContent = credits[1];\n root.element.appendChild(frag);\n root.ref.credits = frag;\n }\n };\n\n var write$9 = function write(_ref3) {\n var root = _ref3.root,\n props = _ref3.props,\n actions = _ref3.actions;\n // route actions\n route$5({ root: root, props: props, actions: actions });\n\n // apply style properties\n actions\n .filter(function(action) {\n return /^DID_SET_STYLE_/.test(action.type);\n })\n .filter(function(action) {\n return !isEmpty(action.data.value);\n })\n .map(function(_ref4) {\n var type = _ref4.type,\n data = _ref4.data;\n var name = toCamels(type.substring(8).toLowerCase(), '_');\n root.element.dataset[name] = data.value;\n root.invalidateLayout();\n });\n\n if (root.rect.element.hidden) return;\n\n if (root.rect.element.width !== root.ref.widthPrevious) {\n root.ref.widthPrevious = root.rect.element.width;\n root.ref.widthUpdated();\n }\n\n // get box bounds, we do this only once\n var bounds = root.ref.bounds;\n if (!bounds) {\n bounds = root.ref.bounds = calculateRootBoundingBoxHeight(root);\n\n // destroy measure element\n root.element.removeChild(root.ref.measure);\n root.ref.measure = null;\n }\n\n // get quick references to various high level parts of the upload tool\n var _root$ref = root.ref,\n hopper = _root$ref.hopper,\n label = _root$ref.label,\n list = _root$ref.list,\n panel = _root$ref.panel;\n\n // sets correct state to hopper scope\n if (hopper) {\n hopper.updateHopperState();\n }\n\n // bool to indicate if we're full or not\n var aspectRatio = root.query('GET_PANEL_ASPECT_RATIO');\n var isMultiItem = root.query('GET_ALLOW_MULTIPLE');\n var totalItems = root.query('GET_TOTAL_ITEMS');\n var maxItems = isMultiItem ? root.query('GET_MAX_FILES') || MAX_FILES_LIMIT : 1;\n var atMaxCapacity = totalItems === maxItems;\n\n // action used to add item\n var addAction = actions.find(function(action) {\n return action.type === 'DID_ADD_ITEM';\n });\n\n // if reached max capacity and we've just reached it\n if (atMaxCapacity && addAction) {\n // get interaction type\n var interactionMethod = addAction.data.interactionMethod;\n\n // hide label\n label.opacity = 0;\n\n if (isMultiItem) {\n label.translateY = -40;\n } else {\n if (interactionMethod === InteractionMethod.API) {\n label.translateX = 40;\n } else if (interactionMethod === InteractionMethod.BROWSE) {\n label.translateY = 40;\n } else {\n label.translateY = 30;\n }\n }\n } else if (!atMaxCapacity) {\n label.opacity = 1;\n label.translateX = 0;\n label.translateY = 0;\n }\n\n var listItemMargin = calculateListItemMargin(root);\n\n var listHeight = calculateListHeight(root);\n\n var labelHeight = label.rect.element.height;\n var currentLabelHeight = !isMultiItem || atMaxCapacity ? 0 : labelHeight;\n\n var listMarginTop = atMaxCapacity ? list.rect.element.marginTop : 0;\n var listMarginBottom = totalItems === 0 ? 0 : list.rect.element.marginBottom;\n\n var visualHeight =\n currentLabelHeight + listMarginTop + listHeight.visual + listMarginBottom;\n var boundsHeight =\n currentLabelHeight + listMarginTop + listHeight.bounds + listMarginBottom;\n\n // link list to label bottom position\n list.translateY =\n Math.max(0, currentLabelHeight - list.rect.element.marginTop) - listItemMargin.top;\n\n if (aspectRatio) {\n // fixed aspect ratio\n\n // calculate height based on width\n var width = root.rect.element.width;\n var height = width * aspectRatio;\n\n // clear history if aspect ratio has changed\n if (aspectRatio !== root.ref.previousAspectRatio) {\n root.ref.previousAspectRatio = aspectRatio;\n root.ref.updateHistory = [];\n }\n\n // remember this width\n var history = root.ref.updateHistory;\n history.push(width);\n\n var MAX_BOUNCES = 2;\n if (history.length > MAX_BOUNCES * 2) {\n var l = history.length;\n var bottom = l - 10;\n var bounces = 0;\n for (var i = l; i >= bottom; i--) {\n if (history[i] === history[i - 2]) {\n bounces++;\n }\n\n if (bounces >= MAX_BOUNCES) {\n // dont adjust height\n return;\n }\n }\n }\n\n // fix height of panel so it adheres to aspect ratio\n panel.scalable = false;\n panel.height = height;\n\n // available height for list\n var listAvailableHeight =\n // the height of the panel minus the label height\n height -\n currentLabelHeight -\n // the room we leave open between the end of the list and the panel bottom\n (listMarginBottom - listItemMargin.bottom) -\n // if we're full we need to leave some room between the top of the panel and the list\n (atMaxCapacity ? listMarginTop : 0);\n\n if (listHeight.visual > listAvailableHeight) {\n list.overflow = listAvailableHeight;\n } else {\n list.overflow = null;\n }\n\n // set container bounds (so pushes siblings downwards)\n root.height = height;\n } else if (bounds.fixedHeight) {\n // fixed height\n\n // fix height of panel\n panel.scalable = false;\n\n // available height for list\n var _listAvailableHeight =\n // the height of the panel minus the label height\n bounds.fixedHeight -\n currentLabelHeight -\n // the room we leave open between the end of the list and the panel bottom\n (listMarginBottom - listItemMargin.bottom) -\n // if we're full we need to leave some room between the top of the panel and the list\n (atMaxCapacity ? listMarginTop : 0);\n\n // set list height\n if (listHeight.visual > _listAvailableHeight) {\n list.overflow = _listAvailableHeight;\n } else {\n list.overflow = null;\n }\n\n // no need to set container bounds as these are handles by CSS fixed height\n } else if (bounds.cappedHeight) {\n // max-height\n\n // not a fixed height panel\n var isCappedHeight = visualHeight >= bounds.cappedHeight;\n var panelHeight = Math.min(bounds.cappedHeight, visualHeight);\n panel.scalable = true;\n panel.height = isCappedHeight\n ? panelHeight\n : panelHeight - listItemMargin.top - listItemMargin.bottom;\n\n // available height for list\n var _listAvailableHeight2 =\n // the height of the panel minus the label height\n panelHeight -\n currentLabelHeight -\n // the room we leave open between the end of the list and the panel bottom\n (listMarginBottom - listItemMargin.bottom) -\n // if we're full we need to leave some room between the top of the panel and the list\n (atMaxCapacity ? listMarginTop : 0);\n\n // set list height (if is overflowing)\n if (visualHeight > bounds.cappedHeight && listHeight.visual > _listAvailableHeight2) {\n list.overflow = _listAvailableHeight2;\n } else {\n list.overflow = null;\n }\n\n // set container bounds (so pushes siblings downwards)\n root.height = Math.min(\n bounds.cappedHeight,\n boundsHeight - listItemMargin.top - listItemMargin.bottom\n );\n } else {\n // flexible height\n\n // not a fixed height panel\n var itemMargin = totalItems > 0 ? listItemMargin.top + listItemMargin.bottom : 0;\n panel.scalable = true;\n panel.height = Math.max(labelHeight, visualHeight - itemMargin);\n\n // set container bounds (so pushes siblings downwards)\n root.height = Math.max(labelHeight, boundsHeight - itemMargin);\n }\n\n // move credits to bottom\n if (root.ref.credits && panel.heightCurrent)\n root.ref.credits.style.transform = 'translateY(' + panel.heightCurrent + 'px)';\n };\n\n var calculateListItemMargin = function calculateListItemMargin(root) {\n var item = root.ref.list.childViews[0].childViews[0];\n return item\n ? {\n top: item.rect.element.marginTop,\n bottom: item.rect.element.marginBottom,\n }\n : {\n top: 0,\n bottom: 0,\n };\n };\n\n var calculateListHeight = function calculateListHeight(root) {\n var visual = 0;\n var bounds = 0;\n\n // get file list reference\n var scrollList = root.ref.list;\n var itemList = scrollList.childViews[0];\n var visibleChildren = itemList.childViews.filter(function(child) {\n return child.rect.element.height;\n });\n var children = root\n .query('GET_ACTIVE_ITEMS')\n .map(function(item) {\n return visibleChildren.find(function(child) {\n return child.id === item.id;\n });\n })\n .filter(function(item) {\n return item;\n });\n\n // no children, done!\n if (children.length === 0) return { visual: visual, bounds: bounds };\n\n var horizontalSpace = itemList.rect.element.width;\n var dragIndex = getItemIndexByPosition(itemList, children, scrollList.dragCoordinates);\n\n var childRect = children[0].rect.element;\n\n var itemVerticalMargin = childRect.marginTop + childRect.marginBottom;\n var itemHorizontalMargin = childRect.marginLeft + childRect.marginRight;\n\n var itemWidth = childRect.width + itemHorizontalMargin;\n var itemHeight = childRect.height + itemVerticalMargin;\n\n var newItem = typeof dragIndex !== 'undefined' && dragIndex >= 0 ? 1 : 0;\n var removedItem = children.find(function(child) {\n return child.markedForRemoval && child.opacity < 0.45;\n })\n ? -1\n : 0;\n var verticalItemCount = children.length + newItem + removedItem;\n var itemsPerRow = getItemsPerRow(horizontalSpace, itemWidth);\n\n // stack\n if (itemsPerRow === 1) {\n children.forEach(function(item) {\n var height = item.rect.element.height + itemVerticalMargin;\n bounds += height;\n visual += height * item.opacity;\n });\n }\n // grid\n else {\n bounds = Math.ceil(verticalItemCount / itemsPerRow) * itemHeight;\n visual = bounds;\n }\n\n return { visual: visual, bounds: bounds };\n };\n\n var calculateRootBoundingBoxHeight = function calculateRootBoundingBoxHeight(root) {\n var height = root.ref.measureHeight || null;\n var cappedHeight = parseInt(root.style.maxHeight, 10) || null;\n var fixedHeight = height === 0 ? null : height;\n\n return {\n cappedHeight: cappedHeight,\n fixedHeight: fixedHeight,\n };\n };\n\n var exceedsMaxFiles = function exceedsMaxFiles(root, items) {\n var allowReplace = root.query('GET_ALLOW_REPLACE');\n var allowMultiple = root.query('GET_ALLOW_MULTIPLE');\n var totalItems = root.query('GET_TOTAL_ITEMS');\n var maxItems = root.query('GET_MAX_FILES');\n\n // total amount of items being dragged\n var totalBrowseItems = items.length;\n\n // if does not allow multiple items and dragging more than one item\n if (!allowMultiple && totalBrowseItems > 1) {\n root.dispatch('DID_THROW_MAX_FILES', {\n source: items,\n error: createResponse('warning', 0, 'Max files'),\n });\n\n return true;\n }\n\n // limit max items to one if not allowed to drop multiple items\n maxItems = allowMultiple ? maxItems : 1;\n\n if (!allowMultiple && allowReplace) {\n // There is only one item, so there is room to replace or add an item\n return false;\n }\n\n // no more room?\n var hasMaxItems = isInt(maxItems);\n if (hasMaxItems && totalItems + totalBrowseItems > maxItems) {\n root.dispatch('DID_THROW_MAX_FILES', {\n source: items,\n error: createResponse('warning', 0, 'Max files'),\n });\n\n return true;\n }\n\n return false;\n };\n\n var getDragIndex = function getDragIndex(list, children, position) {\n var itemList = list.childViews[0];\n return getItemIndexByPosition(itemList, children, {\n left: position.scopeLeft - itemList.rect.element.left,\n top:\n position.scopeTop -\n (list.rect.outer.top + list.rect.element.marginTop + list.rect.element.scrollTop),\n });\n };\n\n /**\n * Enable or disable file drop functionality\n */\n var toggleDrop = function toggleDrop(root) {\n var isAllowed = root.query('GET_ALLOW_DROP');\n var isDisabled = root.query('GET_DISABLED');\n var enabled = isAllowed && !isDisabled;\n if (enabled && !root.ref.hopper) {\n var hopper = createHopper(\n root.element,\n function(items) {\n // allow quick validation of dropped items\n var beforeDropFile =\n root.query('GET_BEFORE_DROP_FILE') ||\n function() {\n return true;\n };\n\n // all items should be validated by all filters as valid\n var dropValidation = root.query('GET_DROP_VALIDATION');\n return dropValidation\n ? items.every(function(item) {\n return (\n applyFilters('ALLOW_HOPPER_ITEM', item, {\n query: root.query,\n }).every(function(result) {\n return result === true;\n }) && beforeDropFile(item)\n );\n })\n : true;\n },\n {\n filterItems: function filterItems(items) {\n var ignoredFiles = root.query('GET_IGNORED_FILES');\n return items.filter(function(item) {\n if (isFile(item)) {\n return !ignoredFiles.includes(item.name.toLowerCase());\n }\n return true;\n });\n },\n catchesDropsOnPage: root.query('GET_DROP_ON_PAGE'),\n requiresDropOnElement: root.query('GET_DROP_ON_ELEMENT'),\n }\n );\n\n hopper.onload = function(items, position) {\n // get item children elements and sort based on list sort\n var list = root.ref.list.childViews[0];\n var visibleChildren = list.childViews.filter(function(child) {\n return child.rect.element.height;\n });\n var children = root\n .query('GET_ACTIVE_ITEMS')\n .map(function(item) {\n return visibleChildren.find(function(child) {\n return child.id === item.id;\n });\n })\n .filter(function(item) {\n return item;\n });\n\n applyFilterChain('ADD_ITEMS', items, { dispatch: root.dispatch }).then(function(\n queue\n ) {\n // these files don't fit so stop here\n if (exceedsMaxFiles(root, queue)) return false;\n\n // go\n root.dispatch('ADD_ITEMS', {\n items: queue,\n index: getDragIndex(root.ref.list, children, position),\n interactionMethod: InteractionMethod.DROP,\n });\n });\n\n root.dispatch('DID_DROP', { position: position });\n\n root.dispatch('DID_END_DRAG', { position: position });\n };\n\n hopper.ondragstart = function(position) {\n root.dispatch('DID_START_DRAG', { position: position });\n };\n\n hopper.ondrag = debounce(function(position) {\n root.dispatch('DID_DRAG', { position: position });\n });\n\n hopper.ondragend = function(position) {\n root.dispatch('DID_END_DRAG', { position: position });\n };\n\n root.ref.hopper = hopper;\n\n root.ref.drip = root.appendChildView(root.createChildView(drip));\n } else if (!enabled && root.ref.hopper) {\n root.ref.hopper.destroy();\n root.ref.hopper = null;\n root.removeChildView(root.ref.drip);\n }\n };\n\n /**\n * Enable or disable browse functionality\n */\n var toggleBrowse = function toggleBrowse(root, props) {\n var isAllowed = root.query('GET_ALLOW_BROWSE');\n var isDisabled = root.query('GET_DISABLED');\n var enabled = isAllowed && !isDisabled;\n if (enabled && !root.ref.browser) {\n root.ref.browser = root.appendChildView(\n root.createChildView(\n browser,\n Object.assign({}, props, {\n onload: function onload(items) {\n applyFilterChain('ADD_ITEMS', items, {\n dispatch: root.dispatch,\n }).then(function(queue) {\n // these files don't fit so stop here\n if (exceedsMaxFiles(root, queue)) return false;\n\n // add items!\n root.dispatch('ADD_ITEMS', {\n items: queue,\n index: -1,\n interactionMethod: InteractionMethod.BROWSE,\n });\n });\n },\n })\n ),\n\n 0\n );\n } else if (!enabled && root.ref.browser) {\n root.removeChildView(root.ref.browser);\n root.ref.browser = null;\n }\n };\n\n /**\n * Enable or disable paste functionality\n */\n var togglePaste = function togglePaste(root) {\n var isAllowed = root.query('GET_ALLOW_PASTE');\n var isDisabled = root.query('GET_DISABLED');\n var enabled = isAllowed && !isDisabled;\n if (enabled && !root.ref.paster) {\n root.ref.paster = createPaster();\n root.ref.paster.onload = function(items) {\n applyFilterChain('ADD_ITEMS', items, { dispatch: root.dispatch }).then(function(\n queue\n ) {\n // these files don't fit so stop here\n if (exceedsMaxFiles(root, queue)) return false;\n\n // add items!\n root.dispatch('ADD_ITEMS', {\n items: queue,\n index: -1,\n interactionMethod: InteractionMethod.PASTE,\n });\n });\n };\n } else if (!enabled && root.ref.paster) {\n root.ref.paster.destroy();\n root.ref.paster = null;\n }\n };\n\n /**\n * Route actions\n */\n var route$5 = createRoute({\n DID_SET_ALLOW_BROWSE: function DID_SET_ALLOW_BROWSE(_ref5) {\n var root = _ref5.root,\n props = _ref5.props;\n toggleBrowse(root, props);\n },\n DID_SET_ALLOW_DROP: function DID_SET_ALLOW_DROP(_ref6) {\n var root = _ref6.root;\n toggleDrop(root);\n },\n DID_SET_ALLOW_PASTE: function DID_SET_ALLOW_PASTE(_ref7) {\n var root = _ref7.root;\n togglePaste(root);\n },\n DID_SET_DISABLED: function DID_SET_DISABLED(_ref8) {\n var root = _ref8.root,\n props = _ref8.props;\n toggleDrop(root);\n togglePaste(root);\n toggleBrowse(root, props);\n var isDisabled = root.query('GET_DISABLED');\n if (isDisabled) {\n root.element.dataset.disabled = 'disabled';\n } else {\n // delete root.element.dataset.disabled; <= this does not work on iOS 10\n root.element.removeAttribute('data-disabled');\n }\n },\n });\n\n var root = createView({\n name: 'root',\n read: function read(_ref9) {\n var root = _ref9.root;\n if (root.ref.measure) {\n root.ref.measureHeight = root.ref.measure.offsetHeight;\n }\n },\n create: create$e,\n write: write$9,\n destroy: function destroy(_ref10) {\n var root = _ref10.root;\n if (root.ref.paster) {\n root.ref.paster.destroy();\n }\n if (root.ref.hopper) {\n root.ref.hopper.destroy();\n }\n root.element.removeEventListener('touchmove', prevent);\n root.element.removeEventListener('gesturestart', prevent);\n },\n mixins: {\n styles: ['height'],\n },\n });\n\n // creates the app\n var createApp = function createApp() {\n var initialOptions = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};\n // let element\n var originalElement = null;\n\n // get default options\n var defaultOptions = getOptions();\n\n // create the data store, this will contain all our app info\n var store = createStore(\n // initial state (should be serializable)\n createInitialState(defaultOptions),\n\n // queries\n [queries, createOptionQueries(defaultOptions)],\n\n // action handlers\n [actions, createOptionActions(defaultOptions)]\n );\n\n // set initial options\n store.dispatch('SET_OPTIONS', { options: initialOptions });\n\n // kick thread if visibility changes\n var visibilityHandler = function visibilityHandler() {\n if (document.hidden) return;\n store.dispatch('KICK');\n };\n document.addEventListener('visibilitychange', visibilityHandler);\n\n // re-render on window resize start and finish\n var resizeDoneTimer = null;\n var isResizing = false;\n var isResizingHorizontally = false;\n var initialWindowWidth = null;\n var currentWindowWidth = null;\n var resizeHandler = function resizeHandler() {\n if (!isResizing) {\n isResizing = true;\n }\n clearTimeout(resizeDoneTimer);\n resizeDoneTimer = setTimeout(function() {\n isResizing = false;\n initialWindowWidth = null;\n currentWindowWidth = null;\n if (isResizingHorizontally) {\n isResizingHorizontally = false;\n store.dispatch('DID_STOP_RESIZE');\n }\n }, 500);\n };\n window.addEventListener('resize', resizeHandler);\n\n // render initial view\n var view = root(store, { id: getUniqueId() });\n\n //\n // PRIVATE API -------------------------------------------------------------------------------------\n //\n var isResting = false;\n var isHidden = false;\n\n var readWriteApi = {\n // necessary for update loop\n\n /**\n * Reads from dom (never call manually)\n * @private\n */\n _read: function _read() {\n // test if we're resizing horizontally\n // TODO: see if we can optimize this by measuring root rect\n if (isResizing) {\n currentWindowWidth = window.innerWidth;\n if (!initialWindowWidth) {\n initialWindowWidth = currentWindowWidth;\n }\n\n if (!isResizingHorizontally && currentWindowWidth !== initialWindowWidth) {\n store.dispatch('DID_START_RESIZE');\n isResizingHorizontally = true;\n }\n }\n\n if (isHidden && isResting) {\n // test if is no longer hidden\n isResting = view.element.offsetParent === null;\n }\n\n // if resting, no need to read as numbers will still all be correct\n if (isResting) return;\n\n // read view data\n view._read();\n\n // if is hidden we need to know so we exit rest mode when revealed\n isHidden = view.rect.element.hidden;\n },\n\n /**\n * Writes to dom (never call manually)\n * @private\n */\n _write: function _write(ts) {\n // get all actions from store\n var actions = store\n .processActionQueue()\n\n // filter out set actions (these will automatically trigger DID_SET)\n .filter(function(action) {\n return !/^SET_/.test(action.type);\n });\n\n // if was idling and no actions stop here\n if (isResting && !actions.length) return;\n\n // some actions might trigger events\n routeActionsToEvents(actions);\n\n // update the view\n isResting = view._write(ts, actions, isResizingHorizontally);\n\n // will clean up all archived items\n removeReleasedItems(store.query('GET_ITEMS'));\n\n // now idling\n if (isResting) {\n store.processDispatchQueue();\n }\n },\n };\n\n //\n // EXPOSE EVENTS -------------------------------------------------------------------------------------\n //\n var createEvent = function createEvent(name) {\n return function(data) {\n // create default event\n var event = {\n type: name,\n };\n\n // no data to add\n if (!data) {\n return event;\n }\n\n // copy relevant props\n if (data.hasOwnProperty('error')) {\n event.error = data.error ? Object.assign({}, data.error) : null;\n }\n\n if (data.status) {\n event.status = Object.assign({}, data.status);\n }\n\n if (data.file) {\n event.output = data.file;\n }\n\n // only source is available, else add item if possible\n if (data.source) {\n event.file = data.source;\n } else if (data.item || data.id) {\n var item = data.item ? data.item : store.query('GET_ITEM', data.id);\n event.file = item ? createItemAPI(item) : null;\n }\n\n // map all items in a possible items array\n if (data.items) {\n event.items = data.items.map(createItemAPI);\n }\n\n // if this is a progress event add the progress amount\n if (/progress/.test(name)) {\n event.progress = data.progress;\n }\n\n // copy relevant props\n if (data.hasOwnProperty('origin') && data.hasOwnProperty('target')) {\n event.origin = data.origin;\n event.target = data.target;\n }\n\n return event;\n };\n };\n\n var eventRoutes = {\n DID_DESTROY: createEvent('destroy'),\n\n DID_INIT: createEvent('init'),\n\n DID_THROW_MAX_FILES: createEvent('warning'),\n\n DID_INIT_ITEM: createEvent('initfile'),\n DID_START_ITEM_LOAD: createEvent('addfilestart'),\n DID_UPDATE_ITEM_LOAD_PROGRESS: createEvent('addfileprogress'),\n DID_LOAD_ITEM: createEvent('addfile'),\n\n DID_THROW_ITEM_INVALID: [createEvent('error'), createEvent('addfile')],\n\n DID_THROW_ITEM_LOAD_ERROR: [createEvent('error'), createEvent('addfile')],\n\n DID_THROW_ITEM_REMOVE_ERROR: [createEvent('error'), createEvent('removefile')],\n\n DID_PREPARE_OUTPUT: createEvent('preparefile'),\n\n DID_START_ITEM_PROCESSING: createEvent('processfilestart'),\n DID_UPDATE_ITEM_PROCESS_PROGRESS: createEvent('processfileprogress'),\n DID_ABORT_ITEM_PROCESSING: createEvent('processfileabort'),\n DID_COMPLETE_ITEM_PROCESSING: createEvent('processfile'),\n DID_COMPLETE_ITEM_PROCESSING_ALL: createEvent('processfiles'),\n DID_REVERT_ITEM_PROCESSING: createEvent('processfilerevert'),\n\n DID_THROW_ITEM_PROCESSING_ERROR: [createEvent('error'), createEvent('processfile')],\n\n DID_REMOVE_ITEM: createEvent('removefile'),\n\n DID_UPDATE_ITEMS: createEvent('updatefiles'),\n\n DID_ACTIVATE_ITEM: createEvent('activatefile'),\n\n DID_REORDER_ITEMS: createEvent('reorderfiles'),\n };\n\n var exposeEvent = function exposeEvent(event) {\n // create event object to be dispatched\n var detail = Object.assign({ pond: exports }, event);\n delete detail.type;\n view.element.dispatchEvent(\n new CustomEvent('FilePond:' + event.type, {\n // event info\n detail: detail,\n\n // event behaviour\n bubbles: true,\n cancelable: true,\n composed: true, // triggers listeners outside of shadow root\n })\n );\n\n // event object to params used for `on()` event handlers and callbacks `oninit()`\n var params = [];\n\n // if is possible error event, make it the first param\n if (event.hasOwnProperty('error')) {\n params.push(event.error);\n }\n\n // file is always section\n if (event.hasOwnProperty('file')) {\n params.push(event.file);\n }\n\n // append other props\n var filtered = ['type', 'error', 'file'];\n Object.keys(event)\n .filter(function(key) {\n return !filtered.includes(key);\n })\n .forEach(function(key) {\n return params.push(event[key]);\n });\n\n // on(type, () => { })\n exports.fire.apply(exports, [event.type].concat(params));\n\n // oninit = () => {}\n var handler = store.query('GET_ON' + event.type.toUpperCase());\n if (handler) {\n handler.apply(void 0, params);\n }\n };\n\n var routeActionsToEvents = function routeActionsToEvents(actions) {\n if (!actions.length) return;\n actions\n .filter(function(action) {\n return eventRoutes[action.type];\n })\n .forEach(function(action) {\n var routes = eventRoutes[action.type];\n (Array.isArray(routes) ? routes : [routes]).forEach(function(route) {\n // this isn't fantastic, but because of the stacking of settimeouts plugins can handle the did_load before the did_init\n if (action.type === 'DID_INIT_ITEM') {\n exposeEvent(route(action.data));\n } else {\n setTimeout(function() {\n exposeEvent(route(action.data));\n }, 0);\n }\n });\n });\n };\n\n //\n // PUBLIC API -------------------------------------------------------------------------------------\n //\n var setOptions = function setOptions(options) {\n return store.dispatch('SET_OPTIONS', { options: options });\n };\n\n var getFile = function getFile(query) {\n return store.query('GET_ACTIVE_ITEM', query);\n };\n\n var prepareFile = function prepareFile(query) {\n return new Promise(function(resolve, reject) {\n store.dispatch('REQUEST_ITEM_PREPARE', {\n query: query,\n success: function success(item) {\n resolve(item);\n },\n failure: function failure(error) {\n reject(error);\n },\n });\n });\n };\n\n var addFile = function addFile(source) {\n var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};\n return new Promise(function(resolve, reject) {\n addFiles([{ source: source, options: options }], { index: options.index })\n .then(function(items) {\n return resolve(items && items[0]);\n })\n .catch(reject);\n });\n };\n\n var isFilePondFile = function isFilePondFile(obj) {\n return obj.file && obj.id;\n };\n\n var removeFile = function removeFile(query, options) {\n // if only passed options\n if (typeof query === 'object' && !isFilePondFile(query) && !options) {\n options = query;\n query = undefined;\n }\n\n // request item removal\n store.dispatch('REMOVE_ITEM', Object.assign({}, options, { query: query }));\n\n // see if item has been removed\n return store.query('GET_ACTIVE_ITEM', query) === null;\n };\n\n var addFiles = function addFiles() {\n for (\n var _len = arguments.length, args = new Array(_len), _key = 0;\n _key < _len;\n _key++\n ) {\n args[_key] = arguments[_key];\n }\n return new Promise(function(resolve, reject) {\n var sources = [];\n var options = {};\n\n // user passed a sources array\n if (isArray(args[0])) {\n sources.push.apply(sources, args[0]);\n Object.assign(options, args[1] || {});\n } else {\n // user passed sources as arguments, last one might be options object\n var lastArgument = args[args.length - 1];\n if (typeof lastArgument === 'object' && !(lastArgument instanceof Blob)) {\n Object.assign(options, args.pop());\n }\n\n // add rest to sources\n sources.push.apply(sources, args);\n }\n\n store.dispatch('ADD_ITEMS', {\n items: sources,\n index: options.index,\n interactionMethod: InteractionMethod.API,\n success: resolve,\n failure: reject,\n });\n });\n };\n\n var getFiles = function getFiles() {\n return store.query('GET_ACTIVE_ITEMS');\n };\n\n var processFile = function processFile(query) {\n return new Promise(function(resolve, reject) {\n store.dispatch('REQUEST_ITEM_PROCESSING', {\n query: query,\n success: function success(item) {\n resolve(item);\n },\n failure: function failure(error) {\n reject(error);\n },\n });\n });\n };\n\n var prepareFiles = function prepareFiles() {\n for (\n var _len2 = arguments.length, args = new Array(_len2), _key2 = 0;\n _key2 < _len2;\n _key2++\n ) {\n args[_key2] = arguments[_key2];\n }\n var queries = Array.isArray(args[0]) ? args[0] : args;\n var items = queries.length ? queries : getFiles();\n return Promise.all(items.map(prepareFile));\n };\n\n var processFiles = function processFiles() {\n for (\n var _len3 = arguments.length, args = new Array(_len3), _key3 = 0;\n _key3 < _len3;\n _key3++\n ) {\n args[_key3] = arguments[_key3];\n }\n var queries = Array.isArray(args[0]) ? args[0] : args;\n if (!queries.length) {\n var files = getFiles().filter(function(item) {\n return (\n !(item.status === ItemStatus.IDLE && item.origin === FileOrigin.LOCAL) &&\n item.status !== ItemStatus.PROCESSING &&\n item.status !== ItemStatus.PROCESSING_COMPLETE &&\n item.status !== ItemStatus.PROCESSING_REVERT_ERROR\n );\n });\n\n return Promise.all(files.map(processFile));\n }\n return Promise.all(queries.map(processFile));\n };\n\n var removeFiles = function removeFiles() {\n for (\n var _len4 = arguments.length, args = new Array(_len4), _key4 = 0;\n _key4 < _len4;\n _key4++\n ) {\n args[_key4] = arguments[_key4];\n }\n\n var queries = Array.isArray(args[0]) ? args[0] : args;\n\n var options;\n if (typeof queries[queries.length - 1] === 'object') {\n options = queries.pop();\n } else if (Array.isArray(args[0])) {\n options = args[1];\n }\n\n var files = getFiles();\n\n if (!queries.length)\n return Promise.all(\n files.map(function(file) {\n return removeFile(file, options);\n })\n );\n\n // when removing by index the indexes shift after each file removal so we need to convert indexes to ids\n var mappedQueries = queries\n .map(function(query) {\n return isNumber(query) ? (files[query] ? files[query].id : null) : query;\n })\n .filter(function(query) {\n return query;\n });\n\n return mappedQueries.map(function(q) {\n return removeFile(q, options);\n });\n };\n\n var exports = Object.assign(\n {},\n\n on(),\n {},\n\n readWriteApi,\n {},\n\n createOptionAPI(store, defaultOptions),\n {\n /**\n * Override options defined in options object\n * @param options\n */\n setOptions: setOptions,\n\n /**\n * Load the given file\n * @param source - the source of the file (either a File, base64 data uri or url)\n * @param options - object, { index: 0 }\n */\n addFile: addFile,\n\n /**\n * Load the given files\n * @param sources - the sources of the files to load\n * @param options - object, { index: 0 }\n */\n addFiles: addFiles,\n\n /**\n * Returns the file objects matching the given query\n * @param query { string, number, null }\n */\n getFile: getFile,\n\n /**\n * Upload file with given name\n * @param query { string, number, null }\n */\n processFile: processFile,\n\n /**\n * Request prepare output for file with given name\n * @param query { string, number, null }\n */\n prepareFile: prepareFile,\n\n /**\n * Removes a file by its name\n * @param query { string, number, null }\n */\n removeFile: removeFile,\n\n /**\n * Moves a file to a new location in the files list\n */\n moveFile: function moveFile(query, index) {\n return store.dispatch('MOVE_ITEM', { query: query, index: index });\n },\n\n /**\n * Returns all files (wrapped in public api)\n */\n getFiles: getFiles,\n\n /**\n * Starts uploading all files\n */\n processFiles: processFiles,\n\n /**\n * Clears all files from the files list\n */\n removeFiles: removeFiles,\n\n /**\n * Starts preparing output of all files\n */\n prepareFiles: prepareFiles,\n\n /**\n * Sort list of files\n */\n sort: function sort(compare) {\n return store.dispatch('SORT', { compare: compare });\n },\n\n /**\n * Browse the file system for a file\n */\n browse: function browse() {\n // needs to be trigger directly as user action needs to be traceable (is not traceable in requestAnimationFrame)\n var input = view.element.querySelector('input[type=file]');\n if (input) {\n input.click();\n }\n },\n\n /**\n * Destroys the app\n */\n destroy: function destroy() {\n // request destruction\n exports.fire('destroy', view.element);\n\n // stop active processes (file uploads, fetches, stuff like that)\n // loop over items and depending on states call abort for ongoing processes\n store.dispatch('ABORT_ALL');\n\n // destroy view\n view._destroy();\n\n // stop listening to resize\n window.removeEventListener('resize', resizeHandler);\n\n // stop listening to the visiblitychange event\n document.removeEventListener('visibilitychange', visibilityHandler);\n\n // dispatch destroy\n store.dispatch('DID_DESTROY');\n },\n\n /**\n * Inserts the plugin before the target element\n */\n insertBefore: function insertBefore$1(element) {\n return insertBefore(view.element, element);\n },\n\n /**\n * Inserts the plugin after the target element\n */\n insertAfter: function insertAfter$1(element) {\n return insertAfter(view.element, element);\n },\n\n /**\n * Appends the plugin to the target element\n */\n appendTo: function appendTo(element) {\n return element.appendChild(view.element);\n },\n\n /**\n * Replaces an element with the app\n */\n replaceElement: function replaceElement(element) {\n // insert the app before the element\n insertBefore(view.element, element);\n\n // remove the original element\n element.parentNode.removeChild(element);\n\n // remember original element\n originalElement = element;\n },\n\n /**\n * Restores the original element\n */\n restoreElement: function restoreElement() {\n if (!originalElement) {\n return; // no element to restore\n }\n\n // restore original element\n insertAfter(originalElement, view.element);\n\n // remove our element\n view.element.parentNode.removeChild(view.element);\n\n // remove reference\n originalElement = null;\n },\n\n /**\n * Returns true if the app root is attached to given element\n * @param element\n */\n isAttachedTo: function isAttachedTo(element) {\n return view.element === element || originalElement === element;\n },\n\n /**\n * Returns the root element\n */\n element: {\n get: function get() {\n return view.element;\n },\n },\n\n /**\n * Returns the current pond status\n */\n status: {\n get: function get() {\n return store.query('GET_STATUS');\n },\n },\n }\n );\n\n // Done!\n store.dispatch('DID_INIT');\n\n // create actual api object\n return createObject(exports);\n };\n\n var createAppObject = function createAppObject() {\n var customOptions = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};\n // default options\n var defaultOptions = {};\n forin(getOptions(), function(key, value) {\n defaultOptions[key] = value[0];\n });\n\n // set app options\n var app = createApp(\n Object.assign(\n {},\n\n defaultOptions,\n {},\n\n customOptions\n )\n );\n\n // return the plugin instance\n return app;\n };\n\n var lowerCaseFirstLetter = function lowerCaseFirstLetter(string) {\n return string.charAt(0).toLowerCase() + string.slice(1);\n };\n\n var attributeNameToPropertyName = function attributeNameToPropertyName(attributeName) {\n return toCamels(attributeName.replace(/^data-/, ''));\n };\n\n var mapObject = function mapObject(object, propertyMap) {\n // remove unwanted\n forin(propertyMap, function(selector, mapping) {\n forin(object, function(property, value) {\n // create regexp shortcut\n var selectorRegExp = new RegExp(selector);\n\n // tests if\n var matches = selectorRegExp.test(property);\n\n // no match, skip\n if (!matches) {\n return;\n }\n\n // if there's a mapping, the original property is always removed\n delete object[property];\n\n // should only remove, we done!\n if (mapping === false) {\n return;\n }\n\n // move value to new property\n if (isString(mapping)) {\n object[mapping] = value;\n return;\n }\n\n // move to group\n var group = mapping.group;\n if (isObject(mapping) && !object[group]) {\n object[group] = {};\n }\n\n object[group][lowerCaseFirstLetter(property.replace(selectorRegExp, ''))] = value;\n });\n\n // do submapping\n if (mapping.mapping) {\n mapObject(object[mapping.group], mapping.mapping);\n }\n });\n };\n\n var getAttributesAsObject = function getAttributesAsObject(node) {\n var attributeMapping =\n arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};\n // turn attributes into object\n var attributes = [];\n forin(node.attributes, function(index) {\n attributes.push(node.attributes[index]);\n });\n\n var output = attributes\n .filter(function(attribute) {\n return attribute.name;\n })\n .reduce(function(obj, attribute) {\n var value = attr(node, attribute.name);\n\n obj[attributeNameToPropertyName(attribute.name)] =\n value === attribute.name ? true : value;\n return obj;\n }, {});\n\n // do mapping of object properties\n mapObject(output, attributeMapping);\n\n return output;\n };\n\n var createAppAtElement = function createAppAtElement(element) {\n var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};\n\n // how attributes of the input element are mapped to the options for the plugin\n var attributeMapping = {\n // translate to other name\n '^class$': 'className',\n '^multiple$': 'allowMultiple',\n '^capture$': 'captureMethod',\n '^webkitdirectory$': 'allowDirectoriesOnly',\n\n // group under single property\n '^server': {\n group: 'server',\n mapping: {\n '^process': {\n group: 'process',\n },\n\n '^revert': {\n group: 'revert',\n },\n\n '^fetch': {\n group: 'fetch',\n },\n\n '^restore': {\n group: 'restore',\n },\n\n '^load': {\n group: 'load',\n },\n },\n },\n\n // don't include in object\n '^type$': false,\n '^files$': false,\n };\n\n // add additional option translators\n applyFilters('SET_ATTRIBUTE_TO_OPTION_MAP', attributeMapping);\n\n // create final options object by setting options object and then overriding options supplied on element\n var mergedOptions = Object.assign({}, options);\n\n var attributeOptions = getAttributesAsObject(\n element.nodeName === 'FIELDSET' ? element.querySelector('input[type=file]') : element,\n attributeMapping\n );\n\n // merge with options object\n Object.keys(attributeOptions).forEach(function(key) {\n if (isObject(attributeOptions[key])) {\n if (!isObject(mergedOptions[key])) {\n mergedOptions[key] = {};\n }\n Object.assign(mergedOptions[key], attributeOptions[key]);\n } else {\n mergedOptions[key] = attributeOptions[key];\n }\n });\n\n // if parent is a fieldset, get files from parent by selecting all input fields that are not file upload fields\n // these will then be automatically set to the initial files\n mergedOptions.files = (options.files || []).concat(\n Array.from(element.querySelectorAll('input:not([type=file])')).map(function(input) {\n return {\n source: input.value,\n options: {\n type: input.dataset.type,\n },\n };\n })\n );\n\n // build plugin\n var app = createAppObject(mergedOptions);\n\n // add already selected files\n if (element.files) {\n Array.from(element.files).forEach(function(file) {\n app.addFile(file);\n });\n }\n\n // replace the target element\n app.replaceElement(element);\n\n // expose\n return app;\n };\n\n // if an element is passed, we create the instance at that element, if not, we just create an up object\n var createApp$1 = function createApp() {\n return isNode(arguments.length <= 0 ? undefined : arguments[0])\n ? createAppAtElement.apply(void 0, arguments)\n : createAppObject.apply(void 0, arguments);\n };\n\n var PRIVATE_METHODS = ['fire', '_read', '_write'];\n\n var createAppAPI = function createAppAPI(app) {\n var api = {};\n\n copyObjectPropertiesToObject(app, api, PRIVATE_METHODS);\n\n return api;\n };\n\n /**\n * Replaces placeholders in given string with replacements\n * @param string - \"Foo {bar}\"\"\n * @param replacements - { \"bar\": 10 }\n */\n var replaceInString = function replaceInString(string, replacements) {\n return string.replace(/(?:{([a-zA-Z]+)})/g, function(match, group) {\n return replacements[group];\n });\n };\n\n var createWorker = function createWorker(fn) {\n var workerBlob = new Blob(['(', fn.toString(), ')()'], {\n type: 'application/javascript',\n });\n\n var workerURL = URL.createObjectURL(workerBlob);\n var worker = new Worker(workerURL);\n\n return {\n transfer: function transfer(message, cb) {},\n post: function post(message, cb, transferList) {\n var id = getUniqueId();\n\n worker.onmessage = function(e) {\n if (e.data.id === id) {\n cb(e.data.message);\n }\n };\n\n worker.postMessage(\n {\n id: id,\n message: message,\n },\n\n transferList\n );\n },\n terminate: function terminate() {\n worker.terminate();\n URL.revokeObjectURL(workerURL);\n },\n };\n };\n\n var loadImage = function loadImage(url) {\n return new Promise(function(resolve, reject) {\n var img = new Image();\n img.onload = function() {\n resolve(img);\n };\n img.onerror = function(e) {\n reject(e);\n };\n img.src = url;\n });\n };\n\n var renameFile = function renameFile(file, name) {\n var renamedFile = file.slice(0, file.size, file.type);\n renamedFile.lastModifiedDate = file.lastModifiedDate;\n renamedFile.name = name;\n return renamedFile;\n };\n\n var copyFile = function copyFile(file) {\n return renameFile(file, file.name);\n };\n\n // already registered plugins (can't register twice)\n var registeredPlugins = [];\n\n // pass utils to plugin\n var createAppPlugin = function createAppPlugin(plugin) {\n // already registered\n if (registeredPlugins.includes(plugin)) {\n return;\n }\n\n // remember this plugin\n registeredPlugins.push(plugin);\n\n // setup!\n var pluginOutline = plugin({\n addFilter: addFilter,\n utils: {\n Type: Type,\n forin: forin,\n isString: isString,\n isFile: isFile,\n toNaturalFileSize: toNaturalFileSize,\n replaceInString: replaceInString,\n getExtensionFromFilename: getExtensionFromFilename,\n getFilenameWithoutExtension: getFilenameWithoutExtension,\n guesstimateMimeType: guesstimateMimeType,\n getFileFromBlob: getFileFromBlob,\n getFilenameFromURL: getFilenameFromURL,\n createRoute: createRoute,\n createWorker: createWorker,\n createView: createView,\n createItemAPI: createItemAPI,\n loadImage: loadImage,\n copyFile: copyFile,\n renameFile: renameFile,\n createBlob: createBlob,\n applyFilterChain: applyFilterChain,\n text: text,\n getNumericAspectRatioFromString: getNumericAspectRatioFromString,\n },\n\n views: {\n fileActionButton: fileActionButton,\n },\n });\n\n // add plugin options to default options\n extendDefaultOptions(pluginOutline.options);\n };\n\n // feature detection used by supported() method\n var isOperaMini = function isOperaMini() {\n return Object.prototype.toString.call(window.operamini) === '[object OperaMini]';\n };\n var hasPromises = function hasPromises() {\n return 'Promise' in window;\n };\n var hasBlobSlice = function hasBlobSlice() {\n return 'slice' in Blob.prototype;\n };\n var hasCreateObjectURL = function hasCreateObjectURL() {\n return 'URL' in window && 'createObjectURL' in window.URL;\n };\n var hasVisibility = function hasVisibility() {\n return 'visibilityState' in document;\n };\n var hasTiming = function hasTiming() {\n return 'performance' in window;\n }; // iOS 8.x\n var hasCSSSupports = function hasCSSSupports() {\n return 'supports' in (window.CSS || {});\n }; // use to detect Safari 9+\n var isIE11 = function isIE11() {\n return /MSIE|Trident/.test(window.navigator.userAgent);\n };\n\n var supported = (function() {\n // Runs immediately and then remembers result for subsequent calls\n var isSupported =\n // Has to be a browser\n isBrowser() &&\n // Can't run on Opera Mini due to lack of everything\n !isOperaMini() &&\n // Require these APIs to feature detect a modern browser\n hasVisibility() &&\n hasPromises() &&\n hasBlobSlice() &&\n hasCreateObjectURL() &&\n hasTiming() &&\n // doesn't need CSSSupports but is a good way to detect Safari 9+ (we do want to support IE11 though)\n (hasCSSSupports() || isIE11());\n\n return function() {\n return isSupported;\n };\n })();\n\n /**\n * Plugin internal state (over all instances)\n */\n var state = {\n // active app instances, used to redraw the apps and to find the later\n apps: [],\n };\n\n // plugin name\n var name = 'filepond';\n\n /**\n * Public Plugin methods\n */\n var fn = function fn() {};\n exports.Status = {};\n exports.FileStatus = {};\n exports.FileOrigin = {};\n exports.OptionTypes = {};\n exports.create = fn;\n exports.destroy = fn;\n exports.parse = fn;\n exports.find = fn;\n exports.registerPlugin = fn;\n exports.getOptions = fn;\n exports.setOptions = fn;\n\n // if not supported, no API\n if (supported()) {\n // start painter and fire load event\n createPainter(\n function() {\n state.apps.forEach(function(app) {\n return app._read();\n });\n },\n function(ts) {\n state.apps.forEach(function(app) {\n return app._write(ts);\n });\n }\n );\n\n // fire loaded event so we know when FilePond is available\n var dispatch = function dispatch() {\n // let others know we have area ready\n document.dispatchEvent(\n new CustomEvent('FilePond:loaded', {\n detail: {\n supported: supported,\n create: exports.create,\n destroy: exports.destroy,\n parse: exports.parse,\n find: exports.find,\n registerPlugin: exports.registerPlugin,\n setOptions: exports.setOptions,\n },\n })\n );\n\n // clean up event\n document.removeEventListener('DOMContentLoaded', dispatch);\n };\n\n if (document.readyState !== 'loading') {\n // move to back of execution queue, FilePond should have been exported by then\n setTimeout(function() {\n return dispatch();\n }, 0);\n } else {\n document.addEventListener('DOMContentLoaded', dispatch);\n }\n\n // updates the OptionTypes object based on the current options\n var updateOptionTypes = function updateOptionTypes() {\n return forin(getOptions(), function(key, value) {\n exports.OptionTypes[key] = value[1];\n });\n };\n\n exports.Status = Object.assign({}, Status);\n exports.FileOrigin = Object.assign({}, FileOrigin);\n exports.FileStatus = Object.assign({}, ItemStatus);\n\n exports.OptionTypes = {};\n updateOptionTypes();\n\n // create method, creates apps and adds them to the app array\n exports.create = function create() {\n var app = createApp$1.apply(void 0, arguments);\n app.on('destroy', exports.destroy);\n state.apps.push(app);\n return createAppAPI(app);\n };\n\n // destroys apps and removes them from the app array\n exports.destroy = function destroy(hook) {\n // returns true if the app was destroyed successfully\n var indexToRemove = state.apps.findIndex(function(app) {\n return app.isAttachedTo(hook);\n });\n if (indexToRemove >= 0) {\n // remove from apps\n var app = state.apps.splice(indexToRemove, 1)[0];\n\n // restore original dom element\n app.restoreElement();\n\n return true;\n }\n\n return false;\n };\n\n // parses the given context for plugins (does not include the context element itself)\n exports.parse = function parse(context) {\n // get all possible hooks\n var matchedHooks = Array.from(context.querySelectorAll('.' + name));\n\n // filter out already active hooks\n var newHooks = matchedHooks.filter(function(newHook) {\n return !state.apps.find(function(app) {\n return app.isAttachedTo(newHook);\n });\n });\n\n // create new instance for each hook\n return newHooks.map(function(hook) {\n return exports.create(hook);\n });\n };\n\n // returns an app based on the given element hook\n exports.find = function find(hook) {\n var app = state.apps.find(function(app) {\n return app.isAttachedTo(hook);\n });\n if (!app) {\n return null;\n }\n return createAppAPI(app);\n };\n\n // adds a plugin extension\n exports.registerPlugin = function registerPlugin() {\n for (\n var _len = arguments.length, plugins = new Array(_len), _key = 0;\n _key < _len;\n _key++\n ) {\n plugins[_key] = arguments[_key];\n }\n\n // register plugins\n plugins.forEach(createAppPlugin);\n\n // update OptionTypes, each plugin might have extended the default options\n updateOptionTypes();\n };\n\n exports.getOptions = function getOptions$1() {\n var opts = {};\n forin(getOptions(), function(key, value) {\n opts[key] = value[0];\n });\n return opts;\n };\n\n exports.setOptions = function setOptions$1(opts) {\n if (isObject(opts)) {\n // update existing plugins\n state.apps.forEach(function(app) {\n app.setOptions(opts);\n });\n\n // override defaults\n setOptions(opts);\n }\n\n // return new options\n return exports.getOptions();\n };\n }\n\n exports.supported = supported;\n\n Object.defineProperty(exports, '__esModule', { value: true });\n});\n", "/*!\n * FilePondPluginFileValidateSize 2.2.8\n * Licensed under MIT, https://opensource.org/licenses/MIT/\n * Please visit https://pqina.nl/filepond/ for details.\n */\n\n/* eslint-disable */\n\n(function(global, factory) {\n typeof exports === 'object' && typeof module !== 'undefined'\n ? (module.exports = factory())\n : typeof define === 'function' && define.amd\n ? define(factory)\n : ((global = global || self), (global.FilePondPluginFileValidateSize = factory()));\n})(this, function() {\n 'use strict';\n\n var plugin = function plugin(_ref) {\n var addFilter = _ref.addFilter,\n utils = _ref.utils;\n // get quick reference to Type utils\n var Type = utils.Type,\n replaceInString = utils.replaceInString,\n toNaturalFileSize = utils.toNaturalFileSize;\n\n // filtering if an item is allowed in hopper\n addFilter('ALLOW_HOPPER_ITEM', function(file, _ref2) {\n var query = _ref2.query;\n if (!query('GET_ALLOW_FILE_SIZE_VALIDATION')) {\n return true;\n }\n\n var sizeMax = query('GET_MAX_FILE_SIZE');\n if (sizeMax !== null && file.size > sizeMax) {\n return false;\n }\n\n var sizeMin = query('GET_MIN_FILE_SIZE');\n if (sizeMin !== null && file.size < sizeMin) {\n return false;\n }\n\n return true;\n });\n\n // called for each file that is loaded\n // right before it is set to the item state\n // should return a promise\n addFilter('LOAD_FILE', function(file, _ref3) {\n var query = _ref3.query;\n return new Promise(function(resolve, reject) {\n // if not allowed, all fine, exit\n if (!query('GET_ALLOW_FILE_SIZE_VALIDATION')) {\n return resolve(file);\n }\n\n // check if file should be filtered\n var fileFilter = query('GET_FILE_VALIDATE_SIZE_FILTER');\n if (fileFilter && !fileFilter(file)) {\n return resolve(file);\n }\n\n // reject or resolve based on file size\n var sizeMax = query('GET_MAX_FILE_SIZE');\n if (sizeMax !== null && file.size > sizeMax) {\n reject({\n status: {\n main: query('GET_LABEL_MAX_FILE_SIZE_EXCEEDED'),\n sub: replaceInString(query('GET_LABEL_MAX_FILE_SIZE'), {\n filesize: toNaturalFileSize(\n sizeMax,\n '.',\n query('GET_FILE_SIZE_BASE'),\n query('GET_FILE_SIZE_LABELS', query)\n ),\n }),\n },\n });\n\n return;\n }\n\n // reject or resolve based on file size\n var sizeMin = query('GET_MIN_FILE_SIZE');\n if (sizeMin !== null && file.size < sizeMin) {\n reject({\n status: {\n main: query('GET_LABEL_MIN_FILE_SIZE_EXCEEDED'),\n sub: replaceInString(query('GET_LABEL_MIN_FILE_SIZE'), {\n filesize: toNaturalFileSize(\n sizeMin,\n '.',\n query('GET_FILE_SIZE_BASE'),\n query('GET_FILE_SIZE_LABELS', query)\n ),\n }),\n },\n });\n\n return;\n }\n\n // returns the current option value\n var totalSizeMax = query('GET_MAX_TOTAL_FILE_SIZE');\n if (totalSizeMax !== null) {\n // get the current total file size\n var currentTotalSize = query('GET_ACTIVE_ITEMS').reduce(function(total, item) {\n return total + item.fileSize;\n }, 0);\n\n // get the size of the new file\n if (currentTotalSize > totalSizeMax) {\n reject({\n status: {\n main: query('GET_LABEL_MAX_TOTAL_FILE_SIZE_EXCEEDED'),\n sub: replaceInString(query('GET_LABEL_MAX_TOTAL_FILE_SIZE'), {\n filesize: toNaturalFileSize(\n totalSizeMax,\n '.',\n query('GET_FILE_SIZE_BASE'),\n query('GET_FILE_SIZE_LABELS', query)\n ),\n }),\n },\n });\n\n return;\n }\n }\n\n // file is fine, let's pass it back\n resolve(file);\n });\n });\n\n return {\n options: {\n // Enable or disable file type validation\n allowFileSizeValidation: [true, Type.BOOLEAN],\n\n // Max individual file size in bytes\n maxFileSize: [null, Type.INT],\n\n // Min individual file size in bytes\n minFileSize: [null, Type.INT],\n\n // Max total file size in bytes\n maxTotalFileSize: [null, Type.INT],\n\n // Filter the files that need to be validated for size\n fileValidateSizeFilter: [null, Type.FUNCTION],\n\n // error labels\n labelMinFileSizeExceeded: ['File is too small', Type.STRING],\n labelMinFileSize: ['Minimum file size is {filesize}', Type.STRING],\n\n labelMaxFileSizeExceeded: ['File is too large', Type.STRING],\n labelMaxFileSize: ['Maximum file size is {filesize}', Type.STRING],\n\n labelMaxTotalFileSizeExceeded: ['Maximum total size exceeded', Type.STRING],\n labelMaxTotalFileSize: ['Maximum total file size is {filesize}', Type.STRING],\n },\n };\n };\n\n // fire pluginloaded event if running in browser, this allows registering the plugin when using async script tags\n var isBrowser = typeof window !== 'undefined' && typeof window.document !== 'undefined';\n if (isBrowser) {\n document.dispatchEvent(new CustomEvent('FilePond:pluginloaded', { detail: plugin }));\n }\n\n return plugin;\n});\n", "/*!\n * FilePondPluginImagePreview 4.6.12\n * Licensed under MIT, https://opensource.org/licenses/MIT/\n * Please visit https://pqina.nl/filepond/ for details.\n */\n\n/* eslint-disable */\n\n(function(global, factory) {\n typeof exports === 'object' && typeof module !== 'undefined'\n ? (module.exports = factory())\n : typeof define === 'function' && define.amd\n ? define(factory)\n : ((global = global || self),\n (global.FilePondPluginImagePreview = factory()));\n})(this, function() {\n 'use strict';\n\n // test if file is of type image and can be viewed in canvas\n var isPreviewableImage = function isPreviewableImage(file) {\n return /^image/.test(file.type);\n };\n\n function _typeof(obj) {\n if (typeof Symbol === 'function' && typeof Symbol.iterator === 'symbol') {\n _typeof = function(obj) {\n return typeof obj;\n };\n } else {\n _typeof = function(obj) {\n return obj &&\n typeof Symbol === 'function' &&\n obj.constructor === Symbol &&\n obj !== Symbol.prototype\n ? 'symbol'\n : typeof obj;\n };\n }\n\n return _typeof(obj);\n }\n\n var REACT_ELEMENT_TYPE;\n\n function _jsx(type, props, key, children) {\n if (!REACT_ELEMENT_TYPE) {\n REACT_ELEMENT_TYPE =\n (typeof Symbol === 'function' &&\n Symbol.for &&\n Symbol.for('react.element')) ||\n 0xeac7;\n }\n\n var defaultProps = type && type.defaultProps;\n var childrenLength = arguments.length - 3;\n\n if (!props && childrenLength !== 0) {\n props = {\n children: void 0\n };\n }\n\n if (props && defaultProps) {\n for (var propName in defaultProps) {\n if (props[propName] === void 0) {\n props[propName] = defaultProps[propName];\n }\n }\n } else if (!props) {\n props = defaultProps || {};\n }\n\n if (childrenLength === 1) {\n props.children = children;\n } else if (childrenLength > 1) {\n var childArray = new Array(childrenLength);\n\n for (var i = 0; i < childrenLength; i++) {\n childArray[i] = arguments[i + 3];\n }\n\n props.children = childArray;\n }\n\n return {\n $$typeof: REACT_ELEMENT_TYPE,\n type: type,\n key: key === undefined ? null : '' + key,\n ref: null,\n props: props,\n _owner: null\n };\n }\n\n function _asyncIterator(iterable) {\n var method;\n\n if (typeof Symbol === 'function') {\n if (Symbol.asyncIterator) {\n method = iterable[Symbol.asyncIterator];\n if (method != null) return method.call(iterable);\n }\n\n if (Symbol.iterator) {\n method = iterable[Symbol.iterator];\n if (method != null) return method.call(iterable);\n }\n }\n\n throw new TypeError('Object is not async iterable');\n }\n\n function _AwaitValue(value) {\n this.wrapped = value;\n }\n\n function _AsyncGenerator(gen) {\n var front, back;\n\n function send(key, arg) {\n return new Promise(function(resolve, reject) {\n var request = {\n key: key,\n arg: arg,\n resolve: resolve,\n reject: reject,\n next: null\n };\n\n if (back) {\n back = back.next = request;\n } else {\n front = back = request;\n resume(key, arg);\n }\n });\n }\n\n function resume(key, arg) {\n try {\n var result = gen[key](arg);\n var value = result.value;\n var wrappedAwait = value instanceof _AwaitValue;\n Promise.resolve(wrappedAwait ? value.wrapped : value).then(\n function(arg) {\n if (wrappedAwait) {\n resume('next', arg);\n return;\n }\n\n settle(result.done ? 'return' : 'normal', arg);\n },\n function(err) {\n resume('throw', err);\n }\n );\n } catch (err) {\n settle('throw', err);\n }\n }\n\n function settle(type, value) {\n switch (type) {\n case 'return':\n front.resolve({\n value: value,\n done: true\n });\n break;\n\n case 'throw':\n front.reject(value);\n break;\n\n default:\n front.resolve({\n value: value,\n done: false\n });\n break;\n }\n\n front = front.next;\n\n if (front) {\n resume(front.key, front.arg);\n } else {\n back = null;\n }\n }\n\n this._invoke = send;\n\n if (typeof gen.return !== 'function') {\n this.return = undefined;\n }\n }\n\n if (typeof Symbol === 'function' && Symbol.asyncIterator) {\n _AsyncGenerator.prototype[Symbol.asyncIterator] = function() {\n return this;\n };\n }\n\n _AsyncGenerator.prototype.next = function(arg) {\n return this._invoke('next', arg);\n };\n\n _AsyncGenerator.prototype.throw = function(arg) {\n return this._invoke('throw', arg);\n };\n\n _AsyncGenerator.prototype.return = function(arg) {\n return this._invoke('return', arg);\n };\n\n function _wrapAsyncGenerator(fn) {\n return function() {\n return new _AsyncGenerator(fn.apply(this, arguments));\n };\n }\n\n function _awaitAsyncGenerator(value) {\n return new _AwaitValue(value);\n }\n\n function _asyncGeneratorDelegate(inner, awaitWrap) {\n var iter = {},\n waiting = false;\n\n function pump(key, value) {\n waiting = true;\n value = new Promise(function(resolve) {\n resolve(inner[key](value));\n });\n return {\n done: false,\n value: awaitWrap(value)\n };\n }\n\n if (typeof Symbol === 'function' && Symbol.iterator) {\n iter[Symbol.iterator] = function() {\n return this;\n };\n }\n\n iter.next = function(value) {\n if (waiting) {\n waiting = false;\n return value;\n }\n\n return pump('next', value);\n };\n\n if (typeof inner.throw === 'function') {\n iter.throw = function(value) {\n if (waiting) {\n waiting = false;\n throw value;\n }\n\n return pump('throw', value);\n };\n }\n\n if (typeof inner.return === 'function') {\n iter.return = function(value) {\n return pump('return', value);\n };\n }\n\n return iter;\n }\n\n function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {\n try {\n var info = gen[key](arg);\n var value = info.value;\n } catch (error) {\n reject(error);\n return;\n }\n\n if (info.done) {\n resolve(value);\n } else {\n Promise.resolve(value).then(_next, _throw);\n }\n }\n\n function _asyncToGenerator(fn) {\n return function() {\n var self = this,\n args = arguments;\n return new Promise(function(resolve, reject) {\n var gen = fn.apply(self, args);\n\n function _next(value) {\n asyncGeneratorStep(\n gen,\n resolve,\n reject,\n _next,\n _throw,\n 'next',\n value\n );\n }\n\n function _throw(err) {\n asyncGeneratorStep(gen, resolve, reject, _next, _throw, 'throw', err);\n }\n\n _next(undefined);\n });\n };\n }\n\n function _classCallCheck(instance, Constructor) {\n if (!(instance instanceof Constructor)) {\n throw new TypeError('Cannot call a class as a function');\n }\n }\n\n function _defineProperties(target, props) {\n for (var i = 0; i < props.length; i++) {\n var descriptor = props[i];\n descriptor.enumerable = descriptor.enumerable || false;\n descriptor.configurable = true;\n if ('value' in descriptor) descriptor.writable = true;\n Object.defineProperty(target, descriptor.key, descriptor);\n }\n }\n\n function _createClass(Constructor, protoProps, staticProps) {\n if (protoProps) _defineProperties(Constructor.prototype, protoProps);\n if (staticProps) _defineProperties(Constructor, staticProps);\n return Constructor;\n }\n\n function _defineEnumerableProperties(obj, descs) {\n for (var key in descs) {\n var desc = descs[key];\n desc.configurable = desc.enumerable = true;\n if ('value' in desc) desc.writable = true;\n Object.defineProperty(obj, key, desc);\n }\n\n if (Object.getOwnPropertySymbols) {\n var objectSymbols = Object.getOwnPropertySymbols(descs);\n\n for (var i = 0; i < objectSymbols.length; i++) {\n var sym = objectSymbols[i];\n var desc = descs[sym];\n desc.configurable = desc.enumerable = true;\n if ('value' in desc) desc.writable = true;\n Object.defineProperty(obj, sym, desc);\n }\n }\n\n return obj;\n }\n\n function _defaults(obj, defaults) {\n var keys = Object.getOwnPropertyNames(defaults);\n\n for (var i = 0; i < keys.length; i++) {\n var key = keys[i];\n var value = Object.getOwnPropertyDescriptor(defaults, key);\n\n if (value && value.configurable && obj[key] === undefined) {\n Object.defineProperty(obj, key, value);\n }\n }\n\n return obj;\n }\n\n function _defineProperty(obj, key, value) {\n if (key in obj) {\n Object.defineProperty(obj, key, {\n value: value,\n enumerable: true,\n configurable: true,\n writable: true\n });\n } else {\n obj[key] = value;\n }\n\n return obj;\n }\n\n function _extends() {\n _extends =\n Object.assign ||\n function(target) {\n for (var i = 1; i < arguments.length; i++) {\n var source = arguments[i];\n\n for (var key in source) {\n if (Object.prototype.hasOwnProperty.call(source, key)) {\n target[key] = source[key];\n }\n }\n }\n\n return target;\n };\n\n return _extends.apply(this, arguments);\n }\n\n function _objectSpread(target) {\n for (var i = 1; i < arguments.length; i++) {\n var source = arguments[i] != null ? arguments[i] : {};\n var ownKeys = Object.keys(source);\n\n if (typeof Object.getOwnPropertySymbols === 'function') {\n ownKeys = ownKeys.concat(\n Object.getOwnPropertySymbols(source).filter(function(sym) {\n return Object.getOwnPropertyDescriptor(source, sym).enumerable;\n })\n );\n }\n\n ownKeys.forEach(function(key) {\n _defineProperty(target, key, source[key]);\n });\n }\n\n return target;\n }\n\n function _inherits(subClass, superClass) {\n if (typeof superClass !== 'function' && superClass !== null) {\n throw new TypeError('Super expression must either be null or a function');\n }\n\n subClass.prototype = Object.create(superClass && superClass.prototype, {\n constructor: {\n value: subClass,\n writable: true,\n configurable: true\n }\n });\n if (superClass) _setPrototypeOf(subClass, superClass);\n }\n\n function _inheritsLoose(subClass, superClass) {\n subClass.prototype = Object.create(superClass.prototype);\n subClass.prototype.constructor = subClass;\n subClass.__proto__ = superClass;\n }\n\n function _getPrototypeOf(o) {\n _getPrototypeOf = Object.setPrototypeOf\n ? Object.getPrototypeOf\n : function _getPrototypeOf(o) {\n return o.__proto__ || Object.getPrototypeOf(o);\n };\n return _getPrototypeOf(o);\n }\n\n function _setPrototypeOf(o, p) {\n _setPrototypeOf =\n Object.setPrototypeOf ||\n function _setPrototypeOf(o, p) {\n o.__proto__ = p;\n return o;\n };\n\n return _setPrototypeOf(o, p);\n }\n\n function isNativeReflectConstruct() {\n if (typeof Reflect === 'undefined' || !Reflect.construct) return false;\n if (Reflect.construct.sham) return false;\n if (typeof Proxy === 'function') return true;\n\n try {\n Date.prototype.toString.call(Reflect.construct(Date, [], function() {}));\n return true;\n } catch (e) {\n return false;\n }\n }\n\n function _construct(Parent, args, Class) {\n if (isNativeReflectConstruct()) {\n _construct = Reflect.construct;\n } else {\n _construct = function _construct(Parent, args, Class) {\n var a = [null];\n a.push.apply(a, args);\n var Constructor = Function.bind.apply(Parent, a);\n var instance = new Constructor();\n if (Class) _setPrototypeOf(instance, Class.prototype);\n return instance;\n };\n }\n\n return _construct.apply(null, arguments);\n }\n\n function _isNativeFunction(fn) {\n return Function.toString.call(fn).indexOf('[native code]') !== -1;\n }\n\n function _wrapNativeSuper(Class) {\n var _cache = typeof Map === 'function' ? new Map() : undefined;\n\n _wrapNativeSuper = function _wrapNativeSuper(Class) {\n if (Class === null || !_isNativeFunction(Class)) return Class;\n\n if (typeof Class !== 'function') {\n throw new TypeError(\n 'Super expression must either be null or a function'\n );\n }\n\n if (typeof _cache !== 'undefined') {\n if (_cache.has(Class)) return _cache.get(Class);\n\n _cache.set(Class, Wrapper);\n }\n\n function Wrapper() {\n return _construct(Class, arguments, _getPrototypeOf(this).constructor);\n }\n\n Wrapper.prototype = Object.create(Class.prototype, {\n constructor: {\n value: Wrapper,\n enumerable: false,\n writable: true,\n configurable: true\n }\n });\n return _setPrototypeOf(Wrapper, Class);\n };\n\n return _wrapNativeSuper(Class);\n }\n\n function _instanceof(left, right) {\n if (\n right != null &&\n typeof Symbol !== 'undefined' &&\n right[Symbol.hasInstance]\n ) {\n return right[Symbol.hasInstance](left);\n } else {\n return left instanceof right;\n }\n }\n\n function _interopRequireDefault(obj) {\n return obj && obj.__esModule\n ? obj\n : {\n default: obj\n };\n }\n\n function _interopRequireWildcard(obj) {\n if (obj && obj.__esModule) {\n return obj;\n } else {\n var newObj = {};\n\n if (obj != null) {\n for (var key in obj) {\n if (Object.prototype.hasOwnProperty.call(obj, key)) {\n var desc =\n Object.defineProperty && Object.getOwnPropertyDescriptor\n ? Object.getOwnPropertyDescriptor(obj, key)\n : {};\n\n if (desc.get || desc.set) {\n Object.defineProperty(newObj, key, desc);\n } else {\n newObj[key] = obj[key];\n }\n }\n }\n }\n\n newObj.default = obj;\n return newObj;\n }\n }\n\n function _newArrowCheck(innerThis, boundThis) {\n if (innerThis !== boundThis) {\n throw new TypeError('Cannot instantiate an arrow function');\n }\n }\n\n function _objectDestructuringEmpty(obj) {\n if (obj == null) throw new TypeError('Cannot destructure undefined');\n }\n\n function _objectWithoutPropertiesLoose(source, excluded) {\n if (source == null) return {};\n var target = {};\n var sourceKeys = Object.keys(source);\n var key, i;\n\n for (i = 0; i < sourceKeys.length; i++) {\n key = sourceKeys[i];\n if (excluded.indexOf(key) >= 0) continue;\n target[key] = source[key];\n }\n\n return target;\n }\n\n function _objectWithoutProperties(source, excluded) {\n if (source == null) return {};\n\n var target = _objectWithoutPropertiesLoose(source, excluded);\n\n var key, i;\n\n if (Object.getOwnPropertySymbols) {\n var sourceSymbolKeys = Object.getOwnPropertySymbols(source);\n\n for (i = 0; i < sourceSymbolKeys.length; i++) {\n key = sourceSymbolKeys[i];\n if (excluded.indexOf(key) >= 0) continue;\n if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue;\n target[key] = source[key];\n }\n }\n\n return target;\n }\n\n function _assertThisInitialized(self) {\n if (self === void 0) {\n throw new ReferenceError(\n \"this hasn't been initialised - super() hasn't been called\"\n );\n }\n\n return self;\n }\n\n function _possibleConstructorReturn(self, call) {\n if (call && (typeof call === 'object' || typeof call === 'function')) {\n return call;\n }\n\n return _assertThisInitialized(self);\n }\n\n function _superPropBase(object, property) {\n while (!Object.prototype.hasOwnProperty.call(object, property)) {\n object = _getPrototypeOf(object);\n if (object === null) break;\n }\n\n return object;\n }\n\n function _get(target, property, receiver) {\n if (typeof Reflect !== 'undefined' && Reflect.get) {\n _get = Reflect.get;\n } else {\n _get = function _get(target, property, receiver) {\n var base = _superPropBase(target, property);\n\n if (!base) return;\n var desc = Object.getOwnPropertyDescriptor(base, property);\n\n if (desc.get) {\n return desc.get.call(receiver);\n }\n\n return desc.value;\n };\n }\n\n return _get(target, property, receiver || target);\n }\n\n function set(target, property, value, receiver) {\n if (typeof Reflect !== 'undefined' && Reflect.set) {\n set = Reflect.set;\n } else {\n set = function set(target, property, value, receiver) {\n var base = _superPropBase(target, property);\n\n var desc;\n\n if (base) {\n desc = Object.getOwnPropertyDescriptor(base, property);\n\n if (desc.set) {\n desc.set.call(receiver, value);\n return true;\n } else if (!desc.writable) {\n return false;\n }\n }\n\n desc = Object.getOwnPropertyDescriptor(receiver, property);\n\n if (desc) {\n if (!desc.writable) {\n return false;\n }\n\n desc.value = value;\n Object.defineProperty(receiver, property, desc);\n } else {\n _defineProperty(receiver, property, value);\n }\n\n return true;\n };\n }\n\n return set(target, property, value, receiver);\n }\n\n function _set(target, property, value, receiver, isStrict) {\n var s = set(target, property, value, receiver || target);\n\n if (!s && isStrict) {\n throw new Error('failed to set property');\n }\n\n return value;\n }\n\n function _taggedTemplateLiteral(strings, raw) {\n if (!raw) {\n raw = strings.slice(0);\n }\n\n return Object.freeze(\n Object.defineProperties(strings, {\n raw: {\n value: Object.freeze(raw)\n }\n })\n );\n }\n\n function _taggedTemplateLiteralLoose(strings, raw) {\n if (!raw) {\n raw = strings.slice(0);\n }\n\n strings.raw = raw;\n return strings;\n }\n\n function _temporalRef(val, name) {\n if (val === _temporalUndefined) {\n throw new ReferenceError(name + ' is not defined - temporal dead zone');\n } else {\n return val;\n }\n }\n\n function _readOnlyError(name) {\n throw new Error('\"' + name + '\" is read-only');\n }\n\n function _classNameTDZError(name) {\n throw new Error(\n 'Class \"' + name + '\" cannot be referenced in computed property keys.'\n );\n }\n\n var _temporalUndefined = {};\n\n function _slicedToArray(arr, i) {\n return (\n _arrayWithHoles(arr) ||\n _iterableToArrayLimit(arr, i) ||\n _nonIterableRest()\n );\n }\n\n function _slicedToArrayLoose(arr, i) {\n return (\n _arrayWithHoles(arr) ||\n _iterableToArrayLimitLoose(arr, i) ||\n _nonIterableRest()\n );\n }\n\n function _toArray(arr) {\n return _arrayWithHoles(arr) || _iterableToArray(arr) || _nonIterableRest();\n }\n\n function _toConsumableArray(arr) {\n return (\n _arrayWithoutHoles(arr) || _iterableToArray(arr) || _nonIterableSpread()\n );\n }\n\n function _arrayWithoutHoles(arr) {\n if (Array.isArray(arr)) {\n for (var i = 0, arr2 = new Array(arr.length); i < arr.length; i++)\n arr2[i] = arr[i];\n\n return arr2;\n }\n }\n\n function _arrayWithHoles(arr) {\n if (Array.isArray(arr)) return arr;\n }\n\n function _iterableToArray(iter) {\n if (\n Symbol.iterator in Object(iter) ||\n Object.prototype.toString.call(iter) === '[object Arguments]'\n )\n return Array.from(iter);\n }\n\n function _iterableToArrayLimit(arr, i) {\n var _arr = [];\n var _n = true;\n var _d = false;\n var _e = undefined;\n\n try {\n for (\n var _i = arr[Symbol.iterator](), _s;\n !(_n = (_s = _i.next()).done);\n _n = true\n ) {\n _arr.push(_s.value);\n\n if (i && _arr.length === i) break;\n }\n } catch (err) {\n _d = true;\n _e = err;\n } finally {\n try {\n if (!_n && _i['return'] != null) _i['return']();\n } finally {\n if (_d) throw _e;\n }\n }\n\n return _arr;\n }\n\n function _iterableToArrayLimitLoose(arr, i) {\n var _arr = [];\n\n for (\n var _iterator = arr[Symbol.iterator](), _step;\n !(_step = _iterator.next()).done;\n\n ) {\n _arr.push(_step.value);\n\n if (i && _arr.length === i) break;\n }\n\n return _arr;\n }\n\n function _nonIterableSpread() {\n throw new TypeError('Invalid attempt to spread non-iterable instance');\n }\n\n function _nonIterableRest() {\n throw new TypeError('Invalid attempt to destructure non-iterable instance');\n }\n\n function _skipFirstGeneratorNext(fn) {\n return function() {\n var it = fn.apply(this, arguments);\n it.next();\n return it;\n };\n }\n\n function _toPrimitive(input, hint) {\n if (typeof input !== 'object' || input === null) return input;\n var prim = input[Symbol.toPrimitive];\n\n if (prim !== undefined) {\n var res = prim.call(input, hint || 'default');\n if (typeof res !== 'object') return res;\n throw new TypeError('@@toPrimitive must return a primitive value.');\n }\n\n return (hint === 'string' ? String : Number)(input);\n }\n\n function _toPropertyKey(arg) {\n var key = _toPrimitive(arg, 'string');\n\n return typeof key === 'symbol' ? key : String(key);\n }\n\n function _initializerWarningHelper(descriptor, context) {\n throw new Error(\n 'Decorating class property failed. Please ensure that ' +\n 'proposal-class-properties is enabled and set to use loose mode. ' +\n 'To use proposal-class-properties in spec mode with decorators, wait for ' +\n 'the next major version of decorators in stage 2.'\n );\n }\n\n function _initializerDefineProperty(target, property, descriptor, context) {\n if (!descriptor) return;\n Object.defineProperty(target, property, {\n enumerable: descriptor.enumerable,\n configurable: descriptor.configurable,\n writable: descriptor.writable,\n value: descriptor.initializer\n ? descriptor.initializer.call(context)\n : void 0\n });\n }\n\n function _applyDecoratedDescriptor(\n target,\n property,\n decorators,\n descriptor,\n context\n ) {\n var desc = {};\n Object.keys(descriptor).forEach(function(key) {\n desc[key] = descriptor[key];\n });\n desc.enumerable = !!desc.enumerable;\n desc.configurable = !!desc.configurable;\n\n if ('value' in desc || desc.initializer) {\n desc.writable = true;\n }\n\n desc = decorators\n .slice()\n .reverse()\n .reduce(function(desc, decorator) {\n return decorator(target, property, desc) || desc;\n }, desc);\n\n if (context && desc.initializer !== void 0) {\n desc.value = desc.initializer ? desc.initializer.call(context) : void 0;\n desc.initializer = undefined;\n }\n\n if (desc.initializer === void 0) {\n Object.defineProperty(target, property, desc);\n desc = null;\n }\n\n return desc;\n }\n\n var id = 0;\n\n function _classPrivateFieldLooseKey(name) {\n return '__private_' + id++ + '_' + name;\n }\n\n function _classPrivateFieldLooseBase(receiver, privateKey) {\n if (!Object.prototype.hasOwnProperty.call(receiver, privateKey)) {\n throw new TypeError('attempted to use private field on non-instance');\n }\n\n return receiver;\n }\n\n function _classPrivateFieldGet(receiver, privateMap) {\n if (!privateMap.has(receiver)) {\n throw new TypeError('attempted to get private field on non-instance');\n }\n\n var descriptor = privateMap.get(receiver);\n\n if (descriptor.get) {\n return descriptor.get.call(receiver);\n }\n\n return descriptor.value;\n }\n\n function _classPrivateFieldSet(receiver, privateMap, value) {\n if (!privateMap.has(receiver)) {\n throw new TypeError('attempted to set private field on non-instance');\n }\n\n var descriptor = privateMap.get(receiver);\n\n if (descriptor.set) {\n descriptor.set.call(receiver, value);\n } else {\n if (!descriptor.writable) {\n throw new TypeError('attempted to set read only private field');\n }\n\n descriptor.value = value;\n }\n\n return value;\n }\n\n function _classStaticPrivateFieldSpecGet(\n receiver,\n classConstructor,\n descriptor\n ) {\n if (receiver !== classConstructor) {\n throw new TypeError('Private static access of wrong provenance');\n }\n\n return descriptor.value;\n }\n\n function _classStaticPrivateFieldSpecSet(\n receiver,\n classConstructor,\n descriptor,\n value\n ) {\n if (receiver !== classConstructor) {\n throw new TypeError('Private static access of wrong provenance');\n }\n\n if (!descriptor.writable) {\n throw new TypeError('attempted to set read only private field');\n }\n\n descriptor.value = value;\n return value;\n }\n\n function _classStaticPrivateMethodGet(receiver, classConstructor, method) {\n if (receiver !== classConstructor) {\n throw new TypeError('Private static access of wrong provenance');\n }\n\n return method;\n }\n\n function _classStaticPrivateMethodSet() {\n throw new TypeError('attempted to set read only static private field');\n }\n\n function _decorate(decorators, factory, superClass, mixins) {\n var api = _getDecoratorsApi();\n\n if (mixins) {\n for (var i = 0; i < mixins.length; i++) {\n api = mixins[i](api);\n }\n }\n\n var r = factory(function initialize(O) {\n api.initializeInstanceElements(O, decorated.elements);\n }, superClass);\n var decorated = api.decorateClass(\n _coalesceClassElements(r.d.map(_createElementDescriptor)),\n decorators\n );\n api.initializeClassElements(r.F, decorated.elements);\n return api.runClassFinishers(r.F, decorated.finishers);\n }\n\n function _getDecoratorsApi() {\n _getDecoratorsApi = function() {\n return api;\n };\n\n var api = {\n elementsDefinitionOrder: [['method'], ['field']],\n initializeInstanceElements: function(O, elements) {\n ['method', 'field'].forEach(function(kind) {\n elements.forEach(function(element) {\n if (element.kind === kind && element.placement === 'own') {\n this.defineClassElement(O, element);\n }\n }, this);\n }, this);\n },\n initializeClassElements: function(F, elements) {\n var proto = F.prototype;\n ['method', 'field'].forEach(function(kind) {\n elements.forEach(function(element) {\n var placement = element.placement;\n\n if (\n element.kind === kind &&\n (placement === 'static' || placement === 'prototype')\n ) {\n var receiver = placement === 'static' ? F : proto;\n this.defineClassElement(receiver, element);\n }\n }, this);\n }, this);\n },\n defineClassElement: function(receiver, element) {\n var descriptor = element.descriptor;\n\n if (element.kind === 'field') {\n var initializer = element.initializer;\n descriptor = {\n enumerable: descriptor.enumerable,\n writable: descriptor.writable,\n configurable: descriptor.configurable,\n value: initializer === void 0 ? void 0 : initializer.call(receiver)\n };\n }\n\n Object.defineProperty(receiver, element.key, descriptor);\n },\n decorateClass: function(elements, decorators) {\n var newElements = [];\n var finishers = [];\n var placements = {\n static: [],\n prototype: [],\n own: []\n };\n elements.forEach(function(element) {\n this.addElementPlacement(element, placements);\n }, this);\n elements.forEach(function(element) {\n if (!_hasDecorators(element)) return newElements.push(element);\n var elementFinishersExtras = this.decorateElement(\n element,\n placements\n );\n newElements.push(elementFinishersExtras.element);\n newElements.push.apply(newElements, elementFinishersExtras.extras);\n finishers.push.apply(finishers, elementFinishersExtras.finishers);\n }, this);\n\n if (!decorators) {\n return {\n elements: newElements,\n finishers: finishers\n };\n }\n\n var result = this.decorateConstructor(newElements, decorators);\n finishers.push.apply(finishers, result.finishers);\n result.finishers = finishers;\n return result;\n },\n addElementPlacement: function(element, placements, silent) {\n var keys = placements[element.placement];\n\n if (!silent && keys.indexOf(element.key) !== -1) {\n throw new TypeError('Duplicated element (' + element.key + ')');\n }\n\n keys.push(element.key);\n },\n decorateElement: function(element, placements) {\n var extras = [];\n var finishers = [];\n\n for (\n var decorators = element.decorators, i = decorators.length - 1;\n i >= 0;\n i--\n ) {\n var keys = placements[element.placement];\n keys.splice(keys.indexOf(element.key), 1);\n var elementObject = this.fromElementDescriptor(element);\n var elementFinisherExtras = this.toElementFinisherExtras(\n (0, decorators[i])(elementObject) || elementObject\n );\n element = elementFinisherExtras.element;\n this.addElementPlacement(element, placements);\n\n if (elementFinisherExtras.finisher) {\n finishers.push(elementFinisherExtras.finisher);\n }\n\n var newExtras = elementFinisherExtras.extras;\n\n if (newExtras) {\n for (var j = 0; j < newExtras.length; j++) {\n this.addElementPlacement(newExtras[j], placements);\n }\n\n extras.push.apply(extras, newExtras);\n }\n }\n\n return {\n element: element,\n finishers: finishers,\n extras: extras\n };\n },\n decorateConstructor: function(elements, decorators) {\n var finishers = [];\n\n for (var i = decorators.length - 1; i >= 0; i--) {\n var obj = this.fromClassDescriptor(elements);\n var elementsAndFinisher = this.toClassDescriptor(\n (0, decorators[i])(obj) || obj\n );\n\n if (elementsAndFinisher.finisher !== undefined) {\n finishers.push(elementsAndFinisher.finisher);\n }\n\n if (elementsAndFinisher.elements !== undefined) {\n elements = elementsAndFinisher.elements;\n\n for (var j = 0; j < elements.length - 1; j++) {\n for (var k = j + 1; k < elements.length; k++) {\n if (\n elements[j].key === elements[k].key &&\n elements[j].placement === elements[k].placement\n ) {\n throw new TypeError(\n 'Duplicated element (' + elements[j].key + ')'\n );\n }\n }\n }\n }\n }\n\n return {\n elements: elements,\n finishers: finishers\n };\n },\n fromElementDescriptor: function(element) {\n var obj = {\n kind: element.kind,\n key: element.key,\n placement: element.placement,\n descriptor: element.descriptor\n };\n var desc = {\n value: 'Descriptor',\n configurable: true\n };\n Object.defineProperty(obj, Symbol.toStringTag, desc);\n if (element.kind === 'field') obj.initializer = element.initializer;\n return obj;\n },\n toElementDescriptors: function(elementObjects) {\n if (elementObjects === undefined) return;\n return _toArray(elementObjects).map(function(elementObject) {\n var element = this.toElementDescriptor(elementObject);\n this.disallowProperty(\n elementObject,\n 'finisher',\n 'An element descriptor'\n );\n this.disallowProperty(\n elementObject,\n 'extras',\n 'An element descriptor'\n );\n return element;\n }, this);\n },\n toElementDescriptor: function(elementObject) {\n var kind = String(elementObject.kind);\n\n if (kind !== 'method' && kind !== 'field') {\n throw new TypeError(\n 'An element descriptor\\'s .kind property must be either \"method\" or' +\n ' \"field\", but a decorator created an element descriptor with' +\n ' .kind \"' +\n kind +\n '\"'\n );\n }\n\n var key = _toPropertyKey(elementObject.key);\n\n var placement = String(elementObject.placement);\n\n if (\n placement !== 'static' &&\n placement !== 'prototype' &&\n placement !== 'own'\n ) {\n throw new TypeError(\n 'An element descriptor\\'s .placement property must be one of \"static\",' +\n ' \"prototype\" or \"own\", but a decorator created an element descriptor' +\n ' with .placement \"' +\n placement +\n '\"'\n );\n }\n\n var descriptor = elementObject.descriptor;\n this.disallowProperty(\n elementObject,\n 'elements',\n 'An element descriptor'\n );\n var element = {\n kind: kind,\n key: key,\n placement: placement,\n descriptor: Object.assign({}, descriptor)\n };\n\n if (kind !== 'field') {\n this.disallowProperty(\n elementObject,\n 'initializer',\n 'A method descriptor'\n );\n } else {\n this.disallowProperty(\n descriptor,\n 'get',\n 'The property descriptor of a field descriptor'\n );\n this.disallowProperty(\n descriptor,\n 'set',\n 'The property descriptor of a field descriptor'\n );\n this.disallowProperty(\n descriptor,\n 'value',\n 'The property descriptor of a field descriptor'\n );\n element.initializer = elementObject.initializer;\n }\n\n return element;\n },\n toElementFinisherExtras: function(elementObject) {\n var element = this.toElementDescriptor(elementObject);\n\n var finisher = _optionalCallableProperty(elementObject, 'finisher');\n\n var extras = this.toElementDescriptors(elementObject.extras);\n return {\n element: element,\n finisher: finisher,\n extras: extras\n };\n },\n fromClassDescriptor: function(elements) {\n var obj = {\n kind: 'class',\n elements: elements.map(this.fromElementDescriptor, this)\n };\n var desc = {\n value: 'Descriptor',\n configurable: true\n };\n Object.defineProperty(obj, Symbol.toStringTag, desc);\n return obj;\n },\n toClassDescriptor: function(obj) {\n var kind = String(obj.kind);\n\n if (kind !== 'class') {\n throw new TypeError(\n 'A class descriptor\\'s .kind property must be \"class\", but a decorator' +\n ' created a class descriptor with .kind \"' +\n kind +\n '\"'\n );\n }\n\n this.disallowProperty(obj, 'key', 'A class descriptor');\n this.disallowProperty(obj, 'placement', 'A class descriptor');\n this.disallowProperty(obj, 'descriptor', 'A class descriptor');\n this.disallowProperty(obj, 'initializer', 'A class descriptor');\n this.disallowProperty(obj, 'extras', 'A class descriptor');\n\n var finisher = _optionalCallableProperty(obj, 'finisher');\n\n var elements = this.toElementDescriptors(obj.elements);\n return {\n elements: elements,\n finisher: finisher\n };\n },\n runClassFinishers: function(constructor, finishers) {\n for (var i = 0; i < finishers.length; i++) {\n var newConstructor = (0, finishers[i])(constructor);\n\n if (newConstructor !== undefined) {\n if (typeof newConstructor !== 'function') {\n throw new TypeError('Finishers must return a constructor.');\n }\n\n constructor = newConstructor;\n }\n }\n\n return constructor;\n },\n disallowProperty: function(obj, name, objectType) {\n if (obj[name] !== undefined) {\n throw new TypeError(\n objectType + \" can't have a .\" + name + ' property.'\n );\n }\n }\n };\n return api;\n }\n\n function _createElementDescriptor(def) {\n var key = _toPropertyKey(def.key);\n\n var descriptor;\n\n if (def.kind === 'method') {\n descriptor = {\n value: def.value,\n writable: true,\n configurable: true,\n enumerable: false\n };\n } else if (def.kind === 'get') {\n descriptor = {\n get: def.value,\n configurable: true,\n enumerable: false\n };\n } else if (def.kind === 'set') {\n descriptor = {\n set: def.value,\n configurable: true,\n enumerable: false\n };\n } else if (def.kind === 'field') {\n descriptor = {\n configurable: true,\n writable: true,\n enumerable: true\n };\n }\n\n var element = {\n kind: def.kind === 'field' ? 'field' : 'method',\n key: key,\n placement: def.static\n ? 'static'\n : def.kind === 'field'\n ? 'own'\n : 'prototype',\n descriptor: descriptor\n };\n if (def.decorators) element.decorators = def.decorators;\n if (def.kind === 'field') element.initializer = def.value;\n return element;\n }\n\n function _coalesceGetterSetter(element, other) {\n if (element.descriptor.get !== undefined) {\n other.descriptor.get = element.descriptor.get;\n } else {\n other.descriptor.set = element.descriptor.set;\n }\n }\n\n function _coalesceClassElements(elements) {\n var newElements = [];\n\n var isSameElement = function(other) {\n return (\n other.kind === 'method' &&\n other.key === element.key &&\n other.placement === element.placement\n );\n };\n\n for (var i = 0; i < elements.length; i++) {\n var element = elements[i];\n var other;\n\n if (\n element.kind === 'method' &&\n (other = newElements.find(isSameElement))\n ) {\n if (\n _isDataDescriptor(element.descriptor) ||\n _isDataDescriptor(other.descriptor)\n ) {\n if (_hasDecorators(element) || _hasDecorators(other)) {\n throw new ReferenceError(\n 'Duplicated methods (' + element.key + \") can't be decorated.\"\n );\n }\n\n other.descriptor = element.descriptor;\n } else {\n if (_hasDecorators(element)) {\n if (_hasDecorators(other)) {\n throw new ReferenceError(\n \"Decorators can't be placed on different accessors with for \" +\n 'the same property (' +\n element.key +\n ').'\n );\n }\n\n other.decorators = element.decorators;\n }\n\n _coalesceGetterSetter(element, other);\n }\n } else {\n newElements.push(element);\n }\n }\n\n return newElements;\n }\n\n function _hasDecorators(element) {\n return element.decorators && element.decorators.length;\n }\n\n function _isDataDescriptor(desc) {\n return (\n desc !== undefined &&\n !(desc.value === undefined && desc.writable === undefined)\n );\n }\n\n function _optionalCallableProperty(obj, name) {\n var value = obj[name];\n\n if (value !== undefined && typeof value !== 'function') {\n throw new TypeError(\"Expected '\" + name + \"' to be a function\");\n }\n\n return value;\n }\n\n function _classPrivateMethodGet(receiver, privateSet, fn) {\n if (!privateSet.has(receiver)) {\n throw new TypeError('attempted to get private field on non-instance');\n }\n\n return fn;\n }\n\n function _classPrivateMethodSet() {\n throw new TypeError('attempted to reassign private method');\n }\n\n function _wrapRegExp(re, groups) {\n _wrapRegExp = function(re, groups) {\n return new BabelRegExp(re, groups);\n };\n\n var _RegExp = _wrapNativeSuper(RegExp);\n\n var _super = RegExp.prototype;\n\n var _groups = new WeakMap();\n\n function BabelRegExp(re, groups) {\n var _this = _RegExp.call(this, re);\n\n _groups.set(_this, groups);\n\n return _this;\n }\n\n _inherits(BabelRegExp, _RegExp);\n\n BabelRegExp.prototype.exec = function(str) {\n var result = _super.exec.call(this, str);\n\n if (result) result.groups = buildGroups(result, this);\n return result;\n };\n\n BabelRegExp.prototype[Symbol.replace] = function(str, substitution) {\n if (typeof substitution === 'string') {\n var groups = _groups.get(this);\n\n return _super[Symbol.replace].call(\n this,\n str,\n substitution.replace(/\\$<([^>]+)>/g, function(_, name) {\n return '$' + groups[name];\n })\n );\n } else if (typeof substitution === 'function') {\n var _this = this;\n\n return _super[Symbol.replace].call(this, str, function() {\n var args = [];\n args.push.apply(args, arguments);\n\n if (typeof args[args.length - 1] !== 'object') {\n args.push(buildGroups(args, _this));\n }\n\n return substitution.apply(this, args);\n });\n } else {\n return _super[Symbol.replace].call(this, str, substitution);\n }\n };\n\n function buildGroups(result, re) {\n var g = _groups.get(re);\n\n return Object.keys(g).reduce(function(groups, name) {\n groups[name] = result[g[name]];\n return groups;\n }, Object.create(null));\n }\n\n return _wrapRegExp.apply(this, arguments);\n }\n\n var vectorMultiply = function vectorMultiply(v, amount) {\n return createVector(v.x * amount, v.y * amount);\n };\n\n var vectorAdd = function vectorAdd(a, b) {\n return createVector(a.x + b.x, a.y + b.y);\n };\n\n var vectorNormalize = function vectorNormalize(v) {\n var l = Math.sqrt(v.x * v.x + v.y * v.y);\n if (l === 0) {\n return {\n x: 0,\n y: 0\n };\n }\n return createVector(v.x / l, v.y / l);\n };\n\n var vectorRotate = function vectorRotate(v, radians, origin) {\n var cos = Math.cos(radians);\n var sin = Math.sin(radians);\n var t = createVector(v.x - origin.x, v.y - origin.y);\n return createVector(\n origin.x + cos * t.x - sin * t.y,\n origin.y + sin * t.x + cos * t.y\n );\n };\n\n var createVector = function createVector() {\n var x =\n arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0;\n var y =\n arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0;\n return { x: x, y: y };\n };\n\n var getMarkupValue = function getMarkupValue(value, size) {\n var scalar =\n arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 1;\n var axis = arguments.length > 3 ? arguments[3] : undefined;\n if (typeof value === 'string') {\n return parseFloat(value) * scalar;\n }\n if (typeof value === 'number') {\n return value * (axis ? size[axis] : Math.min(size.width, size.height));\n }\n return;\n };\n\n var getMarkupStyles = function getMarkupStyles(markup, size, scale) {\n var lineStyle = markup.borderStyle || markup.lineStyle || 'solid';\n var fill = markup.backgroundColor || markup.fontColor || 'transparent';\n var stroke = markup.borderColor || markup.lineColor || 'transparent';\n var strokeWidth = getMarkupValue(\n markup.borderWidth || markup.lineWidth,\n size,\n scale\n );\n var lineCap = markup.lineCap || 'round';\n var lineJoin = markup.lineJoin || 'round';\n var dashes =\n typeof lineStyle === 'string'\n ? ''\n : lineStyle\n .map(function(v) {\n return getMarkupValue(v, size, scale);\n })\n .join(',');\n var opacity = markup.opacity || 1;\n return {\n 'stroke-linecap': lineCap,\n 'stroke-linejoin': lineJoin,\n 'stroke-width': strokeWidth || 0,\n 'stroke-dasharray': dashes,\n stroke: stroke,\n fill: fill,\n opacity: opacity\n };\n };\n\n var isDefined = function isDefined(value) {\n return value != null;\n };\n\n var getMarkupRect = function getMarkupRect(rect, size) {\n var scalar =\n arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 1;\n\n var left =\n getMarkupValue(rect.x, size, scalar, 'width') ||\n getMarkupValue(rect.left, size, scalar, 'width');\n var top =\n getMarkupValue(rect.y, size, scalar, 'height') ||\n getMarkupValue(rect.top, size, scalar, 'height');\n var width = getMarkupValue(rect.width, size, scalar, 'width');\n var height = getMarkupValue(rect.height, size, scalar, 'height');\n var right = getMarkupValue(rect.right, size, scalar, 'width');\n var bottom = getMarkupValue(rect.bottom, size, scalar, 'height');\n\n if (!isDefined(top)) {\n if (isDefined(height) && isDefined(bottom)) {\n top = size.height - height - bottom;\n } else {\n top = bottom;\n }\n }\n\n if (!isDefined(left)) {\n if (isDefined(width) && isDefined(right)) {\n left = size.width - width - right;\n } else {\n left = right;\n }\n }\n\n if (!isDefined(width)) {\n if (isDefined(left) && isDefined(right)) {\n width = size.width - left - right;\n } else {\n width = 0;\n }\n }\n\n if (!isDefined(height)) {\n if (isDefined(top) && isDefined(bottom)) {\n height = size.height - top - bottom;\n } else {\n height = 0;\n }\n }\n\n return {\n x: left || 0,\n y: top || 0,\n width: width || 0,\n height: height || 0\n };\n };\n\n var pointsToPathShape = function pointsToPathShape(points) {\n return points\n .map(function(point, index) {\n return ''\n .concat(index === 0 ? 'M' : 'L', ' ')\n .concat(point.x, ' ')\n .concat(point.y);\n })\n .join(' ');\n };\n\n var setAttributes = function setAttributes(element, attr) {\n return Object.keys(attr).forEach(function(key) {\n return element.setAttribute(key, attr[key]);\n });\n };\n\n var ns = 'http://www.w3.org/2000/svg';\n var svg = function svg(tag, attr) {\n var element = document.createElementNS(ns, tag);\n if (attr) {\n setAttributes(element, attr);\n }\n return element;\n };\n\n var updateRect = function updateRect(element) {\n return setAttributes(\n element,\n Object.assign({}, element.rect, element.styles)\n );\n };\n\n var updateEllipse = function updateEllipse(element) {\n var cx = element.rect.x + element.rect.width * 0.5;\n var cy = element.rect.y + element.rect.height * 0.5;\n var rx = element.rect.width * 0.5;\n var ry = element.rect.height * 0.5;\n return setAttributes(\n element,\n Object.assign(\n {\n cx: cx,\n cy: cy,\n rx: rx,\n ry: ry\n },\n element.styles\n )\n );\n };\n\n var IMAGE_FIT_STYLE = {\n contain: 'xMidYMid meet',\n cover: 'xMidYMid slice'\n };\n\n var updateImage = function updateImage(element, markup) {\n setAttributes(\n element,\n Object.assign({}, element.rect, element.styles, {\n preserveAspectRatio: IMAGE_FIT_STYLE[markup.fit] || 'none'\n })\n );\n };\n\n var TEXT_ANCHOR = {\n left: 'start',\n center: 'middle',\n right: 'end'\n };\n\n var updateText = function updateText(element, markup, size, scale) {\n var fontSize = getMarkupValue(markup.fontSize, size, scale);\n var fontFamily = markup.fontFamily || 'sans-serif';\n var fontWeight = markup.fontWeight || 'normal';\n var textAlign = TEXT_ANCHOR[markup.textAlign] || 'start';\n\n setAttributes(\n element,\n Object.assign({}, element.rect, element.styles, {\n 'stroke-width': 0,\n 'font-weight': fontWeight,\n 'font-size': fontSize,\n 'font-family': fontFamily,\n 'text-anchor': textAlign\n })\n );\n\n // update text\n if (element.text !== markup.text) {\n element.text = markup.text;\n element.textContent = markup.text.length ? markup.text : ' ';\n }\n };\n\n var updateLine = function updateLine(element, markup, size, scale) {\n setAttributes(\n element,\n Object.assign({}, element.rect, element.styles, {\n fill: 'none'\n })\n );\n\n var line = element.childNodes[0];\n var begin = element.childNodes[1];\n var end = element.childNodes[2];\n\n var origin = element.rect;\n\n var target = {\n x: element.rect.x + element.rect.width,\n y: element.rect.y + element.rect.height\n };\n\n setAttributes(line, {\n x1: origin.x,\n y1: origin.y,\n x2: target.x,\n y2: target.y\n });\n\n if (!markup.lineDecoration) return;\n\n begin.style.display = 'none';\n end.style.display = 'none';\n\n var v = vectorNormalize({\n x: target.x - origin.x,\n y: target.y - origin.y\n });\n\n var l = getMarkupValue(0.05, size, scale);\n\n if (markup.lineDecoration.indexOf('arrow-begin') !== -1) {\n var arrowBeginRotationPoint = vectorMultiply(v, l);\n var arrowBeginCenter = vectorAdd(origin, arrowBeginRotationPoint);\n var arrowBeginA = vectorRotate(origin, 2, arrowBeginCenter);\n var arrowBeginB = vectorRotate(origin, -2, arrowBeginCenter);\n\n setAttributes(begin, {\n style: 'display:block;',\n d: 'M'\n .concat(arrowBeginA.x, ',')\n .concat(arrowBeginA.y, ' L')\n .concat(origin.x, ',')\n .concat(origin.y, ' L')\n .concat(arrowBeginB.x, ',')\n .concat(arrowBeginB.y)\n });\n }\n\n if (markup.lineDecoration.indexOf('arrow-end') !== -1) {\n var arrowEndRotationPoint = vectorMultiply(v, -l);\n var arrowEndCenter = vectorAdd(target, arrowEndRotationPoint);\n var arrowEndA = vectorRotate(target, 2, arrowEndCenter);\n var arrowEndB = vectorRotate(target, -2, arrowEndCenter);\n\n setAttributes(end, {\n style: 'display:block;',\n d: 'M'\n .concat(arrowEndA.x, ',')\n .concat(arrowEndA.y, ' L')\n .concat(target.x, ',')\n .concat(target.y, ' L')\n .concat(arrowEndB.x, ',')\n .concat(arrowEndB.y)\n });\n }\n };\n\n var updatePath = function updatePath(element, markup, size, scale) {\n setAttributes(\n element,\n Object.assign({}, element.styles, {\n fill: 'none',\n d: pointsToPathShape(\n markup.points.map(function(point) {\n return {\n x: getMarkupValue(point.x, size, scale, 'width'),\n y: getMarkupValue(point.y, size, scale, 'height')\n };\n })\n )\n })\n );\n };\n\n var createShape = function createShape(node) {\n return function(markup) {\n return svg(node, { id: markup.id });\n };\n };\n\n var createImage = function createImage(markup) {\n var shape = svg('image', {\n id: markup.id,\n 'stroke-linecap': 'round',\n 'stroke-linejoin': 'round',\n opacity: '0'\n });\n\n shape.onload = function() {\n shape.setAttribute('opacity', markup.opacity || 1);\n };\n shape.setAttributeNS(\n 'http://www.w3.org/1999/xlink',\n 'xlink:href',\n markup.src\n );\n return shape;\n };\n\n var createLine = function createLine(markup) {\n var shape = svg('g', {\n id: markup.id,\n 'stroke-linecap': 'round',\n 'stroke-linejoin': 'round'\n });\n\n var line = svg('line');\n shape.appendChild(line);\n\n var begin = svg('path');\n shape.appendChild(begin);\n\n var end = svg('path');\n shape.appendChild(end);\n\n return shape;\n };\n\n var CREATE_TYPE_ROUTES = {\n image: createImage,\n rect: createShape('rect'),\n ellipse: createShape('ellipse'),\n text: createShape('text'),\n path: createShape('path'),\n line: createLine\n };\n\n var UPDATE_TYPE_ROUTES = {\n rect: updateRect,\n ellipse: updateEllipse,\n image: updateImage,\n text: updateText,\n path: updatePath,\n line: updateLine\n };\n\n var createMarkupByType = function createMarkupByType(type, markup) {\n return CREATE_TYPE_ROUTES[type](markup);\n };\n\n var updateMarkupByType = function updateMarkupByType(\n element,\n type,\n markup,\n size,\n scale\n ) {\n if (type !== 'path') {\n element.rect = getMarkupRect(markup, size, scale);\n }\n element.styles = getMarkupStyles(markup, size, scale);\n UPDATE_TYPE_ROUTES[type](element, markup, size, scale);\n };\n\n var MARKUP_RECT = [\n 'x',\n 'y',\n 'left',\n 'top',\n 'right',\n 'bottom',\n 'width',\n 'height'\n ];\n\n var toOptionalFraction = function toOptionalFraction(value) {\n return typeof value === 'string' && /%/.test(value)\n ? parseFloat(value) / 100\n : value;\n };\n\n // adds default markup properties, clones markup\n var prepareMarkup = function prepareMarkup(markup) {\n var _markup = _slicedToArray(markup, 2),\n type = _markup[0],\n props = _markup[1];\n\n var rect = props.points\n ? {}\n : MARKUP_RECT.reduce(function(prev, curr) {\n prev[curr] = toOptionalFraction(props[curr]);\n return prev;\n }, {});\n\n return [\n type,\n Object.assign(\n {\n zIndex: 0\n },\n props,\n rect\n )\n ];\n };\n\n var sortMarkupByZIndex = function sortMarkupByZIndex(a, b) {\n if (a[1].zIndex > b[1].zIndex) {\n return 1;\n }\n if (a[1].zIndex < b[1].zIndex) {\n return -1;\n }\n return 0;\n };\n\n var createMarkupView = function createMarkupView(_) {\n return _.utils.createView({\n name: 'image-preview-markup',\n tag: 'svg',\n ignoreRect: true,\n mixins: {\n apis: ['width', 'height', 'crop', 'markup', 'resize', 'dirty']\n },\n\n write: function write(_ref) {\n var root = _ref.root,\n props = _ref.props;\n\n if (!props.dirty) return;\n var crop = props.crop,\n resize = props.resize,\n markup = props.markup;\n\n var viewWidth = props.width;\n var viewHeight = props.height;\n\n var cropWidth = crop.width;\n var cropHeight = crop.height;\n\n if (resize) {\n var _size = resize.size;\n\n var outputWidth = _size && _size.width;\n var outputHeight = _size && _size.height;\n var outputFit = resize.mode;\n var outputUpscale = resize.upscale;\n\n if (outputWidth && !outputHeight) outputHeight = outputWidth;\n if (outputHeight && !outputWidth) outputWidth = outputHeight;\n\n var shouldUpscale =\n cropWidth < outputWidth && cropHeight < outputHeight;\n\n if (!shouldUpscale || (shouldUpscale && outputUpscale)) {\n var scalarWidth = outputWidth / cropWidth;\n var scalarHeight = outputHeight / cropHeight;\n\n if (outputFit === 'force') {\n cropWidth = outputWidth;\n cropHeight = outputHeight;\n } else {\n var scalar;\n if (outputFit === 'cover') {\n scalar = Math.max(scalarWidth, scalarHeight);\n } else if (outputFit === 'contain') {\n scalar = Math.min(scalarWidth, scalarHeight);\n }\n cropWidth = cropWidth * scalar;\n cropHeight = cropHeight * scalar;\n }\n }\n }\n\n var size = {\n width: viewWidth,\n height: viewHeight\n };\n\n root.element.setAttribute('width', size.width);\n root.element.setAttribute('height', size.height);\n\n var scale = Math.min(viewWidth / cropWidth, viewHeight / cropHeight);\n\n // clear\n root.element.innerHTML = '';\n\n // get filter\n var markupFilter = root.query('GET_IMAGE_PREVIEW_MARKUP_FILTER');\n\n // draw new\n markup\n .filter(markupFilter)\n .map(prepareMarkup)\n .sort(sortMarkupByZIndex)\n .forEach(function(markup) {\n var _markup = _slicedToArray(markup, 2),\n type = _markup[0],\n settings = _markup[1];\n\n // create\n var element = createMarkupByType(type, settings);\n\n // update\n updateMarkupByType(element, type, settings, size, scale);\n\n // add\n root.element.appendChild(element);\n });\n }\n });\n };\n\n var createVector$1 = function createVector(x, y) {\n return { x: x, y: y };\n };\n\n var vectorDot = function vectorDot(a, b) {\n return a.x * b.x + a.y * b.y;\n };\n\n var vectorSubtract = function vectorSubtract(a, b) {\n return createVector$1(a.x - b.x, a.y - b.y);\n };\n\n var vectorDistanceSquared = function vectorDistanceSquared(a, b) {\n return vectorDot(vectorSubtract(a, b), vectorSubtract(a, b));\n };\n\n var vectorDistance = function vectorDistance(a, b) {\n return Math.sqrt(vectorDistanceSquared(a, b));\n };\n\n var getOffsetPointOnEdge = function getOffsetPointOnEdge(length, rotation) {\n var a = length;\n\n var A = 1.5707963267948966;\n var B = rotation;\n var C = 1.5707963267948966 - rotation;\n\n var sinA = Math.sin(A);\n var sinB = Math.sin(B);\n var sinC = Math.sin(C);\n var cosC = Math.cos(C);\n var ratio = a / sinA;\n var b = ratio * sinB;\n var c = ratio * sinC;\n\n return createVector$1(cosC * b, cosC * c);\n };\n\n var getRotatedRectSize = function getRotatedRectSize(rect, rotation) {\n var w = rect.width;\n var h = rect.height;\n\n var hor = getOffsetPointOnEdge(w, rotation);\n var ver = getOffsetPointOnEdge(h, rotation);\n\n var tl = createVector$1(rect.x + Math.abs(hor.x), rect.y - Math.abs(hor.y));\n\n var tr = createVector$1(\n rect.x + rect.width + Math.abs(ver.y),\n rect.y + Math.abs(ver.x)\n );\n\n var bl = createVector$1(\n rect.x - Math.abs(ver.y),\n rect.y + rect.height - Math.abs(ver.x)\n );\n\n return {\n width: vectorDistance(tl, tr),\n height: vectorDistance(tl, bl)\n };\n };\n\n var calculateCanvasSize = function calculateCanvasSize(\n image,\n canvasAspectRatio\n ) {\n var zoom =\n arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 1;\n\n var imageAspectRatio = image.height / image.width;\n\n // determine actual pixels on x and y axis\n var canvasWidth = 1;\n var canvasHeight = canvasAspectRatio;\n var imgWidth = 1;\n var imgHeight = imageAspectRatio;\n if (imgHeight > canvasHeight) {\n imgHeight = canvasHeight;\n imgWidth = imgHeight / imageAspectRatio;\n }\n\n var scalar = Math.max(canvasWidth / imgWidth, canvasHeight / imgHeight);\n var width = image.width / (zoom * scalar * imgWidth);\n var height = width * canvasAspectRatio;\n\n return {\n width: width,\n height: height\n };\n };\n\n var getImageRectZoomFactor = function getImageRectZoomFactor(\n imageRect,\n cropRect,\n rotation,\n center\n ) {\n // calculate available space round image center position\n var cx = center.x > 0.5 ? 1 - center.x : center.x;\n var cy = center.y > 0.5 ? 1 - center.y : center.y;\n var imageWidth = cx * 2 * imageRect.width;\n var imageHeight = cy * 2 * imageRect.height;\n\n // calculate rotated crop rectangle size\n var rotatedCropSize = getRotatedRectSize(cropRect, rotation);\n\n // calculate scalar required to fit image\n return Math.max(\n rotatedCropSize.width / imageWidth,\n rotatedCropSize.height / imageHeight\n );\n };\n\n var getCenteredCropRect = function getCenteredCropRect(\n container,\n aspectRatio\n ) {\n var width = container.width;\n var height = width * aspectRatio;\n if (height > container.height) {\n height = container.height;\n width = height / aspectRatio;\n }\n var x = (container.width - width) * 0.5;\n var y = (container.height - height) * 0.5;\n\n return {\n x: x,\n y: y,\n width: width,\n height: height\n };\n };\n\n var getCurrentCropSize = function getCurrentCropSize(imageSize) {\n var crop =\n arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};\n var zoom = crop.zoom,\n rotation = crop.rotation,\n center = crop.center,\n aspectRatio = crop.aspectRatio;\n\n if (!aspectRatio) aspectRatio = imageSize.height / imageSize.width;\n\n var canvasSize = calculateCanvasSize(imageSize, aspectRatio, zoom);\n\n var canvasCenter = {\n x: canvasSize.width * 0.5,\n y: canvasSize.height * 0.5\n };\n\n var stage = {\n x: 0,\n y: 0,\n width: canvasSize.width,\n height: canvasSize.height,\n center: canvasCenter\n };\n\n var shouldLimit = typeof crop.scaleToFit === 'undefined' || crop.scaleToFit;\n\n var stageZoomFactor = getImageRectZoomFactor(\n imageSize,\n getCenteredCropRect(stage, aspectRatio),\n rotation,\n shouldLimit ? center : { x: 0.5, y: 0.5 }\n );\n\n var scale = zoom * stageZoomFactor;\n\n // start drawing\n return {\n widthFloat: canvasSize.width / scale,\n heightFloat: canvasSize.height / scale,\n width: Math.round(canvasSize.width / scale),\n height: Math.round(canvasSize.height / scale)\n };\n };\n\n var IMAGE_SCALE_SPRING_PROPS = {\n type: 'spring',\n stiffness: 0.5,\n damping: 0.45,\n mass: 10\n };\n\n // does horizontal and vertical flipping\n var createBitmapView = function createBitmapView(_) {\n return _.utils.createView({\n name: 'image-bitmap',\n ignoreRect: true,\n mixins: { styles: ['scaleX', 'scaleY'] },\n create: function create(_ref) {\n var root = _ref.root,\n props = _ref.props;\n root.appendChild(props.image);\n }\n });\n };\n\n // shifts and rotates image\n var createImageCanvasWrapper = function createImageCanvasWrapper(_) {\n return _.utils.createView({\n name: 'image-canvas-wrapper',\n tag: 'div',\n ignoreRect: true,\n mixins: {\n apis: ['crop', 'width', 'height'],\n\n styles: [\n 'originX',\n 'originY',\n 'translateX',\n 'translateY',\n 'scaleX',\n 'scaleY',\n 'rotateZ'\n ],\n\n animations: {\n originX: IMAGE_SCALE_SPRING_PROPS,\n originY: IMAGE_SCALE_SPRING_PROPS,\n scaleX: IMAGE_SCALE_SPRING_PROPS,\n scaleY: IMAGE_SCALE_SPRING_PROPS,\n translateX: IMAGE_SCALE_SPRING_PROPS,\n translateY: IMAGE_SCALE_SPRING_PROPS,\n rotateZ: IMAGE_SCALE_SPRING_PROPS\n }\n },\n\n create: function create(_ref2) {\n var root = _ref2.root,\n props = _ref2.props;\n props.width = props.image.width;\n props.height = props.image.height;\n root.ref.bitmap = root.appendChildView(\n root.createChildView(createBitmapView(_), { image: props.image })\n );\n },\n write: function write(_ref3) {\n var root = _ref3.root,\n props = _ref3.props;\n var flip = props.crop.flip;\n var bitmap = root.ref.bitmap;\n bitmap.scaleX = flip.horizontal ? -1 : 1;\n bitmap.scaleY = flip.vertical ? -1 : 1;\n }\n });\n };\n\n // clips canvas to correct aspect ratio\n var createClipView = function createClipView(_) {\n return _.utils.createView({\n name: 'image-clip',\n tag: 'div',\n ignoreRect: true,\n mixins: {\n apis: [\n 'crop',\n 'markup',\n 'resize',\n 'width',\n 'height',\n 'dirty',\n 'background'\n ],\n\n styles: ['width', 'height', 'opacity'],\n animations: {\n opacity: { type: 'tween', duration: 250 }\n }\n },\n\n didWriteView: function didWriteView(_ref4) {\n var root = _ref4.root,\n props = _ref4.props;\n if (!props.background) return;\n root.element.style.backgroundColor = props.background;\n },\n create: function create(_ref5) {\n var root = _ref5.root,\n props = _ref5.props;\n\n root.ref.image = root.appendChildView(\n root.createChildView(\n createImageCanvasWrapper(_),\n Object.assign({}, props)\n )\n );\n\n root.ref.createMarkup = function() {\n if (root.ref.markup) return;\n root.ref.markup = root.appendChildView(\n root.createChildView(createMarkupView(_), Object.assign({}, props))\n );\n };\n\n root.ref.destroyMarkup = function() {\n if (!root.ref.markup) return;\n root.removeChildView(root.ref.markup);\n root.ref.markup = null;\n };\n\n // set up transparency grid\n var transparencyIndicator = root.query(\n 'GET_IMAGE_PREVIEW_TRANSPARENCY_INDICATOR'\n );\n if (transparencyIndicator === null) return;\n\n // grid pattern\n if (transparencyIndicator === 'grid') {\n root.element.dataset.transparencyIndicator = transparencyIndicator;\n }\n // basic color\n else {\n root.element.dataset.transparencyIndicator = 'color';\n }\n },\n write: function write(_ref6) {\n var root = _ref6.root,\n props = _ref6.props,\n shouldOptimize = _ref6.shouldOptimize;\n var crop = props.crop,\n markup = props.markup,\n resize = props.resize,\n dirty = props.dirty,\n width = props.width,\n height = props.height;\n\n root.ref.image.crop = crop;\n\n var stage = {\n x: 0,\n y: 0,\n width: width,\n height: height,\n center: {\n x: width * 0.5,\n y: height * 0.5\n }\n };\n\n var image = {\n width: root.ref.image.width,\n height: root.ref.image.height\n };\n\n var origin = {\n x: crop.center.x * image.width,\n y: crop.center.y * image.height\n };\n\n var translation = {\n x: stage.center.x - image.width * crop.center.x,\n y: stage.center.y - image.height * crop.center.y\n };\n\n var rotation = Math.PI * 2 + (crop.rotation % (Math.PI * 2));\n\n var cropAspectRatio = crop.aspectRatio || image.height / image.width;\n\n var shouldLimit =\n typeof crop.scaleToFit === 'undefined' || crop.scaleToFit;\n\n var stageZoomFactor = getImageRectZoomFactor(\n image,\n getCenteredCropRect(stage, cropAspectRatio),\n\n rotation,\n shouldLimit ? crop.center : { x: 0.5, y: 0.5 }\n );\n\n var scale = crop.zoom * stageZoomFactor;\n\n // update markup view\n if (markup && markup.length) {\n root.ref.createMarkup();\n root.ref.markup.width = width;\n root.ref.markup.height = height;\n root.ref.markup.resize = resize;\n root.ref.markup.dirty = dirty;\n root.ref.markup.markup = markup;\n root.ref.markup.crop = getCurrentCropSize(image, crop);\n } else if (root.ref.markup) {\n root.ref.destroyMarkup();\n }\n\n // update image view\n var imageView = root.ref.image;\n\n // don't update clip layout\n if (shouldOptimize) {\n imageView.originX = null;\n imageView.originY = null;\n imageView.translateX = null;\n imageView.translateY = null;\n imageView.rotateZ = null;\n imageView.scaleX = null;\n imageView.scaleY = null;\n return;\n }\n\n imageView.originX = origin.x;\n imageView.originY = origin.y;\n imageView.translateX = translation.x;\n imageView.translateY = translation.y;\n imageView.rotateZ = rotation;\n imageView.scaleX = scale;\n imageView.scaleY = scale;\n }\n });\n };\n\n var createImageView = function createImageView(_) {\n return _.utils.createView({\n name: 'image-preview',\n tag: 'div',\n ignoreRect: true,\n mixins: {\n apis: ['image', 'crop', 'markup', 'resize', 'dirty', 'background'],\n\n styles: ['translateY', 'scaleX', 'scaleY', 'opacity'],\n\n animations: {\n scaleX: IMAGE_SCALE_SPRING_PROPS,\n scaleY: IMAGE_SCALE_SPRING_PROPS,\n translateY: IMAGE_SCALE_SPRING_PROPS,\n opacity: { type: 'tween', duration: 400 }\n }\n },\n\n create: function create(_ref7) {\n var root = _ref7.root,\n props = _ref7.props;\n root.ref.clip = root.appendChildView(\n root.createChildView(createClipView(_), {\n id: props.id,\n image: props.image,\n crop: props.crop,\n markup: props.markup,\n resize: props.resize,\n dirty: props.dirty,\n background: props.background\n })\n );\n },\n write: function write(_ref8) {\n var root = _ref8.root,\n props = _ref8.props,\n shouldOptimize = _ref8.shouldOptimize;\n var clip = root.ref.clip;\n var image = props.image,\n crop = props.crop,\n markup = props.markup,\n resize = props.resize,\n dirty = props.dirty;\n\n clip.crop = crop;\n clip.markup = markup;\n clip.resize = resize;\n clip.dirty = dirty;\n\n // don't update clip layout\n clip.opacity = shouldOptimize ? 0 : 1;\n\n // don't re-render if optimizing or hidden (width will be zero resulting in weird animations)\n if (shouldOptimize || root.rect.element.hidden) return;\n\n // calculate scaled preview image size\n var imageAspectRatio = image.height / image.width;\n var aspectRatio = crop.aspectRatio || imageAspectRatio;\n\n // calculate container size\n var containerWidth = root.rect.inner.width;\n var containerHeight = root.rect.inner.height;\n\n var fixedPreviewHeight = root.query('GET_IMAGE_PREVIEW_HEIGHT');\n var minPreviewHeight = root.query('GET_IMAGE_PREVIEW_MIN_HEIGHT');\n var maxPreviewHeight = root.query('GET_IMAGE_PREVIEW_MAX_HEIGHT');\n\n var panelAspectRatio = root.query('GET_PANEL_ASPECT_RATIO');\n var allowMultiple = root.query('GET_ALLOW_MULTIPLE');\n\n if (panelAspectRatio && !allowMultiple) {\n fixedPreviewHeight = containerWidth * panelAspectRatio;\n aspectRatio = panelAspectRatio;\n }\n\n // determine clip width and height\n var clipHeight =\n fixedPreviewHeight !== null\n ? fixedPreviewHeight\n : Math.max(\n minPreviewHeight,\n Math.min(containerWidth * aspectRatio, maxPreviewHeight)\n );\n\n var clipWidth = clipHeight / aspectRatio;\n if (clipWidth > containerWidth) {\n clipWidth = containerWidth;\n clipHeight = clipWidth * aspectRatio;\n }\n\n if (clipHeight > containerHeight) {\n clipHeight = containerHeight;\n clipWidth = containerHeight / aspectRatio;\n }\n\n clip.width = clipWidth;\n clip.height = clipHeight;\n }\n });\n };\n\n var SVG_MASK =\n '\\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n';\n\n var SVGMaskUniqueId = 0;\n\n var createImageOverlayView = function createImageOverlayView(fpAPI) {\n return fpAPI.utils.createView({\n name: 'image-preview-overlay',\n tag: 'div',\n ignoreRect: true,\n create: function create(_ref) {\n var root = _ref.root,\n props = _ref.props;\n var mask = SVG_MASK;\n if (document.querySelector('base')) {\n var url = new URL(\n window.location.href.replace(window.location.hash, '')\n ).href;\n mask = mask.replace(/url\\(\\#/g, 'url(' + url + '#');\n }\n\n SVGMaskUniqueId++;\n root.element.classList.add(\n 'filepond--image-preview-overlay-'.concat(props.status)\n );\n\n root.element.innerHTML = mask.replace(/__UID__/g, SVGMaskUniqueId);\n },\n mixins: {\n styles: ['opacity'],\n animations: {\n opacity: { type: 'spring', mass: 25 }\n }\n }\n });\n };\n\n /**\n * Bitmap Worker\n */\n var BitmapWorker = function BitmapWorker() {\n self.onmessage = function(e) {\n createImageBitmap(e.data.message.file).then(function(bitmap) {\n self.postMessage({ id: e.data.id, message: bitmap }, [bitmap]);\n });\n };\n };\n\n /**\n * ColorMatrix Worker\n */\n var ColorMatrixWorker = function ColorMatrixWorker() {\n self.onmessage = function(e) {\n var imageData = e.data.message.imageData;\n var matrix = e.data.message.colorMatrix;\n\n var data = imageData.data;\n var l = data.length;\n\n var m11 = matrix[0];\n var m12 = matrix[1];\n var m13 = matrix[2];\n var m14 = matrix[3];\n var m15 = matrix[4];\n\n var m21 = matrix[5];\n var m22 = matrix[6];\n var m23 = matrix[7];\n var m24 = matrix[8];\n var m25 = matrix[9];\n\n var m31 = matrix[10];\n var m32 = matrix[11];\n var m33 = matrix[12];\n var m34 = matrix[13];\n var m35 = matrix[14];\n\n var m41 = matrix[15];\n var m42 = matrix[16];\n var m43 = matrix[17];\n var m44 = matrix[18];\n var m45 = matrix[19];\n\n var index = 0,\n r = 0.0,\n g = 0.0,\n b = 0.0,\n a = 0.0;\n\n for (; index < l; index += 4) {\n r = data[index] / 255;\n g = data[index + 1] / 255;\n b = data[index + 2] / 255;\n a = data[index + 3] / 255;\n data[index] = Math.max(\n 0,\n Math.min((r * m11 + g * m12 + b * m13 + a * m14 + m15) * 255, 255)\n );\n data[index + 1] = Math.max(\n 0,\n Math.min((r * m21 + g * m22 + b * m23 + a * m24 + m25) * 255, 255)\n );\n data[index + 2] = Math.max(\n 0,\n Math.min((r * m31 + g * m32 + b * m33 + a * m34 + m35) * 255, 255)\n );\n data[index + 3] = Math.max(\n 0,\n Math.min((r * m41 + g * m42 + b * m43 + a * m44 + m45) * 255, 255)\n );\n }\n\n self.postMessage({ id: e.data.id, message: imageData }, [\n imageData.data.buffer\n ]);\n };\n };\n\n var getImageSize = function getImageSize(url, cb) {\n var image = new Image();\n image.onload = function() {\n var width = image.naturalWidth;\n var height = image.naturalHeight;\n image = null;\n cb(width, height);\n };\n image.src = url;\n };\n\n var transforms = {\n 1: function _() {\n return [1, 0, 0, 1, 0, 0];\n },\n 2: function _(width) {\n return [-1, 0, 0, 1, width, 0];\n },\n 3: function _(width, height) {\n return [-1, 0, 0, -1, width, height];\n },\n 4: function _(width, height) {\n return [1, 0, 0, -1, 0, height];\n },\n 5: function _() {\n return [0, 1, 1, 0, 0, 0];\n },\n 6: function _(width, height) {\n return [0, 1, -1, 0, height, 0];\n },\n 7: function _(width, height) {\n return [0, -1, -1, 0, height, width];\n },\n 8: function _(width) {\n return [0, -1, 1, 0, 0, width];\n }\n };\n\n var fixImageOrientation = function fixImageOrientation(\n ctx,\n width,\n height,\n orientation\n ) {\n // no orientation supplied\n if (orientation === -1) {\n return;\n }\n\n ctx.transform.apply(ctx, transforms[orientation](width, height));\n };\n\n // draws the preview image to canvas\n var createPreviewImage = function createPreviewImage(\n data,\n width,\n height,\n orientation\n ) {\n // can't draw on half pixels\n width = Math.round(width);\n height = Math.round(height);\n\n // draw image\n var canvas = document.createElement('canvas');\n canvas.width = width;\n canvas.height = height;\n var ctx = canvas.getContext('2d');\n\n // if is rotated incorrectly swap width and height\n if (orientation >= 5 && orientation <= 8) {\n var _ref = [height, width];\n width = _ref[0];\n height = _ref[1];\n }\n\n // correct image orientation\n fixImageOrientation(ctx, width, height, orientation);\n\n // draw the image\n ctx.drawImage(data, 0, 0, width, height);\n\n return canvas;\n };\n\n var isBitmap = function isBitmap(file) {\n return /^image/.test(file.type) && !/svg/.test(file.type);\n };\n\n var MAX_WIDTH = 10;\n var MAX_HEIGHT = 10;\n\n var calculateAverageColor = function calculateAverageColor(image) {\n var scalar = Math.min(MAX_WIDTH / image.width, MAX_HEIGHT / image.height);\n\n var canvas = document.createElement('canvas');\n var ctx = canvas.getContext('2d');\n var width = (canvas.width = Math.ceil(image.width * scalar));\n var height = (canvas.height = Math.ceil(image.height * scalar));\n ctx.drawImage(image, 0, 0, width, height);\n var data = null;\n try {\n data = ctx.getImageData(0, 0, width, height).data;\n } catch (e) {\n return null;\n }\n var l = data.length;\n\n var r = 0;\n var g = 0;\n var b = 0;\n var i = 0;\n\n for (; i < l; i += 4) {\n r += data[i] * data[i];\n g += data[i + 1] * data[i + 1];\n b += data[i + 2] * data[i + 2];\n }\n\n r = averageColor(r, l);\n g = averageColor(g, l);\n b = averageColor(b, l);\n\n return { r: r, g: g, b: b };\n };\n\n var averageColor = function averageColor(c, l) {\n return Math.floor(Math.sqrt(c / (l / 4)));\n };\n\n var cloneCanvas = function cloneCanvas(origin, target) {\n target = target || document.createElement('canvas');\n target.width = origin.width;\n target.height = origin.height;\n var ctx = target.getContext('2d');\n ctx.drawImage(origin, 0, 0);\n return target;\n };\n\n var cloneImageData = function cloneImageData(imageData) {\n var id;\n try {\n id = new ImageData(imageData.width, imageData.height);\n } catch (e) {\n var canvas = document.createElement('canvas');\n var ctx = canvas.getContext('2d');\n id = ctx.createImageData(imageData.width, imageData.height);\n }\n id.data.set(new Uint8ClampedArray(imageData.data));\n return id;\n };\n\n var loadImage = function loadImage(url) {\n return new Promise(function(resolve, reject) {\n var img = new Image();\n img.crossOrigin = 'Anonymous';\n img.onload = function() {\n resolve(img);\n };\n img.onerror = function(e) {\n reject(e);\n };\n img.src = url;\n });\n };\n\n var createImageWrapperView = function createImageWrapperView(_) {\n // create overlay view\n var OverlayView = createImageOverlayView(_);\n\n var ImageView = createImageView(_);\n var createWorker = _.utils.createWorker;\n\n var applyFilter = function applyFilter(root, filter, target) {\n return new Promise(function(resolve) {\n // will store image data for future filter updates\n if (!root.ref.imageData) {\n root.ref.imageData = target\n .getContext('2d')\n .getImageData(0, 0, target.width, target.height);\n }\n\n // get image data reference\n var imageData = cloneImageData(root.ref.imageData);\n\n if (!filter || filter.length !== 20) {\n target.getContext('2d').putImageData(imageData, 0, 0);\n return resolve();\n }\n\n var worker = createWorker(ColorMatrixWorker);\n worker.post(\n {\n imageData: imageData,\n colorMatrix: filter\n },\n\n function(response) {\n // apply filtered colors\n target.getContext('2d').putImageData(response, 0, 0);\n\n // stop worker\n worker.terminate();\n\n // done!\n resolve();\n },\n [imageData.data.buffer]\n );\n });\n };\n\n var removeImageView = function removeImageView(root, imageView) {\n root.removeChildView(imageView);\n imageView.image.width = 1;\n imageView.image.height = 1;\n imageView._destroy();\n };\n\n // remove an image\n var shiftImage = function shiftImage(_ref) {\n var root = _ref.root;\n var imageView = root.ref.images.shift();\n imageView.opacity = 0;\n imageView.translateY = -15;\n root.ref.imageViewBin.push(imageView);\n return imageView;\n };\n\n // add new image\n var pushImage = function pushImage(_ref2) {\n var root = _ref2.root,\n props = _ref2.props,\n image = _ref2.image;\n var id = props.id;\n var item = root.query('GET_ITEM', { id: id });\n if (!item) return;\n\n var crop = item.getMetadata('crop') || {\n center: {\n x: 0.5,\n y: 0.5\n },\n\n flip: {\n horizontal: false,\n vertical: false\n },\n\n zoom: 1,\n rotation: 0,\n aspectRatio: null\n };\n\n var background = root.query(\n 'GET_IMAGE_TRANSFORM_CANVAS_BACKGROUND_COLOR'\n );\n\n var markup;\n var resize;\n var dirty = false;\n if (root.query('GET_IMAGE_PREVIEW_MARKUP_SHOW')) {\n markup = item.getMetadata('markup') || [];\n resize = item.getMetadata('resize');\n dirty = true;\n }\n\n // append image presenter\n var imageView = root.appendChildView(\n root.createChildView(ImageView, {\n id: id,\n image: image,\n crop: crop,\n resize: resize,\n markup: markup,\n dirty: dirty,\n background: background,\n opacity: 0,\n scaleX: 1.15,\n scaleY: 1.15,\n translateY: 15\n }),\n\n root.childViews.length\n );\n\n root.ref.images.push(imageView);\n\n // reveal the preview image\n imageView.opacity = 1;\n imageView.scaleX = 1;\n imageView.scaleY = 1;\n imageView.translateY = 0;\n\n // the preview is now ready to be drawn\n setTimeout(function() {\n root.dispatch('DID_IMAGE_PREVIEW_SHOW', { id: id });\n }, 250);\n };\n\n var updateImage = function updateImage(_ref3) {\n var root = _ref3.root,\n props = _ref3.props;\n var item = root.query('GET_ITEM', { id: props.id });\n if (!item) return;\n var imageView = root.ref.images[root.ref.images.length - 1];\n imageView.crop = item.getMetadata('crop');\n imageView.background = root.query(\n 'GET_IMAGE_TRANSFORM_CANVAS_BACKGROUND_COLOR'\n );\n\n if (root.query('GET_IMAGE_PREVIEW_MARKUP_SHOW')) {\n imageView.dirty = true;\n imageView.resize = item.getMetadata('resize');\n imageView.markup = item.getMetadata('markup');\n }\n };\n\n // replace image preview\n var didUpdateItemMetadata = function didUpdateItemMetadata(_ref4) {\n var root = _ref4.root,\n props = _ref4.props,\n action = _ref4.action;\n // only filter and crop trigger redraw\n if (!/crop|filter|markup|resize/.test(action.change.key)) return;\n\n // no images to update, exit\n if (!root.ref.images.length) return;\n\n // no item found, exit\n var item = root.query('GET_ITEM', { id: props.id });\n if (!item) return;\n\n // for now, update existing image when filtering\n if (/filter/.test(action.change.key)) {\n var imageView = root.ref.images[root.ref.images.length - 1];\n applyFilter(root, action.change.value, imageView.image);\n return;\n }\n\n if (/crop|markup|resize/.test(action.change.key)) {\n var crop = item.getMetadata('crop');\n var image = root.ref.images[root.ref.images.length - 1];\n\n // if aspect ratio has changed, we need to create a new image\n if (\n crop &&\n crop.aspectRatio &&\n image.crop &&\n image.crop.aspectRatio &&\n Math.abs(crop.aspectRatio - image.crop.aspectRatio) > 0.00001\n ) {\n var _imageView = shiftImage({ root: root });\n pushImage({\n root: root,\n props: props,\n image: cloneCanvas(_imageView.image)\n });\n }\n // if not, we can update the current image\n else {\n updateImage({ root: root, props: props });\n }\n }\n };\n\n var canCreateImageBitmap = function canCreateImageBitmap(file) {\n // Firefox versions before 58 will freeze when running createImageBitmap\n // in a Web Worker so we detect those versions and return false for support\n var userAgent = window.navigator.userAgent;\n var isFirefox = userAgent.match(/Firefox\\/([0-9]+)\\./);\n var firefoxVersion = isFirefox ? parseInt(isFirefox[1]) : null;\n if (firefoxVersion !== null && firefoxVersion <= 58) return false;\n\n return 'createImageBitmap' in window && isBitmap(file);\n };\n\n /**\n * Write handler for when preview container has been created\n */\n var didCreatePreviewContainer = function didCreatePreviewContainer(_ref5) {\n var root = _ref5.root,\n props = _ref5.props;\n var id = props.id;\n\n // we need to get the file data to determine the eventual image size\n var item = root.query('GET_ITEM', id);\n if (!item) return;\n\n // get url to file (we'll revoke it later on when done)\n var fileURL = URL.createObjectURL(item.file);\n\n // determine image size of this item\n getImageSize(fileURL, function(width, height) {\n // we can now scale the panel to the final size\n root.dispatch('DID_IMAGE_PREVIEW_CALCULATE_SIZE', {\n id: id,\n width: width,\n height: height\n });\n });\n };\n\n var drawPreview = function drawPreview(_ref6) {\n var root = _ref6.root,\n props = _ref6.props;\n var id = props.id;\n\n // we need to get the file data to determine the eventual image size\n var item = root.query('GET_ITEM', id);\n if (!item) return;\n\n // get url to file (we'll revoke it later on when done)\n var fileURL = URL.createObjectURL(item.file);\n\n // fallback\n var loadPreviewFallback = function loadPreviewFallback() {\n // let's scale the image in the main thread :(\n loadImage(fileURL).then(previewImageLoaded);\n };\n\n // image is now ready\n var previewImageLoaded = function previewImageLoaded(imageData) {\n // the file url is no longer needed\n URL.revokeObjectURL(fileURL);\n\n // draw the scaled down version here and use that as source so bitmapdata can be closed\n // orientation info\n var exif = item.getMetadata('exif') || {};\n var orientation = exif.orientation || -1;\n\n // get width and height from action, and swap if orientation is incorrect\n var width = imageData.width,\n height = imageData.height;\n\n // if no width or height, just return early.\n if (!width || !height) return;\n\n if (orientation >= 5 && orientation <= 8) {\n var _ref7 = [height, width];\n width = _ref7[0];\n height = _ref7[1];\n }\n\n // scale canvas based on pixel density\n // we multiply by .75 as that creates smaller but still clear images on screens with high res displays\n var pixelDensityFactor = Math.max(1, window.devicePixelRatio * 0.75);\n\n // we want as much pixels to work with as possible,\n // this multiplies the minimum image resolution,\n // so when zooming in it doesn't get too blurry\n var zoomFactor = root.query('GET_IMAGE_PREVIEW_ZOOM_FACTOR');\n\n // imaeg scale factor\n var scaleFactor = zoomFactor * pixelDensityFactor;\n\n // calculate scaled preview image size\n var previewImageRatio = height / width;\n\n // calculate image preview height and width\n var previewContainerWidth = root.rect.element.width;\n var previewContainerHeight = root.rect.element.height;\n\n var imageWidth = previewContainerWidth;\n var imageHeight = imageWidth * previewImageRatio;\n\n if (previewImageRatio > 1) {\n imageWidth = Math.min(width, previewContainerWidth * scaleFactor);\n imageHeight = imageWidth * previewImageRatio;\n } else {\n imageHeight = Math.min(height, previewContainerHeight * scaleFactor);\n imageWidth = imageHeight / previewImageRatio;\n }\n\n // transfer to image tag so no canvas memory wasted on iOS\n var previewImage = createPreviewImage(\n imageData,\n imageWidth,\n imageHeight,\n orientation\n );\n\n // done\n var done = function done() {\n // calculate average image color, disabled for now\n var averageColor = root.query(\n 'GET_IMAGE_PREVIEW_CALCULATE_AVERAGE_IMAGE_COLOR'\n )\n ? calculateAverageColor(data)\n : null;\n item.setMetadata('color', averageColor, true);\n\n // data has been transferred to canvas ( if was ImageBitmap )\n if ('close' in imageData) {\n imageData.close();\n }\n\n // show the overlay\n root.ref.overlayShadow.opacity = 1;\n\n // create the first image\n pushImage({ root: root, props: props, image: previewImage });\n };\n\n // apply filter\n var filter = item.getMetadata('filter');\n if (filter) {\n applyFilter(root, filter, previewImage).then(done);\n } else {\n done();\n }\n };\n\n // if we support scaling using createImageBitmap we use a worker\n if (canCreateImageBitmap(item.file)) {\n // let's scale the image in a worker\n var worker = createWorker(BitmapWorker);\n\n worker.post(\n {\n file: item.file\n },\n\n function(imageBitmap) {\n // destroy worker\n worker.terminate();\n\n // no bitmap returned, must be something wrong,\n // try the oldschool way\n if (!imageBitmap) {\n loadPreviewFallback();\n return;\n }\n\n // yay we got our bitmap, let's continue showing the preview\n previewImageLoaded(imageBitmap);\n }\n );\n } else {\n // create fallback preview\n loadPreviewFallback();\n }\n };\n\n /**\n * Write handler for when the preview image is ready to be animated\n */\n var didDrawPreview = function didDrawPreview(_ref8) {\n var root = _ref8.root;\n // get last added image\n var image = root.ref.images[root.ref.images.length - 1];\n image.translateY = 0;\n image.scaleX = 1.0;\n image.scaleY = 1.0;\n image.opacity = 1;\n };\n\n /**\n * Write handler for when the preview has been loaded\n */\n var restoreOverlay = function restoreOverlay(_ref9) {\n var root = _ref9.root;\n root.ref.overlayShadow.opacity = 1;\n root.ref.overlayError.opacity = 0;\n root.ref.overlaySuccess.opacity = 0;\n };\n\n var didThrowError = function didThrowError(_ref10) {\n var root = _ref10.root;\n root.ref.overlayShadow.opacity = 0.25;\n root.ref.overlayError.opacity = 1;\n };\n\n var didCompleteProcessing = function didCompleteProcessing(_ref11) {\n var root = _ref11.root;\n root.ref.overlayShadow.opacity = 0.25;\n root.ref.overlaySuccess.opacity = 1;\n };\n\n /**\n * Constructor\n */\n var create = function create(_ref12) {\n var root = _ref12.root;\n // image view\n root.ref.images = [];\n\n // the preview image data (we need this to filter the image)\n root.ref.imageData = null;\n\n // image bin\n root.ref.imageViewBin = [];\n\n // image overlays\n root.ref.overlayShadow = root.appendChildView(\n root.createChildView(OverlayView, {\n opacity: 0,\n status: 'idle'\n })\n );\n\n root.ref.overlaySuccess = root.appendChildView(\n root.createChildView(OverlayView, {\n opacity: 0,\n status: 'success'\n })\n );\n\n root.ref.overlayError = root.appendChildView(\n root.createChildView(OverlayView, {\n opacity: 0,\n status: 'failure'\n })\n );\n };\n\n return _.utils.createView({\n name: 'image-preview-wrapper',\n create: create,\n styles: ['height'],\n apis: ['height'],\n destroy: function destroy(_ref13) {\n var root = _ref13.root;\n // we resize the image so memory on iOS 12 is released more quickly (it seems)\n root.ref.images.forEach(function(imageView) {\n imageView.image.width = 1;\n imageView.image.height = 1;\n });\n },\n didWriteView: function didWriteView(_ref14) {\n var root = _ref14.root;\n root.ref.images.forEach(function(imageView) {\n imageView.dirty = false;\n });\n },\n write: _.utils.createRoute(\n {\n // image preview stated\n DID_IMAGE_PREVIEW_DRAW: didDrawPreview,\n DID_IMAGE_PREVIEW_CONTAINER_CREATE: didCreatePreviewContainer,\n DID_FINISH_CALCULATE_PREVIEWSIZE: drawPreview,\n DID_UPDATE_ITEM_METADATA: didUpdateItemMetadata,\n\n // file states\n DID_THROW_ITEM_LOAD_ERROR: didThrowError,\n DID_THROW_ITEM_PROCESSING_ERROR: didThrowError,\n DID_THROW_ITEM_INVALID: didThrowError,\n DID_COMPLETE_ITEM_PROCESSING: didCompleteProcessing,\n DID_START_ITEM_PROCESSING: restoreOverlay,\n DID_REVERT_ITEM_PROCESSING: restoreOverlay\n },\n\n function(_ref15) {\n var root = _ref15.root;\n // views on death row\n var viewsToRemove = root.ref.imageViewBin.filter(function(imageView) {\n return imageView.opacity === 0;\n });\n\n // views to retain\n root.ref.imageViewBin = root.ref.imageViewBin.filter(function(\n imageView\n ) {\n return imageView.opacity > 0;\n });\n\n // remove these views\n viewsToRemove.forEach(function(imageView) {\n return removeImageView(root, imageView);\n });\n viewsToRemove.length = 0;\n }\n )\n });\n };\n\n /**\n * Image Preview Plugin\n */\n var plugin = function plugin(fpAPI) {\n var addFilter = fpAPI.addFilter,\n utils = fpAPI.utils;\n var Type = utils.Type,\n createRoute = utils.createRoute,\n isFile = utils.isFile;\n\n // imagePreviewView\n var imagePreviewView = createImageWrapperView(fpAPI);\n\n // called for each view that is created right after the 'create' method\n addFilter('CREATE_VIEW', function(viewAPI) {\n // get reference to created view\n var is = viewAPI.is,\n view = viewAPI.view,\n query = viewAPI.query;\n\n // only hook up to item view and only if is enabled for this cropper\n if (!is('file') || !query('GET_ALLOW_IMAGE_PREVIEW')) return;\n\n // create the image preview plugin, but only do so if the item is an image\n var didLoadItem = function didLoadItem(_ref) {\n var root = _ref.root,\n props = _ref.props;\n var id = props.id;\n var item = query('GET_ITEM', id);\n\n // item could theoretically have been removed in the mean time\n if (!item || !isFile(item.file) || item.archived) return;\n\n // get the file object\n var file = item.file;\n\n // exit if this is not an image\n if (!isPreviewableImage(file)) return;\n\n // test if is filtered\n if (!query('GET_IMAGE_PREVIEW_FILTER_ITEM')(item)) return;\n\n // exit if image size is too high and no createImageBitmap support\n // this would simply bring the browser to its knees and that is not what we want\n var supportsCreateImageBitmap = 'createImageBitmap' in (window || {});\n var maxPreviewFileSize = query('GET_IMAGE_PREVIEW_MAX_FILE_SIZE');\n if (\n !supportsCreateImageBitmap &&\n maxPreviewFileSize &&\n file.size > maxPreviewFileSize\n )\n return;\n\n // set preview view\n root.ref.imagePreview = view.appendChildView(\n view.createChildView(imagePreviewView, { id: id })\n );\n\n // update height if is fixed\n var fixedPreviewHeight = root.query('GET_IMAGE_PREVIEW_HEIGHT');\n if (fixedPreviewHeight) {\n root.dispatch('DID_UPDATE_PANEL_HEIGHT', {\n id: item.id,\n height: fixedPreviewHeight\n });\n }\n\n // now ready\n var queue =\n !supportsCreateImageBitmap &&\n file.size > query('GET_IMAGE_PREVIEW_MAX_INSTANT_PREVIEW_FILE_SIZE');\n root.dispatch('DID_IMAGE_PREVIEW_CONTAINER_CREATE', { id: id }, queue);\n };\n\n var rescaleItem = function rescaleItem(root, props) {\n if (!root.ref.imagePreview) return;\n var id = props.id;\n\n // get item\n var item = root.query('GET_ITEM', { id: id });\n if (!item) return;\n\n // if is fixed height or panel has aspect ratio, exit here, height has already been defined\n var panelAspectRatio = root.query('GET_PANEL_ASPECT_RATIO');\n var itemPanelAspectRatio = root.query('GET_ITEM_PANEL_ASPECT_RATIO');\n var fixedHeight = root.query('GET_IMAGE_PREVIEW_HEIGHT');\n if (panelAspectRatio || itemPanelAspectRatio || fixedHeight) return;\n\n // no data!\n var _root$ref = root.ref,\n imageWidth = _root$ref.imageWidth,\n imageHeight = _root$ref.imageHeight;\n if (!imageWidth || !imageHeight) return;\n\n // get height min and max\n var minPreviewHeight = root.query('GET_IMAGE_PREVIEW_MIN_HEIGHT');\n var maxPreviewHeight = root.query('GET_IMAGE_PREVIEW_MAX_HEIGHT');\n\n // orientation info\n var exif = item.getMetadata('exif') || {};\n var orientation = exif.orientation || -1;\n\n // get width and height from action, and swap of orientation is incorrect\n if (orientation >= 5 && orientation <= 8) {\n var _ref2 = [imageHeight, imageWidth];\n imageWidth = _ref2[0];\n imageHeight = _ref2[1];\n }\n\n // scale up width and height when we're dealing with an SVG\n if (!isBitmap(item.file) || root.query('GET_IMAGE_PREVIEW_UPSCALE')) {\n var scalar = 2048 / imageWidth;\n imageWidth *= scalar;\n imageHeight *= scalar;\n }\n\n // image aspect ratio\n var imageAspectRatio = imageHeight / imageWidth;\n\n // we need the item to get to the crop size\n var previewAspectRatio =\n (item.getMetadata('crop') || {}).aspectRatio || imageAspectRatio;\n\n // preview height range\n var previewHeightMax = Math.max(\n minPreviewHeight,\n Math.min(imageHeight, maxPreviewHeight)\n );\n\n var itemWidth = root.rect.element.width;\n var previewHeight = Math.min(\n itemWidth * previewAspectRatio,\n previewHeightMax\n );\n\n // request update to panel height\n root.dispatch('DID_UPDATE_PANEL_HEIGHT', {\n id: item.id,\n height: previewHeight\n });\n };\n\n var didResizeView = function didResizeView(_ref3) {\n var root = _ref3.root;\n // actions in next write operation\n root.ref.shouldRescale = true;\n };\n\n var didUpdateItemMetadata = function didUpdateItemMetadata(_ref4) {\n var root = _ref4.root,\n action = _ref4.action;\n if (action.change.key !== 'crop') return;\n\n // actions in next write operation\n root.ref.shouldRescale = true;\n };\n\n var didCalculatePreviewSize = function didCalculatePreviewSize(_ref5) {\n var root = _ref5.root,\n action = _ref5.action;\n // remember dimensions\n root.ref.imageWidth = action.width;\n root.ref.imageHeight = action.height;\n\n // actions in next write operation\n root.ref.shouldRescale = true;\n root.ref.shouldDrawPreview = true;\n\n // as image load could take a while and fire when draw loop is resting we need to give it a kick\n root.dispatch('KICK');\n };\n\n // start writing\n view.registerWriter(\n createRoute(\n {\n DID_RESIZE_ROOT: didResizeView,\n DID_STOP_RESIZE: didResizeView,\n DID_LOAD_ITEM: didLoadItem,\n DID_IMAGE_PREVIEW_CALCULATE_SIZE: didCalculatePreviewSize,\n DID_UPDATE_ITEM_METADATA: didUpdateItemMetadata\n },\n\n function(_ref6) {\n var root = _ref6.root,\n props = _ref6.props;\n // no preview view attached\n if (!root.ref.imagePreview) return;\n\n // don't do anything while hidden\n if (root.rect.element.hidden) return;\n\n // resize the item panel\n if (root.ref.shouldRescale) {\n rescaleItem(root, props);\n root.ref.shouldRescale = false;\n }\n\n if (root.ref.shouldDrawPreview) {\n // queue till next frame so we're sure the height has been applied this forces the draw image call inside the wrapper view to use the correct height\n requestAnimationFrame(function() {\n // this requestAnimationFrame nesting is horrible but it fixes an issue with 100hz displays on Chrome\n // https://github.com/pqina/filepond-plugin-image-preview/issues/57\n requestAnimationFrame(function() {\n root.dispatch('DID_FINISH_CALCULATE_PREVIEWSIZE', {\n id: props.id\n });\n });\n });\n\n root.ref.shouldDrawPreview = false;\n }\n }\n )\n );\n });\n\n // expose plugin\n return {\n options: {\n // Enable or disable image preview\n allowImagePreview: [true, Type.BOOLEAN],\n\n // filters file items to determine which are shown as preview\n imagePreviewFilterItem: [\n function() {\n return true;\n },\n Type.FUNCTION\n ],\n\n // Fixed preview height\n imagePreviewHeight: [null, Type.INT],\n\n // Min image height\n imagePreviewMinHeight: [44, Type.INT],\n\n // Max image height\n imagePreviewMaxHeight: [256, Type.INT],\n\n // Max size of preview file for when createImageBitmap is not supported\n imagePreviewMaxFileSize: [null, Type.INT],\n\n // The amount of extra pixels added to the image preview to allow comfortable zooming\n imagePreviewZoomFactor: [2, Type.INT],\n\n // Should we upscale small images to fit the max bounding box of the preview area\n imagePreviewUpscale: [false, Type.BOOLEAN],\n\n // Max size of preview file that we allow to try to instant preview if createImageBitmap is not supported, else image is queued for loading\n imagePreviewMaxInstantPreviewFileSize: [1000000, Type.INT],\n\n // Style of the transparancy indicator used behind images\n imagePreviewTransparencyIndicator: [null, Type.STRING],\n\n // Enables or disables reading average image color\n imagePreviewCalculateAverageImageColor: [false, Type.BOOLEAN],\n\n // Enables or disables the previewing of markup\n imagePreviewMarkupShow: [true, Type.BOOLEAN],\n\n // Allows filtering of markup to only show certain shapes\n imagePreviewMarkupFilter: [\n function() {\n return true;\n },\n Type.FUNCTION\n ]\n }\n };\n };\n\n // fire pluginloaded event if running in browser, this allows registering the plugin when using async script tags\n var isBrowser =\n typeof window !== 'undefined' && typeof window.document !== 'undefined';\n if (isBrowser) {\n document.dispatchEvent(\n new CustomEvent('FilePond:pluginloaded', { detail: plugin })\n );\n }\n\n return plugin;\n});\n", "/*\nStimulus 3.0.1\nCopyright \u00A9 2021 Basecamp, LLC\n */\n(function (global, factory) {\n typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :\n typeof define === 'function' && define.amd ? define(['exports'], factory) :\n (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.Stimulus = {}));\n}(this, (function (exports) { 'use strict';\n\n class EventListener {\n constructor(eventTarget, eventName, eventOptions) {\n this.eventTarget = eventTarget;\n this.eventName = eventName;\n this.eventOptions = eventOptions;\n this.unorderedBindings = new Set();\n }\n connect() {\n this.eventTarget.addEventListener(this.eventName, this, this.eventOptions);\n }\n disconnect() {\n this.eventTarget.removeEventListener(this.eventName, this, this.eventOptions);\n }\n bindingConnected(binding) {\n this.unorderedBindings.add(binding);\n }\n bindingDisconnected(binding) {\n this.unorderedBindings.delete(binding);\n }\n handleEvent(event) {\n const extendedEvent = extendEvent(event);\n for (const binding of this.bindings) {\n if (extendedEvent.immediatePropagationStopped) {\n break;\n }\n else {\n binding.handleEvent(extendedEvent);\n }\n }\n }\n get bindings() {\n return Array.from(this.unorderedBindings).sort((left, right) => {\n const leftIndex = left.index, rightIndex = right.index;\n return leftIndex < rightIndex ? -1 : leftIndex > rightIndex ? 1 : 0;\n });\n }\n }\n function extendEvent(event) {\n if (\"immediatePropagationStopped\" in event) {\n return event;\n }\n else {\n const { stopImmediatePropagation } = event;\n return Object.assign(event, {\n immediatePropagationStopped: false,\n stopImmediatePropagation() {\n this.immediatePropagationStopped = true;\n stopImmediatePropagation.call(this);\n }\n });\n }\n }\n\n class Dispatcher {\n constructor(application) {\n this.application = application;\n this.eventListenerMaps = new Map;\n this.started = false;\n }\n start() {\n if (!this.started) {\n this.started = true;\n this.eventListeners.forEach(eventListener => eventListener.connect());\n }\n }\n stop() {\n if (this.started) {\n this.started = false;\n this.eventListeners.forEach(eventListener => eventListener.disconnect());\n }\n }\n get eventListeners() {\n return Array.from(this.eventListenerMaps.values())\n .reduce((listeners, map) => listeners.concat(Array.from(map.values())), []);\n }\n bindingConnected(binding) {\n this.fetchEventListenerForBinding(binding).bindingConnected(binding);\n }\n bindingDisconnected(binding) {\n this.fetchEventListenerForBinding(binding).bindingDisconnected(binding);\n }\n handleError(error, message, detail = {}) {\n this.application.handleError(error, `Error ${message}`, detail);\n }\n fetchEventListenerForBinding(binding) {\n const { eventTarget, eventName, eventOptions } = binding;\n return this.fetchEventListener(eventTarget, eventName, eventOptions);\n }\n fetchEventListener(eventTarget, eventName, eventOptions) {\n const eventListenerMap = this.fetchEventListenerMapForEventTarget(eventTarget);\n const cacheKey = this.cacheKey(eventName, eventOptions);\n let eventListener = eventListenerMap.get(cacheKey);\n if (!eventListener) {\n eventListener = this.createEventListener(eventTarget, eventName, eventOptions);\n eventListenerMap.set(cacheKey, eventListener);\n }\n return eventListener;\n }\n createEventListener(eventTarget, eventName, eventOptions) {\n const eventListener = new EventListener(eventTarget, eventName, eventOptions);\n if (this.started) {\n eventListener.connect();\n }\n return eventListener;\n }\n fetchEventListenerMapForEventTarget(eventTarget) {\n let eventListenerMap = this.eventListenerMaps.get(eventTarget);\n if (!eventListenerMap) {\n eventListenerMap = new Map;\n this.eventListenerMaps.set(eventTarget, eventListenerMap);\n }\n return eventListenerMap;\n }\n cacheKey(eventName, eventOptions) {\n const parts = [eventName];\n Object.keys(eventOptions).sort().forEach(key => {\n parts.push(`${eventOptions[key] ? \"\" : \"!\"}${key}`);\n });\n return parts.join(\":\");\n }\n }\n\n const descriptorPattern = /^((.+?)(@(window|document))?->)?(.+?)(#([^:]+?))(:(.+))?$/;\n function parseActionDescriptorString(descriptorString) {\n const source = descriptorString.trim();\n const matches = source.match(descriptorPattern) || [];\n return {\n eventTarget: parseEventTarget(matches[4]),\n eventName: matches[2],\n eventOptions: matches[9] ? parseEventOptions(matches[9]) : {},\n identifier: matches[5],\n methodName: matches[7]\n };\n }\n function parseEventTarget(eventTargetName) {\n if (eventTargetName == \"window\") {\n return window;\n }\n else if (eventTargetName == \"document\") {\n return document;\n }\n }\n function parseEventOptions(eventOptions) {\n return eventOptions.split(\":\").reduce((options, token) => Object.assign(options, { [token.replace(/^!/, \"\")]: !/^!/.test(token) }), {});\n }\n function stringifyEventTarget(eventTarget) {\n if (eventTarget == window) {\n return \"window\";\n }\n else if (eventTarget == document) {\n return \"document\";\n }\n }\n\n function camelize(value) {\n return value.replace(/(?:[_-])([a-z0-9])/g, (_, char) => char.toUpperCase());\n }\n function capitalize(value) {\n return value.charAt(0).toUpperCase() + value.slice(1);\n }\n function dasherize(value) {\n return value.replace(/([A-Z])/g, (_, char) => `-${char.toLowerCase()}`);\n }\n function tokenize(value) {\n return value.match(/[^\\s]+/g) || [];\n }\n\n class Action {\n constructor(element, index, descriptor) {\n this.element = element;\n this.index = index;\n this.eventTarget = descriptor.eventTarget || element;\n this.eventName = descriptor.eventName || getDefaultEventNameForElement(element) || error(\"missing event name\");\n this.eventOptions = descriptor.eventOptions || {};\n this.identifier = descriptor.identifier || error(\"missing identifier\");\n this.methodName = descriptor.methodName || error(\"missing method name\");\n }\n static forToken(token) {\n return new this(token.element, token.index, parseActionDescriptorString(token.content));\n }\n toString() {\n const eventNameSuffix = this.eventTargetName ? `@${this.eventTargetName}` : \"\";\n return `${this.eventName}${eventNameSuffix}->${this.identifier}#${this.methodName}`;\n }\n get params() {\n if (this.eventTarget instanceof Element) {\n return this.getParamsFromEventTargetAttributes(this.eventTarget);\n }\n else {\n return {};\n }\n }\n getParamsFromEventTargetAttributes(eventTarget) {\n const params = {};\n const pattern = new RegExp(`^data-${this.identifier}-(.+)-param$`);\n const attributes = Array.from(eventTarget.attributes);\n attributes.forEach(({ name, value }) => {\n const match = name.match(pattern);\n const key = match && match[1];\n if (key) {\n Object.assign(params, { [camelize(key)]: typecast(value) });\n }\n });\n return params;\n }\n get eventTargetName() {\n return stringifyEventTarget(this.eventTarget);\n }\n }\n const defaultEventNames = {\n \"a\": e => \"click\",\n \"button\": e => \"click\",\n \"form\": e => \"submit\",\n \"details\": e => \"toggle\",\n \"input\": e => e.getAttribute(\"type\") == \"submit\" ? \"click\" : \"input\",\n \"select\": e => \"change\",\n \"textarea\": e => \"input\"\n };\n function getDefaultEventNameForElement(element) {\n const tagName = element.tagName.toLowerCase();\n if (tagName in defaultEventNames) {\n return defaultEventNames[tagName](element);\n }\n }\n function error(message) {\n throw new Error(message);\n }\n function typecast(value) {\n try {\n return JSON.parse(value);\n }\n catch (o_O) {\n return value;\n }\n }\n\n class Binding {\n constructor(context, action) {\n this.context = context;\n this.action = action;\n }\n get index() {\n return this.action.index;\n }\n get eventTarget() {\n return this.action.eventTarget;\n }\n get eventOptions() {\n return this.action.eventOptions;\n }\n get identifier() {\n return this.context.identifier;\n }\n handleEvent(event) {\n if (this.willBeInvokedByEvent(event)) {\n this.invokeWithEvent(event);\n }\n }\n get eventName() {\n return this.action.eventName;\n }\n get method() {\n const method = this.controller[this.methodName];\n if (typeof method == \"function\") {\n return method;\n }\n throw new Error(`Action \"${this.action}\" references undefined method \"${this.methodName}\"`);\n }\n invokeWithEvent(event) {\n const { target, currentTarget } = event;\n try {\n const { params } = this.action;\n const actionEvent = Object.assign(event, { params });\n this.method.call(this.controller, actionEvent);\n this.context.logDebugActivity(this.methodName, { event, target, currentTarget, action: this.methodName });\n }\n catch (error) {\n const { identifier, controller, element, index } = this;\n const detail = { identifier, controller, element, index, event };\n this.context.handleError(error, `invoking action \"${this.action}\"`, detail);\n }\n }\n willBeInvokedByEvent(event) {\n const eventTarget = event.target;\n if (this.element === eventTarget) {\n return true;\n }\n else if (eventTarget instanceof Element && this.element.contains(eventTarget)) {\n return this.scope.containsElement(eventTarget);\n }\n else {\n return this.scope.containsElement(this.action.element);\n }\n }\n get controller() {\n return this.context.controller;\n }\n get methodName() {\n return this.action.methodName;\n }\n get element() {\n return this.scope.element;\n }\n get scope() {\n return this.context.scope;\n }\n }\n\n class ElementObserver {\n constructor(element, delegate) {\n this.mutationObserverInit = { attributes: true, childList: true, subtree: true };\n this.element = element;\n this.started = false;\n this.delegate = delegate;\n this.elements = new Set;\n this.mutationObserver = new MutationObserver((mutations) => this.processMutations(mutations));\n }\n start() {\n if (!this.started) {\n this.started = true;\n this.mutationObserver.observe(this.element, this.mutationObserverInit);\n this.refresh();\n }\n }\n pause(callback) {\n if (this.started) {\n this.mutationObserver.disconnect();\n this.started = false;\n }\n callback();\n if (!this.started) {\n this.mutationObserver.observe(this.element, this.mutationObserverInit);\n this.started = true;\n }\n }\n stop() {\n if (this.started) {\n this.mutationObserver.takeRecords();\n this.mutationObserver.disconnect();\n this.started = false;\n }\n }\n refresh() {\n if (this.started) {\n const matches = new Set(this.matchElementsInTree());\n for (const element of Array.from(this.elements)) {\n if (!matches.has(element)) {\n this.removeElement(element);\n }\n }\n for (const element of Array.from(matches)) {\n this.addElement(element);\n }\n }\n }\n processMutations(mutations) {\n if (this.started) {\n for (const mutation of mutations) {\n this.processMutation(mutation);\n }\n }\n }\n processMutation(mutation) {\n if (mutation.type == \"attributes\") {\n this.processAttributeChange(mutation.target, mutation.attributeName);\n }\n else if (mutation.type == \"childList\") {\n this.processRemovedNodes(mutation.removedNodes);\n this.processAddedNodes(mutation.addedNodes);\n }\n }\n processAttributeChange(node, attributeName) {\n const element = node;\n if (this.elements.has(element)) {\n if (this.delegate.elementAttributeChanged && this.matchElement(element)) {\n this.delegate.elementAttributeChanged(element, attributeName);\n }\n else {\n this.removeElement(element);\n }\n }\n else if (this.matchElement(element)) {\n this.addElement(element);\n }\n }\n processRemovedNodes(nodes) {\n for (const node of Array.from(nodes)) {\n const element = this.elementFromNode(node);\n if (element) {\n this.processTree(element, this.removeElement);\n }\n }\n }\n processAddedNodes(nodes) {\n for (const node of Array.from(nodes)) {\n const element = this.elementFromNode(node);\n if (element && this.elementIsActive(element)) {\n this.processTree(element, this.addElement);\n }\n }\n }\n matchElement(element) {\n return this.delegate.matchElement(element);\n }\n matchElementsInTree(tree = this.element) {\n return this.delegate.matchElementsInTree(tree);\n }\n processTree(tree, processor) {\n for (const element of this.matchElementsInTree(tree)) {\n processor.call(this, element);\n }\n }\n elementFromNode(node) {\n if (node.nodeType == Node.ELEMENT_NODE) {\n return node;\n }\n }\n elementIsActive(element) {\n if (element.isConnected != this.element.isConnected) {\n return false;\n }\n else {\n return this.element.contains(element);\n }\n }\n addElement(element) {\n if (!this.elements.has(element)) {\n if (this.elementIsActive(element)) {\n this.elements.add(element);\n if (this.delegate.elementMatched) {\n this.delegate.elementMatched(element);\n }\n }\n }\n }\n removeElement(element) {\n if (this.elements.has(element)) {\n this.elements.delete(element);\n if (this.delegate.elementUnmatched) {\n this.delegate.elementUnmatched(element);\n }\n }\n }\n }\n\n class AttributeObserver {\n constructor(element, attributeName, delegate) {\n this.attributeName = attributeName;\n this.delegate = delegate;\n this.elementObserver = new ElementObserver(element, this);\n }\n get element() {\n return this.elementObserver.element;\n }\n get selector() {\n return `[${this.attributeName}]`;\n }\n start() {\n this.elementObserver.start();\n }\n pause(callback) {\n this.elementObserver.pause(callback);\n }\n stop() {\n this.elementObserver.stop();\n }\n refresh() {\n this.elementObserver.refresh();\n }\n get started() {\n return this.elementObserver.started;\n }\n matchElement(element) {\n return element.hasAttribute(this.attributeName);\n }\n matchElementsInTree(tree) {\n const match = this.matchElement(tree) ? [tree] : [];\n const matches = Array.from(tree.querySelectorAll(this.selector));\n return match.concat(matches);\n }\n elementMatched(element) {\n if (this.delegate.elementMatchedAttribute) {\n this.delegate.elementMatchedAttribute(element, this.attributeName);\n }\n }\n elementUnmatched(element) {\n if (this.delegate.elementUnmatchedAttribute) {\n this.delegate.elementUnmatchedAttribute(element, this.attributeName);\n }\n }\n elementAttributeChanged(element, attributeName) {\n if (this.delegate.elementAttributeValueChanged && this.attributeName == attributeName) {\n this.delegate.elementAttributeValueChanged(element, attributeName);\n }\n }\n }\n\n class StringMapObserver {\n constructor(element, delegate) {\n this.element = element;\n this.delegate = delegate;\n this.started = false;\n this.stringMap = new Map;\n this.mutationObserver = new MutationObserver(mutations => this.processMutations(mutations));\n }\n start() {\n if (!this.started) {\n this.started = true;\n this.mutationObserver.observe(this.element, { attributes: true, attributeOldValue: true });\n this.refresh();\n }\n }\n stop() {\n if (this.started) {\n this.mutationObserver.takeRecords();\n this.mutationObserver.disconnect();\n this.started = false;\n }\n }\n refresh() {\n if (this.started) {\n for (const attributeName of this.knownAttributeNames) {\n this.refreshAttribute(attributeName, null);\n }\n }\n }\n processMutations(mutations) {\n if (this.started) {\n for (const mutation of mutations) {\n this.processMutation(mutation);\n }\n }\n }\n processMutation(mutation) {\n const attributeName = mutation.attributeName;\n if (attributeName) {\n this.refreshAttribute(attributeName, mutation.oldValue);\n }\n }\n refreshAttribute(attributeName, oldValue) {\n const key = this.delegate.getStringMapKeyForAttribute(attributeName);\n if (key != null) {\n if (!this.stringMap.has(attributeName)) {\n this.stringMapKeyAdded(key, attributeName);\n }\n const value = this.element.getAttribute(attributeName);\n if (this.stringMap.get(attributeName) != value) {\n this.stringMapValueChanged(value, key, oldValue);\n }\n if (value == null) {\n const oldValue = this.stringMap.get(attributeName);\n this.stringMap.delete(attributeName);\n if (oldValue)\n this.stringMapKeyRemoved(key, attributeName, oldValue);\n }\n else {\n this.stringMap.set(attributeName, value);\n }\n }\n }\n stringMapKeyAdded(key, attributeName) {\n if (this.delegate.stringMapKeyAdded) {\n this.delegate.stringMapKeyAdded(key, attributeName);\n }\n }\n stringMapValueChanged(value, key, oldValue) {\n if (this.delegate.stringMapValueChanged) {\n this.delegate.stringMapValueChanged(value, key, oldValue);\n }\n }\n stringMapKeyRemoved(key, attributeName, oldValue) {\n if (this.delegate.stringMapKeyRemoved) {\n this.delegate.stringMapKeyRemoved(key, attributeName, oldValue);\n }\n }\n get knownAttributeNames() {\n return Array.from(new Set(this.currentAttributeNames.concat(this.recordedAttributeNames)));\n }\n get currentAttributeNames() {\n return Array.from(this.element.attributes).map(attribute => attribute.name);\n }\n get recordedAttributeNames() {\n return Array.from(this.stringMap.keys());\n }\n }\n\n function add(map, key, value) {\n fetch(map, key).add(value);\n }\n function del(map, key, value) {\n fetch(map, key).delete(value);\n prune(map, key);\n }\n function fetch(map, key) {\n let values = map.get(key);\n if (!values) {\n values = new Set();\n map.set(key, values);\n }\n return values;\n }\n function prune(map, key) {\n const values = map.get(key);\n if (values != null && values.size == 0) {\n map.delete(key);\n }\n }\n\n class Multimap {\n constructor() {\n this.valuesByKey = new Map();\n }\n get keys() {\n return Array.from(this.valuesByKey.keys());\n }\n get values() {\n const sets = Array.from(this.valuesByKey.values());\n return sets.reduce((values, set) => values.concat(Array.from(set)), []);\n }\n get size() {\n const sets = Array.from(this.valuesByKey.values());\n return sets.reduce((size, set) => size + set.size, 0);\n }\n add(key, value) {\n add(this.valuesByKey, key, value);\n }\n delete(key, value) {\n del(this.valuesByKey, key, value);\n }\n has(key, value) {\n const values = this.valuesByKey.get(key);\n return values != null && values.has(value);\n }\n hasKey(key) {\n return this.valuesByKey.has(key);\n }\n hasValue(value) {\n const sets = Array.from(this.valuesByKey.values());\n return sets.some(set => set.has(value));\n }\n getValuesForKey(key) {\n const values = this.valuesByKey.get(key);\n return values ? Array.from(values) : [];\n }\n getKeysForValue(value) {\n return Array.from(this.valuesByKey)\n .filter(([key, values]) => values.has(value))\n .map(([key, values]) => key);\n }\n }\n\n class IndexedMultimap extends Multimap {\n constructor() {\n super();\n this.keysByValue = new Map;\n }\n get values() {\n return Array.from(this.keysByValue.keys());\n }\n add(key, value) {\n super.add(key, value);\n add(this.keysByValue, value, key);\n }\n delete(key, value) {\n super.delete(key, value);\n del(this.keysByValue, value, key);\n }\n hasValue(value) {\n return this.keysByValue.has(value);\n }\n getKeysForValue(value) {\n const set = this.keysByValue.get(value);\n return set ? Array.from(set) : [];\n }\n }\n\n class TokenListObserver {\n constructor(element, attributeName, delegate) {\n this.attributeObserver = new AttributeObserver(element, attributeName, this);\n this.delegate = delegate;\n this.tokensByElement = new Multimap;\n }\n get started() {\n return this.attributeObserver.started;\n }\n start() {\n this.attributeObserver.start();\n }\n pause(callback) {\n this.attributeObserver.pause(callback);\n }\n stop() {\n this.attributeObserver.stop();\n }\n refresh() {\n this.attributeObserver.refresh();\n }\n get element() {\n return this.attributeObserver.element;\n }\n get attributeName() {\n return this.attributeObserver.attributeName;\n }\n elementMatchedAttribute(element) {\n this.tokensMatched(this.readTokensForElement(element));\n }\n elementAttributeValueChanged(element) {\n const [unmatchedTokens, matchedTokens] = this.refreshTokensForElement(element);\n this.tokensUnmatched(unmatchedTokens);\n this.tokensMatched(matchedTokens);\n }\n elementUnmatchedAttribute(element) {\n this.tokensUnmatched(this.tokensByElement.getValuesForKey(element));\n }\n tokensMatched(tokens) {\n tokens.forEach(token => this.tokenMatched(token));\n }\n tokensUnmatched(tokens) {\n tokens.forEach(token => this.tokenUnmatched(token));\n }\n tokenMatched(token) {\n this.delegate.tokenMatched(token);\n this.tokensByElement.add(token.element, token);\n }\n tokenUnmatched(token) {\n this.delegate.tokenUnmatched(token);\n this.tokensByElement.delete(token.element, token);\n }\n refreshTokensForElement(element) {\n const previousTokens = this.tokensByElement.getValuesForKey(element);\n const currentTokens = this.readTokensForElement(element);\n const firstDifferingIndex = zip(previousTokens, currentTokens)\n .findIndex(([previousToken, currentToken]) => !tokensAreEqual(previousToken, currentToken));\n if (firstDifferingIndex == -1) {\n return [[], []];\n }\n else {\n return [previousTokens.slice(firstDifferingIndex), currentTokens.slice(firstDifferingIndex)];\n }\n }\n readTokensForElement(element) {\n const attributeName = this.attributeName;\n const tokenString = element.getAttribute(attributeName) || \"\";\n return parseTokenString(tokenString, element, attributeName);\n }\n }\n function parseTokenString(tokenString, element, attributeName) {\n return tokenString.trim().split(/\\s+/).filter(content => content.length)\n .map((content, index) => ({ element, attributeName, content, index }));\n }\n function zip(left, right) {\n const length = Math.max(left.length, right.length);\n return Array.from({ length }, (_, index) => [left[index], right[index]]);\n }\n function tokensAreEqual(left, right) {\n return left && right && left.index == right.index && left.content == right.content;\n }\n\n class ValueListObserver {\n constructor(element, attributeName, delegate) {\n this.tokenListObserver = new TokenListObserver(element, attributeName, this);\n this.delegate = delegate;\n this.parseResultsByToken = new WeakMap;\n this.valuesByTokenByElement = new WeakMap;\n }\n get started() {\n return this.tokenListObserver.started;\n }\n start() {\n this.tokenListObserver.start();\n }\n stop() {\n this.tokenListObserver.stop();\n }\n refresh() {\n this.tokenListObserver.refresh();\n }\n get element() {\n return this.tokenListObserver.element;\n }\n get attributeName() {\n return this.tokenListObserver.attributeName;\n }\n tokenMatched(token) {\n const { element } = token;\n const { value } = this.fetchParseResultForToken(token);\n if (value) {\n this.fetchValuesByTokenForElement(element).set(token, value);\n this.delegate.elementMatchedValue(element, value);\n }\n }\n tokenUnmatched(token) {\n const { element } = token;\n const { value } = this.fetchParseResultForToken(token);\n if (value) {\n this.fetchValuesByTokenForElement(element).delete(token);\n this.delegate.elementUnmatchedValue(element, value);\n }\n }\n fetchParseResultForToken(token) {\n let parseResult = this.parseResultsByToken.get(token);\n if (!parseResult) {\n parseResult = this.parseToken(token);\n this.parseResultsByToken.set(token, parseResult);\n }\n return parseResult;\n }\n fetchValuesByTokenForElement(element) {\n let valuesByToken = this.valuesByTokenByElement.get(element);\n if (!valuesByToken) {\n valuesByToken = new Map;\n this.valuesByTokenByElement.set(element, valuesByToken);\n }\n return valuesByToken;\n }\n parseToken(token) {\n try {\n const value = this.delegate.parseValueForToken(token);\n return { value };\n }\n catch (error) {\n return { error };\n }\n }\n }\n\n class BindingObserver {\n constructor(context, delegate) {\n this.context = context;\n this.delegate = delegate;\n this.bindingsByAction = new Map;\n }\n start() {\n if (!this.valueListObserver) {\n this.valueListObserver = new ValueListObserver(this.element, this.actionAttribute, this);\n this.valueListObserver.start();\n }\n }\n stop() {\n if (this.valueListObserver) {\n this.valueListObserver.stop();\n delete this.valueListObserver;\n this.disconnectAllActions();\n }\n }\n get element() {\n return this.context.element;\n }\n get identifier() {\n return this.context.identifier;\n }\n get actionAttribute() {\n return this.schema.actionAttribute;\n }\n get schema() {\n return this.context.schema;\n }\n get bindings() {\n return Array.from(this.bindingsByAction.values());\n }\n connectAction(action) {\n const binding = new Binding(this.context, action);\n this.bindingsByAction.set(action, binding);\n this.delegate.bindingConnected(binding);\n }\n disconnectAction(action) {\n const binding = this.bindingsByAction.get(action);\n if (binding) {\n this.bindingsByAction.delete(action);\n this.delegate.bindingDisconnected(binding);\n }\n }\n disconnectAllActions() {\n this.bindings.forEach(binding => this.delegate.bindingDisconnected(binding));\n this.bindingsByAction.clear();\n }\n parseValueForToken(token) {\n const action = Action.forToken(token);\n if (action.identifier == this.identifier) {\n return action;\n }\n }\n elementMatchedValue(element, action) {\n this.connectAction(action);\n }\n elementUnmatchedValue(element, action) {\n this.disconnectAction(action);\n }\n }\n\n class ValueObserver {\n constructor(context, receiver) {\n this.context = context;\n this.receiver = receiver;\n this.stringMapObserver = new StringMapObserver(this.element, this);\n this.valueDescriptorMap = this.controller.valueDescriptorMap;\n this.invokeChangedCallbacksForDefaultValues();\n }\n start() {\n this.stringMapObserver.start();\n }\n stop() {\n this.stringMapObserver.stop();\n }\n get element() {\n return this.context.element;\n }\n get controller() {\n return this.context.controller;\n }\n getStringMapKeyForAttribute(attributeName) {\n if (attributeName in this.valueDescriptorMap) {\n return this.valueDescriptorMap[attributeName].name;\n }\n }\n stringMapKeyAdded(key, attributeName) {\n const descriptor = this.valueDescriptorMap[attributeName];\n if (!this.hasValue(key)) {\n this.invokeChangedCallback(key, descriptor.writer(this.receiver[key]), descriptor.writer(descriptor.defaultValue));\n }\n }\n stringMapValueChanged(value, name, oldValue) {\n const descriptor = this.valueDescriptorNameMap[name];\n if (value === null)\n return;\n if (oldValue === null) {\n oldValue = descriptor.writer(descriptor.defaultValue);\n }\n this.invokeChangedCallback(name, value, oldValue);\n }\n stringMapKeyRemoved(key, attributeName, oldValue) {\n const descriptor = this.valueDescriptorNameMap[key];\n if (this.hasValue(key)) {\n this.invokeChangedCallback(key, descriptor.writer(this.receiver[key]), oldValue);\n }\n else {\n this.invokeChangedCallback(key, descriptor.writer(descriptor.defaultValue), oldValue);\n }\n }\n invokeChangedCallbacksForDefaultValues() {\n for (const { key, name, defaultValue, writer } of this.valueDescriptors) {\n if (defaultValue != undefined && !this.controller.data.has(key)) {\n this.invokeChangedCallback(name, writer(defaultValue), undefined);\n }\n }\n }\n invokeChangedCallback(name, rawValue, rawOldValue) {\n const changedMethodName = `${name}Changed`;\n const changedMethod = this.receiver[changedMethodName];\n if (typeof changedMethod == \"function\") {\n const descriptor = this.valueDescriptorNameMap[name];\n const value = descriptor.reader(rawValue);\n let oldValue = rawOldValue;\n if (rawOldValue) {\n oldValue = descriptor.reader(rawOldValue);\n }\n changedMethod.call(this.receiver, value, oldValue);\n }\n }\n get valueDescriptors() {\n const { valueDescriptorMap } = this;\n return Object.keys(valueDescriptorMap).map(key => valueDescriptorMap[key]);\n }\n get valueDescriptorNameMap() {\n const descriptors = {};\n Object.keys(this.valueDescriptorMap).forEach(key => {\n const descriptor = this.valueDescriptorMap[key];\n descriptors[descriptor.name] = descriptor;\n });\n return descriptors;\n }\n hasValue(attributeName) {\n const descriptor = this.valueDescriptorNameMap[attributeName];\n const hasMethodName = `has${capitalize(descriptor.name)}`;\n return this.receiver[hasMethodName];\n }\n }\n\n class TargetObserver {\n constructor(context, delegate) {\n this.context = context;\n this.delegate = delegate;\n this.targetsByName = new Multimap;\n }\n start() {\n if (!this.tokenListObserver) {\n this.tokenListObserver = new TokenListObserver(this.element, this.attributeName, this);\n this.tokenListObserver.start();\n }\n }\n stop() {\n if (this.tokenListObserver) {\n this.disconnectAllTargets();\n this.tokenListObserver.stop();\n delete this.tokenListObserver;\n }\n }\n tokenMatched({ element, content: name }) {\n if (this.scope.containsElement(element)) {\n this.connectTarget(element, name);\n }\n }\n tokenUnmatched({ element, content: name }) {\n this.disconnectTarget(element, name);\n }\n connectTarget(element, name) {\n var _a;\n if (!this.targetsByName.has(name, element)) {\n this.targetsByName.add(name, element);\n (_a = this.tokenListObserver) === null || _a === void 0 ? void 0 : _a.pause(() => this.delegate.targetConnected(element, name));\n }\n }\n disconnectTarget(element, name) {\n var _a;\n if (this.targetsByName.has(name, element)) {\n this.targetsByName.delete(name, element);\n (_a = this.tokenListObserver) === null || _a === void 0 ? void 0 : _a.pause(() => this.delegate.targetDisconnected(element, name));\n }\n }\n disconnectAllTargets() {\n for (const name of this.targetsByName.keys) {\n for (const element of this.targetsByName.getValuesForKey(name)) {\n this.disconnectTarget(element, name);\n }\n }\n }\n get attributeName() {\n return `data-${this.context.identifier}-target`;\n }\n get element() {\n return this.context.element;\n }\n get scope() {\n return this.context.scope;\n }\n }\n\n class Context {\n constructor(module, scope) {\n this.logDebugActivity = (functionName, detail = {}) => {\n const { identifier, controller, element } = this;\n detail = Object.assign({ identifier, controller, element }, detail);\n this.application.logDebugActivity(this.identifier, functionName, detail);\n };\n this.module = module;\n this.scope = scope;\n this.controller = new module.controllerConstructor(this);\n this.bindingObserver = new BindingObserver(this, this.dispatcher);\n this.valueObserver = new ValueObserver(this, this.controller);\n this.targetObserver = new TargetObserver(this, this);\n try {\n this.controller.initialize();\n this.logDebugActivity(\"initialize\");\n }\n catch (error) {\n this.handleError(error, \"initializing controller\");\n }\n }\n connect() {\n this.bindingObserver.start();\n this.valueObserver.start();\n this.targetObserver.start();\n try {\n this.controller.connect();\n this.logDebugActivity(\"connect\");\n }\n catch (error) {\n this.handleError(error, \"connecting controller\");\n }\n }\n disconnect() {\n try {\n this.controller.disconnect();\n this.logDebugActivity(\"disconnect\");\n }\n catch (error) {\n this.handleError(error, \"disconnecting controller\");\n }\n this.targetObserver.stop();\n this.valueObserver.stop();\n this.bindingObserver.stop();\n }\n get application() {\n return this.module.application;\n }\n get identifier() {\n return this.module.identifier;\n }\n get schema() {\n return this.application.schema;\n }\n get dispatcher() {\n return this.application.dispatcher;\n }\n get element() {\n return this.scope.element;\n }\n get parentElement() {\n return this.element.parentElement;\n }\n handleError(error, message, detail = {}) {\n const { identifier, controller, element } = this;\n detail = Object.assign({ identifier, controller, element }, detail);\n this.application.handleError(error, `Error ${message}`, detail);\n }\n targetConnected(element, name) {\n this.invokeControllerMethod(`${name}TargetConnected`, element);\n }\n targetDisconnected(element, name) {\n this.invokeControllerMethod(`${name}TargetDisconnected`, element);\n }\n invokeControllerMethod(methodName, ...args) {\n const controller = this.controller;\n if (typeof controller[methodName] == \"function\") {\n controller[methodName](...args);\n }\n }\n }\n\n function readInheritableStaticArrayValues(constructor, propertyName) {\n const ancestors = getAncestorsForConstructor(constructor);\n return Array.from(ancestors.reduce((values, constructor) => {\n getOwnStaticArrayValues(constructor, propertyName).forEach(name => values.add(name));\n return values;\n }, new Set));\n }\n function readInheritableStaticObjectPairs(constructor, propertyName) {\n const ancestors = getAncestorsForConstructor(constructor);\n return ancestors.reduce((pairs, constructor) => {\n pairs.push(...getOwnStaticObjectPairs(constructor, propertyName));\n return pairs;\n }, []);\n }\n function getAncestorsForConstructor(constructor) {\n const ancestors = [];\n while (constructor) {\n ancestors.push(constructor);\n constructor = Object.getPrototypeOf(constructor);\n }\n return ancestors.reverse();\n }\n function getOwnStaticArrayValues(constructor, propertyName) {\n const definition = constructor[propertyName];\n return Array.isArray(definition) ? definition : [];\n }\n function getOwnStaticObjectPairs(constructor, propertyName) {\n const definition = constructor[propertyName];\n return definition ? Object.keys(definition).map(key => [key, definition[key]]) : [];\n }\n\n function bless(constructor) {\n return shadow(constructor, getBlessedProperties(constructor));\n }\n function shadow(constructor, properties) {\n const shadowConstructor = extend(constructor);\n const shadowProperties = getShadowProperties(constructor.prototype, properties);\n Object.defineProperties(shadowConstructor.prototype, shadowProperties);\n return shadowConstructor;\n }\n function getBlessedProperties(constructor) {\n const blessings = readInheritableStaticArrayValues(constructor, \"blessings\");\n return blessings.reduce((blessedProperties, blessing) => {\n const properties = blessing(constructor);\n for (const key in properties) {\n const descriptor = blessedProperties[key] || {};\n blessedProperties[key] = Object.assign(descriptor, properties[key]);\n }\n return blessedProperties;\n }, {});\n }\n function getShadowProperties(prototype, properties) {\n return getOwnKeys(properties).reduce((shadowProperties, key) => {\n const descriptor = getShadowedDescriptor(prototype, properties, key);\n if (descriptor) {\n Object.assign(shadowProperties, { [key]: descriptor });\n }\n return shadowProperties;\n }, {});\n }\n function getShadowedDescriptor(prototype, properties, key) {\n const shadowingDescriptor = Object.getOwnPropertyDescriptor(prototype, key);\n const shadowedByValue = shadowingDescriptor && \"value\" in shadowingDescriptor;\n if (!shadowedByValue) {\n const descriptor = Object.getOwnPropertyDescriptor(properties, key).value;\n if (shadowingDescriptor) {\n descriptor.get = shadowingDescriptor.get || descriptor.get;\n descriptor.set = shadowingDescriptor.set || descriptor.set;\n }\n return descriptor;\n }\n }\n const getOwnKeys = (() => {\n if (typeof Object.getOwnPropertySymbols == \"function\") {\n return (object) => [\n ...Object.getOwnPropertyNames(object),\n ...Object.getOwnPropertySymbols(object)\n ];\n }\n else {\n return Object.getOwnPropertyNames;\n }\n })();\n const extend = (() => {\n function extendWithReflect(constructor) {\n function extended() {\n return Reflect.construct(constructor, arguments, new.target);\n }\n extended.prototype = Object.create(constructor.prototype, {\n constructor: { value: extended }\n });\n Reflect.setPrototypeOf(extended, constructor);\n return extended;\n }\n function testReflectExtension() {\n const a = function () { this.a.call(this); };\n const b = extendWithReflect(a);\n b.prototype.a = function () { };\n return new b;\n }\n try {\n testReflectExtension();\n return extendWithReflect;\n }\n catch (error) {\n return (constructor) => class extended extends constructor {\n };\n }\n })();\n\n function blessDefinition(definition) {\n return {\n identifier: definition.identifier,\n controllerConstructor: bless(definition.controllerConstructor)\n };\n }\n\n class Module {\n constructor(application, definition) {\n this.application = application;\n this.definition = blessDefinition(definition);\n this.contextsByScope = new WeakMap;\n this.connectedContexts = new Set;\n }\n get identifier() {\n return this.definition.identifier;\n }\n get controllerConstructor() {\n return this.definition.controllerConstructor;\n }\n get contexts() {\n return Array.from(this.connectedContexts);\n }\n connectContextForScope(scope) {\n const context = this.fetchContextForScope(scope);\n this.connectedContexts.add(context);\n context.connect();\n }\n disconnectContextForScope(scope) {\n const context = this.contextsByScope.get(scope);\n if (context) {\n this.connectedContexts.delete(context);\n context.disconnect();\n }\n }\n fetchContextForScope(scope) {\n let context = this.contextsByScope.get(scope);\n if (!context) {\n context = new Context(this, scope);\n this.contextsByScope.set(scope, context);\n }\n return context;\n }\n }\n\n class ClassMap {\n constructor(scope) {\n this.scope = scope;\n }\n has(name) {\n return this.data.has(this.getDataKey(name));\n }\n get(name) {\n return this.getAll(name)[0];\n }\n getAll(name) {\n const tokenString = this.data.get(this.getDataKey(name)) || \"\";\n return tokenize(tokenString);\n }\n getAttributeName(name) {\n return this.data.getAttributeNameForKey(this.getDataKey(name));\n }\n getDataKey(name) {\n return `${name}-class`;\n }\n get data() {\n return this.scope.data;\n }\n }\n\n class DataMap {\n constructor(scope) {\n this.scope = scope;\n }\n get element() {\n return this.scope.element;\n }\n get identifier() {\n return this.scope.identifier;\n }\n get(key) {\n const name = this.getAttributeNameForKey(key);\n return this.element.getAttribute(name);\n }\n set(key, value) {\n const name = this.getAttributeNameForKey(key);\n this.element.setAttribute(name, value);\n return this.get(key);\n }\n has(key) {\n const name = this.getAttributeNameForKey(key);\n return this.element.hasAttribute(name);\n }\n delete(key) {\n if (this.has(key)) {\n const name = this.getAttributeNameForKey(key);\n this.element.removeAttribute(name);\n return true;\n }\n else {\n return false;\n }\n }\n getAttributeNameForKey(key) {\n return `data-${this.identifier}-${dasherize(key)}`;\n }\n }\n\n class Guide {\n constructor(logger) {\n this.warnedKeysByObject = new WeakMap;\n this.logger = logger;\n }\n warn(object, key, message) {\n let warnedKeys = this.warnedKeysByObject.get(object);\n if (!warnedKeys) {\n warnedKeys = new Set;\n this.warnedKeysByObject.set(object, warnedKeys);\n }\n if (!warnedKeys.has(key)) {\n warnedKeys.add(key);\n this.logger.warn(message, object);\n }\n }\n }\n\n function attributeValueContainsToken(attributeName, token) {\n return `[${attributeName}~=\"${token}\"]`;\n }\n\n class TargetSet {\n constructor(scope) {\n this.scope = scope;\n }\n get element() {\n return this.scope.element;\n }\n get identifier() {\n return this.scope.identifier;\n }\n get schema() {\n return this.scope.schema;\n }\n has(targetName) {\n return this.find(targetName) != null;\n }\n find(...targetNames) {\n return targetNames.reduce((target, targetName) => target\n || this.findTarget(targetName)\n || this.findLegacyTarget(targetName), undefined);\n }\n findAll(...targetNames) {\n return targetNames.reduce((targets, targetName) => [\n ...targets,\n ...this.findAllTargets(targetName),\n ...this.findAllLegacyTargets(targetName)\n ], []);\n }\n findTarget(targetName) {\n const selector = this.getSelectorForTargetName(targetName);\n return this.scope.findElement(selector);\n }\n findAllTargets(targetName) {\n const selector = this.getSelectorForTargetName(targetName);\n return this.scope.findAllElements(selector);\n }\n getSelectorForTargetName(targetName) {\n const attributeName = this.schema.targetAttributeForScope(this.identifier);\n return attributeValueContainsToken(attributeName, targetName);\n }\n findLegacyTarget(targetName) {\n const selector = this.getLegacySelectorForTargetName(targetName);\n return this.deprecate(this.scope.findElement(selector), targetName);\n }\n findAllLegacyTargets(targetName) {\n const selector = this.getLegacySelectorForTargetName(targetName);\n return this.scope.findAllElements(selector).map(element => this.deprecate(element, targetName));\n }\n getLegacySelectorForTargetName(targetName) {\n const targetDescriptor = `${this.identifier}.${targetName}`;\n return attributeValueContainsToken(this.schema.targetAttribute, targetDescriptor);\n }\n deprecate(element, targetName) {\n if (element) {\n const { identifier } = this;\n const attributeName = this.schema.targetAttribute;\n const revisedAttributeName = this.schema.targetAttributeForScope(identifier);\n this.guide.warn(element, `target:${targetName}`, `Please replace ${attributeName}=\"${identifier}.${targetName}\" with ${revisedAttributeName}=\"${targetName}\". ` +\n `The ${attributeName} attribute is deprecated and will be removed in a future version of Stimulus.`);\n }\n return element;\n }\n get guide() {\n return this.scope.guide;\n }\n }\n\n class Scope {\n constructor(schema, element, identifier, logger) {\n this.targets = new TargetSet(this);\n this.classes = new ClassMap(this);\n this.data = new DataMap(this);\n this.containsElement = (element) => {\n return element.closest(this.controllerSelector) === this.element;\n };\n this.schema = schema;\n this.element = element;\n this.identifier = identifier;\n this.guide = new Guide(logger);\n }\n findElement(selector) {\n return this.element.matches(selector)\n ? this.element\n : this.queryElements(selector).find(this.containsElement);\n }\n findAllElements(selector) {\n return [\n ...this.element.matches(selector) ? [this.element] : [],\n ...this.queryElements(selector).filter(this.containsElement)\n ];\n }\n queryElements(selector) {\n return Array.from(this.element.querySelectorAll(selector));\n }\n get controllerSelector() {\n return attributeValueContainsToken(this.schema.controllerAttribute, this.identifier);\n }\n }\n\n class ScopeObserver {\n constructor(element, schema, delegate) {\n this.element = element;\n this.schema = schema;\n this.delegate = delegate;\n this.valueListObserver = new ValueListObserver(this.element, this.controllerAttribute, this);\n this.scopesByIdentifierByElement = new WeakMap;\n this.scopeReferenceCounts = new WeakMap;\n }\n start() {\n this.valueListObserver.start();\n }\n stop() {\n this.valueListObserver.stop();\n }\n get controllerAttribute() {\n return this.schema.controllerAttribute;\n }\n parseValueForToken(token) {\n const { element, content: identifier } = token;\n const scopesByIdentifier = this.fetchScopesByIdentifierForElement(element);\n let scope = scopesByIdentifier.get(identifier);\n if (!scope) {\n scope = this.delegate.createScopeForElementAndIdentifier(element, identifier);\n scopesByIdentifier.set(identifier, scope);\n }\n return scope;\n }\n elementMatchedValue(element, value) {\n const referenceCount = (this.scopeReferenceCounts.get(value) || 0) + 1;\n this.scopeReferenceCounts.set(value, referenceCount);\n if (referenceCount == 1) {\n this.delegate.scopeConnected(value);\n }\n }\n elementUnmatchedValue(element, value) {\n const referenceCount = this.scopeReferenceCounts.get(value);\n if (referenceCount) {\n this.scopeReferenceCounts.set(value, referenceCount - 1);\n if (referenceCount == 1) {\n this.delegate.scopeDisconnected(value);\n }\n }\n }\n fetchScopesByIdentifierForElement(element) {\n let scopesByIdentifier = this.scopesByIdentifierByElement.get(element);\n if (!scopesByIdentifier) {\n scopesByIdentifier = new Map;\n this.scopesByIdentifierByElement.set(element, scopesByIdentifier);\n }\n return scopesByIdentifier;\n }\n }\n\n class Router {\n constructor(application) {\n this.application = application;\n this.scopeObserver = new ScopeObserver(this.element, this.schema, this);\n this.scopesByIdentifier = new Multimap;\n this.modulesByIdentifier = new Map;\n }\n get element() {\n return this.application.element;\n }\n get schema() {\n return this.application.schema;\n }\n get logger() {\n return this.application.logger;\n }\n get controllerAttribute() {\n return this.schema.controllerAttribute;\n }\n get modules() {\n return Array.from(this.modulesByIdentifier.values());\n }\n get contexts() {\n return this.modules.reduce((contexts, module) => contexts.concat(module.contexts), []);\n }\n start() {\n this.scopeObserver.start();\n }\n stop() {\n this.scopeObserver.stop();\n }\n loadDefinition(definition) {\n this.unloadIdentifier(definition.identifier);\n const module = new Module(this.application, definition);\n this.connectModule(module);\n }\n unloadIdentifier(identifier) {\n const module = this.modulesByIdentifier.get(identifier);\n if (module) {\n this.disconnectModule(module);\n }\n }\n getContextForElementAndIdentifier(element, identifier) {\n const module = this.modulesByIdentifier.get(identifier);\n if (module) {\n return module.contexts.find(context => context.element == element);\n }\n }\n handleError(error, message, detail) {\n this.application.handleError(error, message, detail);\n }\n createScopeForElementAndIdentifier(element, identifier) {\n return new Scope(this.schema, element, identifier, this.logger);\n }\n scopeConnected(scope) {\n this.scopesByIdentifier.add(scope.identifier, scope);\n const module = this.modulesByIdentifier.get(scope.identifier);\n if (module) {\n module.connectContextForScope(scope);\n }\n }\n scopeDisconnected(scope) {\n this.scopesByIdentifier.delete(scope.identifier, scope);\n const module = this.modulesByIdentifier.get(scope.identifier);\n if (module) {\n module.disconnectContextForScope(scope);\n }\n }\n connectModule(module) {\n this.modulesByIdentifier.set(module.identifier, module);\n const scopes = this.scopesByIdentifier.getValuesForKey(module.identifier);\n scopes.forEach(scope => module.connectContextForScope(scope));\n }\n disconnectModule(module) {\n this.modulesByIdentifier.delete(module.identifier);\n const scopes = this.scopesByIdentifier.getValuesForKey(module.identifier);\n scopes.forEach(scope => module.disconnectContextForScope(scope));\n }\n }\n\n const defaultSchema = {\n controllerAttribute: \"data-controller\",\n actionAttribute: \"data-action\",\n targetAttribute: \"data-target\",\n targetAttributeForScope: identifier => `data-${identifier}-target`\n };\n\n class Application {\n constructor(element = document.documentElement, schema = defaultSchema) {\n this.logger = console;\n this.debug = false;\n this.logDebugActivity = (identifier, functionName, detail = {}) => {\n if (this.debug) {\n this.logFormattedMessage(identifier, functionName, detail);\n }\n };\n this.element = element;\n this.schema = schema;\n this.dispatcher = new Dispatcher(this);\n this.router = new Router(this);\n }\n static start(element, schema) {\n const application = new Application(element, schema);\n application.start();\n return application;\n }\n async start() {\n await domReady();\n this.logDebugActivity(\"application\", \"starting\");\n this.dispatcher.start();\n this.router.start();\n this.logDebugActivity(\"application\", \"start\");\n }\n stop() {\n this.logDebugActivity(\"application\", \"stopping\");\n this.dispatcher.stop();\n this.router.stop();\n this.logDebugActivity(\"application\", \"stop\");\n }\n register(identifier, controllerConstructor) {\n if (controllerConstructor.shouldLoad) {\n this.load({ identifier, controllerConstructor });\n }\n }\n load(head, ...rest) {\n const definitions = Array.isArray(head) ? head : [head, ...rest];\n definitions.forEach(definition => this.router.loadDefinition(definition));\n }\n unload(head, ...rest) {\n const identifiers = Array.isArray(head) ? head : [head, ...rest];\n identifiers.forEach(identifier => this.router.unloadIdentifier(identifier));\n }\n get controllers() {\n return this.router.contexts.map(context => context.controller);\n }\n getControllerForElementAndIdentifier(element, identifier) {\n const context = this.router.getContextForElementAndIdentifier(element, identifier);\n return context ? context.controller : null;\n }\n handleError(error, message, detail) {\n var _a;\n this.logger.error(`%s\\n\\n%o\\n\\n%o`, message, error, detail);\n (_a = window.onerror) === null || _a === void 0 ? void 0 : _a.call(window, message, \"\", 0, 0, error);\n }\n logFormattedMessage(identifier, functionName, detail = {}) {\n detail = Object.assign({ application: this }, detail);\n this.logger.groupCollapsed(`${identifier} #${functionName}`);\n this.logger.log(\"details:\", Object.assign({}, detail));\n this.logger.groupEnd();\n }\n }\n function domReady() {\n return new Promise(resolve => {\n if (document.readyState == \"loading\") {\n document.addEventListener(\"DOMContentLoaded\", () => resolve());\n }\n else {\n resolve();\n }\n });\n }\n\n function ClassPropertiesBlessing(constructor) {\n const classes = readInheritableStaticArrayValues(constructor, \"classes\");\n return classes.reduce((properties, classDefinition) => {\n return Object.assign(properties, propertiesForClassDefinition(classDefinition));\n }, {});\n }\n function propertiesForClassDefinition(key) {\n return {\n [`${key}Class`]: {\n get() {\n const { classes } = this;\n if (classes.has(key)) {\n return classes.get(key);\n }\n else {\n const attribute = classes.getAttributeName(key);\n throw new Error(`Missing attribute \"${attribute}\"`);\n }\n }\n },\n [`${key}Classes`]: {\n get() {\n return this.classes.getAll(key);\n }\n },\n [`has${capitalize(key)}Class`]: {\n get() {\n return this.classes.has(key);\n }\n }\n };\n }\n\n function TargetPropertiesBlessing(constructor) {\n const targets = readInheritableStaticArrayValues(constructor, \"targets\");\n return targets.reduce((properties, targetDefinition) => {\n return Object.assign(properties, propertiesForTargetDefinition(targetDefinition));\n }, {});\n }\n function propertiesForTargetDefinition(name) {\n return {\n [`${name}Target`]: {\n get() {\n const target = this.targets.find(name);\n if (target) {\n return target;\n }\n else {\n throw new Error(`Missing target element \"${name}\" for \"${this.identifier}\" controller`);\n }\n }\n },\n [`${name}Targets`]: {\n get() {\n return this.targets.findAll(name);\n }\n },\n [`has${capitalize(name)}Target`]: {\n get() {\n return this.targets.has(name);\n }\n }\n };\n }\n\n function ValuePropertiesBlessing(constructor) {\n const valueDefinitionPairs = readInheritableStaticObjectPairs(constructor, \"values\");\n const propertyDescriptorMap = {\n valueDescriptorMap: {\n get() {\n return valueDefinitionPairs.reduce((result, valueDefinitionPair) => {\n const valueDescriptor = parseValueDefinitionPair(valueDefinitionPair);\n const attributeName = this.data.getAttributeNameForKey(valueDescriptor.key);\n return Object.assign(result, { [attributeName]: valueDescriptor });\n }, {});\n }\n }\n };\n return valueDefinitionPairs.reduce((properties, valueDefinitionPair) => {\n return Object.assign(properties, propertiesForValueDefinitionPair(valueDefinitionPair));\n }, propertyDescriptorMap);\n }\n function propertiesForValueDefinitionPair(valueDefinitionPair) {\n const definition = parseValueDefinitionPair(valueDefinitionPair);\n const { key, name, reader: read, writer: write } = definition;\n return {\n [name]: {\n get() {\n const value = this.data.get(key);\n if (value !== null) {\n return read(value);\n }\n else {\n return definition.defaultValue;\n }\n },\n set(value) {\n if (value === undefined) {\n this.data.delete(key);\n }\n else {\n this.data.set(key, write(value));\n }\n }\n },\n [`has${capitalize(name)}`]: {\n get() {\n return this.data.has(key) || definition.hasCustomDefaultValue;\n }\n }\n };\n }\n function parseValueDefinitionPair([token, typeDefinition]) {\n return valueDescriptorForTokenAndTypeDefinition(token, typeDefinition);\n }\n function parseValueTypeConstant(constant) {\n switch (constant) {\n case Array: return \"array\";\n case Boolean: return \"boolean\";\n case Number: return \"number\";\n case Object: return \"object\";\n case String: return \"string\";\n }\n }\n function parseValueTypeDefault(defaultValue) {\n switch (typeof defaultValue) {\n case \"boolean\": return \"boolean\";\n case \"number\": return \"number\";\n case \"string\": return \"string\";\n }\n if (Array.isArray(defaultValue))\n return \"array\";\n if (Object.prototype.toString.call(defaultValue) === \"[object Object]\")\n return \"object\";\n }\n function parseValueTypeObject(typeObject) {\n const typeFromObject = parseValueTypeConstant(typeObject.type);\n if (typeFromObject) {\n const defaultValueType = parseValueTypeDefault(typeObject.default);\n if (typeFromObject !== defaultValueType) {\n throw new Error(`Type \"${typeFromObject}\" must match the type of the default value. Given default value: \"${typeObject.default}\" as \"${defaultValueType}\"`);\n }\n return typeFromObject;\n }\n }\n function parseValueTypeDefinition(typeDefinition) {\n const typeFromObject = parseValueTypeObject(typeDefinition);\n const typeFromDefaultValue = parseValueTypeDefault(typeDefinition);\n const typeFromConstant = parseValueTypeConstant(typeDefinition);\n const type = typeFromObject || typeFromDefaultValue || typeFromConstant;\n if (type)\n return type;\n throw new Error(`Unknown value type \"${typeDefinition}\"`);\n }\n function defaultValueForDefinition(typeDefinition) {\n const constant = parseValueTypeConstant(typeDefinition);\n if (constant)\n return defaultValuesByType[constant];\n const defaultValue = typeDefinition.default;\n if (defaultValue !== undefined)\n return defaultValue;\n return typeDefinition;\n }\n function valueDescriptorForTokenAndTypeDefinition(token, typeDefinition) {\n const key = `${dasherize(token)}-value`;\n const type = parseValueTypeDefinition(typeDefinition);\n return {\n type,\n key,\n name: camelize(key),\n get defaultValue() { return defaultValueForDefinition(typeDefinition); },\n get hasCustomDefaultValue() { return parseValueTypeDefault(typeDefinition) !== undefined; },\n reader: readers[type],\n writer: writers[type] || writers.default\n };\n }\n const defaultValuesByType = {\n get array() { return []; },\n boolean: false,\n number: 0,\n get object() { return {}; },\n string: \"\"\n };\n const readers = {\n array(value) {\n const array = JSON.parse(value);\n if (!Array.isArray(array)) {\n throw new TypeError(\"Expected array\");\n }\n return array;\n },\n boolean(value) {\n return !(value == \"0\" || value == \"false\");\n },\n number(value) {\n return Number(value);\n },\n object(value) {\n const object = JSON.parse(value);\n if (object === null || typeof object != \"object\" || Array.isArray(object)) {\n throw new TypeError(\"Expected object\");\n }\n return object;\n },\n string(value) {\n return value;\n }\n };\n const writers = {\n default: writeString,\n array: writeJSON,\n object: writeJSON\n };\n function writeJSON(value) {\n return JSON.stringify(value);\n }\n function writeString(value) {\n return `${value}`;\n }\n\n class Controller {\n constructor(context) {\n this.context = context;\n }\n static get shouldLoad() {\n return true;\n }\n get application() {\n return this.context.application;\n }\n get scope() {\n return this.context.scope;\n }\n get element() {\n return this.scope.element;\n }\n get identifier() {\n return this.scope.identifier;\n }\n get targets() {\n return this.scope.targets;\n }\n get classes() {\n return this.scope.classes;\n }\n get data() {\n return this.scope.data;\n }\n initialize() {\n }\n connect() {\n }\n disconnect() {\n }\n dispatch(eventName, { target = this.element, detail = {}, prefix = this.identifier, bubbles = true, cancelable = true } = {}) {\n const type = prefix ? `${prefix}:${eventName}` : eventName;\n const event = new CustomEvent(type, { detail, bubbles, cancelable });\n target.dispatchEvent(event);\n return event;\n }\n }\n Controller.blessings = [ClassPropertiesBlessing, TargetPropertiesBlessing, ValuePropertiesBlessing];\n Controller.targets = [];\n Controller.values = {};\n\n exports.Application = Application;\n exports.AttributeObserver = AttributeObserver;\n exports.Context = Context;\n exports.Controller = Controller;\n exports.ElementObserver = ElementObserver;\n exports.IndexedMultimap = IndexedMultimap;\n exports.Multimap = Multimap;\n exports.StringMapObserver = StringMapObserver;\n exports.TokenListObserver = TokenListObserver;\n exports.ValueListObserver = ValueListObserver;\n exports.add = add;\n exports.defaultSchema = defaultSchema;\n exports.del = del;\n exports.fetch = fetch;\n exports.prune = prune;\n\n Object.defineProperty(exports, '__esModule', { value: true });\n\n})));\n", "!function(t,e){\"object\"==typeof exports&&\"object\"==typeof module?module.exports=e(require(\"@hotwired/stimulus\")):\"function\"==typeof define&&define.amd?define([\"@hotwired/stimulus\"],e):\"object\"==typeof exports?exports.stimulusReveal=e(require(\"@hotwired/stimulus\")):t.stimulusReveal=e(t[\"@hotwired/stimulus\"])}(window,(function(t){return function(t){var e={};function n(r){if(e[r])return e[r].exports;var o=e[r]={i:r,l:!1,exports:{}};return t[r].call(o.exports,o,o.exports,n),o.l=!0,o.exports}return n.m=t,n.c=e,n.d=function(t,e,r){n.o(t,e)||Object.defineProperty(t,e,{enumerable:!0,get:r})},n.r=function(t){\"undefined\"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(t,Symbol.toStringTag,{value:\"Module\"}),Object.defineProperty(t,\"__esModule\",{value:!0})},n.t=function(t,e){if(1&e&&(t=n(t)),8&e)return t;if(4&e&&\"object\"==typeof t&&t&&t.__esModule)return t;var r=Object.create(null);if(n.r(r),Object.defineProperty(r,\"default\",{enumerable:!0,value:t}),2&e&&\"string\"!=typeof t)for(var o in t)n.d(r,o,function(e){return t[e]}.bind(null,o));return r},n.n=function(t){var e=t&&t.__esModule?function(){return t.default}:function(){return t};return n.d(e,\"a\",e),e},n.o=function(t,e){return Object.prototype.hasOwnProperty.call(t,e)},n.p=\"\",n(n.s=10)}([function(t,e,n){var r=n(11),o=n(12),i=n(13),a=n(14);t.exports=function(t){return r(t)||o(t)||i(t)||a()}},function(t,e,n){t.exports=n(15)},function(t,e){function n(e){return t.exports=n=Object.setPrototypeOf?Object.getPrototypeOf:function(t){return t.__proto__||Object.getPrototypeOf(t)},n(e)}t.exports=n},function(t,e){t.exports=function(t,e){(null==e||e>t.length)&&(e=t.length);for(var n=0,r=new Array(e);n