{"version":3,"file":"js/admin-999d2af227ae43032d79.js","sources":["webpack:///webpack/bootstrap","webpack:///./app/javascript/controllers/application.js","webpack:///./app/javascript/controllers/counter_controller.js","webpack:///./app/javascript/controllers/dropzone_controller.js","webpack:///./app/javascript/controllers/index.js","webpack:///./app/javascript/controllers/metadata_controller.js","webpack:///./app/javascript/controllers/modals_controller.js","webpack:///./app/javascript/controllers/sortable_controller.js","webpack:///./app/javascript/controllers/visual_editor_controller.js","webpack:///./app/javascript/css/admin.css","webpack:///./app/javascript/grapesjs-techtown-block/src/blocks/index.js","webpack:///./app/javascript/grapesjs-techtown-block/src/blocks/techtown.js","webpack:///./app/javascript/grapesjs-techtown-block/src/components.js","webpack:///./app/javascript/grapesjs-techtown-block/src/index.js","webpack:///./app/javascript/helpers/index.js","webpack:///./app/javascript/images sync ^\\.\\/.*$","webpack:///./app/javascript/images/dashboard_logo.png","webpack:///./app/javascript/images/idle_logo.jpeg","webpack:///./app/javascript/images/monster.png","webpack:///./app/javascript/packs/admin.js","webpack:///./app/javascript/packs/ckeditor/config.js","webpack:///./app/javascript/packs/components/map/donut-chart.js","webpack:///./app/javascript/packs/components/map/line-chart.js","webpack:///./app/javascript/packs/components/particles.js","webpack:///./app/javascript/packs/components/select2.js","webpack:///./node_modules/@hotwired/stimulus/dist/stimulus.js","webpack:///./node_modules/@hotwired/stimulus/dist/stimulus.umd.js","webpack:///./node_modules/@hotwired/turbo-rails/app/javascript/turbo/cable.js","webpack:///./node_modules/@hotwired/turbo-rails/app/javascript/turbo/cable_stream_source_element.js","webpack:///./node_modules/@hotwired/turbo-rails/app/javascript/turbo/fetch_requests.js","webpack:///./node_modules/@hotwired/turbo-rails/app/javascript/turbo/index.js","webpack:///./node_modules/@hotwired/turbo-rails/app/javascript/turbo/snakeize.js","webpack:///./node_modules/@hotwired/turbo/dist/turbo.es2017-esm.js","webpack:///./node_modules/@popperjs/core/lib/createPopper.js","webpack:///./node_modules/@popperjs/core/lib/dom-utils/contains.js","webpack:///./node_modules/@popperjs/core/lib/dom-utils/getBoundingClientRect.js","webpack:///./node_modules/@popperjs/core/lib/dom-utils/getClippingRect.js","webpack:///./node_modules/@popperjs/core/lib/dom-utils/getCompositeRect.js","webpack:///./node_modules/@popperjs/core/lib/dom-utils/getComputedStyle.js","webpack:///./node_modules/@popperjs/core/lib/dom-utils/getDocumentElement.js","webpack:///./node_modules/@popperjs/core/lib/dom-utils/getDocumentRect.js","webpack:///./node_modules/@popperjs/core/lib/dom-utils/getHTMLElementScroll.js","webpack:///./node_modules/@popperjs/core/lib/dom-utils/getLayoutRect.js","webpack:///./node_modules/@popperjs/core/lib/dom-utils/getNodeName.js","webpack:///./node_modules/@popperjs/core/lib/dom-utils/getNodeScroll.js","webpack:///./node_modules/@popperjs/core/lib/dom-utils/getOffsetParent.js","webpack:///./node_modules/@popperjs/core/lib/dom-utils/getParentNode.js","webpack:///./node_modules/@popperjs/core/lib/dom-utils/getScrollParent.js","webpack:///./node_modules/@popperjs/core/lib/dom-utils/getViewportRect.js","webpack:///./node_modules/@popperjs/core/lib/dom-utils/getWindow.js","webpack:///./node_modules/@popperjs/core/lib/dom-utils/getWindowScroll.js","webpack:///./node_modules/@popperjs/core/lib/dom-utils/getWindowScrollBarX.js","webpack:///./node_modules/@popperjs/core/lib/dom-utils/instanceOf.js","webpack:///./node_modules/@popperjs/core/lib/dom-utils/isLayoutViewport.js","webpack:///./node_modules/@popperjs/core/lib/dom-utils/isScrollParent.js","webpack:///./node_modules/@popperjs/core/lib/dom-utils/isTableElement.js","webpack:///./node_modules/@popperjs/core/lib/dom-utils/listScrollParents.js","webpack:///./node_modules/@popperjs/core/lib/enums.js","webpack:///./node_modules/@popperjs/core/lib/index.js","webpack:///./node_modules/@popperjs/core/lib/modifiers/applyStyles.js","webpack:///./node_modules/@popperjs/core/lib/modifiers/arrow.js","webpack:///./node_modules/@popperjs/core/lib/modifiers/computeStyles.js","webpack:///./node_modules/@popperjs/core/lib/modifiers/eventListeners.js","webpack:///./node_modules/@popperjs/core/lib/modifiers/flip.js","webpack:///./node_modules/@popperjs/core/lib/modifiers/hide.js","webpack:///./node_modules/@popperjs/core/lib/modifiers/index.js","webpack:///./node_modules/@popperjs/core/lib/modifiers/offset.js","webpack:///./node_modules/@popperjs/core/lib/modifiers/popperOffsets.js","webpack:///./node_modules/@popperjs/core/lib/modifiers/preventOverflow.js","webpack:///./node_modules/@popperjs/core/lib/popper-lite.js","webpack:///./node_modules/@popperjs/core/lib/popper.js","webpack:///./node_modules/@popperjs/core/lib/utils/computeAutoPlacement.js","webpack:///./node_modules/@popperjs/core/lib/utils/computeOffsets.js","webpack:///./node_modules/@popperjs/core/lib/utils/debounce.js","webpack:///./node_modules/@popperjs/core/lib/utils/detectOverflow.js","webpack:///./node_modules/@popperjs/core/lib/utils/expandToHashMap.js","webpack:///./node_modules/@popperjs/core/lib/utils/getAltAxis.js","webpack:///./node_modules/@popperjs/core/lib/utils/getBasePlacement.js","webpack:///./node_modules/@popperjs/core/lib/utils/getFreshSideObject.js","webpack:///./node_modules/@popperjs/core/lib/utils/getMainAxisFromPlacement.js","webpack:///./node_modules/@popperjs/core/lib/utils/getOppositePlacement.js","webpack:///./node_modules/@popperjs/core/lib/utils/getOppositeVariationPlacement.js","webpack:///./node_modules/@popperjs/core/lib/utils/getVariation.js","webpack:///./node_modules/@popperjs/core/lib/utils/math.js","webpack:///./node_modules/@popperjs/core/lib/utils/mergeByName.js","webpack:///./node_modules/@popperjs/core/lib/utils/mergePaddingObject.js","webpack:///./node_modules/@popperjs/core/lib/utils/orderModifiers.js","webpack:///./node_modules/@popperjs/core/lib/utils/rectToClientRect.js","webpack:///./node_modules/@popperjs/core/lib/utils/userAgent.js","webpack:///./node_modules/@popperjs/core/lib/utils/within.js","webpack:///./node_modules/@rails/activestorage/app/assets/javascripts/activestorage.esm.js","webpack:///./node_modules/@rails/request.js/src/fetch_request.js","webpack:///./node_modules/@rails/request.js/src/fetch_response.js","webpack:///./node_modules/@rails/request.js/src/index.js","webpack:///./node_modules/@rails/request.js/src/lib/utils.js","webpack:///./node_modules/@rails/request.js/src/request_interceptor.js","webpack:///./node_modules/@rails/request.js/src/verbs.js","webpack:///./node_modules/apexcharts/dist/apexcharts.common.js","webpack:///./node_modules/dropzone/dist/dropzone.mjs","webpack:///./node_modules/flowbite/lib/esm/components/accordion/index.js","webpack:///./node_modules/flowbite/lib/esm/components/accordion/interface.js","webpack:///./node_modules/flowbite/lib/esm/components/accordion/types.js","webpack:///./node_modules/flowbite/lib/esm/components/carousel/index.js","webpack:///./node_modules/flowbite/lib/esm/components/carousel/interface.js","webpack:///./node_modules/flowbite/lib/esm/components/carousel/types.js","webpack:///./node_modules/flowbite/lib/esm/components/collapse/index.js","webpack:///./node_modules/flowbite/lib/esm/components/collapse/interface.js","webpack:///./node_modules/flowbite/lib/esm/components/collapse/types.js","webpack:///./node_modules/flowbite/lib/esm/components/dial/index.js","webpack:///./node_modules/flowbite/lib/esm/components/dial/interface.js","webpack:///./node_modules/flowbite/lib/esm/components/dial/types.js","webpack:///./node_modules/flowbite/lib/esm/components/dismiss/index.js","webpack:///./node_modules/flowbite/lib/esm/components/dismiss/interface.js","webpack:///./node_modules/flowbite/lib/esm/components/dismiss/types.js","webpack:///./node_modules/flowbite/lib/esm/components/drawer/index.js","webpack:///./node_modules/flowbite/lib/esm/components/drawer/interface.js","webpack:///./node_modules/flowbite/lib/esm/components/drawer/types.js","webpack:///./node_modules/flowbite/lib/esm/components/dropdown/index.js","webpack:///./node_modules/flowbite/lib/esm/components/dropdown/interface.js","webpack:///./node_modules/flowbite/lib/esm/components/dropdown/types.js","webpack:///./node_modules/flowbite/lib/esm/components/index.js","webpack:///./node_modules/flowbite/lib/esm/components/modal/index.js","webpack:///./node_modules/flowbite/lib/esm/components/modal/interface.js","webpack:///./node_modules/flowbite/lib/esm/components/modal/types.js","webpack:///./node_modules/flowbite/lib/esm/components/popover/index.js","webpack:///./node_modules/flowbite/lib/esm/components/popover/interface.js","webpack:///./node_modules/flowbite/lib/esm/components/popover/types.js","webpack:///./node_modules/flowbite/lib/esm/components/tabs/index.js","webpack:///./node_modules/flowbite/lib/esm/components/tabs/interface.js","webpack:///./node_modules/flowbite/lib/esm/components/tabs/types.js","webpack:///./node_modules/flowbite/lib/esm/components/tooltip/index.js","webpack:///./node_modules/flowbite/lib/esm/components/tooltip/interface.js","webpack:///./node_modules/flowbite/lib/esm/components/tooltip/types.js","webpack:///./node_modules/flowbite/lib/esm/dom/events.js","webpack:///./node_modules/flowbite/lib/esm/dom/instances.js","webpack:///./node_modules/flowbite/lib/esm/index.js","webpack:///./node_modules/hotkeys-js/dist/hotkeys.esm.js","webpack:///./node_modules/jquery/dist/jquery.js","webpack:///./node_modules/just-extend/index.js","webpack:///./node_modules/select2/dist/css/select2.css","webpack:///./node_modules/select2/dist/js/select2.js","webpack:///./node_modules/sortablejs/modular/sortable.esm.js","webpack:///./node_modules/stimulus-notification/dist/stimulus-notification.mjs","webpack:///./node_modules/stimulus-use/dist/index.js"],"sourcesContent":[" \t// The module cache\n \tvar installedModules = {};\n\n \t// The require function\n \tfunction __webpack_require__(moduleId) {\n\n \t\t// Check if module is in cache\n \t\tif(installedModules[moduleId]) {\n \t\t\treturn installedModules[moduleId].exports;\n \t\t}\n \t\t// Create a new module (and put it into the cache)\n \t\tvar module = installedModules[moduleId] = {\n \t\t\ti: moduleId,\n \t\t\tl: false,\n \t\t\texports: {}\n \t\t};\n\n \t\t// Execute the module function\n \t\tmodules[moduleId].call(module.exports, module, module.exports, __webpack_require__);\n\n \t\t// Flag the module as loaded\n \t\tmodule.l = true;\n\n \t\t// Return the exports of the module\n \t\treturn module.exports;\n \t}\n\n\n \t// expose the modules object (__webpack_modules__)\n \t__webpack_require__.m = modules;\n\n \t// expose the module cache\n \t__webpack_require__.c = installedModules;\n\n \t// define getter function for harmony exports\n \t__webpack_require__.d = function(exports, name, getter) {\n \t\tif(!__webpack_require__.o(exports, name)) {\n \t\t\tObject.defineProperty(exports, name, { enumerable: true, get: getter });\n \t\t}\n \t};\n\n \t// define __esModule on exports\n \t__webpack_require__.r = function(exports) {\n \t\tif(typeof Symbol !== 'undefined' && Symbol.toStringTag) {\n \t\t\tObject.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });\n \t\t}\n \t\tObject.defineProperty(exports, '__esModule', { value: true });\n \t};\n\n \t// create a fake namespace object\n \t// mode & 1: value is a module id, require it\n \t// mode & 2: merge all properties of value into the ns\n \t// mode & 4: return value when already ns object\n \t// mode & 8|1: behave like require\n \t__webpack_require__.t = function(value, mode) {\n \t\tif(mode & 1) value = __webpack_require__(value);\n \t\tif(mode & 8) return value;\n \t\tif((mode & 4) && typeof value === 'object' && value && value.__esModule) return value;\n \t\tvar ns = Object.create(null);\n \t\t__webpack_require__.r(ns);\n \t\tObject.defineProperty(ns, 'default', { enumerable: true, value: value });\n \t\tif(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key));\n \t\treturn ns;\n \t};\n\n \t// getDefaultExport function for compatibility with non-harmony modules\n \t__webpack_require__.n = function(module) {\n \t\tvar getter = module && module.__esModule ?\n \t\t\tfunction getDefault() { return module['default']; } :\n \t\t\tfunction getModuleExports() { return module; };\n \t\t__webpack_require__.d(getter, 'a', getter);\n \t\treturn getter;\n \t};\n\n \t// Object.prototype.hasOwnProperty.call\n \t__webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };\n\n \t// __webpack_public_path__\n \t__webpack_require__.p = \"/packs/\";\n\n\n \t// Load entry module and return exports\n \treturn __webpack_require__(__webpack_require__.s = \"./app/javascript/packs/admin.js\");\n","// import \"@hotwired/turbo-rails\"\nimport { Application } from \"@hotwired/stimulus\"\nimport Notification from 'stimulus-notification'\n\nconst application = Application.start()\n\n// Configure Stimulus development experience\napplication.debug = false\nwindow.Stimulus = application\n\napplication.register('notification', Notification)\n\nexport { application }\n","import { Controller } from \"@hotwired/stimulus\"\n\n// Connects to data-controller=\"counter\"\nexport default class extends Controller {\n \n static targets = [\"output\"]\n \n connect() {\n this.count = 0\n }\n\n increment(){\n this.count += 1;\n this.outputTarget.textContent = this.count\n }\n}\n","import Dropzone from \"dropzone\";\nimport { Controller } from \"@hotwired/stimulus\"\nimport { DirectUpload } from \"@rails/activestorage\";\nimport {\n getMetaValue,\n toArray,\n findElement,\n removeElement,\n insertAfter\n} from \"helpers\";\n\nexport default class extends Controller {\n static targets = [\"input\"];\n\n connect() {\n this.dropZone = createDropZone(this);\n this.hideFileInput();\n this.bindEvents();\n this.createThumbnailFromUrl();\n Dropzone.autoDiscover = false;\n }\n\n // Private\n hideFileInput() {\n this.inputTarget.disabled = true;\n this.inputTarget.style.display = \"none\";\n }\n\n createThumbnailFromUrl() {\n const url = this.currentUrl;\n\n // show in preview\n if (url) {\n const mockFile = { name: url, size: 12345 };\n this.dropZone.emit(\"addedfile\", mockFile);\n this.dropZone.emit(\"thumbnail\", mockFile, url);\n this.dropZone.emit(\"complete\", mockFile);\n this.dropZone.files.push(mockFile);\n }\n }\n\n bindEvents() {\n\n this.dropZone.on(\"addedfile\", file => {\n\n // Upload single file\n if ( this.maxFiles == 1 && this.dropZone.files.length > 1 ) {\n this.dropZone.removeFile(this.dropZone.files[0]);\n }\n\n setTimeout(() => {\n file.accepted && createDirectUploadController(this, file).start();\n }, 500);\n });\n\n this.dropZone.on(\"removedfile\", file => {\n file.controller && removeElement(file.controller.hiddenInput);\n });\n\n this.dropZone.on(\"canceled\", file => {\n file.controller && file.controller.xhr.abort();\n });\n\n this.dropZone.on(\"maxfilesexceeded\", file => {\n console.log('maxfilesexceeded: ', file )\n // this.dropZone.removeAllFiles();\n });\n\n this.dropZone.on(\"maxfilesreached\", file => {\n console.log('maxfilesreached: ', file )\n });\n\n }\n\n get headers() {\n return { \"X-CSRF-Token\": getMetaValue(\"csrf-token\") };\n }\n\n get url() {\n return this.inputTarget.getAttribute(\"data-direct-upload-url\");\n }\n\n get currentUrl() {\n return this.data.get(\"url\");\n }\n\n get maxFiles() {\n return this.data.get(\"maxFiles\") || 1;\n }\n\n get maxFileSize() {\n return this.data.get(\"maxFileSize\") || 256;\n }\n\n get acceptedFiles() {\n return this.data.get(\"acceptedFiles\");\n }\n\n get addRemoveLinks() {\n return this.data.get(\"addRemoveLinks\") || true;\n }\n}\n\nclass DirectUploadController {\n constructor(source, file) {\n this.directUpload = createDirectUpload(file, source.url, this);\n this.source = source;\n this.file = file;\n }\n\n start() {\n this.file.controller = this;\n this.hiddenInput = this.createHiddenInput();\n this.directUpload.create((error, attributes) => {\n if (error) {\n removeElement(this.hiddenInput);\n this.emitDropzoneError(error);\n } else {\n this.hiddenInput.value = attributes.signed_id;\n this.emitDropzoneSuccess();\n }\n });\n }\n\n createHiddenInput() {\n const input = document.createElement(\"input\");\n input.type = \"hidden\";\n input.name = this.source.inputTarget.name;\n insertAfter(input, this.source.inputTarget);\n return input;\n }\n\n directUploadWillStoreFileWithXHR(xhr) {\n this.bindProgressEvent(xhr);\n this.emitDropzoneUploading();\n }\n\n bindProgressEvent(xhr) {\n this.xhr = xhr;\n this.xhr.upload.addEventListener(\"progress\", event =>\n this.uploadRequestDidProgress(event)\n );\n }\n\n uploadRequestDidProgress(event) {\n const element = this.source.element;\n const progress = (event.loaded / event.total) * 100;\n findElement(\n this.file.previewTemplate,\n \".dz-upload\"\n ).style.width = `${progress}%`;\n }\n\n emitDropzoneUploading() {\n this.file.status = Dropzone.UPLOADING;\n this.source.dropZone.emit(\"processing\", this.file);\n }\n\n emitDropzoneError(error) {\n this.file.status = Dropzone.ERROR;\n this.source.dropZone.emit(\"error\", this.file, error);\n this.source.dropZone.emit(\"complete\", this.file);\n }\n\n emitDropzoneSuccess() {\n this.file.status = Dropzone.SUCCESS;\n this.source.dropZone.emit(\"success\", this.file);\n this.source.dropZone.emit(\"complete\", this.file);\n }\n}\n\nfunction createDirectUploadController(source, file) {\n return new DirectUploadController(source, file);\n}\n\nfunction createDirectUpload(file, url, controller) {\n return new DirectUpload(file, url, controller);\n}\n\n\n\nfunction createDropZone(controller) {\n return new Dropzone(controller.element, {\n url: controller.url,\n headers: controller.headers,\n maxFiles: controller.maxFiles,\n maxFilesize: controller.maxFileSize,\n acceptedFiles: controller.acceptedFiles,\n addRemoveLinks: controller.addRemoveLinks,\n autoQueue: false,\n thumbnailWidth: controller.maxFiles == 1 ? 512 : 120,\n thumbnailHeight: controller.maxFiles == 1 ? 200 : 120,\n\n });\n}","// This file is auto-generated by ./bin/rails stimulus:manifest:update\n// Run that command whenever you add a new controller or create them with\n// ./bin/rails generate stimulus controllerName\n\nimport { application } from \"./application\"\n\nimport CounterController from \"./counter_controller\"\napplication.register(\"counter\", CounterController)\n\nimport DropzoneController from \"./dropzone_controller\"\napplication.register(\"dropzone\", DropzoneController)\n\n// import EditorController from \"./editor_controller\"\n// application.register(\"editor\", EditorController)\n\nimport MetadataController from \"./metadata_controller\"\napplication.register(\"metadata\", MetadataController)\n\nimport ModalsController from \"./modals_controller\"\napplication.register(\"modals\", ModalsController)\n\nimport SortableController from \"./sortable_controller\"\napplication.register(\"sortable\", SortableController)\n\n// import ToolbarController from \"./toolbar_controller\"\n// application.register(\"toolbar\", ToolbarController)\n\nimport VisualEditorController from \"./visual_editor_controller\"\napplication.register(\"visual-editor\", VisualEditorController)\n","import { Controller } from \"@hotwired/stimulus\"\nimport $ from 'jquery'\n\n// Connects to data-controller=\"metadata\"\nexport default class extends Controller {\n static targets = [\n 'seoTitle','seoLink', 'seoDesc', 'seoPreviewTitle', 'seoPreviewLink', 'seoPreviewDesc', 'seoTitleCounter', 'seoDescCounter',//SEO METADATA\n 'fbTitle','fbLink', 'fbDesc', 'fbPreviewTitle', 'fbPreviewLink', 'fbPreviewDesc', 'fbTitleCounter', 'fbDescCounter',//Facebook CARD\n 'xTitle','xLink', 'xDesc', 'xPreviewTitle', 'xPreviewLink', 'xPreviewDesc', 'xTitleCounter', 'xDescCounter', //X CARD\n 'desc', 'descCounter'\n\n ]\n connect() {\n // this.updateMetadata(this.descTarget, null, this.descCounterTarget)\n this.updateMetadata(this.seoTitleTarget, this.seoPreviewTitleTarget, this.seoTitleCounterTarget)\n this.updateMetadata(this.seoLinkTarget, this.seoPreviewLinkTarget)\n this.updateMetadata(this.seoDescTarget, this.seoPreviewDescTarget, this.seoDescCounterTarget)\n\n this.updateMetadata(this.fbTitleTarget, this.fbPreviewTitleTarget,this.fbTitleCounterTarget)\n this.updateMetadata(this.fbDescTarget, this.fbPreviewDescTarget,this.fbDescCounterTarget)\n\n this.updateMetadata(this.xTitleTarget, this.xPreviewTitleTarget, this.xTitleCounterTarget)\n this.updateMetadata(this.xDescTarget, this.xPreviewDescTarget,this.xDescCounterTarget)\n this.multipleSelect()\n }\n\n updateMetadata(target, targetPreview, counter){\n if(targetPreview)\n targetPreview.innerHTML = target.value\n if(counter)\n counter.innerHTML = target.value.length + ''\n target.addEventListener('keyup', () => {\n if(targetPreview)\n targetPreview.innerHTML = target.value\n if(counter)\n counter.innerHTML = target.value.length + ''\n })\n }\n\n multipleSelect(){\n $('select#setting_email_notification').select2({\n tags: true,\n })\n $('select#page_category_ids').select2()\n $('.select2-container--default .select2-selection--multiple ').css({\n 'border-color': 'rgb(209, 213, 219)',\n })\n $('.select2-search--inline .select2-search__field').css({\n 'box-shadow': 'unset',\n })\n }\n}\n","import { Controller } from \"@hotwired/stimulus\"\nimport { Drawer, Popover } from 'flowbite';\nimport $ from 'jquery'\nimport { get } from \"@rails/request.js\";\n// Connects to data-controller=\"modals\"\n// options with default values\nconst options = {\n placement: 'right',\n backdrop: true,\n bodyScrolling: false,\n edge: true,\n edgeOffset: '',\n backdropClasses: 'bg-gray-900 bg-opacity-50 dark:bg-opacity-80 fixed inset-0 z-30',\n onHide: () => {\n },\n onShow: () => {\n },\n onToggle: () => {\n }\n};\n\nconst optionsPopover = {\n placement: 'bottom',\n triggerType: 'click',\n offset: 10,\n onHide: () => {\n },\n onShow: () => {\n },\n onToggle: () => {\n }\n};\n\nlet menuItemLabels = {\n 'Post categories': { label: 'categories', params: {}, label_id: 'category' },\n 'Posts': { label: 'posts', params: { post_type: 'post' }, label_id: 'page' },\n 'Pages': { label: 'pages', params: {}, label_id: 'page' },\n 'Tags': { label: 'tags', params: {}, label_id: 'tag' },\n 'Galleries': { label: 'posts', params: { post_type: 'gallery' }, label_id: 'page' }\n}\nexport default class extends Controller {\n static targets = ['url', 'inputUrl', 'form', 'popoverContent', 'childVal']\n\n connect() {\n this.modal = new Drawer(document.getElementById('modal').children[0], options)\n this.modal.show()\n this.selectField = $('#menu_item_menu_item_type')\n this.selectField.select2()\n // set the popover content element\n const $targetEl = document.getElementById('popover-click');\n // set the element that trigger the popover using hover or click\n const $triggerEl = document.getElementById('test');\n console.log('inside childVal')\n // options with default values\n this.popover = new Popover($targetEl, $triggerEl, optionsPopover);\n this.selectField.on('select2:select', (e) => {\n let data = e.params.data\n const classes = ['hidden']\n\n if (this.childValTarget.classList.contains('hidden')){\n this.childValTarget.classList.remove(...classes)\n }\n let label = $('label#child-val-label')\n var childVal = $('#childVal')\n\n label.empty();\n if (data.text != 'Homepage'){\n label.append(data.text);\n }\n console.log('data.text', data.text)\n let dataLabel = data.text.toLocaleLowerCase().replace(/ /g,'-')\n switch (dataLabel){\n case 'redirect-url':\n this.removeExist()\n childVal.append(`\n \n `)\n break\n case 'homepage':\n break\n default:\n this.removeExist()\n let menuItemLabel = menuItemLabels[`${data.text}`]\n\n let label_id = menuItemLabel.label_id\n childVal.append(`'\n options.append(optionsString)\n }\n\n getData(title, params='') {\n var client = $('.hidden-client-id').val()\n const req = fetch(`${window.location.origin}/api/v1/content/${title}?${new URLSearchParams(params)}`,{\n method: 'GET',\n headers: {\n \"Accept\": \"application/json\",\n \"Content-Type\": \"application/json\",\n \"CLIENT_ID\": client,\n }\n })\n req.then(res => {\n return res.json()\n }).then(data => {\n this.createSelectOption(data.data.items)\n })\n }\n\n submit(e) {\n e.preventDefault()\n this.formTarget.submit()\n\n }\n close(e) {\n e.preventDefault()\n this.modal.close()\n }\n}\n\n","import { Controller } from \"@hotwired/stimulus\"\nimport Sortable from \"sortablejs\"\nimport { put } from \"@rails/request.js\"\n// Connects to data-controller=\"sortable\"\nexport default class extends Controller {\n static values = {url: String}\n\n connect() {\n \n this.sortable = Sortable.create(this.element, {\n onEnd: this.onEnd.bind(this),\n handle: \"[data-sortable-handle]\",\n group: \"nested\",\n })\n }\n \n disconnect() {\n this.sortable.destroy()\n }\n\n onEnd(e) {\n const { newIndex, item} = e \n const id = item.dataset[\"sortableId\"]\n const url = this.urlValue.replace(\":id\", id)\n put(`${url}`, {\n body: JSON.stringify({position: newIndex})\n })\n }\n}\n","import { Controller } from \"@hotwired/stimulus\"\n// import grapesjs from \"grapesjs\"\n// Connects to data-controller=\"visual-editor\"\nimport techtown from \"../grapesjs-techtown-block/src/\";\nexport default class extends Controller {\n static values = {pageslug: String, accesstoken: String}\n csrfToken() {\n const metaTag = document.querySelector(\"meta[name='csrf-token']\");\n return metaTag ? metaTag.content : \"\";\n }\n async connect() {\n console.log('Connected Visual Editor')\n\n const escapeName = (name) => `${name}`.trim().replace(/([^a-z0-9\\w-:/]+)/gi, '-');\n \n this.visualEditor = grapesjs.init({\n container: '#gjs',\n plugins: [\"grapesjs-ga\", \"grapesjs-plugin-forms\",\n techtown, \"grapesjs-tailwind\"],\n pluginsOpts: {\n 'grapesjs-tailwind': { \n cover: ''\n }\n },\n fromElement: true, \n width: 'auto',\n height: '100vh',\n selectorManager: { escapeName },\n storageManager: {\n type: 'remote',\n autosave: true,\n autoload: true,\n stepsBeforeSave: 1,\n options: {\n remote: {\n headers: {\n 'X-CSRF-Token': this.csrfToken()\n },\n urlStore: `/113344/en/pages/${this.pageslugValue}/update_editor`,\n urlLoad: `/113344/en/pages/${this.pageslugValue}/html`,\n fetchOptions: opts => (opts.method === 'POST' ? { method: 'PATCH' } : {}),\n onLoad: result => result.data\n }\n }\n },\n assetManager:{\n headers: {\n 'X-CSRF-Token': this.csrfToken(),\n },\n upload: '/113344/pages/upload_image',\n uploadName: 'image'\n }\n })\n\n const assetManager = this.visualEditor.AssetManager;\n const assets = await fetch(`/113344/en/asset_images?slug=${this.pageslugValue}`, {\n method: 'GET',\n headers: {\n 'X-CSRF-Token': this.csrfToken()\n }\n }).then(response => response.json())\n .then(response => {\n return response\n })\n \n assetManager.add(assets)\n assetManager.render()\n const panelManager = this.visualEditor.Panels\n panelManager.addButton(\"options\", {\n id: \"update-theme\",\n className: \"fa fa-adjust\",\n command: \"open-update-theme\",\n attributes: {\n title: \"Update Theme\",\n \"data-tooltip-pos\": \"bottom\"\n }\n });\n // console.log(panelManager.getPanel())\n panelManager.addButton('options', {\n id: 'show-json',\n className: 'fa fa-heart',\n command(editor) {\n console.log({css: editor.getHtml()})\n // editor.Modal.setTitle('Components JSON')\n // .setContent(``).open();\n },\n context: 'show-json',\n attributes: { title: 'Some title'},\n active: false,\n })\n }\n}\n\n","// extracted by mini-css-extract-plugin","import loadTechtownBlocks from './techtown'\n\nexport default (editor, opts = {}, openBlock) => {\n loadTechtownBlocks(editor, opts, openBlock);\n}","\n\n\nconst getSvgHtml = (svg) => {\n if (typeof window === 'undefined') return ''\n svg.setAttribute('width', '100%')\n svg.setAttribute('height', '100%')\n return svg.outerHTML\n}\n\n\nexport default (editor, options = {}) => {\n const bm = editor.Blocks\n const { category, blocks, stylePrefix, flexGrid, rowHeight, addBasicStyle } = options;\n const clsRow = `gjs-row `;\n const clsCell = `gjs-cell`;\n\n const step = 0.2;\n const minDim = 1;\n const currentUnit = 1;\n const resizerBtm = {\n tl: 0,\n tc: 0,\n tr: 0,\n cl: 0,\n cr: 0,\n bl: 0,\n br: 0,\n minDim\n };\n const resizerRight = {\n ...resizerBtm,\n cr: 1,\n bc: 0,\n currentUnit,\n minDim,\n step\n };\n const rowAttr = {\n 'data-gjs-droppable': `.${clsCell}`,\n 'data-gjs-resizable': resizerBtm,\n 'data-gjs-name': 'Row'\n };\n const colAttr = {\n 'data-gjs-draggable': `.${clsRow}`,\n 'data-gjs-resizable': resizerRight,\n 'data-gjs-name': 'Cell'\n };\n\n const attrsToString = (attrs) => {\n const result = [];\n\n for (let key in attrs) {\n let value = attrs[key];\n const toParse = value instanceof Array || value instanceof Object;\n value = toParse ? JSON.stringify(value) : value;\n result.push(`${key}=${toParse ? `'${value}'` : `'${value}'`}`);\n }\n\n return result.length ? ` ${result.join(' ')}` : '';\n };\n const attrsRow = attrsToString(rowAttr);\n const attrsCell = attrsToString(colAttr);\n\n \n const sources = [\n {\n id: 'text-element-h1',\n class: '',\n label: 'Heading 1',\n content: { type: 'HEADING'},\n category: 'Element',\n order: 1\n },\n {\n id: 'section',\n class: '',\n label: 'Section',\n content: { type: 'SECTION'},\n category: 'Element',\n order: 1\n },\n {\n id: 'category',\n class: '',\n label: 'Category',\n content: { type: 'CATEGORY'},\n category: 'Element',\n order: 1\n },\n ]\n \n sources.forEach((s) => {\n \n bm.add(s.id, {\n label: s.label,\n attributes: { class: `${s.class}` },\n content: s.content,\n category: { label: s.category, open: s.category === options.openCategory },\n })\n })\n}\n","export default (editor, opts = {}) => {\n const domc = editor.DomComponents;\n \n const heading_style = {\n 'h1': 'mb-4 text-5xl font-extrabold',\n 'h2': 'mb-4 text-4xl font-bold',\n 'h3': 'mb-4 text-3xl font-bold',\n 'h4': 'mb-4 text-2xl font-bold',\n 'h5': 'mb-4 text-xl font-bold',\n 'h6': 'mb-4 text-lg font-bold'\n }\n domc.addType('HEADING', {\n model: {\n defaults: {\n tagName: 'h1',\n components: 'Insert your text here',\n traits: [\n {\n type: \"select\",\n name: \"heading\",\n label: \"Heading\",\n changeProp: 1,\n options: [\n { id: 'h1', name: 'H1'},\n { id: 'h2', name: 'H2'},\n { id: 'h3', name: 'H3'},\n { id: 'h4', name: 'H4'},\n { id: 'h5', name: 'H5'},\n { id: 'h6', name: 'H6'},\n ]\n }\n ]\n },\n init() {\n this.on(\"change:heading\", this.handleHeadingTagChange);\n this.updateHeadingStyles(); // Initial update\n },\n handleHeadingTagChange() {\n this.attributes.tagName = this.attributes.heading\n this.updateHeadingStyles();\n this.view.render();\n },\n updateHeadingStyles() {\n const identifier_class = (Math.random() + 1).toString(36).substring(2);\n this.setClass(heading_style[this.attributes.tagName] + ' techtown_' + identifier_class);\n }\n },\n view: {\n \n },\n });\n\n domc.addType('PARTICLES', {\n model: {\n defaults: {\n tagName: 'div',\n components: ''\n },\n },\n view: {\n \n },\n });\n domc.addType('SECTION', {\n model: {\n defaults: {\n tagName: 'section',\n components: '

CATEGORY

Raclette Blueberry Nextious Level

Photo booth fam kinfolk cold-pressed sriracha leggings jianbing microdosing tousled waistcoat.

Learn More
1.2K6

CATEGORY

Ennui Snackwave Thundercats

Photo booth fam kinfolk cold-pressed sriracha leggings jianbing microdosing tousled waistcoat.

Learn More
1.2K6

CATEGORY

Selvage Poke Waistcoat Godard

Photo booth fam kinfolk cold-pressed sriracha leggings jianbing microdosing tousled waistcoat.

Learn More
1.2K6
',\n // traits: [\n // {\n // type: \"select\",\n // name: \"heading\",\n // label: \"Heading\",\n // changeProp: 1,\n // options: [\n // { id: 'h1', name: 'H1'},\n // { id: 'h2', name: 'H2'},\n // { id: 'h3', name: 'H3'},\n // { id: 'h4', name: 'H4'},\n // { id: 'h5', name: 'H5'},\n // { id: 'h6', name: 'H6'},\n // ]\n // },\n // ]\n },\n init() {\n // this.on(\"change:heading\", this.handleHeadingTagChange);\n this.updateSectionStyles(); // Initial update\n \n },\n handleHeadingTagChange() {\n // this.attributes.tagName = this.attributes.heading\n // this.updateHeadingStyles();\n // this.view.render(); // Trigger re-render\n },\n updateSectionStyles() {\n // const identifier_class = (Math.random() + 1).toString(36).substring(2);\n // this.setClass(heading_style[this.attributes.tagName] + ' techtown_' + identifier_class);\n }\n },\n view: {\n \n },\n });\n\n domc.addType('CATEGORY', {\n model: {\n defaults: {\n tagName: 'section',\n components: `

Master Cleanse Reliac Heirloom

Whatever cardigan tote bag tumblr hexagon brooklyn asymmetrical gentrify, subway tile poke farm-to-table. Franzen you probably haven't heard of them man bun deep jianbing selfies heirloom prism food truck ugh squid celiac humblebrag.

Shooting Stars

Fingerstache flexitarian street art 8-bit waistcoat. Distillery hexagon disrupt edison bulbche.

Learn More

The Catalyzer

Fingerstache flexitarian street art 8-bit waistcoat. Distillery hexagon disrupt edison bulbche.

Learn More

Neptune

Fingerstache flexitarian street art 8-bit waistcoat. Distillery hexagon disrupt edison bulbche.

Learn More

Melanchole

Fingerstache flexitarian street art 8-bit waistcoat. Distillery hexagon disrupt edison bulbche.

Learn More
`,\n traits: [\n {\n type: \"select\",\n name: \"category\",\n label: \"Category\",\n changeProp: 1,\n options: [\n ]\n },\n {\n type: \"number\",\n name: \"number_of_posts\",\n label: \"Number Of Posts\",\n changeProp: 1\n },\n ]\n },\n init() {\n fetch('/admin/categories.json')\n .then(response => response.json())\n .then(options => {\n const categoryTrait = this.getTrait('category');\n \n if(categoryTrait) {\n categoryTrait.set('options', options)\n }\n\n })\n this.on(\"change:category\", this.handleCategoryChange);\n this.handleCategoryChange();\n\n },\n handleCategoryChange() {\n const selectedCategory = this.get('category');\n const numberTrait = this.get('number_of_posts');\n\n if (selectedCategory) {\n // Fetch data from API based on selected category\n fetch(`/admin/categories/${selectedCategory}.json?limit=${numberTrait}`)\n .then(response => response.json())\n .then(data => {\n // Update the component's content with the fetched data\n console.log(data.posts)\n let components = `
\n
\n

${data.category.name}

\n

${data.category.desc}

\n
`\n components += `
`\n for (let i=0;i\n
\n \"content\"\n
\n \n

${post.title}

\n

${post.expert}

\n
`\n }\n components += `
`\n this.set('components',components)\n this.view && this.view.render();\n })\n .catch(error => console.error('Error fetching data:', error));\n\n \n }\n },\n updateSectionStyles() {\n // const identifier_class = (Math.random() + 1).toString(36).substring(2);\n // this.setClass(heading_style[this.attributes.tagName] + ' techtown_' + identifier_class);\n }\n },\n view: {\n render() {\n // Implement your view rendering logic here\n console.log('View rendered');\n return this;\n },\n },\n });\n\n\n};\n","import loadComponents from './components';\nimport loadBlocks from './blocks';\n\nexport default (editor, opts = {}) => {\n\n const options = {\n ...{\n i18n: {},\n // default options\n tailwindPlayCdn: 'https://cdn.tailwindcss.com',\n plugins: [],\n config: {},\n cover: `.object-cover { filter: sepia(1) hue-rotate(190deg) opacity(.46) grayscale(.7) !important; }`,\n changeThemeText: 'Change Theme',\n openCategory: 'Element',\n }, ...opts\n };\n \n // Add components\n loadComponents(editor, options);\n // Add blocks\n loadBlocks(editor, options);\n // Load i18n files\n // editor.I18n && editor.I18n.addMessages({\n // en,\n // ...options.i18n,\n // });\n\n // Load Template\n\n const appendTemplateCss = async(frame) => {\n const iframe = frame.view.getEl()\n if(!iframe) return \n\n const {tailwindPlayCdn, plugins, config, cover} = options\n\n const init = () => {\n iframe.contentWindow.tailwind.config = config;\n }\n\n const script = document.createElement('script');\n script.src = tailwindPlayCdn + (plugins.length ? `?plugins=${plugins.join()}` : '');\n script.onload = init;\n\n const cssStyle = document.createElement('style');\n cssStyle.innerHTML = cover;\n\n // checks iframe is ready before loading Tailwind CSS - issue with firefox\n const f = setInterval(() => {\n const doc = iframe.contentDocument;\n if (doc.readyState === 'complete') {\n doc.head.appendChild(script);\n doc.head.appendChild(cssStyle);\n clearInterval(f);\n }\n }, 100)\n }\n \n \n editor.Canvas.getModel()['on']('change:frames', (m, frames) => {\n frames.forEach(frame => frame.once('loaded', () => appendTemplateCss(frame)));\n });\n \n};","export function getMetaValue(name) {\n const element = findElement(document.head, `meta[name=\"${name}\"]`);\n if (element) {\n return element.getAttribute(\"content\");\n }\n}\n\nexport function findElement(root, selector) {\n if (typeof root == \"string\") {\n selector = root;\n root = document;\n }\n return root.querySelector(selector);\n}\n\nexport function toArray(value) {\n if (Array.isArray(value)) {\n return value;\n } else if (Array.from) {\n return Array.from(value);\n } else {\n return [].slice.call(value);\n }\n}\n\nexport function removeElement(el) {\n if (el && el.parentNode) {\n el.parentNode.removeChild(el);\n }\n}\n\nexport function insertAfter(el, referenceNode) {\n return referenceNode.parentNode.insertBefore(el, referenceNode.nextSibling);\n}","var map = {\n\t\"./dashboard_logo\": \"./app/javascript/images/dashboard_logo.png\",\n\t\"./dashboard_logo.png\": \"./app/javascript/images/dashboard_logo.png\",\n\t\"./idle_logo\": \"./app/javascript/images/idle_logo.jpeg\",\n\t\"./idle_logo.jpeg\": \"./app/javascript/images/idle_logo.jpeg\",\n\t\"./monster\": \"./app/javascript/images/monster.png\",\n\t\"./monster.png\": \"./app/javascript/images/monster.png\"\n};\n\n\nfunction webpackContext(req) {\n\tvar id = webpackContextResolve(req);\n\treturn __webpack_require__(id);\n}\nfunction webpackContextResolve(req) {\n\tif(!__webpack_require__.o(map, req)) {\n\t\tvar e = new Error(\"Cannot find module '\" + req + \"'\");\n\t\te.code = 'MODULE_NOT_FOUND';\n\t\tthrow e;\n\t}\n\treturn map[req];\n}\nwebpackContext.keys = function webpackContextKeys() {\n\treturn Object.keys(map);\n};\nwebpackContext.resolve = webpackContextResolve;\nmodule.exports = webpackContext;\nwebpackContext.id = \"./app/javascript/images sync recursive ^\\\\.\\\\/.*$\";","module.exports = __webpack_public_path__ + \"media/images/dashboard_logo-618631196d7bf8b63078498a211c72a0.png\";","module.exports = __webpack_public_path__ + \"media/images/idle_logo-8efc8e841d21ab719974a7133a5908e3.jpeg\";","module.exports = __webpack_public_path__ + \"media/images/monster-4276143f4cc6c55481f34fe6520e3044.png\";","// styles\nimport \"../css/admin.css\";\n\n// libs\nimport 'flowbite';\nimport \"@hotwired/turbo\"\nimport \"@hotwired/turbo-rails\"\nimport \"@rails/activestorage\"\n\n// controllers stimulus\nimport \"../controllers\"\n\n// custom\nimport \"./components/map/line-chart\";\nimport \"./components/map/donut-chart\";\nimport \"./components/select2\";\nimport \"./components/particles\";\nimport \"./ckeditor/config\";\n\nconst images = require.context('../images', true)\n\nwindow.onload = function() {\n const particle = document.getElementById(\"particles-js\")\n if(particle) {\n particlesJS('particles-js',\n {\n \"particles\": {\n \"number\": {\n \"value\": 80,\n \"density\": {\n \"enable\": true,\n \"value_area\": 800\n }\n },\n \"color\": {\n \"value\": \"#ffffff\"\n },\n \"shape\": {\n \"type\": \"circle\",\n \"stroke\": {\n \"width\": 0,\n \"color\": \"#000000\"\n },\n \"polygon\": {\n \"nb_sides\": 5\n },\n \"image\": {\n \"src\": \"img/github.svg\",\n \"width\": 100,\n \"height\": 100\n }\n },\n \"opacity\": {\n \"value\": 0.5,\n \"random\": false,\n \"anim\": {\n \"enable\": false,\n \"speed\": 1,\n \"opacity_min\": 0.1,\n \"sync\": false\n }\n },\n \"size\": {\n \"value\": 5,\n \"random\": true,\n \"anim\": {\n \"enable\": false,\n \"speed\": 40,\n \"size_min\": 0.1,\n \"sync\": false\n }\n },\n \"line_linked\": {\n \"enable\": true,\n \"distance\": 150,\n \"color\": \"#ffffff\",\n \"opacity\": 0.4,\n \"width\": 1\n },\n \"move\": {\n \"enable\": true,\n \"speed\": 6,\n \"direction\": \"none\",\n \"random\": false,\n \"straight\": false,\n \"out_mode\": \"out\",\n \"attract\": {\n \"enable\": false,\n \"rotateX\": 600,\n \"rotateY\": 1200\n }\n }\n },\n \"interactivity\": {\n \"detect_on\": \"canvas\",\n \"events\": {\n \"onhover\": {\n \"enable\": true,\n \"mode\": \"repulse\"\n },\n \"onclick\": {\n \"enable\": true,\n \"mode\": \"push\"\n },\n \"resize\": true\n },\n \"modes\": {\n \"grab\": {\n \"distance\": 400,\n \"line_linked\": {\n \"opacity\": 1\n }\n },\n \"bubble\": {\n \"distance\": 400,\n \"size\": 40,\n \"duration\": 2,\n \"opacity\": 8,\n \"speed\": 3\n },\n \"repulse\": {\n \"distance\": 200\n },\n \"push\": {\n \"particles_nb\": 4\n },\n \"remove\": {\n \"particles_nb\": 2\n }\n }\n },\n \"retina_detect\": true,\n \"config_demo\": {\n \"hide_card\": false,\n \"background_color\": \"#b61924\",\n \"background_image\": \"\",\n \"background_position\": \"50% 50%\",\n \"background_repeat\": \"no-repeat\",\n \"background_size\": \"cover\"\n }\n }\n );\n }\n}","\nif(typeof(CKEDITOR) != 'undefined'){\n\n\nCKEDITOR.editorConfig = function (config) {\n config.height='40rem'\n /* Filebrowser routes */\n // The location of an external file browser, that should be launched when \"Browse Server\" button is pressed.\n config.filebrowserBrowseUrl = \"/ckeditor/attachment_files\";\n\n // The location of an external file browser, that should be launched when \"Browse Server\" button is pressed in the Flash dialog.\n config.filebrowserFlashBrowseUrl = \"/ckeditor/attachment_files\";\n\n // The location of a script that handles file uploads in the Flash dialog.\n config.filebrowserFlashUploadUrl = \"/ckeditor/attachment_files\";\n\n // The location of an external file browser, that should be launched when \"Browse Server\" button is pressed in the Link tab of Image dialog.\n config.filebrowserImageBrowseLinkUrl = \"/ckeditor/pictures\";\n\n // The location of an external file browser, that should be launched when \"Browse Server\" button is pressed in the Image dialog.\n config.filebrowserImageBrowseUrl = \"/ckeditor/pictures\";\n\n // The location of a script that handles file uploads in the Image dialog.\n config.filebrowserImageUploadUrl = \"/ckeditor/pictures?\";\n\n // The location of a script that handles file uploads.\n config.filebrowserUploadUrl = \"/ckeditor/attachment_files\";\n // config.extraPlugins = 'embed';\n // config.removeButtons = [ 'IFrame' ];\n }\n}","import ApexCharts from 'apexcharts';\n\nwindow.addEventListener(\"load\", function() {\n const getChartOptions = () => {\n return {\n series: [35.1, 23.5, 2.4, 5.4],\n colors: [\"#1C64F2\", \"#16BDCA\", \"#FDBA8C\", \"#E74694\"],\n chart: {\n height: 320,\n width: \"100%\",\n type: \"donut\",\n },\n stroke: {\n colors: [\"transparent\"],\n lineCap: \"\",\n },\n plotOptions: {\n pie: {\n donut: {\n labels: {\n show: true,\n name: {\n show: true,\n fontFamily: \"Inter, sans-serif\",\n offsetY: 20,\n },\n total: {\n showAlways: true,\n show: true,\n label: \"Unique visitors\",\n fontFamily: \"Inter, sans-serif\",\n formatter: function (w) {\n const sum = w.globals.seriesTotals.reduce((a, b) => {\n return a + b\n }, 0)\n return `${sum}k`\n },\n },\n value: {\n show: true,\n fontFamily: \"Inter, sans-serif\",\n offsetY: -20,\n formatter: function (value) {\n return value + \"k\"\n },\n },\n },\n size: \"80%\",\n },\n },\n },\n grid: {\n padding: {\n top: -2,\n },\n },\n labels: [\"Direct\", \"Sponsor\", \"Affiliate\", \"Email marketing\"],\n dataLabels: {\n enabled: false,\n },\n legend: {\n position: \"bottom\",\n fontFamily: \"Inter, sans-serif\",\n },\n yaxis: {\n labels: {\n formatter: function (value) {\n return value + \"k\"\n },\n },\n },\n xaxis: {\n labels: {\n formatter: function (value) {\n return value + \"k\"\n },\n },\n axisTicks: {\n show: false,\n },\n axisBorder: {\n show: false,\n },\n },\n }\n }\n\n if (document.getElementById(\"donut-chart\") && typeof ApexCharts !== 'undefined') {\n const chart = new ApexCharts(document.getElementById(\"donut-chart\"), getChartOptions());\n chart.render();\n\n // Get all the checkboxes by their class name\n const checkboxes = document.querySelectorAll('#devices input[type=\"checkbox\"]');\n\n // Function to handle the checkbox change event\n function handleCheckboxChange(event, chart) {\n const checkbox = event.target;\n if (checkbox.checked) {\n switch(checkbox.value) {\n case 'desktop':\n chart.updateSeries([15.1, 22.5, 4.4, 8.4]);\n break;\n case 'tablet':\n chart.updateSeries([25.1, 26.5, 1.4, 3.4]);\n break;\n case 'mobile':\n chart.updateSeries([45.1, 27.5, 8.4, 2.4]);\n break;\n default:\n chart.updateSeries([55.1, 28.5, 1.4, 5.4]);\n }\n\n } else {\n chart.updateSeries([35.1, 23.5, 2.4, 5.4]);\n }\n }\n\n // Attach the event listener to each checkbox\n checkboxes.forEach((checkbox) => {\n checkbox.addEventListener('change', (event) => handleCheckboxChange(event, chart));\n });\n }\n});\n","import ApexCharts from 'apexcharts';\n\nwindow.addEventListener(\"load\", function() {\n let options = {\n chart: {\n height: \"15%\",\n maxWidth: \"100%\",\n type: \"line\",\n fontFamily: \"Inter, sans-serif\",\n dropShadow: {\n enabled: false,\n },\n toolbar: {\n show: false,\n },\n },\n tooltip: {\n enabled: true,\n x: {\n show: false,\n },\n },\n dataLabels: {\n enabled: false,\n },\n stroke: {\n width: 6,\n },\n grid: {\n show: true,\n strokeDashArray: 4,\n padding: {\n left: 2,\n right: 2,\n top: -26\n },\n },\n series: [\n {\n name: \"Clicks\",\n data: [6500, 6418, 6456, 6526, 6356, 6456],\n color: \"#1A56DB\",\n },\n {\n name: \"CPC\",\n data: [6456, 6356, 6526, 6332, 6418, 6500],\n color: \"#7E3AF2\",\n },\n ],\n legend: {\n show: false\n },\n stroke: {\n curve: 'smooth'\n },\n xaxis: {\n categories: ['01 Feb', '02 Feb', '03 Feb', '04 Feb', '05 Feb', '06 Feb', '07 Feb'],\n labels: {\n show: true,\n style: {\n fontFamily: \"Inter, sans-serif\",\n cssClass: 'text-xs font-normal fill-gray-500 dark:fill-gray-400'\n }\n },\n axisBorder: {\n show: false,\n },\n axisTicks: {\n show: false,\n },\n },\n yaxis: {\n show: false,\n },\n }\n\n if (document.getElementById(\"line-chart\") && typeof ApexCharts !== 'undefined') {\n const chart = new ApexCharts(document.getElementById(\"line-chart\"), options);\n chart.render();\n }\n});","/* -----------------------------------------------\n/* Author : Vincent Garreau - vincentgarreau.com\n/* MIT license: http://opensource.org/licenses/MIT\n/* Demo / Generator : vincentgarreau.com/particles.js\n/* GitHub : github.com/VincentGarreau/particles.js\n/* How to use? : Check the GitHub README\n/* v2.0.0\n/* ----------------------------------------------- */\nfunction hexToRgb(e){var a=/^#?([a-f\\d])([a-f\\d])([a-f\\d])$/i;e=e.replace(a,function(e,a,t,i){return a+a+t+t+i+i});var t=/^#?([a-f\\d]{2})([a-f\\d]{2})([a-f\\d]{2})$/i.exec(e);return t?{r:parseInt(t[1],16),g:parseInt(t[2],16),b:parseInt(t[3],16)}:null}function clamp(e,a,t){return Math.min(Math.max(e,a),t)}function isInArray(e,a){return a.indexOf(e)>-1}var pJS=function(e,a){var t=document.querySelector(\"#\"+e+\" > .particles-js-canvas-el\");this.pJS={canvas:{el:t,w:t.offsetWidth,h:t.offsetHeight},particles:{number:{value:400,density:{enable:!0,value_area:800}},color:{value:\"#fff\"},shape:{type:\"circle\",stroke:{width:0,color:\"#ff0000\"},polygon:{nb_sides:5},image:{src:\"\",width:100,height:100}},opacity:{value:1,random:!1,anim:{enable:!1,speed:2,opacity_min:0,sync:!1}},size:{value:20,random:!1,anim:{enable:!1,speed:20,size_min:0,sync:!1}},line_linked:{enable:!0,distance:100,color:\"#fff\",opacity:1,width:1},move:{enable:!0,speed:2,direction:\"none\",random:!1,straight:!1,out_mode:\"out\",bounce:!1,attract:{enable:!1,rotateX:3e3,rotateY:3e3}},array:[]},interactivity:{detect_on:\"canvas\",events:{onhover:{enable:!0,mode:\"grab\"},onclick:{enable:!0,mode:\"push\"},resize:!0},modes:{grab:{distance:100,line_linked:{opacity:1}},bubble:{distance:200,size:80,duration:.4},repulse:{distance:200,duration:.4},push:{particles_nb:4},remove:{particles_nb:2}},mouse:{}},retina_detect:!1,fn:{interact:{},modes:{},vendors:{}},tmp:{}};var i=this.pJS;a&&Object.deepExtend(i,a),i.tmp.obj={size_value:i.particles.size.value,size_anim_speed:i.particles.size.anim.speed,move_speed:i.particles.move.speed,line_linked_distance:i.particles.line_linked.distance,line_linked_width:i.particles.line_linked.width,mode_grab_distance:i.interactivity.modes.grab.distance,mode_bubble_distance:i.interactivity.modes.bubble.distance,mode_bubble_size:i.interactivity.modes.bubble.size,mode_repulse_distance:i.interactivity.modes.repulse.distance},i.fn.retinaInit=function(){i.retina_detect&&window.devicePixelRatio>1?(i.canvas.pxratio=window.devicePixelRatio,i.tmp.retina=!0):(i.canvas.pxratio=1,i.tmp.retina=!1),i.canvas.w=i.canvas.el.offsetWidth*i.canvas.pxratio,i.canvas.h=i.canvas.el.offsetHeight*i.canvas.pxratio,i.particles.size.value=i.tmp.obj.size_value*i.canvas.pxratio,i.particles.size.anim.speed=i.tmp.obj.size_anim_speed*i.canvas.pxratio,i.particles.move.speed=i.tmp.obj.move_speed*i.canvas.pxratio,i.particles.line_linked.distance=i.tmp.obj.line_linked_distance*i.canvas.pxratio,i.interactivity.modes.grab.distance=i.tmp.obj.mode_grab_distance*i.canvas.pxratio,i.interactivity.modes.bubble.distance=i.tmp.obj.mode_bubble_distance*i.canvas.pxratio,i.particles.line_linked.width=i.tmp.obj.line_linked_width*i.canvas.pxratio,i.interactivity.modes.bubble.size=i.tmp.obj.mode_bubble_size*i.canvas.pxratio,i.interactivity.modes.repulse.distance=i.tmp.obj.mode_repulse_distance*i.canvas.pxratio},i.fn.canvasInit=function(){i.canvas.ctx=i.canvas.el.getContext(\"2d\")},i.fn.canvasSize=function(){i.canvas.el.width=i.canvas.w,i.canvas.el.height=i.canvas.h,i&&i.interactivity.events.resize&&window.addEventListener(\"resize\",function(){i.canvas.w=i.canvas.el.offsetWidth,i.canvas.h=i.canvas.el.offsetHeight,i.tmp.retina&&(i.canvas.w*=i.canvas.pxratio,i.canvas.h*=i.canvas.pxratio),i.canvas.el.width=i.canvas.w,i.canvas.el.height=i.canvas.h,i.particles.move.enable||(i.fn.particlesEmpty(),i.fn.particlesCreate(),i.fn.particlesDraw(),i.fn.vendors.densityAutoParticles()),i.fn.vendors.densityAutoParticles()})},i.fn.canvasPaint=function(){i.canvas.ctx.fillRect(0,0,i.canvas.w,i.canvas.h)},i.fn.canvasClear=function(){i.canvas.ctx.clearRect(0,0,i.canvas.w,i.canvas.h)},i.fn.particle=function(e,a,t){if(this.radius=(i.particles.size.random?Math.random():1)*i.particles.size.value,i.particles.size.anim.enable&&(this.size_status=!1,this.vs=i.particles.size.anim.speed/100,i.particles.size.anim.sync||(this.vs=this.vs*Math.random())),this.x=t?t.x:Math.random()*i.canvas.w,this.y=t?t.y:Math.random()*i.canvas.h,this.x>i.canvas.w-2*this.radius?this.x=this.x-this.radius:this.x<2*this.radius&&(this.x=this.x+this.radius),this.y>i.canvas.h-2*this.radius?this.y=this.y-this.radius:this.y<2*this.radius&&(this.y=this.y+this.radius),i.particles.move.bounce&&i.fn.vendors.checkOverlap(this,t),this.color={},\"object\"==typeof e.value)if(e.value instanceof Array){var s=e.value[Math.floor(Math.random()*i.particles.color.value.length)];this.color.rgb=hexToRgb(s)}else void 0!=e.value.r&&void 0!=e.value.g&&void 0!=e.value.b&&(this.color.rgb={r:e.value.r,g:e.value.g,b:e.value.b}),void 0!=e.value.h&&void 0!=e.value.s&&void 0!=e.value.l&&(this.color.hsl={h:e.value.h,s:e.value.s,l:e.value.l});else\"random\"==e.value?this.color.rgb={r:Math.floor(256*Math.random())+0,g:Math.floor(256*Math.random())+0,b:Math.floor(256*Math.random())+0}:\"string\"==typeof e.value&&(this.color=e,this.color.rgb=hexToRgb(this.color.value));this.opacity=(i.particles.opacity.random?Math.random():1)*i.particles.opacity.value,i.particles.opacity.anim.enable&&(this.opacity_status=!1,this.vo=i.particles.opacity.anim.speed/100,i.particles.opacity.anim.sync||(this.vo=this.vo*Math.random()));var n={};switch(i.particles.move.direction){case\"top\":n={x:0,y:-1};break;case\"top-right\":n={x:.5,y:-.5};break;case\"right\":n={x:1,y:-0};break;case\"bottom-right\":n={x:.5,y:.5};break;case\"bottom\":n={x:0,y:1};break;case\"bottom-left\":n={x:-.5,y:1};break;case\"left\":n={x:-1,y:0};break;case\"top-left\":n={x:-.5,y:-.5};break;default:n={x:0,y:0}}i.particles.move.straight?(this.vx=n.x,this.vy=n.y,i.particles.move.random&&(this.vx=this.vx*Math.random(),this.vy=this.vy*Math.random())):(this.vx=n.x+Math.random()-.5,this.vy=n.y+Math.random()-.5),this.vx_i=this.vx,this.vy_i=this.vy;var r=i.particles.shape.type;if(\"object\"==typeof r){if(r instanceof Array){var c=r[Math.floor(Math.random()*r.length)];this.shape=c}}else this.shape=r;if(\"image\"==this.shape){var o=i.particles.shape;this.img={src:o.image.src,ratio:o.image.width/o.image.height},this.img.ratio||(this.img.ratio=1),\"svg\"==i.tmp.img_type&&void 0!=i.tmp.source_svg&&(i.fn.vendors.createSvgImg(this),i.tmp.pushing&&(this.img.loaded=!1))}},i.fn.particle.prototype.draw=function(){function e(){i.canvas.ctx.drawImage(r,a.x-t,a.y-t,2*t,2*t/a.img.ratio)}var a=this;if(void 0!=a.radius_bubble)var t=a.radius_bubble;else var t=a.radius;if(void 0!=a.opacity_bubble)var s=a.opacity_bubble;else var s=a.opacity;if(a.color.rgb)var n=\"rgba(\"+a.color.rgb.r+\",\"+a.color.rgb.g+\",\"+a.color.rgb.b+\",\"+s+\")\";else var n=\"hsla(\"+a.color.hsl.h+\",\"+a.color.hsl.s+\"%,\"+a.color.hsl.l+\"%,\"+s+\")\";switch(i.canvas.ctx.fillStyle=n,i.canvas.ctx.beginPath(),a.shape){case\"circle\":i.canvas.ctx.arc(a.x,a.y,t,0,2*Math.PI,!1);break;case\"edge\":i.canvas.ctx.rect(a.x-t,a.y-t,2*t,2*t);break;case\"triangle\":i.fn.vendors.drawShape(i.canvas.ctx,a.x-t,a.y+t/1.66,2*t,3,2);break;case\"polygon\":i.fn.vendors.drawShape(i.canvas.ctx,a.x-t/(i.particles.shape.polygon.nb_sides/3.5),a.y-t/.76,2.66*t/(i.particles.shape.polygon.nb_sides/3),i.particles.shape.polygon.nb_sides,1);break;case\"star\":i.fn.vendors.drawShape(i.canvas.ctx,a.x-2*t/(i.particles.shape.polygon.nb_sides/4),a.y-t/1.52,2*t*2.66/(i.particles.shape.polygon.nb_sides/3),i.particles.shape.polygon.nb_sides,2);break;case\"image\":if(\"svg\"==i.tmp.img_type)var r=a.img.obj;else var r=i.tmp.img_obj;r&&e()}i.canvas.ctx.closePath(),i.particles.shape.stroke.width>0&&(i.canvas.ctx.strokeStyle=i.particles.shape.stroke.color,i.canvas.ctx.lineWidth=i.particles.shape.stroke.width,i.canvas.ctx.stroke()),i.canvas.ctx.fill()},i.fn.particlesCreate=function(){for(var e=0;e=i.particles.opacity.value&&(a.opacity_status=!1),a.opacity+=a.vo):(a.opacity<=i.particles.opacity.anim.opacity_min&&(a.opacity_status=!0),a.opacity-=a.vo),a.opacity<0&&(a.opacity=0)),i.particles.size.anim.enable&&(1==a.size_status?(a.radius>=i.particles.size.value&&(a.size_status=!1),a.radius+=a.vs):(a.radius<=i.particles.size.anim.size_min&&(a.size_status=!0),a.radius-=a.vs),a.radius<0&&(a.radius=0)),\"bounce\"==i.particles.move.out_mode)var s={x_left:a.radius,x_right:i.canvas.w,y_top:a.radius,y_bottom:i.canvas.h};else var s={x_left:-a.radius,x_right:i.canvas.w+a.radius,y_top:-a.radius,y_bottom:i.canvas.h+a.radius};switch(a.x-a.radius>i.canvas.w?(a.x=s.x_left,a.y=Math.random()*i.canvas.h):a.x+a.radius<0&&(a.x=s.x_right,a.y=Math.random()*i.canvas.h),a.y-a.radius>i.canvas.h?(a.y=s.y_top,a.x=Math.random()*i.canvas.w):a.y+a.radius<0&&(a.y=s.y_bottom,a.x=Math.random()*i.canvas.w),i.particles.move.out_mode){case\"bounce\":a.x+a.radius>i.canvas.w?a.vx=-a.vx:a.x-a.radius<0&&(a.vx=-a.vx),a.y+a.radius>i.canvas.h?a.vy=-a.vy:a.y-a.radius<0&&(a.vy=-a.vy)}if(isInArray(\"grab\",i.interactivity.events.onhover.mode)&&i.fn.modes.grabParticle(a),(isInArray(\"bubble\",i.interactivity.events.onhover.mode)||isInArray(\"bubble\",i.interactivity.events.onclick.mode))&&i.fn.modes.bubbleParticle(a),(isInArray(\"repulse\",i.interactivity.events.onhover.mode)||isInArray(\"repulse\",i.interactivity.events.onclick.mode))&&i.fn.modes.repulseParticle(a),i.particles.line_linked.enable||i.particles.move.attract.enable)for(var n=e+1;n0){var c=i.particles.line_linked.color_rgb_line;i.canvas.ctx.strokeStyle=\"rgba(\"+c.r+\",\"+c.g+\",\"+c.b+\",\"+r+\")\",i.canvas.ctx.lineWidth=i.particles.line_linked.width,i.canvas.ctx.beginPath(),i.canvas.ctx.moveTo(e.x,e.y),i.canvas.ctx.lineTo(a.x,a.y),i.canvas.ctx.stroke(),i.canvas.ctx.closePath()}}},i.fn.interact.attractParticles=function(e,a){var t=e.x-a.x,s=e.y-a.y,n=Math.sqrt(t*t+s*s);if(n<=i.particles.line_linked.distance){var r=t/(1e3*i.particles.move.attract.rotateX),c=s/(1e3*i.particles.move.attract.rotateY);e.vx-=r,e.vy-=c,a.vx+=r,a.vy+=c}},i.fn.interact.bounceParticles=function(e,a){var t=e.x-a.x,i=e.y-a.y,s=Math.sqrt(t*t+i*i),n=e.radius+a.radius;n>=s&&(e.vx=-e.vx,e.vy=-e.vy,a.vx=-a.vx,a.vy=-a.vy)},i.fn.modes.pushParticles=function(e,a){i.tmp.pushing=!0;for(var t=0;e>t;t++)i.particles.array.push(new i.fn.particle(i.particles.color,i.particles.opacity.value,{x:a?a.pos_x:Math.random()*i.canvas.w,y:a?a.pos_y:Math.random()*i.canvas.h})),t==e-1&&(i.particles.move.enable||i.fn.particlesDraw(),i.tmp.pushing=!1)},i.fn.modes.removeParticles=function(e){i.particles.array.splice(0,e),i.particles.move.enable||i.fn.particlesDraw()},i.fn.modes.bubbleParticle=function(e){function a(){e.opacity_bubble=e.opacity,e.radius_bubble=e.radius}function t(a,t,s,n,c){if(a!=t)if(i.tmp.bubble_duration_end){if(void 0!=s){var o=n-p*(n-a)/i.interactivity.modes.bubble.duration,l=a-o;d=a+l,\"size\"==c&&(e.radius_bubble=d),\"opacity\"==c&&(e.opacity_bubble=d)}}else if(r<=i.interactivity.modes.bubble.distance){if(void 0!=s)var v=s;else var v=n;if(v!=a){var d=n-p*(n-a)/i.interactivity.modes.bubble.duration;\"size\"==c&&(e.radius_bubble=d),\"opacity\"==c&&(e.opacity_bubble=d)}}else\"size\"==c&&(e.radius_bubble=void 0),\"opacity\"==c&&(e.opacity_bubble=void 0)}if(i.interactivity.events.onhover.enable&&isInArray(\"bubble\",i.interactivity.events.onhover.mode)){var s=e.x-i.interactivity.mouse.pos_x,n=e.y-i.interactivity.mouse.pos_y,r=Math.sqrt(s*s+n*n),c=1-r/i.interactivity.modes.bubble.distance;if(r<=i.interactivity.modes.bubble.distance){if(c>=0&&\"mousemove\"==i.interactivity.status){if(i.interactivity.modes.bubble.size!=i.particles.size.value)if(i.interactivity.modes.bubble.size>i.particles.size.value){var o=e.radius+i.interactivity.modes.bubble.size*c;o>=0&&(e.radius_bubble=o)}else{var l=e.radius-i.interactivity.modes.bubble.size,o=e.radius-l*c;o>0?e.radius_bubble=o:e.radius_bubble=0}if(i.interactivity.modes.bubble.opacity!=i.particles.opacity.value)if(i.interactivity.modes.bubble.opacity>i.particles.opacity.value){var v=i.interactivity.modes.bubble.opacity*c;v>e.opacity&&v<=i.interactivity.modes.bubble.opacity&&(e.opacity_bubble=v)}else{var v=e.opacity-(i.particles.opacity.value-i.interactivity.modes.bubble.opacity)*c;v=i.interactivity.modes.bubble.opacity&&(e.opacity_bubble=v)}}}else a();\"mouseleave\"==i.interactivity.status&&a()}else if(i.interactivity.events.onclick.enable&&isInArray(\"bubble\",i.interactivity.events.onclick.mode)){if(i.tmp.bubble_clicking){var s=e.x-i.interactivity.mouse.click_pos_x,n=e.y-i.interactivity.mouse.click_pos_y,r=Math.sqrt(s*s+n*n),p=((new Date).getTime()-i.interactivity.mouse.click_time)/1e3;p>i.interactivity.modes.bubble.duration&&(i.tmp.bubble_duration_end=!0),p>2*i.interactivity.modes.bubble.duration&&(i.tmp.bubble_clicking=!1,i.tmp.bubble_duration_end=!1)}i.tmp.bubble_clicking&&(t(i.interactivity.modes.bubble.size,i.particles.size.value,e.radius_bubble,e.radius,\"size\"),t(i.interactivity.modes.bubble.opacity,i.particles.opacity.value,e.opacity_bubble,e.opacity,\"opacity\"))}},i.fn.modes.repulseParticle=function(e){function a(){var a=Math.atan2(d,p);if(e.vx=u*Math.cos(a),e.vy=u*Math.sin(a),\"bounce\"==i.particles.move.out_mode){var t={x:e.x+e.vx,y:e.y+e.vy};t.x+e.radius>i.canvas.w?e.vx=-e.vx:t.x-e.radius<0&&(e.vx=-e.vx),t.y+e.radius>i.canvas.h?e.vy=-e.vy:t.y-e.radius<0&&(e.vy=-e.vy)}}if(i.interactivity.events.onhover.enable&&isInArray(\"repulse\",i.interactivity.events.onhover.mode)&&\"mousemove\"==i.interactivity.status){var t=e.x-i.interactivity.mouse.pos_x,s=e.y-i.interactivity.mouse.pos_y,n=Math.sqrt(t*t+s*s),r={x:t/n,y:s/n},c=i.interactivity.modes.repulse.distance,o=100,l=clamp(1/c*(-1*Math.pow(n/c,2)+1)*c*o,0,50),v={x:e.x+r.x*l,y:e.y+r.y*l};\"bounce\"==i.particles.move.out_mode?(v.x-e.radius>0&&v.x+e.radius0&&v.y+e.radius=m&&a()}else 0==i.tmp.repulse_clicking&&(e.vx=e.vx_i,e.vy=e.vy_i)},i.fn.modes.grabParticle=function(e){if(i.interactivity.events.onhover.enable&&\"mousemove\"==i.interactivity.status){var a=e.x-i.interactivity.mouse.pos_x,t=e.y-i.interactivity.mouse.pos_y,s=Math.sqrt(a*a+t*t);if(s<=i.interactivity.modes.grab.distance){var n=i.interactivity.modes.grab.line_linked.opacity-s/(1/i.interactivity.modes.grab.line_linked.opacity)/i.interactivity.modes.grab.distance;if(n>0){var r=i.particles.line_linked.color_rgb_line;i.canvas.ctx.strokeStyle=\"rgba(\"+r.r+\",\"+r.g+\",\"+r.b+\",\"+n+\")\",i.canvas.ctx.lineWidth=i.particles.line_linked.width,i.canvas.ctx.beginPath(),i.canvas.ctx.moveTo(e.x,e.y),i.canvas.ctx.lineTo(i.interactivity.mouse.pos_x,i.interactivity.mouse.pos_y),i.canvas.ctx.stroke(),i.canvas.ctx.closePath()}}}},i.fn.vendors.eventsListeners=function(){\"window\"==i.interactivity.detect_on?i.interactivity.el=window:i.interactivity.el=i.canvas.el,(i.interactivity.events.onhover.enable||i.interactivity.events.onclick.enable)&&(i.interactivity.el.addEventListener(\"mousemove\",function(e){if(i.interactivity.el==window)var a=e.clientX,t=e.clientY;else var a=e.offsetX||e.clientX,t=e.offsetY||e.clientY;i.interactivity.mouse.pos_x=a,i.interactivity.mouse.pos_y=t,i.tmp.retina&&(i.interactivity.mouse.pos_x*=i.canvas.pxratio,i.interactivity.mouse.pos_y*=i.canvas.pxratio),i.interactivity.status=\"mousemove\"}),i.interactivity.el.addEventListener(\"mouseleave\",function(e){i.interactivity.mouse.pos_x=null,i.interactivity.mouse.pos_y=null,i.interactivity.status=\"mouseleave\"})),i.interactivity.events.onclick.enable&&i.interactivity.el.addEventListener(\"click\",function(){if(i.interactivity.mouse.click_pos_x=i.interactivity.mouse.pos_x,i.interactivity.mouse.click_pos_y=i.interactivity.mouse.pos_y,i.interactivity.mouse.click_time=(new Date).getTime(),i.interactivity.events.onclick.enable)switch(i.interactivity.events.onclick.mode){case\"push\":i.particles.move.enable?i.fn.modes.pushParticles(i.interactivity.modes.push.particles_nb,i.interactivity.mouse):1==i.interactivity.modes.push.particles_nb?i.fn.modes.pushParticles(i.interactivity.modes.push.particles_nb,i.interactivity.mouse):i.interactivity.modes.push.particles_nb>1&&i.fn.modes.pushParticles(i.interactivity.modes.push.particles_nb);break;case\"remove\":i.fn.modes.removeParticles(i.interactivity.modes.remove.particles_nb);break;case\"bubble\":i.tmp.bubble_clicking=!0;break;case\"repulse\":i.tmp.repulse_clicking=!0,i.tmp.repulse_count=0,i.tmp.repulse_finish=!1,setTimeout(function(){i.tmp.repulse_clicking=!1},1e3*i.interactivity.modes.repulse.duration)}})},i.fn.vendors.densityAutoParticles=function(){if(i.particles.number.density.enable){var e=i.canvas.el.width*i.canvas.el.height/1e3;i.tmp.retina&&(e/=2*i.canvas.pxratio);var a=e*i.particles.number.value/i.particles.number.density.value_area,t=i.particles.array.length-a;0>t?i.fn.modes.pushParticles(Math.abs(t)):i.fn.modes.removeParticles(t)}},i.fn.vendors.checkOverlap=function(e,a){for(var t=0;tv;v++)e.lineTo(i,0),e.translate(i,0),e.rotate(l);e.fill(),e.restore()},i.fn.vendors.exportImg=function(){window.open(i.canvas.el.toDataURL(\"image/png\"),\"_blank\")},i.fn.vendors.loadImg=function(e){if(i.tmp.img_error=void 0,\"\"!=i.particles.shape.image.src)if(\"svg\"==e){var a=new XMLHttpRequest;a.open(\"GET\",i.particles.shape.image.src),a.onreadystatechange=function(e){4==a.readyState&&(200==a.status?(i.tmp.source_svg=e.currentTarget.response,i.fn.vendors.checkBeforeDraw()):(console.log(\"Error pJS - Image not found\"),i.tmp.img_error=!0))},a.send()}else{var t=new Image;t.addEventListener(\"load\",function(){i.tmp.img_obj=t,i.fn.vendors.checkBeforeDraw()}),t.src=i.particles.shape.image.src}else console.log(\"Error pJS - No image.src\"),i.tmp.img_error=!0},i.fn.vendors.draw=function(){\"image\"==i.particles.shape.type?\"svg\"==i.tmp.img_type?i.tmp.count_svg>=i.particles.number.value?(i.fn.particlesDraw(),i.particles.move.enable?i.fn.drawAnimFrame=requestAnimFrame(i.fn.vendors.draw):cancelRequestAnimFrame(i.fn.drawAnimFrame)):i.tmp.img_error||(i.fn.drawAnimFrame=requestAnimFrame(i.fn.vendors.draw)):void 0!=i.tmp.img_obj?(i.fn.particlesDraw(),i.particles.move.enable?i.fn.drawAnimFrame=requestAnimFrame(i.fn.vendors.draw):cancelRequestAnimFrame(i.fn.drawAnimFrame)):i.tmp.img_error||(i.fn.drawAnimFrame=requestAnimFrame(i.fn.vendors.draw)):(i.fn.particlesDraw(),i.particles.move.enable?i.fn.drawAnimFrame=requestAnimFrame(i.fn.vendors.draw):cancelRequestAnimFrame(i.fn.drawAnimFrame))},i.fn.vendors.checkBeforeDraw=function(){\"image\"==i.particles.shape.type?\"svg\"==i.tmp.img_type&&void 0==i.tmp.source_svg?i.tmp.checkAnimFrame=requestAnimFrame(check):(cancelRequestAnimFrame(i.tmp.checkAnimFrame),i.tmp.img_error||(i.fn.vendors.init(),i.fn.vendors.draw())):(i.fn.vendors.init(),i.fn.vendors.draw())},i.fn.vendors.init=function(){i.fn.retinaInit(),i.fn.canvasInit(),i.fn.canvasSize(),i.fn.canvasPaint(),i.fn.particlesCreate(),i.fn.vendors.densityAutoParticles(),i.particles.line_linked.color_rgb_line=hexToRgb(i.particles.line_linked.color)},i.fn.vendors.start=function(){isInArray(\"image\",i.particles.shape.type)?(i.tmp.img_type=i.particles.shape.image.src.substr(i.particles.shape.image.src.length-3),i.fn.vendors.loadImg(i.tmp.img_type)):i.fn.vendors.checkBeforeDraw()},i.fn.vendors.eventsListeners(),i.fn.vendors.start()};Object.deepExtend=function(e,a){for(var t in a)a[t]&&a[t].constructor&&a[t].constructor===Object?(e[t]=e[t]||{},arguments.callee(e[t],a[t])):e[t]=a[t];return e},window.requestAnimFrame=function(){return window.requestAnimationFrame||window.webkitRequestAnimationFrame||window.mozRequestAnimationFrame||window.oRequestAnimationFrame||window.msRequestAnimationFrame||function(e){window.setTimeout(e,1e3/60)}}(),window.cancelRequestAnimFrame=function(){return window.cancelAnimationFrame||window.webkitCancelRequestAnimationFrame||window.mozCancelRequestAnimationFrame||window.oCancelRequestAnimationFrame||window.msCancelRequestAnimationFrame||clearTimeout}(),window.pJSDom=[],window.particlesJS=function(e,a){\"string\"!=typeof e&&(a=e,e=\"particles-js\"),e||(e=\"particles-js\");var t=document.getElementById(e),i=\"particles-js-canvas-el\",s=t.getElementsByClassName(i);if(s.length)for(;s.length>0;)t.removeChild(s[0]);var n=document.createElement(\"canvas\");n.className=i,n.style.width=\"100%\",n.style.height=\"100%\";var r=document.getElementById(e).appendChild(n);null!=r&&pJSDom.push(new pJS(e,a))},window.particlesJS.load=function(e,a,t){var i=new XMLHttpRequest;i.open(\"GET\",a),i.onreadystatechange=function(a){if(4==i.readyState)if(200==i.status){var s=JSON.parse(a.currentTarget.response);window.particlesJS(e,s),t&&t()}else console.log(\"Error pJS - XMLHttpRequest status: \"+i.status),console.log(\"Error pJS - File config not found\")},i.send()};","import $ from 'jquery'\nimport 'select2'\nimport 'select2/dist/css/select2.css'\n\nfunction matchStart(params, data) {\n // If there are no search terms, return all of the data\n if ($.trim(params.term) === '') {\n return data;\n }\n\n // Skip if there is no 'children' property\n if (typeof data.children === 'undefined') {\n return null;\n }\n\n // `data.children` contains the actual options that we are matching against\n var filteredChildren = [];\n $.each(data.children, function (idx, child) {\n if (child.text.toUpperCase().indexOf(params.term.toUpperCase()) == 0) {\n filteredChildren.push(child);\n }\n });\n\n // If we matched any of the timezone group's children, then set the matched children on the group\n // and return the group object\n if (filteredChildren.length) {\n var modifiedData = $.extend({}, data, true);\n modifiedData.children = filteredChildren;\n\n // You can return modified objects from here\n // This includes matching the `children` how you want in nested data sets\n return modifiedData;\n }\n\n // Return `null` if the term should not be displayed\n return null;\n}\n\nwindow.addEventListener('DOMContentLoaded', () => {\n $(\"[data-component='select2']\").select2({\n placeholder: $(this).attr(\"data-placeholder\") || 'Choose one',\n multiple: $(this).attr(\"multiple\"),\n \n ...($(this).attr(\"allow-clear\") ? { allowClear: $(this).attr(\"allow-clear\") } : null),\n ...($(this).attr(\"maximum-selection-length\") ? { maximumSelectionLength: $(this).attr(\"maximum-selection-length\") } : null ),\n ...($(this).attr(\"allow-search\") ? { matcher: matchStart } : null ),\n })\n})","function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); }\nfunction _nonIterableRest() { throw new TypeError(\"Invalid attempt to destructure non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.\"); }\nfunction _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === \"string\") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === \"Object\" && o.constructor) n = o.constructor.name; if (n === \"Map\" || n === \"Set\") return Array.from(o); if (n === \"Arguments\" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }\nfunction _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; return arr2; }\nfunction _iterableToArrayLimit(r, l) { var t = null == r ? null : \"undefined\" != typeof Symbol && r[Symbol.iterator] || r[\"@@iterator\"]; if (null != t) { var e, n, i, u, a = [], f = !0, o = !1; try { if (i = (t = t.call(r)).next, 0 === l) { if (Object(t) !== t) return; f = !1; } else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0); } catch (r) { o = !0, n = r; } finally { try { if (!f && null != t.return && (u = t.return(), Object(u) !== u)) return; } finally { if (o) throw n; } } return a; } }\nfunction _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }\n/*\nStimulus 3.2.1\nCopyright © 2023 Basecamp, LLC\n */\nclass EventListener {\n constructor(eventTarget, eventName, eventOptions) {\n this.eventTarget = eventTarget;\n this.eventName = eventName;\n this.eventOptions = eventOptions;\n this.unorderedBindings = new Set();\n }\n connect() {\n this.eventTarget.addEventListener(this.eventName, this, this.eventOptions);\n }\n disconnect() {\n this.eventTarget.removeEventListener(this.eventName, this, this.eventOptions);\n }\n bindingConnected(binding) {\n this.unorderedBindings.add(binding);\n }\n bindingDisconnected(binding) {\n this.unorderedBindings.delete(binding);\n }\n handleEvent(event) {\n const extendedEvent = extendEvent(event);\n for (const binding of this.bindings) {\n if (extendedEvent.immediatePropagationStopped) {\n break;\n } else {\n binding.handleEvent(extendedEvent);\n }\n }\n }\n hasBindings() {\n return this.unorderedBindings.size > 0;\n }\n get bindings() {\n return Array.from(this.unorderedBindings).sort((left, right) => {\n const leftIndex = left.index,\n rightIndex = right.index;\n return leftIndex < rightIndex ? -1 : leftIndex > rightIndex ? 1 : 0;\n });\n }\n}\nfunction extendEvent(event) {\n if (\"immediatePropagationStopped\" in event) {\n return event;\n } else {\n const stopImmediatePropagation = event.stopImmediatePropagation;\n return Object.assign(event, {\n immediatePropagationStopped: false,\n stopImmediatePropagation() {\n this.immediatePropagationStopped = true;\n stopImmediatePropagation.call(this);\n }\n });\n }\n}\nclass Dispatcher {\n constructor(application) {\n this.application = application;\n this.eventListenerMaps = new Map();\n this.started = false;\n }\n start() {\n if (!this.started) {\n this.started = true;\n this.eventListeners.forEach(eventListener => eventListener.connect());\n }\n }\n stop() {\n if (this.started) {\n this.started = false;\n this.eventListeners.forEach(eventListener => eventListener.disconnect());\n }\n }\n get eventListeners() {\n return Array.from(this.eventListenerMaps.values()).reduce((listeners, map) => listeners.concat(Array.from(map.values())), []);\n }\n bindingConnected(binding) {\n this.fetchEventListenerForBinding(binding).bindingConnected(binding);\n }\n bindingDisconnected(binding) {\n let clearEventListeners = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;\n this.fetchEventListenerForBinding(binding).bindingDisconnected(binding);\n if (clearEventListeners) this.clearEventListenersForBinding(binding);\n }\n handleError(error, message) {\n let detail = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};\n this.application.handleError(error, `Error ${message}`, detail);\n }\n clearEventListenersForBinding(binding) {\n const eventListener = this.fetchEventListenerForBinding(binding);\n if (!eventListener.hasBindings()) {\n eventListener.disconnect();\n this.removeMappedEventListenerFor(binding);\n }\n }\n removeMappedEventListenerFor(binding) {\n const eventTarget = binding.eventTarget,\n eventName = binding.eventName,\n eventOptions = binding.eventOptions;\n const eventListenerMap = this.fetchEventListenerMapForEventTarget(eventTarget);\n const cacheKey = this.cacheKey(eventName, eventOptions);\n eventListenerMap.delete(cacheKey);\n if (eventListenerMap.size == 0) this.eventListenerMaps.delete(eventTarget);\n }\n fetchEventListenerForBinding(binding) {\n const eventTarget = binding.eventTarget,\n eventName = binding.eventName,\n eventOptions = binding.eventOptions;\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}\nconst defaultActionDescriptorFilters = {\n stop(_ref) {\n let event = _ref.event,\n value = _ref.value;\n if (value) event.stopPropagation();\n return true;\n },\n prevent(_ref2) {\n let event = _ref2.event,\n value = _ref2.value;\n if (value) event.preventDefault();\n return true;\n },\n self(_ref3) {\n let event = _ref3.event,\n value = _ref3.value,\n element = _ref3.element;\n if (value) {\n return element === event.target;\n } else {\n return true;\n }\n }\n};\nconst descriptorPattern = /^(?:(?:([^.]+?)\\+)?(.+?)(?:\\.(.+?))?(?:@(window|document))?->)?(.+?)(?:#([^:]+?))(?::(.+))?$/;\nfunction parseActionDescriptorString(descriptorString) {\n const source = descriptorString.trim();\n const matches = source.match(descriptorPattern) || [];\n let eventName = matches[2];\n let keyFilter = matches[3];\n if (keyFilter && ![\"keydown\", \"keyup\", \"keypress\"].includes(eventName)) {\n eventName += `.${keyFilter}`;\n keyFilter = \"\";\n }\n return {\n eventTarget: parseEventTarget(matches[4]),\n eventName,\n eventOptions: matches[7] ? parseEventOptions(matches[7]) : {},\n identifier: matches[5],\n methodName: matches[6],\n keyFilter: matches[1] || keyFilter\n };\n}\nfunction parseEventTarget(eventTargetName) {\n if (eventTargetName == \"window\") {\n return window;\n } else if (eventTargetName == \"document\") {\n return document;\n }\n}\nfunction parseEventOptions(eventOptions) {\n return eventOptions.split(\":\").reduce((options, token) => Object.assign(options, {\n [token.replace(/^!/, \"\")]: !/^!/.test(token)\n }), {});\n}\nfunction stringifyEventTarget(eventTarget) {\n if (eventTarget == window) {\n return \"window\";\n } else if (eventTarget == document) {\n return \"document\";\n }\n}\nfunction camelize(value) {\n return value.replace(/(?:[_-])([a-z0-9])/g, (_, char) => char.toUpperCase());\n}\nfunction namespaceCamelize(value) {\n return camelize(value.replace(/--/g, \"-\").replace(/__/g, \"_\"));\n}\nfunction capitalize(value) {\n return value.charAt(0).toUpperCase() + value.slice(1);\n}\nfunction dasherize(value) {\n return value.replace(/([A-Z])/g, (_, char) => `-${char.toLowerCase()}`);\n}\nfunction tokenize(value) {\n return value.match(/[^\\s]+/g) || [];\n}\nfunction isSomething(object) {\n return object !== null && object !== undefined;\n}\nfunction hasProperty(object, property) {\n return Object.prototype.hasOwnProperty.call(object, property);\n}\nconst allModifiers = [\"meta\", \"ctrl\", \"alt\", \"shift\"];\nclass Action {\n constructor(element, index, descriptor, schema) {\n this.element = element;\n this.index = index;\n this.eventTarget = descriptor.eventTarget || element;\n this.eventName = descriptor.eventName || getDefaultEventNameForElement(element) || error(\"missing event name\");\n this.eventOptions = descriptor.eventOptions || {};\n this.identifier = descriptor.identifier || error(\"missing identifier\");\n this.methodName = descriptor.methodName || error(\"missing method name\");\n this.keyFilter = descriptor.keyFilter || \"\";\n this.schema = schema;\n }\n static forToken(token, schema) {\n return new this(token.element, token.index, parseActionDescriptorString(token.content), schema);\n }\n toString() {\n const eventFilter = this.keyFilter ? `.${this.keyFilter}` : \"\";\n const eventTarget = this.eventTargetName ? `@${this.eventTargetName}` : \"\";\n return `${this.eventName}${eventFilter}${eventTarget}->${this.identifier}#${this.methodName}`;\n }\n shouldIgnoreKeyboardEvent(event) {\n if (!this.keyFilter) {\n return false;\n }\n const filters = this.keyFilter.split(\"+\");\n if (this.keyFilterDissatisfied(event, filters)) {\n return true;\n }\n const standardFilter = filters.filter(key => !allModifiers.includes(key))[0];\n if (!standardFilter) {\n return false;\n }\n if (!hasProperty(this.keyMappings, standardFilter)) {\n error(`contains unknown key filter: ${this.keyFilter}`);\n }\n return this.keyMappings[standardFilter].toLowerCase() !== event.key.toLowerCase();\n }\n shouldIgnoreMouseEvent(event) {\n if (!this.keyFilter) {\n return false;\n }\n const filters = [this.keyFilter];\n if (this.keyFilterDissatisfied(event, filters)) {\n return true;\n }\n return false;\n }\n get params() {\n const params = {};\n const pattern = new RegExp(`^data-${this.identifier}-(.+)-param$`, \"i\");\n for (const _ref4 of Array.from(this.element.attributes)) {\n const name = _ref4.name;\n const value = _ref4.value;\n const match = name.match(pattern);\n const key = match && match[1];\n if (key) {\n params[camelize(key)] = typecast(value);\n }\n }\n return params;\n }\n get eventTargetName() {\n return stringifyEventTarget(this.eventTarget);\n }\n get keyMappings() {\n return this.schema.keyMappings;\n }\n keyFilterDissatisfied(event, filters) {\n const _allModifiers$map = allModifiers.map(modifier => filters.includes(modifier)),\n _allModifiers$map2 = _slicedToArray(_allModifiers$map, 4),\n meta = _allModifiers$map2[0],\n ctrl = _allModifiers$map2[1],\n alt = _allModifiers$map2[2],\n shift = _allModifiers$map2[3];\n return event.metaKey !== meta || event.ctrlKey !== ctrl || event.altKey !== alt || event.shiftKey !== shift;\n }\n}\nconst defaultEventNames = {\n a: () => \"click\",\n button: () => \"click\",\n form: () => \"submit\",\n details: () => \"toggle\",\n input: e => e.getAttribute(\"type\") == \"submit\" ? \"click\" : \"input\",\n select: () => \"change\",\n textarea: () => \"input\"\n};\nfunction getDefaultEventNameForElement(element) {\n const tagName = element.tagName.toLowerCase();\n if (tagName in defaultEventNames) {\n return defaultEventNames[tagName](element);\n }\n}\nfunction error(message) {\n throw new Error(message);\n}\nfunction typecast(value) {\n try {\n return JSON.parse(value);\n } catch (o_O) {\n return value;\n }\n}\nclass Binding {\n constructor(context, action) {\n this.context = context;\n this.action = action;\n }\n get index() {\n return this.action.index;\n }\n get eventTarget() {\n return this.action.eventTarget;\n }\n get eventOptions() {\n return this.action.eventOptions;\n }\n get identifier() {\n return this.context.identifier;\n }\n handleEvent(event) {\n const actionEvent = this.prepareActionEvent(event);\n if (this.willBeInvokedByEvent(event) && this.applyEventModifiers(actionEvent)) {\n this.invokeWithEvent(actionEvent);\n }\n }\n get eventName() {\n return this.action.eventName;\n }\n get method() {\n const method = this.controller[this.methodName];\n if (typeof method == \"function\") {\n return method;\n }\n throw new Error(`Action \"${this.action}\" references undefined method \"${this.methodName}\"`);\n }\n applyEventModifiers(event) {\n const element = this.action.element;\n const actionDescriptorFilters = this.context.application.actionDescriptorFilters;\n const controller = this.context.controller;\n let passes = true;\n for (const _ref5 of Object.entries(this.eventOptions)) {\n var _ref6 = _slicedToArray(_ref5, 2);\n const name = _ref6[0];\n const value = _ref6[1];\n if (name in actionDescriptorFilters) {\n const filter = actionDescriptorFilters[name];\n passes = passes && filter({\n name,\n value,\n event,\n element,\n controller\n });\n } else {\n continue;\n }\n }\n return passes;\n }\n prepareActionEvent(event) {\n return Object.assign(event, {\n params: this.action.params\n });\n }\n invokeWithEvent(event) {\n const target = event.target,\n currentTarget = event.currentTarget;\n try {\n this.method.call(this.controller, event);\n this.context.logDebugActivity(this.methodName, {\n event,\n target,\n currentTarget,\n action: this.methodName\n });\n } catch (error) {\n const identifier = this.identifier,\n controller = this.controller,\n element = this.element,\n index = this.index;\n const detail = {\n identifier,\n controller,\n element,\n index,\n event\n };\n this.context.handleError(error, `invoking action \"${this.action}\"`, detail);\n }\n }\n willBeInvokedByEvent(event) {\n const eventTarget = event.target;\n if (event instanceof KeyboardEvent && this.action.shouldIgnoreKeyboardEvent(event)) {\n return false;\n }\n if (event instanceof MouseEvent && this.action.shouldIgnoreMouseEvent(event)) {\n return false;\n }\n if (this.element === eventTarget) {\n return true;\n } else if (eventTarget instanceof Element && this.element.contains(eventTarget)) {\n return this.scope.containsElement(eventTarget);\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}\nclass ElementObserver {\n constructor(element, delegate) {\n this.mutationObserverInit = {\n attributes: true,\n childList: true,\n subtree: true\n };\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 } else if (mutation.type == \"childList\") {\n this.processRemovedNodes(mutation.removedNodes);\n this.processAddedNodes(mutation.addedNodes);\n }\n }\n processAttributeChange(element, attributeName) {\n if (this.elements.has(element)) {\n if (this.delegate.elementAttributeChanged && this.matchElement(element)) {\n this.delegate.elementAttributeChanged(element, attributeName);\n } else {\n this.removeElement(element);\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() {\n let tree = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 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 } 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}\nclass AttributeObserver {\n constructor(element, attributeName, delegate) {\n this.attributeName = attributeName;\n this.delegate = delegate;\n this.elementObserver = new ElementObserver(element, this);\n }\n get element() {\n return this.elementObserver.element;\n }\n get selector() {\n return `[${this.attributeName}]`;\n }\n start() {\n this.elementObserver.start();\n }\n pause(callback) {\n this.elementObserver.pause(callback);\n }\n stop() {\n this.elementObserver.stop();\n }\n refresh() {\n this.elementObserver.refresh();\n }\n get started() {\n return this.elementObserver.started;\n }\n matchElement(element) {\n return element.hasAttribute(this.attributeName);\n }\n matchElementsInTree(tree) {\n const match = this.matchElement(tree) ? [tree] : [];\n const matches = Array.from(tree.querySelectorAll(this.selector));\n return match.concat(matches);\n }\n elementMatched(element) {\n if (this.delegate.elementMatchedAttribute) {\n this.delegate.elementMatchedAttribute(element, this.attributeName);\n }\n }\n elementUnmatched(element) {\n if (this.delegate.elementUnmatchedAttribute) {\n this.delegate.elementUnmatchedAttribute(element, this.attributeName);\n }\n }\n elementAttributeChanged(element, attributeName) {\n if (this.delegate.elementAttributeValueChanged && this.attributeName == attributeName) {\n this.delegate.elementAttributeValueChanged(element, attributeName);\n }\n }\n}\nfunction add(map, key, value) {\n fetch(map, key).add(value);\n}\nfunction del(map, key, value) {\n fetch(map, key).delete(value);\n prune(map, key);\n}\nfunction fetch(map, key) {\n let values = map.get(key);\n if (!values) {\n values = new Set();\n map.set(key, values);\n }\n return values;\n}\nfunction prune(map, key) {\n const values = map.get(key);\n if (values != null && values.size == 0) {\n map.delete(key);\n }\n}\nclass Multimap {\n constructor() {\n this.valuesByKey = new Map();\n }\n get keys() {\n return Array.from(this.valuesByKey.keys());\n }\n get values() {\n const sets = Array.from(this.valuesByKey.values());\n return sets.reduce((values, set) => values.concat(Array.from(set)), []);\n }\n get size() {\n const sets = Array.from(this.valuesByKey.values());\n return sets.reduce((size, set) => size + set.size, 0);\n }\n add(key, value) {\n add(this.valuesByKey, key, value);\n }\n delete(key, value) {\n del(this.valuesByKey, key, value);\n }\n has(key, value) {\n const values = this.valuesByKey.get(key);\n return values != null && values.has(value);\n }\n hasKey(key) {\n return this.valuesByKey.has(key);\n }\n hasValue(value) {\n const sets = Array.from(this.valuesByKey.values());\n return sets.some(set => set.has(value));\n }\n getValuesForKey(key) {\n const values = this.valuesByKey.get(key);\n return values ? Array.from(values) : [];\n }\n getKeysForValue(value) {\n return Array.from(this.valuesByKey).filter(_ref7 => {\n let _ref8 = _slicedToArray(_ref7, 2),\n _key = _ref8[0],\n values = _ref8[1];\n return values.has(value);\n }).map(_ref9 => {\n let _ref10 = _slicedToArray(_ref9, 2),\n key = _ref10[0],\n _values = _ref10[1];\n return key;\n });\n }\n}\nclass IndexedMultimap extends Multimap {\n constructor() {\n super();\n this.keysByValue = new Map();\n }\n get values() {\n return Array.from(this.keysByValue.keys());\n }\n add(key, value) {\n super.add(key, value);\n add(this.keysByValue, value, key);\n }\n delete(key, value) {\n super.delete(key, value);\n del(this.keysByValue, value, key);\n }\n hasValue(value) {\n return this.keysByValue.has(value);\n }\n getKeysForValue(value) {\n const set = this.keysByValue.get(value);\n return set ? Array.from(set) : [];\n }\n}\nclass SelectorObserver {\n constructor(element, selector, delegate, details) {\n this._selector = selector;\n this.details = details;\n this.elementObserver = new ElementObserver(element, this);\n this.delegate = delegate;\n this.matchesByElement = new Multimap();\n }\n get started() {\n return this.elementObserver.started;\n }\n get selector() {\n return this._selector;\n }\n set selector(selector) {\n this._selector = selector;\n this.refresh();\n }\n start() {\n this.elementObserver.start();\n }\n pause(callback) {\n this.elementObserver.pause(callback);\n }\n stop() {\n this.elementObserver.stop();\n }\n refresh() {\n this.elementObserver.refresh();\n }\n get element() {\n return this.elementObserver.element;\n }\n matchElement(element) {\n const selector = this.selector;\n if (selector) {\n const matches = element.matches(selector);\n if (this.delegate.selectorMatchElement) {\n return matches && this.delegate.selectorMatchElement(element, this.details);\n }\n return matches;\n } else {\n return false;\n }\n }\n matchElementsInTree(tree) {\n const selector = this.selector;\n if (selector) {\n const match = this.matchElement(tree) ? [tree] : [];\n const matches = Array.from(tree.querySelectorAll(selector)).filter(match => this.matchElement(match));\n return match.concat(matches);\n } else {\n return [];\n }\n }\n elementMatched(element) {\n const selector = this.selector;\n if (selector) {\n this.selectorMatched(element, selector);\n }\n }\n elementUnmatched(element) {\n const selectors = this.matchesByElement.getKeysForValue(element);\n for (const selector of selectors) {\n this.selectorUnmatched(element, selector);\n }\n }\n elementAttributeChanged(element, _attributeName) {\n const selector = this.selector;\n if (selector) {\n const matches = this.matchElement(element);\n const matchedBefore = this.matchesByElement.has(selector, element);\n if (matches && !matchedBefore) {\n this.selectorMatched(element, selector);\n } else if (!matches && matchedBefore) {\n this.selectorUnmatched(element, selector);\n }\n }\n }\n selectorMatched(element, selector) {\n this.delegate.selectorMatched(element, selector, this.details);\n this.matchesByElement.add(selector, element);\n }\n selectorUnmatched(element, selector) {\n this.delegate.selectorUnmatched(element, selector, this.details);\n this.matchesByElement.delete(selector, element);\n }\n}\nclass StringMapObserver {\n constructor(element, delegate) {\n this.element = element;\n this.delegate = delegate;\n this.started = false;\n this.stringMap = new Map();\n this.mutationObserver = new MutationObserver(mutations => this.processMutations(mutations));\n }\n start() {\n if (!this.started) {\n this.started = true;\n this.mutationObserver.observe(this.element, {\n attributes: true,\n attributeOldValue: true\n });\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) this.stringMapKeyRemoved(key, attributeName, oldValue);\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}\nclass TokenListObserver {\n constructor(element, attributeName, delegate) {\n this.attributeObserver = new AttributeObserver(element, attributeName, this);\n this.delegate = delegate;\n this.tokensByElement = new Multimap();\n }\n get started() {\n return this.attributeObserver.started;\n }\n start() {\n this.attributeObserver.start();\n }\n pause(callback) {\n this.attributeObserver.pause(callback);\n }\n stop() {\n this.attributeObserver.stop();\n }\n refresh() {\n this.attributeObserver.refresh();\n }\n get element() {\n return this.attributeObserver.element;\n }\n get attributeName() {\n return this.attributeObserver.attributeName;\n }\n elementMatchedAttribute(element) {\n this.tokensMatched(this.readTokensForElement(element));\n }\n elementAttributeValueChanged(element) {\n const _this$refreshTokensFo = this.refreshTokensForElement(element),\n _this$refreshTokensFo2 = _slicedToArray(_this$refreshTokensFo, 2),\n unmatchedTokens = _this$refreshTokensFo2[0],\n matchedTokens = _this$refreshTokensFo2[1];\n this.tokensUnmatched(unmatchedTokens);\n this.tokensMatched(matchedTokens);\n }\n elementUnmatchedAttribute(element) {\n this.tokensUnmatched(this.tokensByElement.getValuesForKey(element));\n }\n tokensMatched(tokens) {\n tokens.forEach(token => this.tokenMatched(token));\n }\n tokensUnmatched(tokens) {\n tokens.forEach(token => this.tokenUnmatched(token));\n }\n tokenMatched(token) {\n this.delegate.tokenMatched(token);\n this.tokensByElement.add(token.element, token);\n }\n tokenUnmatched(token) {\n this.delegate.tokenUnmatched(token);\n this.tokensByElement.delete(token.element, token);\n }\n refreshTokensForElement(element) {\n const previousTokens = this.tokensByElement.getValuesForKey(element);\n const currentTokens = this.readTokensForElement(element);\n const firstDifferingIndex = zip(previousTokens, currentTokens).findIndex(_ref11 => {\n let _ref12 = _slicedToArray(_ref11, 2),\n previousToken = _ref12[0],\n currentToken = _ref12[1];\n return !tokensAreEqual(previousToken, currentToken);\n });\n if (firstDifferingIndex == -1) {\n return [[], []];\n } else {\n return [previousTokens.slice(firstDifferingIndex), currentTokens.slice(firstDifferingIndex)];\n }\n }\n readTokensForElement(element) {\n const attributeName = this.attributeName;\n const tokenString = element.getAttribute(attributeName) || \"\";\n return parseTokenString(tokenString, element, attributeName);\n }\n}\nfunction parseTokenString(tokenString, element, attributeName) {\n return tokenString.trim().split(/\\s+/).filter(content => content.length).map((content, index) => ({\n element,\n attributeName,\n content,\n index\n }));\n}\nfunction zip(left, right) {\n const length = Math.max(left.length, right.length);\n return Array.from({\n length\n }, (_, index) => [left[index], right[index]]);\n}\nfunction tokensAreEqual(left, right) {\n return left && right && left.index == right.index && left.content == right.content;\n}\nclass ValueListObserver {\n constructor(element, attributeName, delegate) {\n this.tokenListObserver = new TokenListObserver(element, attributeName, this);\n this.delegate = delegate;\n this.parseResultsByToken = new WeakMap();\n this.valuesByTokenByElement = new WeakMap();\n }\n get started() {\n return this.tokenListObserver.started;\n }\n start() {\n this.tokenListObserver.start();\n }\n stop() {\n this.tokenListObserver.stop();\n }\n refresh() {\n this.tokenListObserver.refresh();\n }\n get element() {\n return this.tokenListObserver.element;\n }\n get attributeName() {\n return this.tokenListObserver.attributeName;\n }\n tokenMatched(token) {\n const element = token.element;\n const _this$fetchParseResul = this.fetchParseResultForToken(token),\n value = _this$fetchParseResul.value;\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.element;\n const _this$fetchParseResul2 = this.fetchParseResultForToken(token),\n value = _this$fetchParseResul2.value;\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 {\n value\n };\n } catch (error) {\n return {\n error\n };\n }\n }\n}\nclass BindingObserver {\n constructor(context, delegate) {\n this.context = context;\n this.delegate = delegate;\n this.bindingsByAction = new Map();\n }\n start() {\n if (!this.valueListObserver) {\n this.valueListObserver = new ValueListObserver(this.element, this.actionAttribute, this);\n this.valueListObserver.start();\n }\n }\n stop() {\n if (this.valueListObserver) {\n this.valueListObserver.stop();\n delete this.valueListObserver;\n this.disconnectAllActions();\n }\n }\n get element() {\n return this.context.element;\n }\n get identifier() {\n return this.context.identifier;\n }\n get actionAttribute() {\n return this.schema.actionAttribute;\n }\n get schema() {\n return this.context.schema;\n }\n get bindings() {\n return Array.from(this.bindingsByAction.values());\n }\n connectAction(action) {\n const binding = new Binding(this.context, action);\n this.bindingsByAction.set(action, binding);\n this.delegate.bindingConnected(binding);\n }\n disconnectAction(action) {\n const binding = this.bindingsByAction.get(action);\n if (binding) {\n this.bindingsByAction.delete(action);\n this.delegate.bindingDisconnected(binding);\n }\n }\n disconnectAllActions() {\n this.bindings.forEach(binding => this.delegate.bindingDisconnected(binding, true));\n this.bindingsByAction.clear();\n }\n parseValueForToken(token) {\n const action = Action.forToken(token, this.schema);\n if (action.identifier == this.identifier) {\n return action;\n }\n }\n elementMatchedValue(element, action) {\n this.connectAction(action);\n }\n elementUnmatchedValue(element, action) {\n this.disconnectAction(action);\n }\n}\nclass ValueObserver {\n constructor(context, receiver) {\n this.context = context;\n this.receiver = receiver;\n this.stringMapObserver = new StringMapObserver(this.element, this);\n this.valueDescriptorMap = this.controller.valueDescriptorMap;\n }\n start() {\n this.stringMapObserver.start();\n this.invokeChangedCallbacksForDefaultValues();\n }\n stop() {\n this.stringMapObserver.stop();\n }\n get element() {\n return this.context.element;\n }\n get controller() {\n return this.context.controller;\n }\n getStringMapKeyForAttribute(attributeName) {\n if (attributeName in this.valueDescriptorMap) {\n return this.valueDescriptorMap[attributeName].name;\n }\n }\n stringMapKeyAdded(key, attributeName) {\n const descriptor = this.valueDescriptorMap[attributeName];\n if (!this.hasValue(key)) {\n this.invokeChangedCallback(key, descriptor.writer(this.receiver[key]), descriptor.writer(descriptor.defaultValue));\n }\n }\n stringMapValueChanged(value, name, oldValue) {\n const descriptor = this.valueDescriptorNameMap[name];\n if (value === null) 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 } else {\n this.invokeChangedCallback(key, descriptor.writer(descriptor.defaultValue), oldValue);\n }\n }\n invokeChangedCallbacksForDefaultValues() {\n for (const _ref13 of this.valueDescriptors) {\n const key = _ref13.key;\n const name = _ref13.name;\n const defaultValue = _ref13.defaultValue;\n const writer = _ref13.writer;\n if (defaultValue != undefined && !this.controller.data.has(key)) {\n this.invokeChangedCallback(name, writer(defaultValue), undefined);\n }\n }\n }\n invokeChangedCallback(name, rawValue, rawOldValue) {\n const changedMethodName = `${name}Changed`;\n const changedMethod = this.receiver[changedMethodName];\n if (typeof changedMethod == \"function\") {\n const descriptor = this.valueDescriptorNameMap[name];\n try {\n const value = descriptor.reader(rawValue);\n let oldValue = rawOldValue;\n if (rawOldValue) {\n oldValue = descriptor.reader(rawOldValue);\n }\n changedMethod.call(this.receiver, value, oldValue);\n } catch (error) {\n if (error instanceof TypeError) {\n error.message = `Stimulus Value \"${this.context.identifier}.${descriptor.name}\" - ${error.message}`;\n }\n throw error;\n }\n }\n }\n get valueDescriptors() {\n const valueDescriptorMap = this.valueDescriptorMap;\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}\nclass TargetObserver {\n constructor(context, delegate) {\n this.context = context;\n this.delegate = delegate;\n this.targetsByName = new Multimap();\n }\n start() {\n if (!this.tokenListObserver) {\n this.tokenListObserver = new TokenListObserver(this.element, this.attributeName, this);\n this.tokenListObserver.start();\n }\n }\n stop() {\n if (this.tokenListObserver) {\n this.disconnectAllTargets();\n this.tokenListObserver.stop();\n delete this.tokenListObserver;\n }\n }\n tokenMatched(_ref14) {\n let element = _ref14.element,\n name = _ref14.content;\n if (this.scope.containsElement(element)) {\n this.connectTarget(element, name);\n }\n }\n tokenUnmatched(_ref15) {\n let element = _ref15.element,\n name = _ref15.content;\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}\nfunction readInheritableStaticArrayValues(constructor, propertyName) {\n const ancestors = getAncestorsForConstructor(constructor);\n return Array.from(ancestors.reduce((values, constructor) => {\n getOwnStaticArrayValues(constructor, propertyName).forEach(name => values.add(name));\n return values;\n }, new Set()));\n}\nfunction readInheritableStaticObjectPairs(constructor, propertyName) {\n const ancestors = getAncestorsForConstructor(constructor);\n return ancestors.reduce((pairs, constructor) => {\n pairs.push(...getOwnStaticObjectPairs(constructor, propertyName));\n return pairs;\n }, []);\n}\nfunction getAncestorsForConstructor(constructor) {\n const ancestors = [];\n while (constructor) {\n ancestors.push(constructor);\n constructor = Object.getPrototypeOf(constructor);\n }\n return ancestors.reverse();\n}\nfunction getOwnStaticArrayValues(constructor, propertyName) {\n const definition = constructor[propertyName];\n return Array.isArray(definition) ? definition : [];\n}\nfunction getOwnStaticObjectPairs(constructor, propertyName) {\n const definition = constructor[propertyName];\n return definition ? Object.keys(definition).map(key => [key, definition[key]]) : [];\n}\nclass OutletObserver {\n constructor(context, delegate) {\n this.started = false;\n this.context = context;\n this.delegate = delegate;\n this.outletsByName = new Multimap();\n this.outletElementsByName = new Multimap();\n this.selectorObserverMap = new Map();\n this.attributeObserverMap = new Map();\n }\n start() {\n if (!this.started) {\n this.outletDefinitions.forEach(outletName => {\n this.setupSelectorObserverForOutlet(outletName);\n this.setupAttributeObserverForOutlet(outletName);\n });\n this.started = true;\n this.dependentContexts.forEach(context => context.refresh());\n }\n }\n refresh() {\n this.selectorObserverMap.forEach(observer => observer.refresh());\n this.attributeObserverMap.forEach(observer => observer.refresh());\n }\n stop() {\n if (this.started) {\n this.started = false;\n this.disconnectAllOutlets();\n this.stopSelectorObservers();\n this.stopAttributeObservers();\n }\n }\n stopSelectorObservers() {\n if (this.selectorObserverMap.size > 0) {\n this.selectorObserverMap.forEach(observer => observer.stop());\n this.selectorObserverMap.clear();\n }\n }\n stopAttributeObservers() {\n if (this.attributeObserverMap.size > 0) {\n this.attributeObserverMap.forEach(observer => observer.stop());\n this.attributeObserverMap.clear();\n }\n }\n selectorMatched(element, _selector, _ref16) {\n let outletName = _ref16.outletName;\n const outlet = this.getOutlet(element, outletName);\n if (outlet) {\n this.connectOutlet(outlet, element, outletName);\n }\n }\n selectorUnmatched(element, _selector, _ref17) {\n let outletName = _ref17.outletName;\n const outlet = this.getOutletFromMap(element, outletName);\n if (outlet) {\n this.disconnectOutlet(outlet, element, outletName);\n }\n }\n selectorMatchElement(element, _ref18) {\n let outletName = _ref18.outletName;\n const selector = this.selector(outletName);\n const hasOutlet = this.hasOutlet(element, outletName);\n const hasOutletController = element.matches(`[${this.schema.controllerAttribute}~=${outletName}]`);\n if (selector) {\n return hasOutlet && hasOutletController && element.matches(selector);\n } else {\n return false;\n }\n }\n elementMatchedAttribute(_element, attributeName) {\n const outletName = this.getOutletNameFromOutletAttributeName(attributeName);\n if (outletName) {\n this.updateSelectorObserverForOutlet(outletName);\n }\n }\n elementAttributeValueChanged(_element, attributeName) {\n const outletName = this.getOutletNameFromOutletAttributeName(attributeName);\n if (outletName) {\n this.updateSelectorObserverForOutlet(outletName);\n }\n }\n elementUnmatchedAttribute(_element, attributeName) {\n const outletName = this.getOutletNameFromOutletAttributeName(attributeName);\n if (outletName) {\n this.updateSelectorObserverForOutlet(outletName);\n }\n }\n connectOutlet(outlet, element, outletName) {\n var _a;\n if (!this.outletElementsByName.has(outletName, element)) {\n this.outletsByName.add(outletName, outlet);\n this.outletElementsByName.add(outletName, element);\n (_a = this.selectorObserverMap.get(outletName)) === null || _a === void 0 ? void 0 : _a.pause(() => this.delegate.outletConnected(outlet, element, outletName));\n }\n }\n disconnectOutlet(outlet, element, outletName) {\n var _a;\n if (this.outletElementsByName.has(outletName, element)) {\n this.outletsByName.delete(outletName, outlet);\n this.outletElementsByName.delete(outletName, element);\n (_a = this.selectorObserverMap.get(outletName)) === null || _a === void 0 ? void 0 : _a.pause(() => this.delegate.outletDisconnected(outlet, element, outletName));\n }\n }\n disconnectAllOutlets() {\n for (const outletName of this.outletElementsByName.keys) {\n for (const element of this.outletElementsByName.getValuesForKey(outletName)) {\n for (const outlet of this.outletsByName.getValuesForKey(outletName)) {\n this.disconnectOutlet(outlet, element, outletName);\n }\n }\n }\n }\n updateSelectorObserverForOutlet(outletName) {\n const observer = this.selectorObserverMap.get(outletName);\n if (observer) {\n observer.selector = this.selector(outletName);\n }\n }\n setupSelectorObserverForOutlet(outletName) {\n const selector = this.selector(outletName);\n const selectorObserver = new SelectorObserver(document.body, selector, this, {\n outletName\n });\n this.selectorObserverMap.set(outletName, selectorObserver);\n selectorObserver.start();\n }\n setupAttributeObserverForOutlet(outletName) {\n const attributeName = this.attributeNameForOutletName(outletName);\n const attributeObserver = new AttributeObserver(this.scope.element, attributeName, this);\n this.attributeObserverMap.set(outletName, attributeObserver);\n attributeObserver.start();\n }\n selector(outletName) {\n return this.scope.outlets.getSelectorForOutletName(outletName);\n }\n attributeNameForOutletName(outletName) {\n return this.scope.schema.outletAttributeForScope(this.identifier, outletName);\n }\n getOutletNameFromOutletAttributeName(attributeName) {\n return this.outletDefinitions.find(outletName => this.attributeNameForOutletName(outletName) === attributeName);\n }\n get outletDependencies() {\n const dependencies = new Multimap();\n this.router.modules.forEach(module => {\n const constructor = module.definition.controllerConstructor;\n const outlets = readInheritableStaticArrayValues(constructor, \"outlets\");\n outlets.forEach(outlet => dependencies.add(outlet, module.identifier));\n });\n return dependencies;\n }\n get outletDefinitions() {\n return this.outletDependencies.getKeysForValue(this.identifier);\n }\n get dependentControllerIdentifiers() {\n return this.outletDependencies.getValuesForKey(this.identifier);\n }\n get dependentContexts() {\n const identifiers = this.dependentControllerIdentifiers;\n return this.router.contexts.filter(context => identifiers.includes(context.identifier));\n }\n hasOutlet(element, outletName) {\n return !!this.getOutlet(element, outletName) || !!this.getOutletFromMap(element, outletName);\n }\n getOutlet(element, outletName) {\n return this.application.getControllerForElementAndIdentifier(element, outletName);\n }\n getOutletFromMap(element, outletName) {\n return this.outletsByName.getValuesForKey(outletName).find(outlet => outlet.element === element);\n }\n get scope() {\n return this.context.scope;\n }\n get schema() {\n return this.context.schema;\n }\n get identifier() {\n return this.context.identifier;\n }\n get application() {\n return this.context.application;\n }\n get router() {\n return this.application.router;\n }\n}\nclass Context {\n constructor(module, scope) {\n var _this = this;\n this.logDebugActivity = function (functionName) {\n let detail = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};\n const identifier = _this.identifier,\n controller = _this.controller,\n element = _this.element;\n detail = Object.assign({\n identifier,\n controller,\n element\n }, detail);\n _this.application.logDebugActivity(_this.identifier, functionName, detail);\n };\n this.module = module;\n this.scope = scope;\n this.controller = new module.controllerConstructor(this);\n this.bindingObserver = new BindingObserver(this, this.dispatcher);\n this.valueObserver = new ValueObserver(this, this.controller);\n this.targetObserver = new TargetObserver(this, this);\n this.outletObserver = new OutletObserver(this, this);\n try {\n this.controller.initialize();\n this.logDebugActivity(\"initialize\");\n } catch (error) {\n this.handleError(error, \"initializing controller\");\n }\n }\n connect() {\n this.bindingObserver.start();\n this.valueObserver.start();\n this.targetObserver.start();\n this.outletObserver.start();\n try {\n this.controller.connect();\n this.logDebugActivity(\"connect\");\n } catch (error) {\n this.handleError(error, \"connecting controller\");\n }\n }\n refresh() {\n this.outletObserver.refresh();\n }\n disconnect() {\n try {\n this.controller.disconnect();\n this.logDebugActivity(\"disconnect\");\n } catch (error) {\n this.handleError(error, \"disconnecting controller\");\n }\n this.outletObserver.stop();\n this.targetObserver.stop();\n this.valueObserver.stop();\n this.bindingObserver.stop();\n }\n get application() {\n return this.module.application;\n }\n get identifier() {\n return this.module.identifier;\n }\n get schema() {\n return this.application.schema;\n }\n get dispatcher() {\n return this.application.dispatcher;\n }\n get element() {\n return this.scope.element;\n }\n get parentElement() {\n return this.element.parentElement;\n }\n handleError(error, message) {\n let detail = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};\n const identifier = this.identifier,\n controller = this.controller,\n element = this.element;\n detail = Object.assign({\n identifier,\n controller,\n element\n }, detail);\n this.application.handleError(error, `Error ${message}`, detail);\n }\n targetConnected(element, name) {\n this.invokeControllerMethod(`${name}TargetConnected`, element);\n }\n targetDisconnected(element, name) {\n this.invokeControllerMethod(`${name}TargetDisconnected`, element);\n }\n outletConnected(outlet, element, name) {\n this.invokeControllerMethod(`${namespaceCamelize(name)}OutletConnected`, outlet, element);\n }\n outletDisconnected(outlet, element, name) {\n this.invokeControllerMethod(`${namespaceCamelize(name)}OutletDisconnected`, outlet, element);\n }\n invokeControllerMethod(methodName) {\n const controller = this.controller;\n if (typeof controller[methodName] == \"function\") {\n for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key2 = 1; _key2 < _len; _key2++) {\n args[_key2 - 1] = arguments[_key2];\n }\n controller[methodName](...args);\n }\n }\n}\nfunction bless(constructor) {\n return shadow(constructor, getBlessedProperties(constructor));\n}\nfunction shadow(constructor, properties) {\n const shadowConstructor = extend(constructor);\n const shadowProperties = getShadowProperties(constructor.prototype, properties);\n Object.defineProperties(shadowConstructor.prototype, shadowProperties);\n return shadowConstructor;\n}\nfunction getBlessedProperties(constructor) {\n const blessings = readInheritableStaticArrayValues(constructor, \"blessings\");\n return blessings.reduce((blessedProperties, blessing) => {\n const properties = blessing(constructor);\n for (const key in properties) {\n const descriptor = blessedProperties[key] || {};\n blessedProperties[key] = Object.assign(descriptor, properties[key]);\n }\n return blessedProperties;\n }, {});\n}\nfunction getShadowProperties(prototype, properties) {\n return getOwnKeys(properties).reduce((shadowProperties, key) => {\n const descriptor = getShadowedDescriptor(prototype, properties, key);\n if (descriptor) {\n Object.assign(shadowProperties, {\n [key]: descriptor\n });\n }\n return shadowProperties;\n }, {});\n}\nfunction getShadowedDescriptor(prototype, properties, key) {\n const shadowingDescriptor = Object.getOwnPropertyDescriptor(prototype, key);\n const shadowedByValue = shadowingDescriptor && \"value\" in shadowingDescriptor;\n if (!shadowedByValue) {\n const descriptor = Object.getOwnPropertyDescriptor(properties, key).value;\n if (shadowingDescriptor) {\n descriptor.get = shadowingDescriptor.get || descriptor.get;\n descriptor.set = shadowingDescriptor.set || descriptor.set;\n }\n return descriptor;\n }\n}\nconst getOwnKeys = (() => {\n if (typeof Object.getOwnPropertySymbols == \"function\") {\n return object => [...Object.getOwnPropertyNames(object), ...Object.getOwnPropertySymbols(object)];\n } else {\n return Object.getOwnPropertyNames;\n }\n})();\nconst extend = (() => {\n function extendWithReflect(constructor) {\n function extended() {\n return Reflect.construct(constructor, arguments, new.target);\n }\n extended.prototype = Object.create(constructor.prototype, {\n constructor: {\n value: extended\n }\n });\n Reflect.setPrototypeOf(extended, constructor);\n return extended;\n }\n function testReflectExtension() {\n const a = function () {\n this.a.call(this);\n };\n const b = extendWithReflect(a);\n b.prototype.a = function () {};\n return new b();\n }\n try {\n testReflectExtension();\n return extendWithReflect;\n } catch (error) {\n return constructor => class extended extends constructor {};\n }\n})();\nfunction blessDefinition(definition) {\n return {\n identifier: definition.identifier,\n controllerConstructor: bless(definition.controllerConstructor)\n };\n}\nclass Module {\n constructor(application, definition) {\n this.application = application;\n this.definition = blessDefinition(definition);\n this.contextsByScope = new WeakMap();\n this.connectedContexts = new Set();\n }\n get identifier() {\n return this.definition.identifier;\n }\n get controllerConstructor() {\n return this.definition.controllerConstructor;\n }\n get contexts() {\n return Array.from(this.connectedContexts);\n }\n connectContextForScope(scope) {\n const context = this.fetchContextForScope(scope);\n this.connectedContexts.add(context);\n context.connect();\n }\n disconnectContextForScope(scope) {\n const context = this.contextsByScope.get(scope);\n if (context) {\n this.connectedContexts.delete(context);\n context.disconnect();\n }\n }\n fetchContextForScope(scope) {\n let context = this.contextsByScope.get(scope);\n if (!context) {\n context = new Context(this, scope);\n this.contextsByScope.set(scope, context);\n }\n return context;\n }\n}\nclass ClassMap {\n constructor(scope) {\n this.scope = scope;\n }\n has(name) {\n return this.data.has(this.getDataKey(name));\n }\n get(name) {\n return this.getAll(name)[0];\n }\n getAll(name) {\n const tokenString = this.data.get(this.getDataKey(name)) || \"\";\n return tokenize(tokenString);\n }\n getAttributeName(name) {\n return this.data.getAttributeNameForKey(this.getDataKey(name));\n }\n getDataKey(name) {\n return `${name}-class`;\n }\n get data() {\n return this.scope.data;\n }\n}\nclass DataMap {\n constructor(scope) {\n this.scope = scope;\n }\n get element() {\n return this.scope.element;\n }\n get identifier() {\n return this.scope.identifier;\n }\n get(key) {\n const name = this.getAttributeNameForKey(key);\n return this.element.getAttribute(name);\n }\n set(key, value) {\n const name = this.getAttributeNameForKey(key);\n this.element.setAttribute(name, value);\n return this.get(key);\n }\n has(key) {\n const name = this.getAttributeNameForKey(key);\n return this.element.hasAttribute(name);\n }\n delete(key) {\n if (this.has(key)) {\n const name = this.getAttributeNameForKey(key);\n this.element.removeAttribute(name);\n return true;\n } else {\n return false;\n }\n }\n getAttributeNameForKey(key) {\n return `data-${this.identifier}-${dasherize(key)}`;\n }\n}\nclass Guide {\n constructor(logger) {\n this.warnedKeysByObject = new WeakMap();\n this.logger = logger;\n }\n warn(object, key, message) {\n let warnedKeys = this.warnedKeysByObject.get(object);\n if (!warnedKeys) {\n warnedKeys = new Set();\n this.warnedKeysByObject.set(object, warnedKeys);\n }\n if (!warnedKeys.has(key)) {\n warnedKeys.add(key);\n this.logger.warn(message, object);\n }\n }\n}\nfunction attributeValueContainsToken(attributeName, token) {\n return `[${attributeName}~=\"${token}\"]`;\n}\nclass TargetSet {\n constructor(scope) {\n this.scope = scope;\n }\n get element() {\n return this.scope.element;\n }\n get identifier() {\n return this.scope.identifier;\n }\n get schema() {\n return this.scope.schema;\n }\n has(targetName) {\n return this.find(targetName) != null;\n }\n find() {\n for (var _len2 = arguments.length, targetNames = new Array(_len2), _key3 = 0; _key3 < _len2; _key3++) {\n targetNames[_key3] = arguments[_key3];\n }\n return targetNames.reduce((target, targetName) => target || this.findTarget(targetName) || this.findLegacyTarget(targetName), undefined);\n }\n findAll() {\n for (var _len3 = arguments.length, targetNames = new Array(_len3), _key4 = 0; _key4 < _len3; _key4++) {\n targetNames[_key4] = arguments[_key4];\n }\n return targetNames.reduce((targets, targetName) => [...targets, ...this.findAllTargets(targetName), ...this.findAllLegacyTargets(targetName)], []);\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.identifier;\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}\". ` + `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}\nclass OutletSet {\n constructor(scope, controllerElement) {\n this.scope = scope;\n this.controllerElement = controllerElement;\n }\n get element() {\n return this.scope.element;\n }\n get identifier() {\n return this.scope.identifier;\n }\n get schema() {\n return this.scope.schema;\n }\n has(outletName) {\n return this.find(outletName) != null;\n }\n find() {\n for (var _len4 = arguments.length, outletNames = new Array(_len4), _key5 = 0; _key5 < _len4; _key5++) {\n outletNames[_key5] = arguments[_key5];\n }\n return outletNames.reduce((outlet, outletName) => outlet || this.findOutlet(outletName), undefined);\n }\n findAll() {\n for (var _len5 = arguments.length, outletNames = new Array(_len5), _key6 = 0; _key6 < _len5; _key6++) {\n outletNames[_key6] = arguments[_key6];\n }\n return outletNames.reduce((outlets, outletName) => [...outlets, ...this.findAllOutlets(outletName)], []);\n }\n getSelectorForOutletName(outletName) {\n const attributeName = this.schema.outletAttributeForScope(this.identifier, outletName);\n return this.controllerElement.getAttribute(attributeName);\n }\n findOutlet(outletName) {\n const selector = this.getSelectorForOutletName(outletName);\n if (selector) return this.findElement(selector, outletName);\n }\n findAllOutlets(outletName) {\n const selector = this.getSelectorForOutletName(outletName);\n return selector ? this.findAllElements(selector, outletName) : [];\n }\n findElement(selector, outletName) {\n const elements = this.scope.queryElements(selector);\n return elements.filter(element => this.matchesElement(element, selector, outletName))[0];\n }\n findAllElements(selector, outletName) {\n const elements = this.scope.queryElements(selector);\n return elements.filter(element => this.matchesElement(element, selector, outletName));\n }\n matchesElement(element, selector, outletName) {\n const controllerAttribute = element.getAttribute(this.scope.schema.controllerAttribute) || \"\";\n return element.matches(selector) && controllerAttribute.split(\" \").includes(outletName);\n }\n}\nclass Scope {\n constructor(schema, element, identifier, logger) {\n this.targets = new TargetSet(this);\n this.classes = new ClassMap(this);\n this.data = new DataMap(this);\n this.containsElement = element => {\n return element.closest(this.controllerSelector) === this.element;\n };\n this.schema = schema;\n this.element = element;\n this.identifier = identifier;\n this.guide = new Guide(logger);\n this.outlets = new OutletSet(this.documentScope, element);\n }\n findElement(selector) {\n return this.element.matches(selector) ? this.element : this.queryElements(selector).find(this.containsElement);\n }\n findAllElements(selector) {\n return [...(this.element.matches(selector) ? [this.element] : []), ...this.queryElements(selector).filter(this.containsElement)];\n }\n queryElements(selector) {\n return Array.from(this.element.querySelectorAll(selector));\n }\n get controllerSelector() {\n return attributeValueContainsToken(this.schema.controllerAttribute, this.identifier);\n }\n get isDocumentScope() {\n return this.element === document.documentElement;\n }\n get documentScope() {\n return this.isDocumentScope ? this : new Scope(this.schema, document.documentElement, this.identifier, this.guide.logger);\n }\n}\nclass ScopeObserver {\n constructor(element, schema, delegate) {\n this.element = element;\n this.schema = schema;\n this.delegate = delegate;\n this.valueListObserver = new ValueListObserver(this.element, this.controllerAttribute, this);\n this.scopesByIdentifierByElement = new WeakMap();\n this.scopeReferenceCounts = new WeakMap();\n }\n start() {\n this.valueListObserver.start();\n }\n stop() {\n this.valueListObserver.stop();\n }\n get controllerAttribute() {\n return this.schema.controllerAttribute;\n }\n parseValueForToken(token) {\n const element = token.element,\n identifier = token.content;\n return this.parseValueForElementAndIdentifier(element, identifier);\n }\n parseValueForElementAndIdentifier(element, identifier) {\n const scopesByIdentifier = this.fetchScopesByIdentifierForElement(element);\n let scope = scopesByIdentifier.get(identifier);\n if (!scope) {\n scope = this.delegate.createScopeForElementAndIdentifier(element, identifier);\n scopesByIdentifier.set(identifier, scope);\n }\n return scope;\n }\n elementMatchedValue(element, value) {\n const referenceCount = (this.scopeReferenceCounts.get(value) || 0) + 1;\n this.scopeReferenceCounts.set(value, referenceCount);\n if (referenceCount == 1) {\n this.delegate.scopeConnected(value);\n }\n }\n elementUnmatchedValue(element, value) {\n const referenceCount = this.scopeReferenceCounts.get(value);\n if (referenceCount) {\n this.scopeReferenceCounts.set(value, referenceCount - 1);\n if (referenceCount == 1) {\n this.delegate.scopeDisconnected(value);\n }\n }\n }\n fetchScopesByIdentifierForElement(element) {\n let scopesByIdentifier = this.scopesByIdentifierByElement.get(element);\n if (!scopesByIdentifier) {\n scopesByIdentifier = new Map();\n this.scopesByIdentifierByElement.set(element, scopesByIdentifier);\n }\n return scopesByIdentifier;\n }\n}\nclass Router {\n constructor(application) {\n this.application = application;\n this.scopeObserver = new ScopeObserver(this.element, this.schema, this);\n this.scopesByIdentifier = new Multimap();\n this.modulesByIdentifier = new Map();\n }\n get element() {\n return this.application.element;\n }\n get schema() {\n return this.application.schema;\n }\n get logger() {\n return this.application.logger;\n }\n get controllerAttribute() {\n return this.schema.controllerAttribute;\n }\n get modules() {\n return Array.from(this.modulesByIdentifier.values());\n }\n get contexts() {\n return this.modules.reduce((contexts, module) => contexts.concat(module.contexts), []);\n }\n start() {\n this.scopeObserver.start();\n }\n stop() {\n this.scopeObserver.stop();\n }\n loadDefinition(definition) {\n this.unloadIdentifier(definition.identifier);\n const module = new Module(this.application, definition);\n this.connectModule(module);\n const afterLoad = definition.controllerConstructor.afterLoad;\n if (afterLoad) {\n afterLoad.call(definition.controllerConstructor, definition.identifier, this.application);\n }\n }\n unloadIdentifier(identifier) {\n const module = this.modulesByIdentifier.get(identifier);\n if (module) {\n this.disconnectModule(module);\n }\n }\n getContextForElementAndIdentifier(element, identifier) {\n const module = this.modulesByIdentifier.get(identifier);\n if (module) {\n return module.contexts.find(context => context.element == element);\n }\n }\n proposeToConnectScopeForElementAndIdentifier(element, identifier) {\n const scope = this.scopeObserver.parseValueForElementAndIdentifier(element, identifier);\n if (scope) {\n this.scopeObserver.elementMatchedValue(scope.element, scope);\n } else {\n console.error(`Couldn't find or create scope for identifier: \"${identifier}\" and element:`, element);\n }\n }\n handleError(error, message, detail) {\n this.application.handleError(error, message, detail);\n }\n createScopeForElementAndIdentifier(element, identifier) {\n return new Scope(this.schema, element, identifier, this.logger);\n }\n scopeConnected(scope) {\n this.scopesByIdentifier.add(scope.identifier, scope);\n const module = this.modulesByIdentifier.get(scope.identifier);\n if (module) {\n module.connectContextForScope(scope);\n }\n }\n scopeDisconnected(scope) {\n this.scopesByIdentifier.delete(scope.identifier, scope);\n const module = this.modulesByIdentifier.get(scope.identifier);\n if (module) {\n module.disconnectContextForScope(scope);\n }\n }\n connectModule(module) {\n this.modulesByIdentifier.set(module.identifier, module);\n const scopes = this.scopesByIdentifier.getValuesForKey(module.identifier);\n scopes.forEach(scope => module.connectContextForScope(scope));\n }\n disconnectModule(module) {\n this.modulesByIdentifier.delete(module.identifier);\n const scopes = this.scopesByIdentifier.getValuesForKey(module.identifier);\n scopes.forEach(scope => module.disconnectContextForScope(scope));\n }\n}\nconst defaultSchema = {\n controllerAttribute: \"data-controller\",\n actionAttribute: \"data-action\",\n targetAttribute: \"data-target\",\n targetAttributeForScope: identifier => `data-${identifier}-target`,\n outletAttributeForScope: (identifier, outlet) => `data-${identifier}-${outlet}-outlet`,\n keyMappings: Object.assign(Object.assign({\n enter: \"Enter\",\n tab: \"Tab\",\n esc: \"Escape\",\n space: \" \",\n up: \"ArrowUp\",\n down: \"ArrowDown\",\n left: \"ArrowLeft\",\n right: \"ArrowRight\",\n home: \"Home\",\n end: \"End\",\n page_up: \"PageUp\",\n page_down: \"PageDown\"\n }, objectFromEntries(\"abcdefghijklmnopqrstuvwxyz\".split(\"\").map(c => [c, c]))), objectFromEntries(\"0123456789\".split(\"\").map(n => [n, n])))\n};\nfunction objectFromEntries(array) {\n return array.reduce((memo, _ref19) => {\n let _ref20 = _slicedToArray(_ref19, 2),\n k = _ref20[0],\n v = _ref20[1];\n return Object.assign(Object.assign({}, memo), {\n [k]: v\n });\n }, {});\n}\nclass Application {\n constructor() {\n var _this2 = this;\n let element = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : document.documentElement;\n let schema = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : defaultSchema;\n this.logger = console;\n this.debug = false;\n this.logDebugActivity = function (identifier, functionName) {\n let detail = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};\n if (_this2.debug) {\n _this2.logFormattedMessage(identifier, functionName, detail);\n }\n };\n this.element = element;\n this.schema = schema;\n this.dispatcher = new Dispatcher(this);\n this.router = new Router(this);\n this.actionDescriptorFilters = Object.assign({}, defaultActionDescriptorFilters);\n }\n static start(element, schema) {\n const application = new this(element, schema);\n application.start();\n return application;\n }\n async start() {\n await domReady();\n this.logDebugActivity(\"application\", \"starting\");\n this.dispatcher.start();\n this.router.start();\n this.logDebugActivity(\"application\", \"start\");\n }\n stop() {\n this.logDebugActivity(\"application\", \"stopping\");\n this.dispatcher.stop();\n this.router.stop();\n this.logDebugActivity(\"application\", \"stop\");\n }\n register(identifier, controllerConstructor) {\n this.load({\n identifier,\n controllerConstructor\n });\n }\n registerActionOption(name, filter) {\n this.actionDescriptorFilters[name] = filter;\n }\n load(head) {\n for (var _len6 = arguments.length, rest = new Array(_len6 > 1 ? _len6 - 1 : 0), _key7 = 1; _key7 < _len6; _key7++) {\n rest[_key7 - 1] = arguments[_key7];\n }\n const definitions = Array.isArray(head) ? head : [head, ...rest];\n definitions.forEach(definition => {\n if (definition.controllerConstructor.shouldLoad) {\n this.router.loadDefinition(definition);\n }\n });\n }\n unload(head) {\n for (var _len7 = arguments.length, rest = new Array(_len7 > 1 ? _len7 - 1 : 0), _key8 = 1; _key8 < _len7; _key8++) {\n rest[_key8 - 1] = arguments[_key8];\n }\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) {\n let detail = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};\n detail = Object.assign({\n application: this\n }, detail);\n this.logger.groupCollapsed(`${identifier} #${functionName}`);\n this.logger.log(\"details:\", Object.assign({}, detail));\n this.logger.groupEnd();\n }\n}\nfunction domReady() {\n return new Promise(resolve => {\n if (document.readyState == \"loading\") {\n document.addEventListener(\"DOMContentLoaded\", () => resolve());\n } else {\n resolve();\n }\n });\n}\nfunction ClassPropertiesBlessing(constructor) {\n const classes = readInheritableStaticArrayValues(constructor, \"classes\");\n return classes.reduce((properties, classDefinition) => {\n return Object.assign(properties, propertiesForClassDefinition(classDefinition));\n }, {});\n}\nfunction propertiesForClassDefinition(key) {\n return {\n [`${key}Class`]: {\n get() {\n const classes = this.classes;\n if (classes.has(key)) {\n return classes.get(key);\n } else {\n const attribute = classes.getAttributeName(key);\n throw new Error(`Missing attribute \"${attribute}\"`);\n }\n }\n },\n [`${key}Classes`]: {\n get() {\n return this.classes.getAll(key);\n }\n },\n [`has${capitalize(key)}Class`]: {\n get() {\n return this.classes.has(key);\n }\n }\n };\n}\nfunction OutletPropertiesBlessing(constructor) {\n const outlets = readInheritableStaticArrayValues(constructor, \"outlets\");\n return outlets.reduce((properties, outletDefinition) => {\n return Object.assign(properties, propertiesForOutletDefinition(outletDefinition));\n }, {});\n}\nfunction getOutletController(controller, element, identifier) {\n return controller.application.getControllerForElementAndIdentifier(element, identifier);\n}\nfunction getControllerAndEnsureConnectedScope(controller, element, outletName) {\n let outletController = getOutletController(controller, element, outletName);\n if (outletController) return outletController;\n controller.application.router.proposeToConnectScopeForElementAndIdentifier(element, outletName);\n outletController = getOutletController(controller, element, outletName);\n if (outletController) return outletController;\n}\nfunction propertiesForOutletDefinition(name) {\n const camelizedName = namespaceCamelize(name);\n return {\n [`${camelizedName}Outlet`]: {\n get() {\n const outletElement = this.outlets.find(name);\n const selector = this.outlets.getSelectorForOutletName(name);\n if (outletElement) {\n const outletController = getControllerAndEnsureConnectedScope(this, outletElement, name);\n if (outletController) return outletController;\n throw new Error(`The provided outlet element is missing an outlet controller \"${name}\" instance for host controller \"${this.identifier}\"`);\n }\n throw new Error(`Missing outlet element \"${name}\" for host controller \"${this.identifier}\". Stimulus couldn't find a matching outlet element using selector \"${selector}\".`);\n }\n },\n [`${camelizedName}Outlets`]: {\n get() {\n const outlets = this.outlets.findAll(name);\n if (outlets.length > 0) {\n return outlets.map(outletElement => {\n const outletController = getControllerAndEnsureConnectedScope(this, outletElement, name);\n if (outletController) return outletController;\n console.warn(`The provided outlet element is missing an outlet controller \"${name}\" instance for host controller \"${this.identifier}\"`, outletElement);\n }).filter(controller => controller);\n }\n return [];\n }\n },\n [`${camelizedName}OutletElement`]: {\n get() {\n const outletElement = this.outlets.find(name);\n const selector = this.outlets.getSelectorForOutletName(name);\n if (outletElement) {\n return outletElement;\n } else {\n throw new Error(`Missing outlet element \"${name}\" for host controller \"${this.identifier}\". Stimulus couldn't find a matching outlet element using selector \"${selector}\".`);\n }\n }\n },\n [`${camelizedName}OutletElements`]: {\n get() {\n return this.outlets.findAll(name);\n }\n },\n [`has${capitalize(camelizedName)}Outlet`]: {\n get() {\n return this.outlets.has(name);\n }\n }\n };\n}\nfunction TargetPropertiesBlessing(constructor) {\n const targets = readInheritableStaticArrayValues(constructor, \"targets\");\n return targets.reduce((properties, targetDefinition) => {\n return Object.assign(properties, propertiesForTargetDefinition(targetDefinition));\n }, {});\n}\nfunction propertiesForTargetDefinition(name) {\n return {\n [`${name}Target`]: {\n get() {\n const target = this.targets.find(name);\n if (target) {\n return target;\n } else {\n throw new Error(`Missing target element \"${name}\" for \"${this.identifier}\" controller`);\n }\n }\n },\n [`${name}Targets`]: {\n get() {\n return this.targets.findAll(name);\n }\n },\n [`has${capitalize(name)}Target`]: {\n get() {\n return this.targets.has(name);\n }\n }\n };\n}\nfunction ValuePropertiesBlessing(constructor) {\n const valueDefinitionPairs = readInheritableStaticObjectPairs(constructor, \"values\");\n const propertyDescriptorMap = {\n valueDescriptorMap: {\n get() {\n return valueDefinitionPairs.reduce((result, valueDefinitionPair) => {\n const valueDescriptor = parseValueDefinitionPair(valueDefinitionPair, this.identifier);\n const attributeName = this.data.getAttributeNameForKey(valueDescriptor.key);\n return Object.assign(result, {\n [attributeName]: valueDescriptor\n });\n }, {});\n }\n }\n };\n return valueDefinitionPairs.reduce((properties, valueDefinitionPair) => {\n return Object.assign(properties, propertiesForValueDefinitionPair(valueDefinitionPair));\n }, propertyDescriptorMap);\n}\nfunction propertiesForValueDefinitionPair(valueDefinitionPair, controller) {\n const definition = parseValueDefinitionPair(valueDefinitionPair, controller);\n const key = definition.key,\n name = definition.name,\n read = definition.reader,\n write = definition.writer;\n return {\n [name]: {\n get() {\n const value = this.data.get(key);\n if (value !== null) {\n return read(value);\n } else {\n return definition.defaultValue;\n }\n },\n set(value) {\n if (value === undefined) {\n this.data.delete(key);\n } else {\n this.data.set(key, write(value));\n }\n }\n },\n [`has${capitalize(name)}`]: {\n get() {\n return this.data.has(key) || definition.hasCustomDefaultValue;\n }\n }\n };\n}\nfunction parseValueDefinitionPair(_ref21, controller) {\n let _ref22 = _slicedToArray(_ref21, 2),\n token = _ref22[0],\n typeDefinition = _ref22[1];\n return valueDescriptorForTokenAndTypeDefinition({\n controller,\n token,\n typeDefinition\n });\n}\nfunction parseValueTypeConstant(constant) {\n switch (constant) {\n case Array:\n return \"array\";\n case Boolean:\n return \"boolean\";\n case Number:\n return \"number\";\n case Object:\n return \"object\";\n case String:\n return \"string\";\n }\n}\nfunction parseValueTypeDefault(defaultValue) {\n switch (typeof defaultValue) {\n case \"boolean\":\n return \"boolean\";\n case \"number\":\n return \"number\";\n case \"string\":\n return \"string\";\n }\n if (Array.isArray(defaultValue)) return \"array\";\n if (Object.prototype.toString.call(defaultValue) === \"[object Object]\") return \"object\";\n}\nfunction parseValueTypeObject(payload) {\n const controller = payload.controller,\n token = payload.token,\n typeObject = payload.typeObject;\n const hasType = isSomething(typeObject.type);\n const hasDefault = isSomething(typeObject.default);\n const fullObject = hasType && hasDefault;\n const onlyType = hasType && !hasDefault;\n const onlyDefault = !hasType && hasDefault;\n const typeFromObject = parseValueTypeConstant(typeObject.type);\n const typeFromDefaultValue = parseValueTypeDefault(payload.typeObject.default);\n if (onlyType) return typeFromObject;\n if (onlyDefault) return typeFromDefaultValue;\n if (typeFromObject !== typeFromDefaultValue) {\n const propertyPath = controller ? `${controller}.${token}` : token;\n throw new Error(`The specified default value for the Stimulus Value \"${propertyPath}\" must match the defined type \"${typeFromObject}\". The provided default value of \"${typeObject.default}\" is of type \"${typeFromDefaultValue}\".`);\n }\n if (fullObject) return typeFromObject;\n}\nfunction parseValueTypeDefinition(payload) {\n const controller = payload.controller,\n token = payload.token,\n typeDefinition = payload.typeDefinition;\n const typeObject = {\n controller,\n token,\n typeObject: typeDefinition\n };\n const typeFromObject = parseValueTypeObject(typeObject);\n const typeFromDefaultValue = parseValueTypeDefault(typeDefinition);\n const typeFromConstant = parseValueTypeConstant(typeDefinition);\n const type = typeFromObject || typeFromDefaultValue || typeFromConstant;\n if (type) return type;\n const propertyPath = controller ? `${controller}.${typeDefinition}` : token;\n throw new Error(`Unknown value type \"${propertyPath}\" for \"${token}\" value`);\n}\nfunction defaultValueForDefinition(typeDefinition) {\n const constant = parseValueTypeConstant(typeDefinition);\n if (constant) return defaultValuesByType[constant];\n const hasDefault = hasProperty(typeDefinition, \"default\");\n const hasType = hasProperty(typeDefinition, \"type\");\n const typeObject = typeDefinition;\n if (hasDefault) return typeObject.default;\n if (hasType) {\n const type = typeObject.type;\n const constantFromType = parseValueTypeConstant(type);\n if (constantFromType) return defaultValuesByType[constantFromType];\n }\n return typeDefinition;\n}\nfunction valueDescriptorForTokenAndTypeDefinition(payload) {\n const token = payload.token,\n typeDefinition = payload.typeDefinition;\n const key = `${dasherize(token)}-value`;\n const type = parseValueTypeDefinition(payload);\n return {\n type,\n key,\n name: camelize(key),\n get defaultValue() {\n return defaultValueForDefinition(typeDefinition);\n },\n get hasCustomDefaultValue() {\n return parseValueTypeDefault(typeDefinition) !== undefined;\n },\n reader: readers[type],\n writer: writers[type] || writers.default\n };\n}\nconst defaultValuesByType = {\n get array() {\n return [];\n },\n boolean: false,\n number: 0,\n get object() {\n return {};\n },\n string: \"\"\n};\nconst readers = {\n array(value) {\n const array = JSON.parse(value);\n if (!Array.isArray(array)) {\n throw new TypeError(`expected value of type \"array\" but instead got value \"${value}\" of type \"${parseValueTypeDefault(array)}\"`);\n }\n return array;\n },\n boolean(value) {\n return !(value == \"0\" || String(value).toLowerCase() == \"false\");\n },\n number(value) {\n return Number(value.replace(/_/g, \"\"));\n },\n object(value) {\n const object = JSON.parse(value);\n if (object === null || typeof object != \"object\" || Array.isArray(object)) {\n throw new TypeError(`expected value of type \"object\" but instead got value \"${value}\" of type \"${parseValueTypeDefault(object)}\"`);\n }\n return object;\n },\n string(value) {\n return value;\n }\n};\nconst writers = {\n default: writeString,\n array: writeJSON,\n object: writeJSON\n};\nfunction writeJSON(value) {\n return JSON.stringify(value);\n}\nfunction writeString(value) {\n return `${value}`;\n}\nclass Controller {\n constructor(context) {\n this.context = context;\n }\n static get shouldLoad() {\n return true;\n }\n static afterLoad(_identifier, _application) {\n return;\n }\n get application() {\n return this.context.application;\n }\n get scope() {\n return this.context.scope;\n }\n get element() {\n return this.scope.element;\n }\n get identifier() {\n return this.scope.identifier;\n }\n get targets() {\n return this.scope.targets;\n }\n get outlets() {\n return this.scope.outlets;\n }\n get classes() {\n return this.scope.classes;\n }\n get data() {\n return this.scope.data;\n }\n initialize() {}\n connect() {}\n disconnect() {}\n dispatch(eventName) {\n let _ref23 = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {},\n _ref23$target = _ref23.target,\n target = _ref23$target === void 0 ? this.element : _ref23$target,\n _ref23$detail = _ref23.detail,\n detail = _ref23$detail === void 0 ? {} : _ref23$detail,\n _ref23$prefix = _ref23.prefix,\n prefix = _ref23$prefix === void 0 ? this.identifier : _ref23$prefix,\n _ref23$bubbles = _ref23.bubbles,\n bubbles = _ref23$bubbles === void 0 ? true : _ref23$bubbles,\n _ref23$cancelable = _ref23.cancelable,\n cancelable = _ref23$cancelable === void 0 ? true : _ref23$cancelable;\n const type = prefix ? `${prefix}:${eventName}` : eventName;\n const event = new CustomEvent(type, {\n detail,\n bubbles,\n cancelable\n });\n target.dispatchEvent(event);\n return event;\n }\n}\nController.blessings = [ClassPropertiesBlessing, TargetPropertiesBlessing, ValuePropertiesBlessing, OutletPropertiesBlessing];\nController.targets = [];\nController.outlets = [];\nController.values = {};\nexport { Application, AttributeObserver, Context, Controller, ElementObserver, IndexedMultimap, Multimap, SelectorObserver, StringMapObserver, TokenListObserver, ValueListObserver, add, defaultSchema, del, fetch, prune };","function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); }\nfunction _nonIterableRest() { throw new TypeError(\"Invalid attempt to destructure non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.\"); }\nfunction _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === \"string\") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === \"Object\" && o.constructor) n = o.constructor.name; if (n === \"Map\" || n === \"Set\") return Array.from(o); if (n === \"Arguments\" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }\nfunction _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; return arr2; }\nfunction _iterableToArrayLimit(r, l) { var t = null == r ? null : \"undefined\" != typeof Symbol && r[Symbol.iterator] || r[\"@@iterator\"]; if (null != t) { var e, n, i, u, a = [], f = !0, o = !1; try { if (i = (t = t.call(r)).next, 0 === l) { if (Object(t) !== t) return; f = !1; } else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0); } catch (r) { o = !0, n = r; } finally { try { if (!f && null != t.return && (u = t.return(), Object(u) !== u)) return; } finally { if (o) throw n; } } return a; } }\nfunction _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }\n/*\nStimulus 3.2.1\nCopyright © 2023 Basecamp, LLC\n */\n(function (global, factory) {\n typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) : typeof define === 'function' && define.amd ? define(['exports'], factory) : (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.Stimulus = {}));\n})(this, function (exports) {\n '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 } else {\n binding.handleEvent(extendedEvent);\n }\n }\n }\n hasBindings() {\n return this.unorderedBindings.size > 0;\n }\n get bindings() {\n return Array.from(this.unorderedBindings).sort((left, right) => {\n const leftIndex = left.index,\n 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 } else {\n const stopImmediatePropagation = event.stopImmediatePropagation;\n return Object.assign(event, {\n immediatePropagationStopped: false,\n stopImmediatePropagation() {\n this.immediatePropagationStopped = true;\n stopImmediatePropagation.call(this);\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()).reduce((listeners, map) => listeners.concat(Array.from(map.values())), []);\n }\n bindingConnected(binding) {\n this.fetchEventListenerForBinding(binding).bindingConnected(binding);\n }\n bindingDisconnected(binding) {\n let clearEventListeners = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;\n this.fetchEventListenerForBinding(binding).bindingDisconnected(binding);\n if (clearEventListeners) this.clearEventListenersForBinding(binding);\n }\n handleError(error, message) {\n let detail = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};\n this.application.handleError(error, `Error ${message}`, detail);\n }\n clearEventListenersForBinding(binding) {\n const eventListener = this.fetchEventListenerForBinding(binding);\n if (!eventListener.hasBindings()) {\n eventListener.disconnect();\n this.removeMappedEventListenerFor(binding);\n }\n }\n removeMappedEventListenerFor(binding) {\n const eventTarget = binding.eventTarget,\n eventName = binding.eventName,\n eventOptions = binding.eventOptions;\n const eventListenerMap = this.fetchEventListenerMapForEventTarget(eventTarget);\n const cacheKey = this.cacheKey(eventName, eventOptions);\n eventListenerMap.delete(cacheKey);\n if (eventListenerMap.size == 0) this.eventListenerMaps.delete(eventTarget);\n }\n fetchEventListenerForBinding(binding) {\n const eventTarget = binding.eventTarget,\n eventName = binding.eventName,\n eventOptions = binding.eventOptions;\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 const defaultActionDescriptorFilters = {\n stop(_ref) {\n let event = _ref.event,\n value = _ref.value;\n if (value) event.stopPropagation();\n return true;\n },\n prevent(_ref2) {\n let event = _ref2.event,\n value = _ref2.value;\n if (value) event.preventDefault();\n return true;\n },\n self(_ref3) {\n let event = _ref3.event,\n value = _ref3.value,\n element = _ref3.element;\n if (value) {\n return element === event.target;\n } else {\n return true;\n }\n }\n };\n const descriptorPattern = /^(?:(?:([^.]+?)\\+)?(.+?)(?:\\.(.+?))?(?:@(window|document))?->)?(.+?)(?:#([^:]+?))(?::(.+))?$/;\n function parseActionDescriptorString(descriptorString) {\n const source = descriptorString.trim();\n const matches = source.match(descriptorPattern) || [];\n let eventName = matches[2];\n let keyFilter = matches[3];\n if (keyFilter && ![\"keydown\", \"keyup\", \"keypress\"].includes(eventName)) {\n eventName += `.${keyFilter}`;\n keyFilter = \"\";\n }\n return {\n eventTarget: parseEventTarget(matches[4]),\n eventName,\n eventOptions: matches[7] ? parseEventOptions(matches[7]) : {},\n identifier: matches[5],\n methodName: matches[6],\n keyFilter: matches[1] || keyFilter\n };\n }\n function parseEventTarget(eventTargetName) {\n if (eventTargetName == \"window\") {\n return window;\n } else if (eventTargetName == \"document\") {\n return document;\n }\n }\n function parseEventOptions(eventOptions) {\n return eventOptions.split(\":\").reduce((options, token) => Object.assign(options, {\n [token.replace(/^!/, \"\")]: !/^!/.test(token)\n }), {});\n }\n function stringifyEventTarget(eventTarget) {\n if (eventTarget == window) {\n return \"window\";\n } else if (eventTarget == document) {\n return \"document\";\n }\n }\n function camelize(value) {\n return value.replace(/(?:[_-])([a-z0-9])/g, (_, char) => char.toUpperCase());\n }\n function namespaceCamelize(value) {\n return camelize(value.replace(/--/g, \"-\").replace(/__/g, \"_\"));\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 function isSomething(object) {\n return object !== null && object !== undefined;\n }\n function hasProperty(object, property) {\n return Object.prototype.hasOwnProperty.call(object, property);\n }\n const allModifiers = [\"meta\", \"ctrl\", \"alt\", \"shift\"];\n class Action {\n constructor(element, index, descriptor, schema) {\n this.element = element;\n this.index = index;\n this.eventTarget = descriptor.eventTarget || element;\n this.eventName = descriptor.eventName || getDefaultEventNameForElement(element) || error(\"missing event name\");\n this.eventOptions = descriptor.eventOptions || {};\n this.identifier = descriptor.identifier || error(\"missing identifier\");\n this.methodName = descriptor.methodName || error(\"missing method name\");\n this.keyFilter = descriptor.keyFilter || \"\";\n this.schema = schema;\n }\n static forToken(token, schema) {\n return new this(token.element, token.index, parseActionDescriptorString(token.content), schema);\n }\n toString() {\n const eventFilter = this.keyFilter ? `.${this.keyFilter}` : \"\";\n const eventTarget = this.eventTargetName ? `@${this.eventTargetName}` : \"\";\n return `${this.eventName}${eventFilter}${eventTarget}->${this.identifier}#${this.methodName}`;\n }\n shouldIgnoreKeyboardEvent(event) {\n if (!this.keyFilter) {\n return false;\n }\n const filters = this.keyFilter.split(\"+\");\n if (this.keyFilterDissatisfied(event, filters)) {\n return true;\n }\n const standardFilter = filters.filter(key => !allModifiers.includes(key))[0];\n if (!standardFilter) {\n return false;\n }\n if (!hasProperty(this.keyMappings, standardFilter)) {\n error(`contains unknown key filter: ${this.keyFilter}`);\n }\n return this.keyMappings[standardFilter].toLowerCase() !== event.key.toLowerCase();\n }\n shouldIgnoreMouseEvent(event) {\n if (!this.keyFilter) {\n return false;\n }\n const filters = [this.keyFilter];\n if (this.keyFilterDissatisfied(event, filters)) {\n return true;\n }\n return false;\n }\n get params() {\n const params = {};\n const pattern = new RegExp(`^data-${this.identifier}-(.+)-param$`, \"i\");\n for (const _ref4 of Array.from(this.element.attributes)) {\n const name = _ref4.name;\n const value = _ref4.value;\n const match = name.match(pattern);\n const key = match && match[1];\n if (key) {\n params[camelize(key)] = typecast(value);\n }\n }\n return params;\n }\n get eventTargetName() {\n return stringifyEventTarget(this.eventTarget);\n }\n get keyMappings() {\n return this.schema.keyMappings;\n }\n keyFilterDissatisfied(event, filters) {\n const _allModifiers$map = allModifiers.map(modifier => filters.includes(modifier)),\n _allModifiers$map2 = _slicedToArray(_allModifiers$map, 4),\n meta = _allModifiers$map2[0],\n ctrl = _allModifiers$map2[1],\n alt = _allModifiers$map2[2],\n shift = _allModifiers$map2[3];\n return event.metaKey !== meta || event.ctrlKey !== ctrl || event.altKey !== alt || event.shiftKey !== shift;\n }\n }\n const defaultEventNames = {\n a: () => \"click\",\n button: () => \"click\",\n form: () => \"submit\",\n details: () => \"toggle\",\n input: e => e.getAttribute(\"type\") == \"submit\" ? \"click\" : \"input\",\n select: () => \"change\",\n textarea: () => \"input\"\n };\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 } catch (o_O) {\n return value;\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 const actionEvent = this.prepareActionEvent(event);\n if (this.willBeInvokedByEvent(event) && this.applyEventModifiers(actionEvent)) {\n this.invokeWithEvent(actionEvent);\n }\n }\n get eventName() {\n return this.action.eventName;\n }\n get method() {\n const method = this.controller[this.methodName];\n if (typeof method == \"function\") {\n return method;\n }\n throw new Error(`Action \"${this.action}\" references undefined method \"${this.methodName}\"`);\n }\n applyEventModifiers(event) {\n const element = this.action.element;\n const actionDescriptorFilters = this.context.application.actionDescriptorFilters;\n const controller = this.context.controller;\n let passes = true;\n for (const _ref5 of Object.entries(this.eventOptions)) {\n var _ref6 = _slicedToArray(_ref5, 2);\n const name = _ref6[0];\n const value = _ref6[1];\n if (name in actionDescriptorFilters) {\n const filter = actionDescriptorFilters[name];\n passes = passes && filter({\n name,\n value,\n event,\n element,\n controller\n });\n } else {\n continue;\n }\n }\n return passes;\n }\n prepareActionEvent(event) {\n return Object.assign(event, {\n params: this.action.params\n });\n }\n invokeWithEvent(event) {\n const target = event.target,\n currentTarget = event.currentTarget;\n try {\n this.method.call(this.controller, event);\n this.context.logDebugActivity(this.methodName, {\n event,\n target,\n currentTarget,\n action: this.methodName\n });\n } catch (error) {\n const identifier = this.identifier,\n controller = this.controller,\n element = this.element,\n index = this.index;\n const detail = {\n identifier,\n controller,\n element,\n index,\n event\n };\n this.context.handleError(error, `invoking action \"${this.action}\"`, detail);\n }\n }\n willBeInvokedByEvent(event) {\n const eventTarget = event.target;\n if (event instanceof KeyboardEvent && this.action.shouldIgnoreKeyboardEvent(event)) {\n return false;\n }\n if (event instanceof MouseEvent && this.action.shouldIgnoreMouseEvent(event)) {\n return false;\n }\n if (this.element === eventTarget) {\n return true;\n } else if (eventTarget instanceof Element && this.element.contains(eventTarget)) {\n return this.scope.containsElement(eventTarget);\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 class ElementObserver {\n constructor(element, delegate) {\n this.mutationObserverInit = {\n attributes: true,\n childList: true,\n subtree: true\n };\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 } else if (mutation.type == \"childList\") {\n this.processRemovedNodes(mutation.removedNodes);\n this.processAddedNodes(mutation.addedNodes);\n }\n }\n processAttributeChange(element, attributeName) {\n if (this.elements.has(element)) {\n if (this.delegate.elementAttributeChanged && this.matchElement(element)) {\n this.delegate.elementAttributeChanged(element, attributeName);\n } else {\n this.removeElement(element);\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() {\n let tree = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 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 } 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 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 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 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).filter(_ref7 => {\n let _ref8 = _slicedToArray(_ref7, 2),\n _key = _ref8[0],\n values = _ref8[1];\n return values.has(value);\n }).map(_ref9 => {\n let _ref10 = _slicedToArray(_ref9, 2),\n key = _ref10[0],\n _values = _ref10[1];\n return 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 class SelectorObserver {\n constructor(element, selector, delegate, details) {\n this._selector = selector;\n this.details = details;\n this.elementObserver = new ElementObserver(element, this);\n this.delegate = delegate;\n this.matchesByElement = new Multimap();\n }\n get started() {\n return this.elementObserver.started;\n }\n get selector() {\n return this._selector;\n }\n set selector(selector) {\n this._selector = selector;\n this.refresh();\n }\n start() {\n this.elementObserver.start();\n }\n pause(callback) {\n this.elementObserver.pause(callback);\n }\n stop() {\n this.elementObserver.stop();\n }\n refresh() {\n this.elementObserver.refresh();\n }\n get element() {\n return this.elementObserver.element;\n }\n matchElement(element) {\n const selector = this.selector;\n if (selector) {\n const matches = element.matches(selector);\n if (this.delegate.selectorMatchElement) {\n return matches && this.delegate.selectorMatchElement(element, this.details);\n }\n return matches;\n } else {\n return false;\n }\n }\n matchElementsInTree(tree) {\n const selector = this.selector;\n if (selector) {\n const match = this.matchElement(tree) ? [tree] : [];\n const matches = Array.from(tree.querySelectorAll(selector)).filter(match => this.matchElement(match));\n return match.concat(matches);\n } else {\n return [];\n }\n }\n elementMatched(element) {\n const selector = this.selector;\n if (selector) {\n this.selectorMatched(element, selector);\n }\n }\n elementUnmatched(element) {\n const selectors = this.matchesByElement.getKeysForValue(element);\n for (const selector of selectors) {\n this.selectorUnmatched(element, selector);\n }\n }\n elementAttributeChanged(element, _attributeName) {\n const selector = this.selector;\n if (selector) {\n const matches = this.matchElement(element);\n const matchedBefore = this.matchesByElement.has(selector, element);\n if (matches && !matchedBefore) {\n this.selectorMatched(element, selector);\n } else if (!matches && matchedBefore) {\n this.selectorUnmatched(element, selector);\n }\n }\n }\n selectorMatched(element, selector) {\n this.delegate.selectorMatched(element, selector, this.details);\n this.matchesByElement.add(selector, element);\n }\n selectorUnmatched(element, selector) {\n this.delegate.selectorUnmatched(element, selector, this.details);\n this.matchesByElement.delete(selector, element);\n }\n }\n 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, {\n attributes: true,\n attributeOldValue: true\n });\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) this.stringMapKeyRemoved(key, attributeName, oldValue);\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 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 _this$refreshTokensFo = this.refreshTokensForElement(element),\n _this$refreshTokensFo2 = _slicedToArray(_this$refreshTokensFo, 2),\n unmatchedTokens = _this$refreshTokensFo2[0],\n matchedTokens = _this$refreshTokensFo2[1];\n this.tokensUnmatched(unmatchedTokens);\n this.tokensMatched(matchedTokens);\n }\n elementUnmatchedAttribute(element) {\n this.tokensUnmatched(this.tokensByElement.getValuesForKey(element));\n }\n tokensMatched(tokens) {\n tokens.forEach(token => this.tokenMatched(token));\n }\n tokensUnmatched(tokens) {\n tokens.forEach(token => this.tokenUnmatched(token));\n }\n tokenMatched(token) {\n this.delegate.tokenMatched(token);\n this.tokensByElement.add(token.element, token);\n }\n tokenUnmatched(token) {\n this.delegate.tokenUnmatched(token);\n this.tokensByElement.delete(token.element, token);\n }\n refreshTokensForElement(element) {\n const previousTokens = this.tokensByElement.getValuesForKey(element);\n const currentTokens = this.readTokensForElement(element);\n const firstDifferingIndex = zip(previousTokens, currentTokens).findIndex(_ref11 => {\n let _ref12 = _slicedToArray(_ref11, 2),\n previousToken = _ref12[0],\n currentToken = _ref12[1];\n return !tokensAreEqual(previousToken, currentToken);\n });\n if (firstDifferingIndex == -1) {\n return [[], []];\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).map((content, index) => ({\n element,\n attributeName,\n content,\n index\n }));\n }\n function zip(left, right) {\n const length = Math.max(left.length, right.length);\n return Array.from({\n length\n }, (_, 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 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.element;\n const _this$fetchParseResul = this.fetchParseResultForToken(token),\n value = _this$fetchParseResul.value;\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.element;\n const _this$fetchParseResul2 = this.fetchParseResultForToken(token),\n value = _this$fetchParseResul2.value;\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 {\n value\n };\n } catch (error) {\n return {\n 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, true));\n this.bindingsByAction.clear();\n }\n parseValueForToken(token) {\n const action = Action.forToken(token, this.schema);\n if (action.identifier == this.identifier) {\n return action;\n }\n }\n elementMatchedValue(element, action) {\n this.connectAction(action);\n }\n elementUnmatchedValue(element, action) {\n this.disconnectAction(action);\n }\n }\n 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 }\n start() {\n this.stringMapObserver.start();\n this.invokeChangedCallbacksForDefaultValues();\n }\n stop() {\n this.stringMapObserver.stop();\n }\n get element() {\n return this.context.element;\n }\n get controller() {\n return this.context.controller;\n }\n getStringMapKeyForAttribute(attributeName) {\n if (attributeName in this.valueDescriptorMap) {\n return this.valueDescriptorMap[attributeName].name;\n }\n }\n stringMapKeyAdded(key, attributeName) {\n const descriptor = this.valueDescriptorMap[attributeName];\n if (!this.hasValue(key)) {\n this.invokeChangedCallback(key, descriptor.writer(this.receiver[key]), descriptor.writer(descriptor.defaultValue));\n }\n }\n stringMapValueChanged(value, name, oldValue) {\n const descriptor = this.valueDescriptorNameMap[name];\n if (value === null) 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 } else {\n this.invokeChangedCallback(key, descriptor.writer(descriptor.defaultValue), oldValue);\n }\n }\n invokeChangedCallbacksForDefaultValues() {\n for (const _ref13 of this.valueDescriptors) {\n const key = _ref13.key;\n const name = _ref13.name;\n const defaultValue = _ref13.defaultValue;\n const writer = _ref13.writer;\n if (defaultValue != undefined && !this.controller.data.has(key)) {\n this.invokeChangedCallback(name, writer(defaultValue), undefined);\n }\n }\n }\n invokeChangedCallback(name, rawValue, rawOldValue) {\n const changedMethodName = `${name}Changed`;\n const changedMethod = this.receiver[changedMethodName];\n if (typeof changedMethod == \"function\") {\n const descriptor = this.valueDescriptorNameMap[name];\n try {\n const value = descriptor.reader(rawValue);\n let oldValue = rawOldValue;\n if (rawOldValue) {\n oldValue = descriptor.reader(rawOldValue);\n }\n changedMethod.call(this.receiver, value, oldValue);\n } catch (error) {\n if (error instanceof TypeError) {\n error.message = `Stimulus Value \"${this.context.identifier}.${descriptor.name}\" - ${error.message}`;\n }\n throw error;\n }\n }\n }\n get valueDescriptors() {\n const valueDescriptorMap = this.valueDescriptorMap;\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 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(_ref14) {\n let element = _ref14.element,\n name = _ref14.content;\n if (this.scope.containsElement(element)) {\n this.connectTarget(element, name);\n }\n }\n tokenUnmatched(_ref15) {\n let element = _ref15.element,\n name = _ref15.content;\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 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 class OutletObserver {\n constructor(context, delegate) {\n this.started = false;\n this.context = context;\n this.delegate = delegate;\n this.outletsByName = new Multimap();\n this.outletElementsByName = new Multimap();\n this.selectorObserverMap = new Map();\n this.attributeObserverMap = new Map();\n }\n start() {\n if (!this.started) {\n this.outletDefinitions.forEach(outletName => {\n this.setupSelectorObserverForOutlet(outletName);\n this.setupAttributeObserverForOutlet(outletName);\n });\n this.started = true;\n this.dependentContexts.forEach(context => context.refresh());\n }\n }\n refresh() {\n this.selectorObserverMap.forEach(observer => observer.refresh());\n this.attributeObserverMap.forEach(observer => observer.refresh());\n }\n stop() {\n if (this.started) {\n this.started = false;\n this.disconnectAllOutlets();\n this.stopSelectorObservers();\n this.stopAttributeObservers();\n }\n }\n stopSelectorObservers() {\n if (this.selectorObserverMap.size > 0) {\n this.selectorObserverMap.forEach(observer => observer.stop());\n this.selectorObserverMap.clear();\n }\n }\n stopAttributeObservers() {\n if (this.attributeObserverMap.size > 0) {\n this.attributeObserverMap.forEach(observer => observer.stop());\n this.attributeObserverMap.clear();\n }\n }\n selectorMatched(element, _selector, _ref16) {\n let outletName = _ref16.outletName;\n const outlet = this.getOutlet(element, outletName);\n if (outlet) {\n this.connectOutlet(outlet, element, outletName);\n }\n }\n selectorUnmatched(element, _selector, _ref17) {\n let outletName = _ref17.outletName;\n const outlet = this.getOutletFromMap(element, outletName);\n if (outlet) {\n this.disconnectOutlet(outlet, element, outletName);\n }\n }\n selectorMatchElement(element, _ref18) {\n let outletName = _ref18.outletName;\n const selector = this.selector(outletName);\n const hasOutlet = this.hasOutlet(element, outletName);\n const hasOutletController = element.matches(`[${this.schema.controllerAttribute}~=${outletName}]`);\n if (selector) {\n return hasOutlet && hasOutletController && element.matches(selector);\n } else {\n return false;\n }\n }\n elementMatchedAttribute(_element, attributeName) {\n const outletName = this.getOutletNameFromOutletAttributeName(attributeName);\n if (outletName) {\n this.updateSelectorObserverForOutlet(outletName);\n }\n }\n elementAttributeValueChanged(_element, attributeName) {\n const outletName = this.getOutletNameFromOutletAttributeName(attributeName);\n if (outletName) {\n this.updateSelectorObserverForOutlet(outletName);\n }\n }\n elementUnmatchedAttribute(_element, attributeName) {\n const outletName = this.getOutletNameFromOutletAttributeName(attributeName);\n if (outletName) {\n this.updateSelectorObserverForOutlet(outletName);\n }\n }\n connectOutlet(outlet, element, outletName) {\n var _a;\n if (!this.outletElementsByName.has(outletName, element)) {\n this.outletsByName.add(outletName, outlet);\n this.outletElementsByName.add(outletName, element);\n (_a = this.selectorObserverMap.get(outletName)) === null || _a === void 0 ? void 0 : _a.pause(() => this.delegate.outletConnected(outlet, element, outletName));\n }\n }\n disconnectOutlet(outlet, element, outletName) {\n var _a;\n if (this.outletElementsByName.has(outletName, element)) {\n this.outletsByName.delete(outletName, outlet);\n this.outletElementsByName.delete(outletName, element);\n (_a = this.selectorObserverMap.get(outletName)) === null || _a === void 0 ? void 0 : _a.pause(() => this.delegate.outletDisconnected(outlet, element, outletName));\n }\n }\n disconnectAllOutlets() {\n for (const outletName of this.outletElementsByName.keys) {\n for (const element of this.outletElementsByName.getValuesForKey(outletName)) {\n for (const outlet of this.outletsByName.getValuesForKey(outletName)) {\n this.disconnectOutlet(outlet, element, outletName);\n }\n }\n }\n }\n updateSelectorObserverForOutlet(outletName) {\n const observer = this.selectorObserverMap.get(outletName);\n if (observer) {\n observer.selector = this.selector(outletName);\n }\n }\n setupSelectorObserverForOutlet(outletName) {\n const selector = this.selector(outletName);\n const selectorObserver = new SelectorObserver(document.body, selector, this, {\n outletName\n });\n this.selectorObserverMap.set(outletName, selectorObserver);\n selectorObserver.start();\n }\n setupAttributeObserverForOutlet(outletName) {\n const attributeName = this.attributeNameForOutletName(outletName);\n const attributeObserver = new AttributeObserver(this.scope.element, attributeName, this);\n this.attributeObserverMap.set(outletName, attributeObserver);\n attributeObserver.start();\n }\n selector(outletName) {\n return this.scope.outlets.getSelectorForOutletName(outletName);\n }\n attributeNameForOutletName(outletName) {\n return this.scope.schema.outletAttributeForScope(this.identifier, outletName);\n }\n getOutletNameFromOutletAttributeName(attributeName) {\n return this.outletDefinitions.find(outletName => this.attributeNameForOutletName(outletName) === attributeName);\n }\n get outletDependencies() {\n const dependencies = new Multimap();\n this.router.modules.forEach(module => {\n const constructor = module.definition.controllerConstructor;\n const outlets = readInheritableStaticArrayValues(constructor, \"outlets\");\n outlets.forEach(outlet => dependencies.add(outlet, module.identifier));\n });\n return dependencies;\n }\n get outletDefinitions() {\n return this.outletDependencies.getKeysForValue(this.identifier);\n }\n get dependentControllerIdentifiers() {\n return this.outletDependencies.getValuesForKey(this.identifier);\n }\n get dependentContexts() {\n const identifiers = this.dependentControllerIdentifiers;\n return this.router.contexts.filter(context => identifiers.includes(context.identifier));\n }\n hasOutlet(element, outletName) {\n return !!this.getOutlet(element, outletName) || !!this.getOutletFromMap(element, outletName);\n }\n getOutlet(element, outletName) {\n return this.application.getControllerForElementAndIdentifier(element, outletName);\n }\n getOutletFromMap(element, outletName) {\n return this.outletsByName.getValuesForKey(outletName).find(outlet => outlet.element === element);\n }\n get scope() {\n return this.context.scope;\n }\n get schema() {\n return this.context.schema;\n }\n get identifier() {\n return this.context.identifier;\n }\n get application() {\n return this.context.application;\n }\n get router() {\n return this.application.router;\n }\n }\n class Context {\n constructor(module, scope) {\n var _this = this;\n this.logDebugActivity = function (functionName) {\n let detail = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};\n const identifier = _this.identifier,\n controller = _this.controller,\n element = _this.element;\n detail = Object.assign({\n identifier,\n controller,\n element\n }, detail);\n _this.application.logDebugActivity(_this.identifier, functionName, detail);\n };\n this.module = module;\n this.scope = scope;\n this.controller = new module.controllerConstructor(this);\n this.bindingObserver = new BindingObserver(this, this.dispatcher);\n this.valueObserver = new ValueObserver(this, this.controller);\n this.targetObserver = new TargetObserver(this, this);\n this.outletObserver = new OutletObserver(this, this);\n try {\n this.controller.initialize();\n this.logDebugActivity(\"initialize\");\n } catch (error) {\n this.handleError(error, \"initializing controller\");\n }\n }\n connect() {\n this.bindingObserver.start();\n this.valueObserver.start();\n this.targetObserver.start();\n this.outletObserver.start();\n try {\n this.controller.connect();\n this.logDebugActivity(\"connect\");\n } catch (error) {\n this.handleError(error, \"connecting controller\");\n }\n }\n refresh() {\n this.outletObserver.refresh();\n }\n disconnect() {\n try {\n this.controller.disconnect();\n this.logDebugActivity(\"disconnect\");\n } catch (error) {\n this.handleError(error, \"disconnecting controller\");\n }\n this.outletObserver.stop();\n this.targetObserver.stop();\n this.valueObserver.stop();\n this.bindingObserver.stop();\n }\n get application() {\n return this.module.application;\n }\n get identifier() {\n return this.module.identifier;\n }\n get schema() {\n return this.application.schema;\n }\n get dispatcher() {\n return this.application.dispatcher;\n }\n get element() {\n return this.scope.element;\n }\n get parentElement() {\n return this.element.parentElement;\n }\n handleError(error, message) {\n let detail = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};\n const identifier = this.identifier,\n controller = this.controller,\n element = this.element;\n detail = Object.assign({\n identifier,\n controller,\n element\n }, detail);\n this.application.handleError(error, `Error ${message}`, detail);\n }\n targetConnected(element, name) {\n this.invokeControllerMethod(`${name}TargetConnected`, element);\n }\n targetDisconnected(element, name) {\n this.invokeControllerMethod(`${name}TargetDisconnected`, element);\n }\n outletConnected(outlet, element, name) {\n this.invokeControllerMethod(`${namespaceCamelize(name)}OutletConnected`, outlet, element);\n }\n outletDisconnected(outlet, element, name) {\n this.invokeControllerMethod(`${namespaceCamelize(name)}OutletDisconnected`, outlet, element);\n }\n invokeControllerMethod(methodName) {\n const controller = this.controller;\n if (typeof controller[methodName] == \"function\") {\n for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key2 = 1; _key2 < _len; _key2++) {\n args[_key2 - 1] = arguments[_key2];\n }\n controller[methodName](...args);\n }\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, {\n [key]: descriptor\n });\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 => [...Object.getOwnPropertyNames(object), ...Object.getOwnPropertySymbols(object)];\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: {\n value: extended\n }\n });\n Reflect.setPrototypeOf(extended, constructor);\n return extended;\n }\n function testReflectExtension() {\n const a = function () {\n this.a.call(this);\n };\n const b = extendWithReflect(a);\n b.prototype.a = function () {};\n return new b();\n }\n try {\n testReflectExtension();\n return extendWithReflect;\n } catch (error) {\n return constructor => class extended extends constructor {};\n }\n })();\n function blessDefinition(definition) {\n return {\n identifier: definition.identifier,\n controllerConstructor: bless(definition.controllerConstructor)\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 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 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 } else {\n return false;\n }\n }\n getAttributeNameForKey(key) {\n return `data-${this.identifier}-${dasherize(key)}`;\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 function attributeValueContainsToken(attributeName, token) {\n return `[${attributeName}~=\"${token}\"]`;\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() {\n for (var _len2 = arguments.length, targetNames = new Array(_len2), _key3 = 0; _key3 < _len2; _key3++) {\n targetNames[_key3] = arguments[_key3];\n }\n return targetNames.reduce((target, targetName) => target || this.findTarget(targetName) || this.findLegacyTarget(targetName), undefined);\n }\n findAll() {\n for (var _len3 = arguments.length, targetNames = new Array(_len3), _key4 = 0; _key4 < _len3; _key4++) {\n targetNames[_key4] = arguments[_key4];\n }\n return targetNames.reduce((targets, targetName) => [...targets, ...this.findAllTargets(targetName), ...this.findAllLegacyTargets(targetName)], []);\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.identifier;\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}\". ` + `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 class OutletSet {\n constructor(scope, controllerElement) {\n this.scope = scope;\n this.controllerElement = controllerElement;\n }\n get element() {\n return this.scope.element;\n }\n get identifier() {\n return this.scope.identifier;\n }\n get schema() {\n return this.scope.schema;\n }\n has(outletName) {\n return this.find(outletName) != null;\n }\n find() {\n for (var _len4 = arguments.length, outletNames = new Array(_len4), _key5 = 0; _key5 < _len4; _key5++) {\n outletNames[_key5] = arguments[_key5];\n }\n return outletNames.reduce((outlet, outletName) => outlet || this.findOutlet(outletName), undefined);\n }\n findAll() {\n for (var _len5 = arguments.length, outletNames = new Array(_len5), _key6 = 0; _key6 < _len5; _key6++) {\n outletNames[_key6] = arguments[_key6];\n }\n return outletNames.reduce((outlets, outletName) => [...outlets, ...this.findAllOutlets(outletName)], []);\n }\n getSelectorForOutletName(outletName) {\n const attributeName = this.schema.outletAttributeForScope(this.identifier, outletName);\n return this.controllerElement.getAttribute(attributeName);\n }\n findOutlet(outletName) {\n const selector = this.getSelectorForOutletName(outletName);\n if (selector) return this.findElement(selector, outletName);\n }\n findAllOutlets(outletName) {\n const selector = this.getSelectorForOutletName(outletName);\n return selector ? this.findAllElements(selector, outletName) : [];\n }\n findElement(selector, outletName) {\n const elements = this.scope.queryElements(selector);\n return elements.filter(element => this.matchesElement(element, selector, outletName))[0];\n }\n findAllElements(selector, outletName) {\n const elements = this.scope.queryElements(selector);\n return elements.filter(element => this.matchesElement(element, selector, outletName));\n }\n matchesElement(element, selector, outletName) {\n const controllerAttribute = element.getAttribute(this.scope.schema.controllerAttribute) || \"\";\n return element.matches(selector) && controllerAttribute.split(\" \").includes(outletName);\n }\n }\n 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 this.outlets = new OutletSet(this.documentScope, element);\n }\n findElement(selector) {\n return this.element.matches(selector) ? this.element : this.queryElements(selector).find(this.containsElement);\n }\n findAllElements(selector) {\n return [...(this.element.matches(selector) ? [this.element] : []), ...this.queryElements(selector).filter(this.containsElement)];\n }\n queryElements(selector) {\n return Array.from(this.element.querySelectorAll(selector));\n }\n get controllerSelector() {\n return attributeValueContainsToken(this.schema.controllerAttribute, this.identifier);\n }\n get isDocumentScope() {\n return this.element === document.documentElement;\n }\n get documentScope() {\n return this.isDocumentScope ? this : new Scope(this.schema, document.documentElement, this.identifier, this.guide.logger);\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 = token.element,\n identifier = token.content;\n return this.parseValueForElementAndIdentifier(element, identifier);\n }\n parseValueForElementAndIdentifier(element, identifier) {\n const scopesByIdentifier = this.fetchScopesByIdentifierForElement(element);\n let scope = scopesByIdentifier.get(identifier);\n if (!scope) {\n scope = this.delegate.createScopeForElementAndIdentifier(element, identifier);\n scopesByIdentifier.set(identifier, scope);\n }\n return scope;\n }\n elementMatchedValue(element, value) {\n const referenceCount = (this.scopeReferenceCounts.get(value) || 0) + 1;\n this.scopeReferenceCounts.set(value, referenceCount);\n if (referenceCount == 1) {\n this.delegate.scopeConnected(value);\n }\n }\n elementUnmatchedValue(element, value) {\n const referenceCount = this.scopeReferenceCounts.get(value);\n if (referenceCount) {\n this.scopeReferenceCounts.set(value, referenceCount - 1);\n if (referenceCount == 1) {\n this.delegate.scopeDisconnected(value);\n }\n }\n }\n fetchScopesByIdentifierForElement(element) {\n let scopesByIdentifier = this.scopesByIdentifierByElement.get(element);\n if (!scopesByIdentifier) {\n scopesByIdentifier = new Map();\n this.scopesByIdentifierByElement.set(element, scopesByIdentifier);\n }\n return scopesByIdentifier;\n }\n }\n 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 const afterLoad = definition.controllerConstructor.afterLoad;\n if (afterLoad) {\n afterLoad.call(definition.controllerConstructor, definition.identifier, this.application);\n }\n }\n unloadIdentifier(identifier) {\n const module = this.modulesByIdentifier.get(identifier);\n if (module) {\n this.disconnectModule(module);\n }\n }\n getContextForElementAndIdentifier(element, identifier) {\n const module = this.modulesByIdentifier.get(identifier);\n if (module) {\n return module.contexts.find(context => context.element == element);\n }\n }\n proposeToConnectScopeForElementAndIdentifier(element, identifier) {\n const scope = this.scopeObserver.parseValueForElementAndIdentifier(element, identifier);\n if (scope) {\n this.scopeObserver.elementMatchedValue(scope.element, scope);\n } else {\n console.error(`Couldn't find or create scope for identifier: \"${identifier}\" and element:`, element);\n }\n }\n handleError(error, message, detail) {\n this.application.handleError(error, message, detail);\n }\n createScopeForElementAndIdentifier(element, identifier) {\n return new Scope(this.schema, element, identifier, this.logger);\n }\n scopeConnected(scope) {\n this.scopesByIdentifier.add(scope.identifier, scope);\n const module = this.modulesByIdentifier.get(scope.identifier);\n if (module) {\n module.connectContextForScope(scope);\n }\n }\n scopeDisconnected(scope) {\n this.scopesByIdentifier.delete(scope.identifier, scope);\n const module = this.modulesByIdentifier.get(scope.identifier);\n if (module) {\n module.disconnectContextForScope(scope);\n }\n }\n connectModule(module) {\n this.modulesByIdentifier.set(module.identifier, module);\n const scopes = this.scopesByIdentifier.getValuesForKey(module.identifier);\n scopes.forEach(scope => module.connectContextForScope(scope));\n }\n disconnectModule(module) {\n this.modulesByIdentifier.delete(module.identifier);\n const scopes = this.scopesByIdentifier.getValuesForKey(module.identifier);\n scopes.forEach(scope => module.disconnectContextForScope(scope));\n }\n }\n const defaultSchema = {\n controllerAttribute: \"data-controller\",\n actionAttribute: \"data-action\",\n targetAttribute: \"data-target\",\n targetAttributeForScope: identifier => `data-${identifier}-target`,\n outletAttributeForScope: (identifier, outlet) => `data-${identifier}-${outlet}-outlet`,\n keyMappings: Object.assign(Object.assign({\n enter: \"Enter\",\n tab: \"Tab\",\n esc: \"Escape\",\n space: \" \",\n up: \"ArrowUp\",\n down: \"ArrowDown\",\n left: \"ArrowLeft\",\n right: \"ArrowRight\",\n home: \"Home\",\n end: \"End\",\n page_up: \"PageUp\",\n page_down: \"PageDown\"\n }, objectFromEntries(\"abcdefghijklmnopqrstuvwxyz\".split(\"\").map(c => [c, c]))), objectFromEntries(\"0123456789\".split(\"\").map(n => [n, n])))\n };\n function objectFromEntries(array) {\n return array.reduce((memo, _ref19) => {\n let _ref20 = _slicedToArray(_ref19, 2),\n k = _ref20[0],\n v = _ref20[1];\n return Object.assign(Object.assign({}, memo), {\n [k]: v\n });\n }, {});\n }\n class Application {\n constructor() {\n var _this2 = this;\n let element = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : document.documentElement;\n let schema = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : defaultSchema;\n this.logger = console;\n this.debug = false;\n this.logDebugActivity = function (identifier, functionName) {\n let detail = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};\n if (_this2.debug) {\n _this2.logFormattedMessage(identifier, functionName, detail);\n }\n };\n this.element = element;\n this.schema = schema;\n this.dispatcher = new Dispatcher(this);\n this.router = new Router(this);\n this.actionDescriptorFilters = Object.assign({}, defaultActionDescriptorFilters);\n }\n static start(element, schema) {\n const application = new this(element, schema);\n application.start();\n return application;\n }\n async start() {\n await domReady();\n this.logDebugActivity(\"application\", \"starting\");\n this.dispatcher.start();\n this.router.start();\n this.logDebugActivity(\"application\", \"start\");\n }\n stop() {\n this.logDebugActivity(\"application\", \"stopping\");\n this.dispatcher.stop();\n this.router.stop();\n this.logDebugActivity(\"application\", \"stop\");\n }\n register(identifier, controllerConstructor) {\n this.load({\n identifier,\n controllerConstructor\n });\n }\n registerActionOption(name, filter) {\n this.actionDescriptorFilters[name] = filter;\n }\n load(head) {\n for (var _len6 = arguments.length, rest = new Array(_len6 > 1 ? _len6 - 1 : 0), _key7 = 1; _key7 < _len6; _key7++) {\n rest[_key7 - 1] = arguments[_key7];\n }\n const definitions = Array.isArray(head) ? head : [head, ...rest];\n definitions.forEach(definition => {\n if (definition.controllerConstructor.shouldLoad) {\n this.router.loadDefinition(definition);\n }\n });\n }\n unload(head) {\n for (var _len7 = arguments.length, rest = new Array(_len7 > 1 ? _len7 - 1 : 0), _key8 = 1; _key8 < _len7; _key8++) {\n rest[_key8 - 1] = arguments[_key8];\n }\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) {\n let detail = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};\n detail = Object.assign({\n application: this\n }, 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 } else {\n resolve();\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.classes;\n if (classes.has(key)) {\n return classes.get(key);\n } else {\n const attribute = classes.getAttributeName(key);\n throw new Error(`Missing attribute \"${attribute}\"`);\n }\n }\n },\n [`${key}Classes`]: {\n get() {\n return this.classes.getAll(key);\n }\n },\n [`has${capitalize(key)}Class`]: {\n get() {\n return this.classes.has(key);\n }\n }\n };\n }\n function OutletPropertiesBlessing(constructor) {\n const outlets = readInheritableStaticArrayValues(constructor, \"outlets\");\n return outlets.reduce((properties, outletDefinition) => {\n return Object.assign(properties, propertiesForOutletDefinition(outletDefinition));\n }, {});\n }\n function getOutletController(controller, element, identifier) {\n return controller.application.getControllerForElementAndIdentifier(element, identifier);\n }\n function getControllerAndEnsureConnectedScope(controller, element, outletName) {\n let outletController = getOutletController(controller, element, outletName);\n if (outletController) return outletController;\n controller.application.router.proposeToConnectScopeForElementAndIdentifier(element, outletName);\n outletController = getOutletController(controller, element, outletName);\n if (outletController) return outletController;\n }\n function propertiesForOutletDefinition(name) {\n const camelizedName = namespaceCamelize(name);\n return {\n [`${camelizedName}Outlet`]: {\n get() {\n const outletElement = this.outlets.find(name);\n const selector = this.outlets.getSelectorForOutletName(name);\n if (outletElement) {\n const outletController = getControllerAndEnsureConnectedScope(this, outletElement, name);\n if (outletController) return outletController;\n throw new Error(`The provided outlet element is missing an outlet controller \"${name}\" instance for host controller \"${this.identifier}\"`);\n }\n throw new Error(`Missing outlet element \"${name}\" for host controller \"${this.identifier}\". Stimulus couldn't find a matching outlet element using selector \"${selector}\".`);\n }\n },\n [`${camelizedName}Outlets`]: {\n get() {\n const outlets = this.outlets.findAll(name);\n if (outlets.length > 0) {\n return outlets.map(outletElement => {\n const outletController = getControllerAndEnsureConnectedScope(this, outletElement, name);\n if (outletController) return outletController;\n console.warn(`The provided outlet element is missing an outlet controller \"${name}\" instance for host controller \"${this.identifier}\"`, outletElement);\n }).filter(controller => controller);\n }\n return [];\n }\n },\n [`${camelizedName}OutletElement`]: {\n get() {\n const outletElement = this.outlets.find(name);\n const selector = this.outlets.getSelectorForOutletName(name);\n if (outletElement) {\n return outletElement;\n } else {\n throw new Error(`Missing outlet element \"${name}\" for host controller \"${this.identifier}\". Stimulus couldn't find a matching outlet element using selector \"${selector}\".`);\n }\n }\n },\n [`${camelizedName}OutletElements`]: {\n get() {\n return this.outlets.findAll(name);\n }\n },\n [`has${capitalize(camelizedName)}Outlet`]: {\n get() {\n return this.outlets.has(name);\n }\n }\n };\n }\n 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 } 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 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, this.identifier);\n const attributeName = this.data.getAttributeNameForKey(valueDescriptor.key);\n return Object.assign(result, {\n [attributeName]: valueDescriptor\n });\n }, {});\n }\n }\n };\n return valueDefinitionPairs.reduce((properties, valueDefinitionPair) => {\n return Object.assign(properties, propertiesForValueDefinitionPair(valueDefinitionPair));\n }, propertyDescriptorMap);\n }\n function propertiesForValueDefinitionPair(valueDefinitionPair, controller) {\n const definition = parseValueDefinitionPair(valueDefinitionPair, controller);\n const key = definition.key,\n name = definition.name,\n read = definition.reader,\n write = definition.writer;\n return {\n [name]: {\n get() {\n const value = this.data.get(key);\n if (value !== null) {\n return read(value);\n } else {\n return definition.defaultValue;\n }\n },\n set(value) {\n if (value === undefined) {\n this.data.delete(key);\n } else {\n this.data.set(key, write(value));\n }\n }\n },\n [`has${capitalize(name)}`]: {\n get() {\n return this.data.has(key) || definition.hasCustomDefaultValue;\n }\n }\n };\n }\n function parseValueDefinitionPair(_ref21, controller) {\n let _ref22 = _slicedToArray(_ref21, 2),\n token = _ref22[0],\n typeDefinition = _ref22[1];\n return valueDescriptorForTokenAndTypeDefinition({\n controller,\n token,\n typeDefinition\n });\n }\n function parseValueTypeConstant(constant) {\n switch (constant) {\n case Array:\n return \"array\";\n case Boolean:\n return \"boolean\";\n case Number:\n return \"number\";\n case Object:\n return \"object\";\n case String:\n return \"string\";\n }\n }\n function parseValueTypeDefault(defaultValue) {\n switch (typeof defaultValue) {\n case \"boolean\":\n return \"boolean\";\n case \"number\":\n return \"number\";\n case \"string\":\n return \"string\";\n }\n if (Array.isArray(defaultValue)) return \"array\";\n if (Object.prototype.toString.call(defaultValue) === \"[object Object]\") return \"object\";\n }\n function parseValueTypeObject(payload) {\n const controller = payload.controller,\n token = payload.token,\n typeObject = payload.typeObject;\n const hasType = isSomething(typeObject.type);\n const hasDefault = isSomething(typeObject.default);\n const fullObject = hasType && hasDefault;\n const onlyType = hasType && !hasDefault;\n const onlyDefault = !hasType && hasDefault;\n const typeFromObject = parseValueTypeConstant(typeObject.type);\n const typeFromDefaultValue = parseValueTypeDefault(payload.typeObject.default);\n if (onlyType) return typeFromObject;\n if (onlyDefault) return typeFromDefaultValue;\n if (typeFromObject !== typeFromDefaultValue) {\n const propertyPath = controller ? `${controller}.${token}` : token;\n throw new Error(`The specified default value for the Stimulus Value \"${propertyPath}\" must match the defined type \"${typeFromObject}\". The provided default value of \"${typeObject.default}\" is of type \"${typeFromDefaultValue}\".`);\n }\n if (fullObject) return typeFromObject;\n }\n function parseValueTypeDefinition(payload) {\n const controller = payload.controller,\n token = payload.token,\n typeDefinition = payload.typeDefinition;\n const typeObject = {\n controller,\n token,\n typeObject: typeDefinition\n };\n const typeFromObject = parseValueTypeObject(typeObject);\n const typeFromDefaultValue = parseValueTypeDefault(typeDefinition);\n const typeFromConstant = parseValueTypeConstant(typeDefinition);\n const type = typeFromObject || typeFromDefaultValue || typeFromConstant;\n if (type) return type;\n const propertyPath = controller ? `${controller}.${typeDefinition}` : token;\n throw new Error(`Unknown value type \"${propertyPath}\" for \"${token}\" value`);\n }\n function defaultValueForDefinition(typeDefinition) {\n const constant = parseValueTypeConstant(typeDefinition);\n if (constant) return defaultValuesByType[constant];\n const hasDefault = hasProperty(typeDefinition, \"default\");\n const hasType = hasProperty(typeDefinition, \"type\");\n const typeObject = typeDefinition;\n if (hasDefault) return typeObject.default;\n if (hasType) {\n const type = typeObject.type;\n const constantFromType = parseValueTypeConstant(type);\n if (constantFromType) return defaultValuesByType[constantFromType];\n }\n return typeDefinition;\n }\n function valueDescriptorForTokenAndTypeDefinition(payload) {\n const token = payload.token,\n typeDefinition = payload.typeDefinition;\n const key = `${dasherize(token)}-value`;\n const type = parseValueTypeDefinition(payload);\n return {\n type,\n key,\n name: camelize(key),\n get defaultValue() {\n return defaultValueForDefinition(typeDefinition);\n },\n get hasCustomDefaultValue() {\n return parseValueTypeDefault(typeDefinition) !== undefined;\n },\n reader: readers[type],\n writer: writers[type] || writers.default\n };\n }\n const defaultValuesByType = {\n get array() {\n return [];\n },\n boolean: false,\n number: 0,\n get object() {\n return {};\n },\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 value of type \"array\" but instead got value \"${value}\" of type \"${parseValueTypeDefault(array)}\"`);\n }\n return array;\n },\n boolean(value) {\n return !(value == \"0\" || String(value).toLowerCase() == \"false\");\n },\n number(value) {\n return Number(value.replace(/_/g, \"\"));\n },\n object(value) {\n const object = JSON.parse(value);\n if (object === null || typeof object != \"object\" || Array.isArray(object)) {\n throw new TypeError(`expected value of type \"object\" but instead got value \"${value}\" of type \"${parseValueTypeDefault(object)}\"`);\n }\n return object;\n },\n string(value) {\n return value;\n }\n };\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 class Controller {\n constructor(context) {\n this.context = context;\n }\n static get shouldLoad() {\n return true;\n }\n static afterLoad(_identifier, _application) {\n return;\n }\n get application() {\n return this.context.application;\n }\n get scope() {\n return this.context.scope;\n }\n get element() {\n return this.scope.element;\n }\n get identifier() {\n return this.scope.identifier;\n }\n get targets() {\n return this.scope.targets;\n }\n get outlets() {\n return this.scope.outlets;\n }\n get classes() {\n return this.scope.classes;\n }\n get data() {\n return this.scope.data;\n }\n initialize() {}\n connect() {}\n disconnect() {}\n dispatch(eventName) {\n let _ref23 = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {},\n _ref23$target = _ref23.target,\n target = _ref23$target === void 0 ? this.element : _ref23$target,\n _ref23$detail = _ref23.detail,\n detail = _ref23$detail === void 0 ? {} : _ref23$detail,\n _ref23$prefix = _ref23.prefix,\n prefix = _ref23$prefix === void 0 ? this.identifier : _ref23$prefix,\n _ref23$bubbles = _ref23.bubbles,\n bubbles = _ref23$bubbles === void 0 ? true : _ref23$bubbles,\n _ref23$cancelable = _ref23.cancelable,\n cancelable = _ref23$cancelable === void 0 ? true : _ref23$cancelable;\n const type = prefix ? `${prefix}:${eventName}` : eventName;\n const event = new CustomEvent(type, {\n detail,\n bubbles,\n cancelable\n });\n target.dispatchEvent(event);\n return event;\n }\n }\n Controller.blessings = [ClassPropertiesBlessing, TargetPropertiesBlessing, ValuePropertiesBlessing, OutletPropertiesBlessing];\n Controller.targets = [];\n Controller.outlets = [];\n Controller.values = {};\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.SelectorObserver = SelectorObserver;\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 Object.defineProperty(exports, '__esModule', {\n value: true\n });\n});","let consumer;\nexport async function getConsumer() {\n return consumer || setConsumer(createConsumer().then(setConsumer));\n}\nexport function setConsumer(newConsumer) {\n return consumer = newConsumer;\n}\nexport async function createConsumer() {\n const _await$import = await import( /* webpackChunkName: \"actioncable\" */\"@rails/actioncable/src\"),\n createConsumer = _await$import.createConsumer;\n return createConsumer();\n}\nexport async function subscribeTo(channel, mixin) {\n const _await$getConsumer = await getConsumer(),\n subscriptions = _await$getConsumer.subscriptions;\n return subscriptions.create(channel, mixin);\n}","function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }\nfunction _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }\nfunction _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }\nfunction _toPropertyKey(arg) { var key = _toPrimitive(arg, \"string\"); return typeof key === \"symbol\" ? key : String(key); }\nfunction _toPrimitive(input, hint) { if (typeof input !== \"object\" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || \"default\"); if (typeof res !== \"object\") return res; throw new TypeError(\"@@toPrimitive must return a primitive value.\"); } return (hint === \"string\" ? String : Number)(input); }\nimport { connectStreamSource, disconnectStreamSource } from \"@hotwired/turbo\";\nimport { subscribeTo } from \"./cable\";\nimport snakeize from \"./snakeize\";\nclass TurboCableStreamSourceElement extends HTMLElement {\n async connectedCallback() {\n connectStreamSource(this);\n this.subscription = await subscribeTo(this.channel, {\n received: this.dispatchMessageEvent.bind(this),\n connected: this.subscriptionConnected.bind(this),\n disconnected: this.subscriptionDisconnected.bind(this)\n });\n }\n disconnectedCallback() {\n disconnectStreamSource(this);\n if (this.subscription) this.subscription.unsubscribe();\n }\n dispatchMessageEvent(data) {\n const event = new MessageEvent(\"message\", {\n data\n });\n return this.dispatchEvent(event);\n }\n subscriptionConnected() {\n this.setAttribute(\"connected\", \"\");\n }\n subscriptionDisconnected() {\n this.removeAttribute(\"connected\");\n }\n get channel() {\n const channel = this.getAttribute(\"channel\");\n const signed_stream_name = this.getAttribute(\"signed-stream-name\");\n return _objectSpread({\n channel,\n signed_stream_name\n }, snakeize(_objectSpread({}, this.dataset)));\n }\n}\nif (customElements.get(\"turbo-cable-stream-source\") === undefined) {\n customElements.define(\"turbo-cable-stream-source\", TurboCableStreamSourceElement);\n}","export function encodeMethodIntoRequestBody(event) {\n if (event.target instanceof HTMLFormElement) {\n const form = event.target,\n fetchOptions = event.detail.fetchOptions;\n form.addEventListener(\"turbo:submit-start\", _ref => {\n let submitter = _ref.detail.formSubmission.submitter;\n const body = isBodyInit(fetchOptions.body) ? fetchOptions.body : new URLSearchParams();\n const method = determineFetchMethod(submitter, body, form);\n if (!/get/i.test(method)) {\n if (/post/i.test(method)) {\n body.delete(\"_method\");\n } else {\n body.set(\"_method\", method);\n }\n fetchOptions.method = \"post\";\n }\n }, {\n once: true\n });\n }\n}\nfunction determineFetchMethod(submitter, body, form) {\n const formMethod = determineFormMethod(submitter);\n const overrideMethod = body.get(\"_method\");\n const method = form.getAttribute(\"method\") || \"get\";\n if (typeof formMethod == \"string\") {\n return formMethod;\n } else if (typeof overrideMethod == \"string\") {\n return overrideMethod;\n } else {\n return method;\n }\n}\nfunction determineFormMethod(submitter) {\n if (submitter instanceof HTMLButtonElement || submitter instanceof HTMLInputElement) {\n if (submitter.hasAttribute(\"formmethod\")) {\n return submitter.formMethod;\n } else {\n return null;\n }\n } else {\n return null;\n }\n}\nfunction isBodyInit(body) {\n return body instanceof FormData || body instanceof URLSearchParams;\n}","import \"./cable_stream_source_element\";\nimport * as Turbo from \"@hotwired/turbo\";\nexport { Turbo };\nimport * as cable from \"./cable\";\nexport { cable };\nimport { encodeMethodIntoRequestBody } from \"./fetch_requests\";\naddEventListener(\"turbo:before-fetch-request\", encodeMethodIntoRequestBody);","// Based on https://github.com/nathan7/snakeize\n//\n// This software is released under the MIT license:\n// Permission is hereby granted, free of charge, to any person obtaining a copy of\n// this software and associated documentation files (the \"Software\"), to deal in\n// the Software without restriction, including without limitation the rights to\n// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of\n// the Software, and to permit persons to whom the Software is furnished to do so,\n// subject to the following conditions:\n\n// The above copyright notice and this permission notice shall be included in all\n// copies or substantial portions of the Software.\n\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS\n// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR\n// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER\n// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\n// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\nexport default function walk(obj) {\n if (!obj || typeof obj !== 'object') return obj;\n if (obj instanceof Date || obj instanceof RegExp) return obj;\n if (Array.isArray(obj)) return obj.map(walk);\n return Object.keys(obj).reduce(function (acc, key) {\n var camel = key[0].toLowerCase() + key.slice(1).replace(/([A-Z]+)/g, function (m, x) {\n return '_' + x.toLowerCase();\n });\n acc[camel] = walk(obj[key]);\n return acc;\n }, {});\n}\n;","function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); }\nfunction _nonIterableRest() { throw new TypeError(\"Invalid attempt to destructure non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.\"); }\nfunction _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === \"string\") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === \"Object\" && o.constructor) n = o.constructor.name; if (n === \"Map\" || n === \"Set\") return Array.from(o); if (n === \"Arguments\" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }\nfunction _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; return arr2; }\nfunction _iterableToArrayLimit(r, l) { var t = null == r ? null : \"undefined\" != typeof Symbol && r[Symbol.iterator] || r[\"@@iterator\"]; if (null != t) { var e, n, i, u, a = [], f = !0, o = !1; try { if (i = (t = t.call(r)).next, 0 === l) { if (Object(t) !== t) return; f = !1; } else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0); } catch (r) { o = !0, n = r; } finally { try { if (!f && null != t.return && (u = t.return(), Object(u) !== u)) return; } finally { if (o) throw n; } } return a; } }\nfunction _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }\n/*\nTurbo 7.3.0\nCopyright © 2023 37signals LLC\n */\n(function () {\n if (window.Reflect === undefined || window.customElements === undefined || window.customElements.polyfillWrapFlushCallback) {\n return;\n }\n const BuiltInHTMLElement = HTMLElement;\n const wrapperForTheName = {\n HTMLElement: function HTMLElement() {\n return Reflect.construct(BuiltInHTMLElement, [], this.constructor);\n }\n };\n window.HTMLElement = wrapperForTheName[\"HTMLElement\"];\n HTMLElement.prototype = BuiltInHTMLElement.prototype;\n HTMLElement.prototype.constructor = HTMLElement;\n Object.setPrototypeOf(HTMLElement, BuiltInHTMLElement);\n})();\n\n/**\n * The MIT License (MIT)\n * \n * Copyright (c) 2019 Javan Makhmali\n * \n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n * \n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n * \n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n */\n\n(function (prototype) {\n if (typeof prototype.requestSubmit == \"function\") return;\n prototype.requestSubmit = function (submitter) {\n if (submitter) {\n validateSubmitter(submitter, this);\n submitter.click();\n } else {\n submitter = document.createElement(\"input\");\n submitter.type = \"submit\";\n submitter.hidden = true;\n this.appendChild(submitter);\n submitter.click();\n this.removeChild(submitter);\n }\n };\n function validateSubmitter(submitter, form) {\n submitter instanceof HTMLElement || raise(TypeError, \"parameter 1 is not of type 'HTMLElement'\");\n submitter.type == \"submit\" || raise(TypeError, \"The specified element is not a submit button\");\n submitter.form == form || raise(DOMException, \"The specified element is not owned by this form element\", \"NotFoundError\");\n }\n function raise(errorConstructor, message, name) {\n throw new errorConstructor(\"Failed to execute 'requestSubmit' on 'HTMLFormElement': \" + message + \".\", name);\n }\n})(HTMLFormElement.prototype);\nconst submittersByForm = new WeakMap();\nfunction findSubmitterFromClickTarget(target) {\n const element = target instanceof Element ? target : target instanceof Node ? target.parentElement : null;\n const candidate = element ? element.closest(\"input, button\") : null;\n return (candidate === null || candidate === void 0 ? void 0 : candidate.type) == \"submit\" ? candidate : null;\n}\nfunction clickCaptured(event) {\n const submitter = findSubmitterFromClickTarget(event.target);\n if (submitter && submitter.form) {\n submittersByForm.set(submitter.form, submitter);\n }\n}\n(function () {\n if (\"submitter\" in Event.prototype) return;\n let prototype = window.Event.prototype;\n if (\"SubmitEvent\" in window && /Apple Computer/.test(navigator.vendor)) {\n prototype = window.SubmitEvent.prototype;\n } else if (\"SubmitEvent\" in window) {\n return;\n }\n addEventListener(\"click\", clickCaptured, true);\n Object.defineProperty(prototype, \"submitter\", {\n get() {\n if (this.type == \"submit\" && this.target instanceof HTMLFormElement) {\n return submittersByForm.get(this.target);\n }\n }\n });\n})();\nvar FrameLoadingStyle;\n(function (FrameLoadingStyle) {\n FrameLoadingStyle[\"eager\"] = \"eager\";\n FrameLoadingStyle[\"lazy\"] = \"lazy\";\n})(FrameLoadingStyle || (FrameLoadingStyle = {}));\nclass FrameElement extends HTMLElement {\n static get observedAttributes() {\n return [\"disabled\", \"complete\", \"loading\", \"src\"];\n }\n constructor() {\n super();\n this.loaded = Promise.resolve();\n this.delegate = new FrameElement.delegateConstructor(this);\n }\n connectedCallback() {\n this.delegate.connect();\n }\n disconnectedCallback() {\n this.delegate.disconnect();\n }\n reload() {\n return this.delegate.sourceURLReloaded();\n }\n attributeChangedCallback(name) {\n if (name == \"loading\") {\n this.delegate.loadingStyleChanged();\n } else if (name == \"complete\") {\n this.delegate.completeChanged();\n } else if (name == \"src\") {\n this.delegate.sourceURLChanged();\n } else {\n this.delegate.disabledChanged();\n }\n }\n get src() {\n return this.getAttribute(\"src\");\n }\n set src(value) {\n if (value) {\n this.setAttribute(\"src\", value);\n } else {\n this.removeAttribute(\"src\");\n }\n }\n get loading() {\n return frameLoadingStyleFromString(this.getAttribute(\"loading\") || \"\");\n }\n set loading(value) {\n if (value) {\n this.setAttribute(\"loading\", value);\n } else {\n this.removeAttribute(\"loading\");\n }\n }\n get disabled() {\n return this.hasAttribute(\"disabled\");\n }\n set disabled(value) {\n if (value) {\n this.setAttribute(\"disabled\", \"\");\n } else {\n this.removeAttribute(\"disabled\");\n }\n }\n get autoscroll() {\n return this.hasAttribute(\"autoscroll\");\n }\n set autoscroll(value) {\n if (value) {\n this.setAttribute(\"autoscroll\", \"\");\n } else {\n this.removeAttribute(\"autoscroll\");\n }\n }\n get complete() {\n return !this.delegate.isLoading;\n }\n get isActive() {\n return this.ownerDocument === document && !this.isPreview;\n }\n get isPreview() {\n var _a, _b;\n return (_b = (_a = this.ownerDocument) === null || _a === void 0 ? void 0 : _a.documentElement) === null || _b === void 0 ? void 0 : _b.hasAttribute(\"data-turbo-preview\");\n }\n}\nfunction frameLoadingStyleFromString(style) {\n switch (style.toLowerCase()) {\n case \"lazy\":\n return FrameLoadingStyle.lazy;\n default:\n return FrameLoadingStyle.eager;\n }\n}\nfunction expandURL(locatable) {\n return new URL(locatable.toString(), document.baseURI);\n}\nfunction getAnchor(url) {\n let anchorMatch;\n if (url.hash) {\n return url.hash.slice(1);\n } else if (anchorMatch = url.href.match(/#(.*)$/)) {\n return anchorMatch[1];\n }\n}\nfunction getAction(form, submitter) {\n const action = (submitter === null || submitter === void 0 ? void 0 : submitter.getAttribute(\"formaction\")) || form.getAttribute(\"action\") || form.action;\n return expandURL(action);\n}\nfunction getExtension(url) {\n return (getLastPathComponent(url).match(/\\.[^.]*$/) || [])[0] || \"\";\n}\nfunction isHTML(url) {\n return !!getExtension(url).match(/^(?:|\\.(?:htm|html|xhtml|php))$/);\n}\nfunction isPrefixedBy(baseURL, url) {\n const prefix = getPrefix(url);\n return baseURL.href === expandURL(prefix).href || baseURL.href.startsWith(prefix);\n}\nfunction locationIsVisitable(location, rootLocation) {\n return isPrefixedBy(location, rootLocation) && isHTML(location);\n}\nfunction getRequestURL(url) {\n const anchor = getAnchor(url);\n return anchor != null ? url.href.slice(0, -(anchor.length + 1)) : url.href;\n}\nfunction toCacheKey(url) {\n return getRequestURL(url);\n}\nfunction urlsAreEqual(left, right) {\n return expandURL(left).href == expandURL(right).href;\n}\nfunction getPathComponents(url) {\n return url.pathname.split(\"/\").slice(1);\n}\nfunction getLastPathComponent(url) {\n return getPathComponents(url).slice(-1)[0];\n}\nfunction getPrefix(url) {\n return addTrailingSlash(url.origin + url.pathname);\n}\nfunction addTrailingSlash(value) {\n return value.endsWith(\"/\") ? value : value + \"/\";\n}\nclass FetchResponse {\n constructor(response) {\n this.response = response;\n }\n get succeeded() {\n return this.response.ok;\n }\n get failed() {\n return !this.succeeded;\n }\n get clientError() {\n return this.statusCode >= 400 && this.statusCode <= 499;\n }\n get serverError() {\n return this.statusCode >= 500 && this.statusCode <= 599;\n }\n get redirected() {\n return this.response.redirected;\n }\n get location() {\n return expandURL(this.response.url);\n }\n get isHTML() {\n return this.contentType && this.contentType.match(/^(?:text\\/([^\\s;,]+\\b)?html|application\\/xhtml\\+xml)\\b/);\n }\n get statusCode() {\n return this.response.status;\n }\n get contentType() {\n return this.header(\"Content-Type\");\n }\n get responseText() {\n return this.response.clone().text();\n }\n get responseHTML() {\n if (this.isHTML) {\n return this.response.clone().text();\n } else {\n return Promise.resolve(undefined);\n }\n }\n header(name) {\n return this.response.headers.get(name);\n }\n}\nfunction activateScriptElement(element) {\n if (element.getAttribute(\"data-turbo-eval\") == \"false\") {\n return element;\n } else {\n const createdScriptElement = document.createElement(\"script\");\n const cspNonce = getMetaContent(\"csp-nonce\");\n if (cspNonce) {\n createdScriptElement.nonce = cspNonce;\n }\n createdScriptElement.textContent = element.textContent;\n createdScriptElement.async = false;\n copyElementAttributes(createdScriptElement, element);\n return createdScriptElement;\n }\n}\nfunction copyElementAttributes(destinationElement, sourceElement) {\n for (const _ref of sourceElement.attributes) {\n const name = _ref.name;\n const value = _ref.value;\n destinationElement.setAttribute(name, value);\n }\n}\nfunction createDocumentFragment(html) {\n const template = document.createElement(\"template\");\n template.innerHTML = html;\n return template.content;\n}\nfunction dispatch(eventName) {\n let _ref2 = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {},\n target = _ref2.target,\n cancelable = _ref2.cancelable,\n detail = _ref2.detail;\n const event = new CustomEvent(eventName, {\n cancelable,\n bubbles: true,\n composed: true,\n detail\n });\n if (target && target.isConnected) {\n target.dispatchEvent(event);\n } else {\n document.documentElement.dispatchEvent(event);\n }\n return event;\n}\nfunction nextAnimationFrame() {\n return new Promise(resolve => requestAnimationFrame(() => resolve()));\n}\nfunction nextEventLoopTick() {\n return new Promise(resolve => setTimeout(() => resolve(), 0));\n}\nfunction nextMicrotask() {\n return Promise.resolve();\n}\nfunction parseHTMLDocument() {\n let html = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : \"\";\n return new DOMParser().parseFromString(html, \"text/html\");\n}\nfunction unindent(strings) {\n for (var _len = arguments.length, values = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {\n values[_key - 1] = arguments[_key];\n }\n const lines = interpolate(strings, values).replace(/^\\n/, \"\").split(\"\\n\");\n const match = lines[0].match(/^\\s+/);\n const indent = match ? match[0].length : 0;\n return lines.map(line => line.slice(indent)).join(\"\\n\");\n}\nfunction interpolate(strings, values) {\n return strings.reduce((result, string, i) => {\n const value = values[i] == undefined ? \"\" : values[i];\n return result + string + value;\n }, \"\");\n}\nfunction uuid() {\n return Array.from({\n length: 36\n }).map((_, i) => {\n if (i == 8 || i == 13 || i == 18 || i == 23) {\n return \"-\";\n } else if (i == 14) {\n return \"4\";\n } else if (i == 19) {\n return (Math.floor(Math.random() * 4) + 8).toString(16);\n } else {\n return Math.floor(Math.random() * 15).toString(16);\n }\n }).join(\"\");\n}\nfunction getAttribute(attributeName) {\n for (var _len2 = arguments.length, elements = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) {\n elements[_key2 - 1] = arguments[_key2];\n }\n for (const value of elements.map(element => element === null || element === void 0 ? void 0 : element.getAttribute(attributeName))) {\n if (typeof value == \"string\") return value;\n }\n return null;\n}\nfunction hasAttribute(attributeName) {\n for (var _len3 = arguments.length, elements = new Array(_len3 > 1 ? _len3 - 1 : 0), _key3 = 1; _key3 < _len3; _key3++) {\n elements[_key3 - 1] = arguments[_key3];\n }\n return elements.some(element => element && element.hasAttribute(attributeName));\n}\nfunction markAsBusy() {\n for (var _len4 = arguments.length, elements = new Array(_len4), _key4 = 0; _key4 < _len4; _key4++) {\n elements[_key4] = arguments[_key4];\n }\n for (const element of elements) {\n if (element.localName == \"turbo-frame\") {\n element.setAttribute(\"busy\", \"\");\n }\n element.setAttribute(\"aria-busy\", \"true\");\n }\n}\nfunction clearBusyState() {\n for (var _len5 = arguments.length, elements = new Array(_len5), _key5 = 0; _key5 < _len5; _key5++) {\n elements[_key5] = arguments[_key5];\n }\n for (const element of elements) {\n if (element.localName == \"turbo-frame\") {\n element.removeAttribute(\"busy\");\n }\n element.removeAttribute(\"aria-busy\");\n }\n}\nfunction waitForLoad(element) {\n let timeoutInMilliseconds = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 2000;\n return new Promise(resolve => {\n const onComplete = () => {\n element.removeEventListener(\"error\", onComplete);\n element.removeEventListener(\"load\", onComplete);\n resolve();\n };\n element.addEventListener(\"load\", onComplete, {\n once: true\n });\n element.addEventListener(\"error\", onComplete, {\n once: true\n });\n setTimeout(resolve, timeoutInMilliseconds);\n });\n}\nfunction getHistoryMethodForAction(action) {\n switch (action) {\n case \"replace\":\n return history.replaceState;\n case \"advance\":\n case \"restore\":\n return history.pushState;\n }\n}\nfunction isAction(action) {\n return action == \"advance\" || action == \"replace\" || action == \"restore\";\n}\nfunction getVisitAction() {\n for (var _len6 = arguments.length, elements = new Array(_len6), _key6 = 0; _key6 < _len6; _key6++) {\n elements[_key6] = arguments[_key6];\n }\n const action = getAttribute(\"data-turbo-action\", ...elements);\n return isAction(action) ? action : null;\n}\nfunction getMetaElement(name) {\n return document.querySelector(`meta[name=\"${name}\"]`);\n}\nfunction getMetaContent(name) {\n const element = getMetaElement(name);\n return element && element.content;\n}\nfunction setMetaContent(name, content) {\n let element = getMetaElement(name);\n if (!element) {\n element = document.createElement(\"meta\");\n element.setAttribute(\"name\", name);\n document.head.appendChild(element);\n }\n element.setAttribute(\"content\", content);\n return element;\n}\nfunction findClosestRecursively(element, selector) {\n var _a;\n if (element instanceof Element) {\n return element.closest(selector) || findClosestRecursively(element.assignedSlot || ((_a = element.getRootNode()) === null || _a === void 0 ? void 0 : _a.host), selector);\n }\n}\nvar FetchMethod;\n(function (FetchMethod) {\n FetchMethod[FetchMethod[\"get\"] = 0] = \"get\";\n FetchMethod[FetchMethod[\"post\"] = 1] = \"post\";\n FetchMethod[FetchMethod[\"put\"] = 2] = \"put\";\n FetchMethod[FetchMethod[\"patch\"] = 3] = \"patch\";\n FetchMethod[FetchMethod[\"delete\"] = 4] = \"delete\";\n})(FetchMethod || (FetchMethod = {}));\nfunction fetchMethodFromString(method) {\n switch (method.toLowerCase()) {\n case \"get\":\n return FetchMethod.get;\n case \"post\":\n return FetchMethod.post;\n case \"put\":\n return FetchMethod.put;\n case \"patch\":\n return FetchMethod.patch;\n case \"delete\":\n return FetchMethod.delete;\n }\n}\nclass FetchRequest {\n constructor(delegate, method, location) {\n let body = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : new URLSearchParams();\n let target = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : null;\n this.abortController = new AbortController();\n this.resolveRequestPromise = _value => {};\n this.delegate = delegate;\n this.method = method;\n this.headers = this.defaultHeaders;\n this.body = body;\n this.url = location;\n this.target = target;\n }\n get location() {\n return this.url;\n }\n get params() {\n return this.url.searchParams;\n }\n get entries() {\n return this.body ? Array.from(this.body.entries()) : [];\n }\n cancel() {\n this.abortController.abort();\n }\n async perform() {\n const fetchOptions = this.fetchOptions;\n this.delegate.prepareRequest(this);\n await this.allowRequestToBeIntercepted(fetchOptions);\n try {\n this.delegate.requestStarted(this);\n const response = await fetch(this.url.href, fetchOptions);\n return await this.receive(response);\n } catch (error) {\n if (error.name !== \"AbortError\") {\n if (this.willDelegateErrorHandling(error)) {\n this.delegate.requestErrored(this, error);\n }\n throw error;\n }\n } finally {\n this.delegate.requestFinished(this);\n }\n }\n async receive(response) {\n const fetchResponse = new FetchResponse(response);\n const event = dispatch(\"turbo:before-fetch-response\", {\n cancelable: true,\n detail: {\n fetchResponse\n },\n target: this.target\n });\n if (event.defaultPrevented) {\n this.delegate.requestPreventedHandlingResponse(this, fetchResponse);\n } else if (fetchResponse.succeeded) {\n this.delegate.requestSucceededWithResponse(this, fetchResponse);\n } else {\n this.delegate.requestFailedWithResponse(this, fetchResponse);\n }\n return fetchResponse;\n }\n get fetchOptions() {\n var _a;\n return {\n method: FetchMethod[this.method].toUpperCase(),\n credentials: \"same-origin\",\n headers: this.headers,\n redirect: \"follow\",\n body: this.isSafe ? null : this.body,\n signal: this.abortSignal,\n referrer: (_a = this.delegate.referrer) === null || _a === void 0 ? void 0 : _a.href\n };\n }\n get defaultHeaders() {\n return {\n Accept: \"text/html, application/xhtml+xml\"\n };\n }\n get isSafe() {\n return this.method === FetchMethod.get;\n }\n get abortSignal() {\n return this.abortController.signal;\n }\n acceptResponseType(mimeType) {\n this.headers[\"Accept\"] = [mimeType, this.headers[\"Accept\"]].join(\", \");\n }\n async allowRequestToBeIntercepted(fetchOptions) {\n const requestInterception = new Promise(resolve => this.resolveRequestPromise = resolve);\n const event = dispatch(\"turbo:before-fetch-request\", {\n cancelable: true,\n detail: {\n fetchOptions,\n url: this.url,\n resume: this.resolveRequestPromise\n },\n target: this.target\n });\n if (event.defaultPrevented) await requestInterception;\n }\n willDelegateErrorHandling(error) {\n const event = dispatch(\"turbo:fetch-request-error\", {\n target: this.target,\n cancelable: true,\n detail: {\n request: this,\n error: error\n }\n });\n return !event.defaultPrevented;\n }\n}\nclass AppearanceObserver {\n constructor(delegate, element) {\n this.started = false;\n this.intersect = entries => {\n const lastEntry = entries.slice(-1)[0];\n if (lastEntry === null || lastEntry === void 0 ? void 0 : lastEntry.isIntersecting) {\n this.delegate.elementAppearedInViewport(this.element);\n }\n };\n this.delegate = delegate;\n this.element = element;\n this.intersectionObserver = new IntersectionObserver(this.intersect);\n }\n start() {\n if (!this.started) {\n this.started = true;\n this.intersectionObserver.observe(this.element);\n }\n }\n stop() {\n if (this.started) {\n this.started = false;\n this.intersectionObserver.unobserve(this.element);\n }\n }\n}\nclass StreamMessage {\n static wrap(message) {\n if (typeof message == \"string\") {\n return new this(createDocumentFragment(message));\n } else {\n return message;\n }\n }\n constructor(fragment) {\n this.fragment = importStreamElements(fragment);\n }\n}\nStreamMessage.contentType = \"text/vnd.turbo-stream.html\";\nfunction importStreamElements(fragment) {\n for (const element of fragment.querySelectorAll(\"turbo-stream\")) {\n const streamElement = document.importNode(element, true);\n for (const inertScriptElement of streamElement.templateElement.content.querySelectorAll(\"script\")) {\n inertScriptElement.replaceWith(activateScriptElement(inertScriptElement));\n }\n element.replaceWith(streamElement);\n }\n return fragment;\n}\nvar FormSubmissionState;\n(function (FormSubmissionState) {\n FormSubmissionState[FormSubmissionState[\"initialized\"] = 0] = \"initialized\";\n FormSubmissionState[FormSubmissionState[\"requesting\"] = 1] = \"requesting\";\n FormSubmissionState[FormSubmissionState[\"waiting\"] = 2] = \"waiting\";\n FormSubmissionState[FormSubmissionState[\"receiving\"] = 3] = \"receiving\";\n FormSubmissionState[FormSubmissionState[\"stopping\"] = 4] = \"stopping\";\n FormSubmissionState[FormSubmissionState[\"stopped\"] = 5] = \"stopped\";\n})(FormSubmissionState || (FormSubmissionState = {}));\nvar FormEnctype;\n(function (FormEnctype) {\n FormEnctype[\"urlEncoded\"] = \"application/x-www-form-urlencoded\";\n FormEnctype[\"multipart\"] = \"multipart/form-data\";\n FormEnctype[\"plain\"] = \"text/plain\";\n})(FormEnctype || (FormEnctype = {}));\nfunction formEnctypeFromString(encoding) {\n switch (encoding.toLowerCase()) {\n case FormEnctype.multipart:\n return FormEnctype.multipart;\n case FormEnctype.plain:\n return FormEnctype.plain;\n default:\n return FormEnctype.urlEncoded;\n }\n}\nclass FormSubmission {\n static confirmMethod(message, _element, _submitter) {\n return Promise.resolve(confirm(message));\n }\n constructor(delegate, formElement, submitter) {\n let mustRedirect = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : false;\n this.state = FormSubmissionState.initialized;\n this.delegate = delegate;\n this.formElement = formElement;\n this.submitter = submitter;\n this.formData = buildFormData(formElement, submitter);\n this.location = expandURL(this.action);\n if (this.method == FetchMethod.get) {\n mergeFormDataEntries(this.location, [...this.body.entries()]);\n }\n this.fetchRequest = new FetchRequest(this, this.method, this.location, this.body, this.formElement);\n this.mustRedirect = mustRedirect;\n }\n get method() {\n var _a;\n const method = ((_a = this.submitter) === null || _a === void 0 ? void 0 : _a.getAttribute(\"formmethod\")) || this.formElement.getAttribute(\"method\") || \"\";\n return fetchMethodFromString(method.toLowerCase()) || FetchMethod.get;\n }\n get action() {\n var _a;\n const formElementAction = typeof this.formElement.action === \"string\" ? this.formElement.action : null;\n if ((_a = this.submitter) === null || _a === void 0 ? void 0 : _a.hasAttribute(\"formaction\")) {\n return this.submitter.getAttribute(\"formaction\") || \"\";\n } else {\n return this.formElement.getAttribute(\"action\") || formElementAction || \"\";\n }\n }\n get body() {\n if (this.enctype == FormEnctype.urlEncoded || this.method == FetchMethod.get) {\n return new URLSearchParams(this.stringFormData);\n } else {\n return this.formData;\n }\n }\n get enctype() {\n var _a;\n return formEnctypeFromString(((_a = this.submitter) === null || _a === void 0 ? void 0 : _a.getAttribute(\"formenctype\")) || this.formElement.enctype);\n }\n get isSafe() {\n return this.fetchRequest.isSafe;\n }\n get stringFormData() {\n return [...this.formData].reduce((entries, _ref3) => {\n let _ref4 = _slicedToArray(_ref3, 2),\n name = _ref4[0],\n value = _ref4[1];\n return entries.concat(typeof value == \"string\" ? [[name, value]] : []);\n }, []);\n }\n async start() {\n const _FormSubmissionState = FormSubmissionState,\n initialized = _FormSubmissionState.initialized,\n requesting = _FormSubmissionState.requesting;\n const confirmationMessage = getAttribute(\"data-turbo-confirm\", this.submitter, this.formElement);\n if (typeof confirmationMessage === \"string\") {\n const answer = await FormSubmission.confirmMethod(confirmationMessage, this.formElement, this.submitter);\n if (!answer) {\n return;\n }\n }\n if (this.state == initialized) {\n this.state = requesting;\n return this.fetchRequest.perform();\n }\n }\n stop() {\n const _FormSubmissionState2 = FormSubmissionState,\n stopping = _FormSubmissionState2.stopping,\n stopped = _FormSubmissionState2.stopped;\n if (this.state != stopping && this.state != stopped) {\n this.state = stopping;\n this.fetchRequest.cancel();\n return true;\n }\n }\n prepareRequest(request) {\n if (!request.isSafe) {\n const token = getCookieValue(getMetaContent(\"csrf-param\")) || getMetaContent(\"csrf-token\");\n if (token) {\n request.headers[\"X-CSRF-Token\"] = token;\n }\n }\n if (this.requestAcceptsTurboStreamResponse(request)) {\n request.acceptResponseType(StreamMessage.contentType);\n }\n }\n requestStarted(_request) {\n var _a;\n this.state = FormSubmissionState.waiting;\n (_a = this.submitter) === null || _a === void 0 ? void 0 : _a.setAttribute(\"disabled\", \"\");\n this.setSubmitsWith();\n dispatch(\"turbo:submit-start\", {\n target: this.formElement,\n detail: {\n formSubmission: this\n }\n });\n this.delegate.formSubmissionStarted(this);\n }\n requestPreventedHandlingResponse(request, response) {\n this.result = {\n success: response.succeeded,\n fetchResponse: response\n };\n }\n requestSucceededWithResponse(request, response) {\n if (response.clientError || response.serverError) {\n this.delegate.formSubmissionFailedWithResponse(this, response);\n } else if (this.requestMustRedirect(request) && responseSucceededWithoutRedirect(response)) {\n const error = new Error(\"Form responses must redirect to another location\");\n this.delegate.formSubmissionErrored(this, error);\n } else {\n this.state = FormSubmissionState.receiving;\n this.result = {\n success: true,\n fetchResponse: response\n };\n this.delegate.formSubmissionSucceededWithResponse(this, response);\n }\n }\n requestFailedWithResponse(request, response) {\n this.result = {\n success: false,\n fetchResponse: response\n };\n this.delegate.formSubmissionFailedWithResponse(this, response);\n }\n requestErrored(request, error) {\n this.result = {\n success: false,\n error\n };\n this.delegate.formSubmissionErrored(this, error);\n }\n requestFinished(_request) {\n var _a;\n this.state = FormSubmissionState.stopped;\n (_a = this.submitter) === null || _a === void 0 ? void 0 : _a.removeAttribute(\"disabled\");\n this.resetSubmitterText();\n dispatch(\"turbo:submit-end\", {\n target: this.formElement,\n detail: Object.assign({\n formSubmission: this\n }, this.result)\n });\n this.delegate.formSubmissionFinished(this);\n }\n setSubmitsWith() {\n if (!this.submitter || !this.submitsWith) return;\n if (this.submitter.matches(\"button\")) {\n this.originalSubmitText = this.submitter.innerHTML;\n this.submitter.innerHTML = this.submitsWith;\n } else if (this.submitter.matches(\"input\")) {\n const input = this.submitter;\n this.originalSubmitText = input.value;\n input.value = this.submitsWith;\n }\n }\n resetSubmitterText() {\n if (!this.submitter || !this.originalSubmitText) return;\n if (this.submitter.matches(\"button\")) {\n this.submitter.innerHTML = this.originalSubmitText;\n } else if (this.submitter.matches(\"input\")) {\n const input = this.submitter;\n input.value = this.originalSubmitText;\n }\n }\n requestMustRedirect(request) {\n return !request.isSafe && this.mustRedirect;\n }\n requestAcceptsTurboStreamResponse(request) {\n return !request.isSafe || hasAttribute(\"data-turbo-stream\", this.submitter, this.formElement);\n }\n get submitsWith() {\n var _a;\n return (_a = this.submitter) === null || _a === void 0 ? void 0 : _a.getAttribute(\"data-turbo-submits-with\");\n }\n}\nfunction buildFormData(formElement, submitter) {\n const formData = new FormData(formElement);\n const name = submitter === null || submitter === void 0 ? void 0 : submitter.getAttribute(\"name\");\n const value = submitter === null || submitter === void 0 ? void 0 : submitter.getAttribute(\"value\");\n if (name) {\n formData.append(name, value || \"\");\n }\n return formData;\n}\nfunction getCookieValue(cookieName) {\n if (cookieName != null) {\n const cookies = document.cookie ? document.cookie.split(\"; \") : [];\n const cookie = cookies.find(cookie => cookie.startsWith(cookieName));\n if (cookie) {\n const value = cookie.split(\"=\").slice(1).join(\"=\");\n return value ? decodeURIComponent(value) : undefined;\n }\n }\n}\nfunction responseSucceededWithoutRedirect(response) {\n return response.statusCode == 200 && !response.redirected;\n}\nfunction mergeFormDataEntries(url, entries) {\n const searchParams = new URLSearchParams();\n for (const _ref5 of entries) {\n var _ref6 = _slicedToArray(_ref5, 2);\n const name = _ref6[0];\n const value = _ref6[1];\n if (value instanceof File) continue;\n searchParams.append(name, value);\n }\n url.search = searchParams.toString();\n return url;\n}\nclass Snapshot {\n constructor(element) {\n this.element = element;\n }\n get activeElement() {\n return this.element.ownerDocument.activeElement;\n }\n get children() {\n return [...this.element.children];\n }\n hasAnchor(anchor) {\n return this.getElementForAnchor(anchor) != null;\n }\n getElementForAnchor(anchor) {\n return anchor ? this.element.querySelector(`[id='${anchor}'], a[name='${anchor}']`) : null;\n }\n get isConnected() {\n return this.element.isConnected;\n }\n get firstAutofocusableElement() {\n const inertDisabledOrHidden = \"[inert], :disabled, [hidden], details:not([open]), dialog:not([open])\";\n for (const element of this.element.querySelectorAll(\"[autofocus]\")) {\n if (element.closest(inertDisabledOrHidden) == null) return element;else continue;\n }\n return null;\n }\n get permanentElements() {\n return queryPermanentElementsAll(this.element);\n }\n getPermanentElementById(id) {\n return getPermanentElementById(this.element, id);\n }\n getPermanentElementMapForSnapshot(snapshot) {\n const permanentElementMap = {};\n for (const currentPermanentElement of this.permanentElements) {\n const id = currentPermanentElement.id;\n const newPermanentElement = snapshot.getPermanentElementById(id);\n if (newPermanentElement) {\n permanentElementMap[id] = [currentPermanentElement, newPermanentElement];\n }\n }\n return permanentElementMap;\n }\n}\nfunction getPermanentElementById(node, id) {\n return node.querySelector(`#${id}[data-turbo-permanent]`);\n}\nfunction queryPermanentElementsAll(node) {\n return node.querySelectorAll(\"[id][data-turbo-permanent]\");\n}\nclass FormSubmitObserver {\n constructor(delegate, eventTarget) {\n this.started = false;\n this.submitCaptured = () => {\n this.eventTarget.removeEventListener(\"submit\", this.submitBubbled, false);\n this.eventTarget.addEventListener(\"submit\", this.submitBubbled, false);\n };\n this.submitBubbled = event => {\n if (!event.defaultPrevented) {\n const form = event.target instanceof HTMLFormElement ? event.target : undefined;\n const submitter = event.submitter || undefined;\n if (form && submissionDoesNotDismissDialog(form, submitter) && submissionDoesNotTargetIFrame(form, submitter) && this.delegate.willSubmitForm(form, submitter)) {\n event.preventDefault();\n event.stopImmediatePropagation();\n this.delegate.formSubmitted(form, submitter);\n }\n }\n };\n this.delegate = delegate;\n this.eventTarget = eventTarget;\n }\n start() {\n if (!this.started) {\n this.eventTarget.addEventListener(\"submit\", this.submitCaptured, true);\n this.started = true;\n }\n }\n stop() {\n if (this.started) {\n this.eventTarget.removeEventListener(\"submit\", this.submitCaptured, true);\n this.started = false;\n }\n }\n}\nfunction submissionDoesNotDismissDialog(form, submitter) {\n const method = (submitter === null || submitter === void 0 ? void 0 : submitter.getAttribute(\"formmethod\")) || form.getAttribute(\"method\");\n return method != \"dialog\";\n}\nfunction submissionDoesNotTargetIFrame(form, submitter) {\n if ((submitter === null || submitter === void 0 ? void 0 : submitter.hasAttribute(\"formtarget\")) || form.hasAttribute(\"target\")) {\n const target = (submitter === null || submitter === void 0 ? void 0 : submitter.getAttribute(\"formtarget\")) || form.target;\n for (const element of document.getElementsByName(target)) {\n if (element instanceof HTMLIFrameElement) return false;\n }\n return true;\n } else {\n return true;\n }\n}\nclass View {\n constructor(delegate, element) {\n this.resolveRenderPromise = _value => {};\n this.resolveInterceptionPromise = _value => {};\n this.delegate = delegate;\n this.element = element;\n }\n scrollToAnchor(anchor) {\n const element = this.snapshot.getElementForAnchor(anchor);\n if (element) {\n this.scrollToElement(element);\n this.focusElement(element);\n } else {\n this.scrollToPosition({\n x: 0,\n y: 0\n });\n }\n }\n scrollToAnchorFromLocation(location) {\n this.scrollToAnchor(getAnchor(location));\n }\n scrollToElement(element) {\n element.scrollIntoView();\n }\n focusElement(element) {\n if (element instanceof HTMLElement) {\n if (element.hasAttribute(\"tabindex\")) {\n element.focus();\n } else {\n element.setAttribute(\"tabindex\", \"-1\");\n element.focus();\n element.removeAttribute(\"tabindex\");\n }\n }\n }\n scrollToPosition(_ref7) {\n let x = _ref7.x,\n y = _ref7.y;\n this.scrollRoot.scrollTo(x, y);\n }\n scrollToTop() {\n this.scrollToPosition({\n x: 0,\n y: 0\n });\n }\n get scrollRoot() {\n return window;\n }\n async render(renderer) {\n const isPreview = renderer.isPreview,\n shouldRender = renderer.shouldRender,\n snapshot = renderer.newSnapshot;\n if (shouldRender) {\n try {\n this.renderPromise = new Promise(resolve => this.resolveRenderPromise = resolve);\n this.renderer = renderer;\n await this.prepareToRenderSnapshot(renderer);\n const renderInterception = new Promise(resolve => this.resolveInterceptionPromise = resolve);\n const options = {\n resume: this.resolveInterceptionPromise,\n render: this.renderer.renderElement\n };\n const immediateRender = this.delegate.allowsImmediateRender(snapshot, options);\n if (!immediateRender) await renderInterception;\n await this.renderSnapshot(renderer);\n this.delegate.viewRenderedSnapshot(snapshot, isPreview);\n this.delegate.preloadOnLoadLinksForView(this.element);\n this.finishRenderingSnapshot(renderer);\n } finally {\n delete this.renderer;\n this.resolveRenderPromise(undefined);\n delete this.renderPromise;\n }\n } else {\n this.invalidate(renderer.reloadReason);\n }\n }\n invalidate(reason) {\n this.delegate.viewInvalidated(reason);\n }\n async prepareToRenderSnapshot(renderer) {\n this.markAsPreview(renderer.isPreview);\n await renderer.prepareToRender();\n }\n markAsPreview(isPreview) {\n if (isPreview) {\n this.element.setAttribute(\"data-turbo-preview\", \"\");\n } else {\n this.element.removeAttribute(\"data-turbo-preview\");\n }\n }\n async renderSnapshot(renderer) {\n await renderer.render();\n }\n finishRenderingSnapshot(renderer) {\n renderer.finishRendering();\n }\n}\nclass FrameView extends View {\n missing() {\n this.element.innerHTML = `Content missing`;\n }\n get snapshot() {\n return new Snapshot(this.element);\n }\n}\nclass LinkInterceptor {\n constructor(delegate, element) {\n this.clickBubbled = event => {\n if (this.respondsToEventTarget(event.target)) {\n this.clickEvent = event;\n } else {\n delete this.clickEvent;\n }\n };\n this.linkClicked = event => {\n if (this.clickEvent && this.respondsToEventTarget(event.target) && event.target instanceof Element) {\n if (this.delegate.shouldInterceptLinkClick(event.target, event.detail.url, event.detail.originalEvent)) {\n this.clickEvent.preventDefault();\n event.preventDefault();\n this.delegate.linkClickIntercepted(event.target, event.detail.url, event.detail.originalEvent);\n }\n }\n delete this.clickEvent;\n };\n this.willVisit = _event => {\n delete this.clickEvent;\n };\n this.delegate = delegate;\n this.element = element;\n }\n start() {\n this.element.addEventListener(\"click\", this.clickBubbled);\n document.addEventListener(\"turbo:click\", this.linkClicked);\n document.addEventListener(\"turbo:before-visit\", this.willVisit);\n }\n stop() {\n this.element.removeEventListener(\"click\", this.clickBubbled);\n document.removeEventListener(\"turbo:click\", this.linkClicked);\n document.removeEventListener(\"turbo:before-visit\", this.willVisit);\n }\n respondsToEventTarget(target) {\n const element = target instanceof Element ? target : target instanceof Node ? target.parentElement : null;\n return element && element.closest(\"turbo-frame, html\") == this.element;\n }\n}\nclass LinkClickObserver {\n constructor(delegate, eventTarget) {\n this.started = false;\n this.clickCaptured = () => {\n this.eventTarget.removeEventListener(\"click\", this.clickBubbled, false);\n this.eventTarget.addEventListener(\"click\", this.clickBubbled, false);\n };\n this.clickBubbled = event => {\n if (event instanceof MouseEvent && this.clickEventIsSignificant(event)) {\n const target = event.composedPath && event.composedPath()[0] || event.target;\n const link = this.findLinkFromClickTarget(target);\n if (link && doesNotTargetIFrame(link)) {\n const location = this.getLocationForLink(link);\n if (this.delegate.willFollowLinkToLocation(link, location, event)) {\n event.preventDefault();\n this.delegate.followedLinkToLocation(link, location);\n }\n }\n }\n };\n this.delegate = delegate;\n this.eventTarget = eventTarget;\n }\n start() {\n if (!this.started) {\n this.eventTarget.addEventListener(\"click\", this.clickCaptured, true);\n this.started = true;\n }\n }\n stop() {\n if (this.started) {\n this.eventTarget.removeEventListener(\"click\", this.clickCaptured, true);\n this.started = false;\n }\n }\n clickEventIsSignificant(event) {\n return !(event.target && event.target.isContentEditable || event.defaultPrevented || event.which > 1 || event.altKey || event.ctrlKey || event.metaKey || event.shiftKey);\n }\n findLinkFromClickTarget(target) {\n return findClosestRecursively(target, \"a[href]:not([target^=_]):not([download])\");\n }\n getLocationForLink(link) {\n return expandURL(link.getAttribute(\"href\") || \"\");\n }\n}\nfunction doesNotTargetIFrame(anchor) {\n if (anchor.hasAttribute(\"target\")) {\n for (const element of document.getElementsByName(anchor.target)) {\n if (element instanceof HTMLIFrameElement) return false;\n }\n return true;\n } else {\n return true;\n }\n}\nclass FormLinkClickObserver {\n constructor(delegate, element) {\n this.delegate = delegate;\n this.linkInterceptor = new LinkClickObserver(this, element);\n }\n start() {\n this.linkInterceptor.start();\n }\n stop() {\n this.linkInterceptor.stop();\n }\n willFollowLinkToLocation(link, location, originalEvent) {\n return this.delegate.willSubmitFormLinkToLocation(link, location, originalEvent) && link.hasAttribute(\"data-turbo-method\");\n }\n followedLinkToLocation(link, location) {\n const form = document.createElement(\"form\");\n const type = \"hidden\";\n for (const _ref8 of location.searchParams) {\n var _ref9 = _slicedToArray(_ref8, 2);\n const name = _ref9[0];\n const value = _ref9[1];\n form.append(Object.assign(document.createElement(\"input\"), {\n type,\n name,\n value\n }));\n }\n const action = Object.assign(location, {\n search: \"\"\n });\n form.setAttribute(\"data-turbo\", \"true\");\n form.setAttribute(\"action\", action.href);\n form.setAttribute(\"hidden\", \"\");\n const method = link.getAttribute(\"data-turbo-method\");\n if (method) form.setAttribute(\"method\", method);\n const turboFrame = link.getAttribute(\"data-turbo-frame\");\n if (turboFrame) form.setAttribute(\"data-turbo-frame\", turboFrame);\n const turboAction = getVisitAction(link);\n if (turboAction) form.setAttribute(\"data-turbo-action\", turboAction);\n const turboConfirm = link.getAttribute(\"data-turbo-confirm\");\n if (turboConfirm) form.setAttribute(\"data-turbo-confirm\", turboConfirm);\n const turboStream = link.hasAttribute(\"data-turbo-stream\");\n if (turboStream) form.setAttribute(\"data-turbo-stream\", \"\");\n this.delegate.submittedFormLinkToLocation(link, location, form);\n document.body.appendChild(form);\n form.addEventListener(\"turbo:submit-end\", () => form.remove(), {\n once: true\n });\n requestAnimationFrame(() => form.requestSubmit());\n }\n}\nclass Bardo {\n static async preservingPermanentElements(delegate, permanentElementMap, callback) {\n const bardo = new this(delegate, permanentElementMap);\n bardo.enter();\n await callback();\n bardo.leave();\n }\n constructor(delegate, permanentElementMap) {\n this.delegate = delegate;\n this.permanentElementMap = permanentElementMap;\n }\n enter() {\n for (const id in this.permanentElementMap) {\n const _this$permanentElemen = _slicedToArray(this.permanentElementMap[id], 2),\n currentPermanentElement = _this$permanentElemen[0],\n newPermanentElement = _this$permanentElemen[1];\n this.delegate.enteringBardo(currentPermanentElement, newPermanentElement);\n this.replaceNewPermanentElementWithPlaceholder(newPermanentElement);\n }\n }\n leave() {\n for (const id in this.permanentElementMap) {\n const _this$permanentElemen2 = _slicedToArray(this.permanentElementMap[id], 1),\n currentPermanentElement = _this$permanentElemen2[0];\n this.replaceCurrentPermanentElementWithClone(currentPermanentElement);\n this.replacePlaceholderWithPermanentElement(currentPermanentElement);\n this.delegate.leavingBardo(currentPermanentElement);\n }\n }\n replaceNewPermanentElementWithPlaceholder(permanentElement) {\n const placeholder = createPlaceholderForPermanentElement(permanentElement);\n permanentElement.replaceWith(placeholder);\n }\n replaceCurrentPermanentElementWithClone(permanentElement) {\n const clone = permanentElement.cloneNode(true);\n permanentElement.replaceWith(clone);\n }\n replacePlaceholderWithPermanentElement(permanentElement) {\n const placeholder = this.getPlaceholderById(permanentElement.id);\n placeholder === null || placeholder === void 0 ? void 0 : placeholder.replaceWith(permanentElement);\n }\n getPlaceholderById(id) {\n return this.placeholders.find(element => element.content == id);\n }\n get placeholders() {\n return [...document.querySelectorAll(\"meta[name=turbo-permanent-placeholder][content]\")];\n }\n}\nfunction createPlaceholderForPermanentElement(permanentElement) {\n const element = document.createElement(\"meta\");\n element.setAttribute(\"name\", \"turbo-permanent-placeholder\");\n element.setAttribute(\"content\", permanentElement.id);\n return element;\n}\nclass Renderer {\n constructor(currentSnapshot, newSnapshot, renderElement, isPreview) {\n let willRender = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : true;\n this.activeElement = null;\n this.currentSnapshot = currentSnapshot;\n this.newSnapshot = newSnapshot;\n this.isPreview = isPreview;\n this.willRender = willRender;\n this.renderElement = renderElement;\n this.promise = new Promise((resolve, reject) => this.resolvingFunctions = {\n resolve,\n reject\n });\n }\n get shouldRender() {\n return true;\n }\n get reloadReason() {\n return;\n }\n prepareToRender() {\n return;\n }\n finishRendering() {\n if (this.resolvingFunctions) {\n this.resolvingFunctions.resolve();\n delete this.resolvingFunctions;\n }\n }\n async preservingPermanentElements(callback) {\n await Bardo.preservingPermanentElements(this, this.permanentElementMap, callback);\n }\n focusFirstAutofocusableElement() {\n const element = this.connectedSnapshot.firstAutofocusableElement;\n if (elementIsFocusable(element)) {\n element.focus();\n }\n }\n enteringBardo(currentPermanentElement) {\n if (this.activeElement) return;\n if (currentPermanentElement.contains(this.currentSnapshot.activeElement)) {\n this.activeElement = this.currentSnapshot.activeElement;\n }\n }\n leavingBardo(currentPermanentElement) {\n if (currentPermanentElement.contains(this.activeElement) && this.activeElement instanceof HTMLElement) {\n this.activeElement.focus();\n this.activeElement = null;\n }\n }\n get connectedSnapshot() {\n return this.newSnapshot.isConnected ? this.newSnapshot : this.currentSnapshot;\n }\n get currentElement() {\n return this.currentSnapshot.element;\n }\n get newElement() {\n return this.newSnapshot.element;\n }\n get permanentElementMap() {\n return this.currentSnapshot.getPermanentElementMapForSnapshot(this.newSnapshot);\n }\n}\nfunction elementIsFocusable(element) {\n return element && typeof element.focus == \"function\";\n}\nclass FrameRenderer extends Renderer {\n static renderElement(currentElement, newElement) {\n var _a;\n const destinationRange = document.createRange();\n destinationRange.selectNodeContents(currentElement);\n destinationRange.deleteContents();\n const frameElement = newElement;\n const sourceRange = (_a = frameElement.ownerDocument) === null || _a === void 0 ? void 0 : _a.createRange();\n if (sourceRange) {\n sourceRange.selectNodeContents(frameElement);\n currentElement.appendChild(sourceRange.extractContents());\n }\n }\n constructor(delegate, currentSnapshot, newSnapshot, renderElement, isPreview) {\n let willRender = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : true;\n super(currentSnapshot, newSnapshot, renderElement, isPreview, willRender);\n this.delegate = delegate;\n }\n get shouldRender() {\n return true;\n }\n async render() {\n await nextAnimationFrame();\n this.preservingPermanentElements(() => {\n this.loadFrameElement();\n });\n this.scrollFrameIntoView();\n await nextAnimationFrame();\n this.focusFirstAutofocusableElement();\n await nextAnimationFrame();\n this.activateScriptElements();\n }\n loadFrameElement() {\n this.delegate.willRenderFrame(this.currentElement, this.newElement);\n this.renderElement(this.currentElement, this.newElement);\n }\n scrollFrameIntoView() {\n if (this.currentElement.autoscroll || this.newElement.autoscroll) {\n const element = this.currentElement.firstElementChild;\n const block = readScrollLogicalPosition(this.currentElement.getAttribute(\"data-autoscroll-block\"), \"end\");\n const behavior = readScrollBehavior(this.currentElement.getAttribute(\"data-autoscroll-behavior\"), \"auto\");\n if (element) {\n element.scrollIntoView({\n block,\n behavior\n });\n return true;\n }\n }\n return false;\n }\n activateScriptElements() {\n for (const inertScriptElement of this.newScriptElements) {\n const activatedScriptElement = activateScriptElement(inertScriptElement);\n inertScriptElement.replaceWith(activatedScriptElement);\n }\n }\n get newScriptElements() {\n return this.currentElement.querySelectorAll(\"script\");\n }\n}\nfunction readScrollLogicalPosition(value, defaultValue) {\n if (value == \"end\" || value == \"start\" || value == \"center\" || value == \"nearest\") {\n return value;\n } else {\n return defaultValue;\n }\n}\nfunction readScrollBehavior(value, defaultValue) {\n if (value == \"auto\" || value == \"smooth\") {\n return value;\n } else {\n return defaultValue;\n }\n}\nclass ProgressBar {\n static get defaultCSS() {\n return unindent`\n .turbo-progress-bar {\n position: fixed;\n display: block;\n top: 0;\n left: 0;\n height: 3px;\n background: #0076ff;\n z-index: 2147483647;\n transition:\n width ${ProgressBar.animationDuration}ms ease-out,\n opacity ${ProgressBar.animationDuration / 2}ms ${ProgressBar.animationDuration / 2}ms ease-in;\n transform: translate3d(0, 0, 0);\n }\n `;\n }\n constructor() {\n this.hiding = false;\n this.value = 0;\n this.visible = false;\n this.trickle = () => {\n this.setValue(this.value + Math.random() / 100);\n };\n this.stylesheetElement = this.createStylesheetElement();\n this.progressElement = this.createProgressElement();\n this.installStylesheetElement();\n this.setValue(0);\n }\n show() {\n if (!this.visible) {\n this.visible = true;\n this.installProgressElement();\n this.startTrickling();\n }\n }\n hide() {\n if (this.visible && !this.hiding) {\n this.hiding = true;\n this.fadeProgressElement(() => {\n this.uninstallProgressElement();\n this.stopTrickling();\n this.visible = false;\n this.hiding = false;\n });\n }\n }\n setValue(value) {\n this.value = value;\n this.refresh();\n }\n installStylesheetElement() {\n document.head.insertBefore(this.stylesheetElement, document.head.firstChild);\n }\n installProgressElement() {\n this.progressElement.style.width = \"0\";\n this.progressElement.style.opacity = \"1\";\n document.documentElement.insertBefore(this.progressElement, document.body);\n this.refresh();\n }\n fadeProgressElement(callback) {\n this.progressElement.style.opacity = \"0\";\n setTimeout(callback, ProgressBar.animationDuration * 1.5);\n }\n uninstallProgressElement() {\n if (this.progressElement.parentNode) {\n document.documentElement.removeChild(this.progressElement);\n }\n }\n startTrickling() {\n if (!this.trickleInterval) {\n this.trickleInterval = window.setInterval(this.trickle, ProgressBar.animationDuration);\n }\n }\n stopTrickling() {\n window.clearInterval(this.trickleInterval);\n delete this.trickleInterval;\n }\n refresh() {\n requestAnimationFrame(() => {\n this.progressElement.style.width = `${10 + this.value * 90}%`;\n });\n }\n createStylesheetElement() {\n const element = document.createElement(\"style\");\n element.type = \"text/css\";\n element.textContent = ProgressBar.defaultCSS;\n if (this.cspNonce) {\n element.nonce = this.cspNonce;\n }\n return element;\n }\n createProgressElement() {\n const element = document.createElement(\"div\");\n element.className = \"turbo-progress-bar\";\n return element;\n }\n get cspNonce() {\n return getMetaContent(\"csp-nonce\");\n }\n}\nProgressBar.animationDuration = 300;\nclass HeadSnapshot extends Snapshot {\n constructor() {\n super(...arguments);\n this.detailsByOuterHTML = this.children.filter(element => !elementIsNoscript(element)).map(element => elementWithoutNonce(element)).reduce((result, element) => {\n const outerHTML = element.outerHTML;\n const details = outerHTML in result ? result[outerHTML] : {\n type: elementType(element),\n tracked: elementIsTracked(element),\n elements: []\n };\n return Object.assign(Object.assign({}, result), {\n [outerHTML]: Object.assign(Object.assign({}, details), {\n elements: [...details.elements, element]\n })\n });\n }, {});\n }\n get trackedElementSignature() {\n return Object.keys(this.detailsByOuterHTML).filter(outerHTML => this.detailsByOuterHTML[outerHTML].tracked).join(\"\");\n }\n getScriptElementsNotInSnapshot(snapshot) {\n return this.getElementsMatchingTypeNotInSnapshot(\"script\", snapshot);\n }\n getStylesheetElementsNotInSnapshot(snapshot) {\n return this.getElementsMatchingTypeNotInSnapshot(\"stylesheet\", snapshot);\n }\n getElementsMatchingTypeNotInSnapshot(matchedType, snapshot) {\n return Object.keys(this.detailsByOuterHTML).filter(outerHTML => !(outerHTML in snapshot.detailsByOuterHTML)).map(outerHTML => this.detailsByOuterHTML[outerHTML]).filter(_ref10 => {\n let type = _ref10.type;\n return type == matchedType;\n }).map(_ref11 => {\n let _ref11$elements = _slicedToArray(_ref11.elements, 1),\n element = _ref11$elements[0];\n return element;\n });\n }\n get provisionalElements() {\n return Object.keys(this.detailsByOuterHTML).reduce((result, outerHTML) => {\n const _this$detailsByOuterH = this.detailsByOuterHTML[outerHTML],\n type = _this$detailsByOuterH.type,\n tracked = _this$detailsByOuterH.tracked,\n elements = _this$detailsByOuterH.elements;\n if (type == null && !tracked) {\n return [...result, ...elements];\n } else if (elements.length > 1) {\n return [...result, ...elements.slice(1)];\n } else {\n return result;\n }\n }, []);\n }\n getMetaValue(name) {\n const element = this.findMetaElementByName(name);\n return element ? element.getAttribute(\"content\") : null;\n }\n findMetaElementByName(name) {\n return Object.keys(this.detailsByOuterHTML).reduce((result, outerHTML) => {\n const _this$detailsByOuterH2 = _slicedToArray(this.detailsByOuterHTML[outerHTML].elements, 1),\n element = _this$detailsByOuterH2[0];\n return elementIsMetaElementWithName(element, name) ? element : result;\n }, undefined);\n }\n}\nfunction elementType(element) {\n if (elementIsScript(element)) {\n return \"script\";\n } else if (elementIsStylesheet(element)) {\n return \"stylesheet\";\n }\n}\nfunction elementIsTracked(element) {\n return element.getAttribute(\"data-turbo-track\") == \"reload\";\n}\nfunction elementIsScript(element) {\n const tagName = element.localName;\n return tagName == \"script\";\n}\nfunction elementIsNoscript(element) {\n const tagName = element.localName;\n return tagName == \"noscript\";\n}\nfunction elementIsStylesheet(element) {\n const tagName = element.localName;\n return tagName == \"style\" || tagName == \"link\" && element.getAttribute(\"rel\") == \"stylesheet\";\n}\nfunction elementIsMetaElementWithName(element, name) {\n const tagName = element.localName;\n return tagName == \"meta\" && element.getAttribute(\"name\") == name;\n}\nfunction elementWithoutNonce(element) {\n if (element.hasAttribute(\"nonce\")) {\n element.setAttribute(\"nonce\", \"\");\n }\n return element;\n}\nclass PageSnapshot extends Snapshot {\n static fromHTMLString() {\n let html = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : \"\";\n return this.fromDocument(parseHTMLDocument(html));\n }\n static fromElement(element) {\n return this.fromDocument(element.ownerDocument);\n }\n static fromDocument(_ref12) {\n let head = _ref12.head,\n body = _ref12.body;\n return new this(body, new HeadSnapshot(head));\n }\n constructor(element, headSnapshot) {\n super(element);\n this.headSnapshot = headSnapshot;\n }\n clone() {\n const clonedElement = this.element.cloneNode(true);\n const selectElements = this.element.querySelectorAll(\"select\");\n const clonedSelectElements = clonedElement.querySelectorAll(\"select\");\n for (const _ref13 of selectElements.entries()) {\n var _ref14 = _slicedToArray(_ref13, 2);\n const index = _ref14[0];\n const source = _ref14[1];\n const clone = clonedSelectElements[index];\n for (const option of clone.selectedOptions) option.selected = false;\n for (const option of source.selectedOptions) clone.options[option.index].selected = true;\n }\n for (const clonedPasswordInput of clonedElement.querySelectorAll('input[type=\"password\"]')) {\n clonedPasswordInput.value = \"\";\n }\n return new PageSnapshot(clonedElement, this.headSnapshot);\n }\n get headElement() {\n return this.headSnapshot.element;\n }\n get rootLocation() {\n var _a;\n const root = (_a = this.getSetting(\"root\")) !== null && _a !== void 0 ? _a : \"/\";\n return expandURL(root);\n }\n get cacheControlValue() {\n return this.getSetting(\"cache-control\");\n }\n get isPreviewable() {\n return this.cacheControlValue != \"no-preview\";\n }\n get isCacheable() {\n return this.cacheControlValue != \"no-cache\";\n }\n get isVisitable() {\n return this.getSetting(\"visit-control\") != \"reload\";\n }\n getSetting(name) {\n return this.headSnapshot.getMetaValue(`turbo-${name}`);\n }\n}\nvar TimingMetric;\n(function (TimingMetric) {\n TimingMetric[\"visitStart\"] = \"visitStart\";\n TimingMetric[\"requestStart\"] = \"requestStart\";\n TimingMetric[\"requestEnd\"] = \"requestEnd\";\n TimingMetric[\"visitEnd\"] = \"visitEnd\";\n})(TimingMetric || (TimingMetric = {}));\nvar VisitState;\n(function (VisitState) {\n VisitState[\"initialized\"] = \"initialized\";\n VisitState[\"started\"] = \"started\";\n VisitState[\"canceled\"] = \"canceled\";\n VisitState[\"failed\"] = \"failed\";\n VisitState[\"completed\"] = \"completed\";\n})(VisitState || (VisitState = {}));\nconst defaultOptions = {\n action: \"advance\",\n historyChanged: false,\n visitCachedSnapshot: () => {},\n willRender: true,\n updateHistory: true,\n shouldCacheSnapshot: true,\n acceptsStreamResponse: false\n};\nvar SystemStatusCode;\n(function (SystemStatusCode) {\n SystemStatusCode[SystemStatusCode[\"networkFailure\"] = 0] = \"networkFailure\";\n SystemStatusCode[SystemStatusCode[\"timeoutFailure\"] = -1] = \"timeoutFailure\";\n SystemStatusCode[SystemStatusCode[\"contentTypeMismatch\"] = -2] = \"contentTypeMismatch\";\n})(SystemStatusCode || (SystemStatusCode = {}));\nclass Visit {\n constructor(delegate, location, restorationIdentifier) {\n let options = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {};\n this.identifier = uuid();\n this.timingMetrics = {};\n this.followedRedirect = false;\n this.historyChanged = false;\n this.scrolled = false;\n this.shouldCacheSnapshot = true;\n this.acceptsStreamResponse = false;\n this.snapshotCached = false;\n this.state = VisitState.initialized;\n this.delegate = delegate;\n this.location = location;\n this.restorationIdentifier = restorationIdentifier || uuid();\n const _Object$assign = Object.assign(Object.assign({}, defaultOptions), options),\n action = _Object$assign.action,\n historyChanged = _Object$assign.historyChanged,\n referrer = _Object$assign.referrer,\n snapshot = _Object$assign.snapshot,\n snapshotHTML = _Object$assign.snapshotHTML,\n response = _Object$assign.response,\n visitCachedSnapshot = _Object$assign.visitCachedSnapshot,\n willRender = _Object$assign.willRender,\n updateHistory = _Object$assign.updateHistory,\n shouldCacheSnapshot = _Object$assign.shouldCacheSnapshot,\n acceptsStreamResponse = _Object$assign.acceptsStreamResponse;\n this.action = action;\n this.historyChanged = historyChanged;\n this.referrer = referrer;\n this.snapshot = snapshot;\n this.snapshotHTML = snapshotHTML;\n this.response = response;\n this.isSamePage = this.delegate.locationWithActionIsSamePage(this.location, this.action);\n this.visitCachedSnapshot = visitCachedSnapshot;\n this.willRender = willRender;\n this.updateHistory = updateHistory;\n this.scrolled = !willRender;\n this.shouldCacheSnapshot = shouldCacheSnapshot;\n this.acceptsStreamResponse = acceptsStreamResponse;\n }\n get adapter() {\n return this.delegate.adapter;\n }\n get view() {\n return this.delegate.view;\n }\n get history() {\n return this.delegate.history;\n }\n get restorationData() {\n return this.history.getRestorationDataForIdentifier(this.restorationIdentifier);\n }\n get silent() {\n return this.isSamePage;\n }\n start() {\n if (this.state == VisitState.initialized) {\n this.recordTimingMetric(TimingMetric.visitStart);\n this.state = VisitState.started;\n this.adapter.visitStarted(this);\n this.delegate.visitStarted(this);\n }\n }\n cancel() {\n if (this.state == VisitState.started) {\n if (this.request) {\n this.request.cancel();\n }\n this.cancelRender();\n this.state = VisitState.canceled;\n }\n }\n complete() {\n if (this.state == VisitState.started) {\n this.recordTimingMetric(TimingMetric.visitEnd);\n this.state = VisitState.completed;\n this.followRedirect();\n if (!this.followedRedirect) {\n this.adapter.visitCompleted(this);\n this.delegate.visitCompleted(this);\n }\n }\n }\n fail() {\n if (this.state == VisitState.started) {\n this.state = VisitState.failed;\n this.adapter.visitFailed(this);\n }\n }\n changeHistory() {\n var _a;\n if (!this.historyChanged && this.updateHistory) {\n const actionForHistory = this.location.href === ((_a = this.referrer) === null || _a === void 0 ? void 0 : _a.href) ? \"replace\" : this.action;\n const method = getHistoryMethodForAction(actionForHistory);\n this.history.update(method, this.location, this.restorationIdentifier);\n this.historyChanged = true;\n }\n }\n issueRequest() {\n if (this.hasPreloadedResponse()) {\n this.simulateRequest();\n } else if (this.shouldIssueRequest() && !this.request) {\n this.request = new FetchRequest(this, FetchMethod.get, this.location);\n this.request.perform();\n }\n }\n simulateRequest() {\n if (this.response) {\n this.startRequest();\n this.recordResponse();\n this.finishRequest();\n }\n }\n startRequest() {\n this.recordTimingMetric(TimingMetric.requestStart);\n this.adapter.visitRequestStarted(this);\n }\n recordResponse() {\n let response = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : this.response;\n this.response = response;\n if (response) {\n const statusCode = response.statusCode;\n if (isSuccessful(statusCode)) {\n this.adapter.visitRequestCompleted(this);\n } else {\n this.adapter.visitRequestFailedWithStatusCode(this, statusCode);\n }\n }\n }\n finishRequest() {\n this.recordTimingMetric(TimingMetric.requestEnd);\n this.adapter.visitRequestFinished(this);\n }\n loadResponse() {\n if (this.response) {\n const _this$response = this.response,\n statusCode = _this$response.statusCode,\n responseHTML = _this$response.responseHTML;\n this.render(async () => {\n if (this.shouldCacheSnapshot) this.cacheSnapshot();\n if (this.view.renderPromise) await this.view.renderPromise;\n if (isSuccessful(statusCode) && responseHTML != null) {\n await this.view.renderPage(PageSnapshot.fromHTMLString(responseHTML), false, this.willRender, this);\n this.performScroll();\n this.adapter.visitRendered(this);\n this.complete();\n } else {\n await this.view.renderError(PageSnapshot.fromHTMLString(responseHTML), this);\n this.adapter.visitRendered(this);\n this.fail();\n }\n });\n }\n }\n getCachedSnapshot() {\n const snapshot = this.view.getCachedSnapshotForLocation(this.location) || this.getPreloadedSnapshot();\n if (snapshot && (!getAnchor(this.location) || snapshot.hasAnchor(getAnchor(this.location)))) {\n if (this.action == \"restore\" || snapshot.isPreviewable) {\n return snapshot;\n }\n }\n }\n getPreloadedSnapshot() {\n if (this.snapshotHTML) {\n return PageSnapshot.fromHTMLString(this.snapshotHTML);\n }\n }\n hasCachedSnapshot() {\n return this.getCachedSnapshot() != null;\n }\n loadCachedSnapshot() {\n const snapshot = this.getCachedSnapshot();\n if (snapshot) {\n const isPreview = this.shouldIssueRequest();\n this.render(async () => {\n this.cacheSnapshot();\n if (this.isSamePage) {\n this.adapter.visitRendered(this);\n } else {\n if (this.view.renderPromise) await this.view.renderPromise;\n await this.view.renderPage(snapshot, isPreview, this.willRender, this);\n this.performScroll();\n this.adapter.visitRendered(this);\n if (!isPreview) {\n this.complete();\n }\n }\n });\n }\n }\n followRedirect() {\n var _a;\n if (this.redirectedToLocation && !this.followedRedirect && ((_a = this.response) === null || _a === void 0 ? void 0 : _a.redirected)) {\n this.adapter.visitProposedToLocation(this.redirectedToLocation, {\n action: \"replace\",\n response: this.response,\n shouldCacheSnapshot: false,\n willRender: false\n });\n this.followedRedirect = true;\n }\n }\n goToSamePageAnchor() {\n if (this.isSamePage) {\n this.render(async () => {\n this.cacheSnapshot();\n this.performScroll();\n this.changeHistory();\n this.adapter.visitRendered(this);\n });\n }\n }\n prepareRequest(request) {\n if (this.acceptsStreamResponse) {\n request.acceptResponseType(StreamMessage.contentType);\n }\n }\n requestStarted() {\n this.startRequest();\n }\n requestPreventedHandlingResponse(_request, _response) {}\n async requestSucceededWithResponse(request, response) {\n const responseHTML = await response.responseHTML;\n const redirected = response.redirected,\n statusCode = response.statusCode;\n if (responseHTML == undefined) {\n this.recordResponse({\n statusCode: SystemStatusCode.contentTypeMismatch,\n redirected\n });\n } else {\n this.redirectedToLocation = response.redirected ? response.location : undefined;\n this.recordResponse({\n statusCode: statusCode,\n responseHTML,\n redirected\n });\n }\n }\n async requestFailedWithResponse(request, response) {\n const responseHTML = await response.responseHTML;\n const redirected = response.redirected,\n statusCode = response.statusCode;\n if (responseHTML == undefined) {\n this.recordResponse({\n statusCode: SystemStatusCode.contentTypeMismatch,\n redirected\n });\n } else {\n this.recordResponse({\n statusCode: statusCode,\n responseHTML,\n redirected\n });\n }\n }\n requestErrored(_request, _error) {\n this.recordResponse({\n statusCode: SystemStatusCode.networkFailure,\n redirected: false\n });\n }\n requestFinished() {\n this.finishRequest();\n }\n performScroll() {\n if (!this.scrolled && !this.view.forceReloaded) {\n if (this.action == \"restore\") {\n this.scrollToRestoredPosition() || this.scrollToAnchor() || this.view.scrollToTop();\n } else {\n this.scrollToAnchor() || this.view.scrollToTop();\n }\n if (this.isSamePage) {\n this.delegate.visitScrolledToSamePageLocation(this.view.lastRenderedLocation, this.location);\n }\n this.scrolled = true;\n }\n }\n scrollToRestoredPosition() {\n const scrollPosition = this.restorationData.scrollPosition;\n if (scrollPosition) {\n this.view.scrollToPosition(scrollPosition);\n return true;\n }\n }\n scrollToAnchor() {\n const anchor = getAnchor(this.location);\n if (anchor != null) {\n this.view.scrollToAnchor(anchor);\n return true;\n }\n }\n recordTimingMetric(metric) {\n this.timingMetrics[metric] = new Date().getTime();\n }\n getTimingMetrics() {\n return Object.assign({}, this.timingMetrics);\n }\n getHistoryMethodForAction(action) {\n switch (action) {\n case \"replace\":\n return history.replaceState;\n case \"advance\":\n case \"restore\":\n return history.pushState;\n }\n }\n hasPreloadedResponse() {\n return typeof this.response == \"object\";\n }\n shouldIssueRequest() {\n if (this.isSamePage) {\n return false;\n } else if (this.action == \"restore\") {\n return !this.hasCachedSnapshot();\n } else {\n return this.willRender;\n }\n }\n cacheSnapshot() {\n if (!this.snapshotCached) {\n this.view.cacheSnapshot(this.snapshot).then(snapshot => snapshot && this.visitCachedSnapshot(snapshot));\n this.snapshotCached = true;\n }\n }\n async render(callback) {\n this.cancelRender();\n await new Promise(resolve => {\n this.frame = requestAnimationFrame(() => resolve());\n });\n await callback();\n delete this.frame;\n }\n cancelRender() {\n if (this.frame) {\n cancelAnimationFrame(this.frame);\n delete this.frame;\n }\n }\n}\nfunction isSuccessful(statusCode) {\n return statusCode >= 200 && statusCode < 300;\n}\nclass BrowserAdapter {\n constructor(session) {\n this.progressBar = new ProgressBar();\n this.showProgressBar = () => {\n this.progressBar.show();\n };\n this.session = session;\n }\n visitProposedToLocation(location, options) {\n this.navigator.startVisit(location, (options === null || options === void 0 ? void 0 : options.restorationIdentifier) || uuid(), options);\n }\n visitStarted(visit) {\n this.location = visit.location;\n visit.loadCachedSnapshot();\n visit.issueRequest();\n visit.goToSamePageAnchor();\n }\n visitRequestStarted(visit) {\n this.progressBar.setValue(0);\n if (visit.hasCachedSnapshot() || visit.action != \"restore\") {\n this.showVisitProgressBarAfterDelay();\n } else {\n this.showProgressBar();\n }\n }\n visitRequestCompleted(visit) {\n visit.loadResponse();\n }\n visitRequestFailedWithStatusCode(visit, statusCode) {\n switch (statusCode) {\n case SystemStatusCode.networkFailure:\n case SystemStatusCode.timeoutFailure:\n case SystemStatusCode.contentTypeMismatch:\n return this.reload({\n reason: \"request_failed\",\n context: {\n statusCode\n }\n });\n default:\n return visit.loadResponse();\n }\n }\n visitRequestFinished(_visit) {\n this.progressBar.setValue(1);\n this.hideVisitProgressBar();\n }\n visitCompleted(_visit) {}\n pageInvalidated(reason) {\n this.reload(reason);\n }\n visitFailed(_visit) {}\n visitRendered(_visit) {}\n formSubmissionStarted(_formSubmission) {\n this.progressBar.setValue(0);\n this.showFormProgressBarAfterDelay();\n }\n formSubmissionFinished(_formSubmission) {\n this.progressBar.setValue(1);\n this.hideFormProgressBar();\n }\n showVisitProgressBarAfterDelay() {\n this.visitProgressBarTimeout = window.setTimeout(this.showProgressBar, this.session.progressBarDelay);\n }\n hideVisitProgressBar() {\n this.progressBar.hide();\n if (this.visitProgressBarTimeout != null) {\n window.clearTimeout(this.visitProgressBarTimeout);\n delete this.visitProgressBarTimeout;\n }\n }\n showFormProgressBarAfterDelay() {\n if (this.formProgressBarTimeout == null) {\n this.formProgressBarTimeout = window.setTimeout(this.showProgressBar, this.session.progressBarDelay);\n }\n }\n hideFormProgressBar() {\n this.progressBar.hide();\n if (this.formProgressBarTimeout != null) {\n window.clearTimeout(this.formProgressBarTimeout);\n delete this.formProgressBarTimeout;\n }\n }\n reload(reason) {\n var _a;\n dispatch(\"turbo:reload\", {\n detail: reason\n });\n window.location.href = ((_a = this.location) === null || _a === void 0 ? void 0 : _a.toString()) || window.location.href;\n }\n get navigator() {\n return this.session.navigator;\n }\n}\nclass CacheObserver {\n constructor() {\n this.selector = \"[data-turbo-temporary]\";\n this.deprecatedSelector = \"[data-turbo-cache=false]\";\n this.started = false;\n this.removeTemporaryElements = _event => {\n for (const element of this.temporaryElements) {\n element.remove();\n }\n };\n }\n start() {\n if (!this.started) {\n this.started = true;\n addEventListener(\"turbo:before-cache\", this.removeTemporaryElements, false);\n }\n }\n stop() {\n if (this.started) {\n this.started = false;\n removeEventListener(\"turbo:before-cache\", this.removeTemporaryElements, false);\n }\n }\n get temporaryElements() {\n return [...document.querySelectorAll(this.selector), ...this.temporaryElementsWithDeprecation];\n }\n get temporaryElementsWithDeprecation() {\n const elements = document.querySelectorAll(this.deprecatedSelector);\n if (elements.length) {\n console.warn(`The ${this.deprecatedSelector} selector is deprecated and will be removed in a future version. Use ${this.selector} instead.`);\n }\n return [...elements];\n }\n}\nclass FrameRedirector {\n constructor(session, element) {\n this.session = session;\n this.element = element;\n this.linkInterceptor = new LinkInterceptor(this, element);\n this.formSubmitObserver = new FormSubmitObserver(this, element);\n }\n start() {\n this.linkInterceptor.start();\n this.formSubmitObserver.start();\n }\n stop() {\n this.linkInterceptor.stop();\n this.formSubmitObserver.stop();\n }\n shouldInterceptLinkClick(element, _location, _event) {\n return this.shouldRedirect(element);\n }\n linkClickIntercepted(element, url, event) {\n const frame = this.findFrameElement(element);\n if (frame) {\n frame.delegate.linkClickIntercepted(element, url, event);\n }\n }\n willSubmitForm(element, submitter) {\n return element.closest(\"turbo-frame\") == null && this.shouldSubmit(element, submitter) && this.shouldRedirect(element, submitter);\n }\n formSubmitted(element, submitter) {\n const frame = this.findFrameElement(element, submitter);\n if (frame) {\n frame.delegate.formSubmitted(element, submitter);\n }\n }\n shouldSubmit(form, submitter) {\n var _a;\n const action = getAction(form, submitter);\n const meta = this.element.ownerDocument.querySelector(`meta[name=\"turbo-root\"]`);\n const rootLocation = expandURL((_a = meta === null || meta === void 0 ? void 0 : meta.content) !== null && _a !== void 0 ? _a : \"/\");\n return this.shouldRedirect(form, submitter) && locationIsVisitable(action, rootLocation);\n }\n shouldRedirect(element, submitter) {\n const isNavigatable = element instanceof HTMLFormElement ? this.session.submissionIsNavigatable(element, submitter) : this.session.elementIsNavigatable(element);\n if (isNavigatable) {\n const frame = this.findFrameElement(element, submitter);\n return frame ? frame != element.closest(\"turbo-frame\") : false;\n } else {\n return false;\n }\n }\n findFrameElement(element, submitter) {\n const id = (submitter === null || submitter === void 0 ? void 0 : submitter.getAttribute(\"data-turbo-frame\")) || element.getAttribute(\"data-turbo-frame\");\n if (id && id != \"_top\") {\n const frame = this.element.querySelector(`#${id}:not([disabled])`);\n if (frame instanceof FrameElement) {\n return frame;\n }\n }\n }\n}\nclass History {\n constructor(delegate) {\n this.restorationIdentifier = uuid();\n this.restorationData = {};\n this.started = false;\n this.pageLoaded = false;\n this.onPopState = event => {\n if (this.shouldHandlePopState()) {\n const _ref15 = event.state || {},\n turbo = _ref15.turbo;\n if (turbo) {\n this.location = new URL(window.location.href);\n const restorationIdentifier = turbo.restorationIdentifier;\n this.restorationIdentifier = restorationIdentifier;\n this.delegate.historyPoppedToLocationWithRestorationIdentifier(this.location, restorationIdentifier);\n }\n }\n };\n this.onPageLoad = async _event => {\n await nextMicrotask();\n this.pageLoaded = true;\n };\n this.delegate = delegate;\n }\n start() {\n if (!this.started) {\n addEventListener(\"popstate\", this.onPopState, false);\n addEventListener(\"load\", this.onPageLoad, false);\n this.started = true;\n this.replace(new URL(window.location.href));\n }\n }\n stop() {\n if (this.started) {\n removeEventListener(\"popstate\", this.onPopState, false);\n removeEventListener(\"load\", this.onPageLoad, false);\n this.started = false;\n }\n }\n push(location, restorationIdentifier) {\n this.update(history.pushState, location, restorationIdentifier);\n }\n replace(location, restorationIdentifier) {\n this.update(history.replaceState, location, restorationIdentifier);\n }\n update(method, location) {\n let restorationIdentifier = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : uuid();\n const state = {\n turbo: {\n restorationIdentifier\n }\n };\n method.call(history, state, \"\", location.href);\n this.location = location;\n this.restorationIdentifier = restorationIdentifier;\n }\n getRestorationDataForIdentifier(restorationIdentifier) {\n return this.restorationData[restorationIdentifier] || {};\n }\n updateRestorationData(additionalData) {\n const restorationIdentifier = this.restorationIdentifier;\n const restorationData = this.restorationData[restorationIdentifier];\n this.restorationData[restorationIdentifier] = Object.assign(Object.assign({}, restorationData), additionalData);\n }\n assumeControlOfScrollRestoration() {\n var _a;\n if (!this.previousScrollRestoration) {\n this.previousScrollRestoration = (_a = history.scrollRestoration) !== null && _a !== void 0 ? _a : \"auto\";\n history.scrollRestoration = \"manual\";\n }\n }\n relinquishControlOfScrollRestoration() {\n if (this.previousScrollRestoration) {\n history.scrollRestoration = this.previousScrollRestoration;\n delete this.previousScrollRestoration;\n }\n }\n shouldHandlePopState() {\n return this.pageIsLoaded();\n }\n pageIsLoaded() {\n return this.pageLoaded || document.readyState == \"complete\";\n }\n}\nclass Navigator {\n constructor(delegate) {\n this.delegate = delegate;\n }\n proposeVisit(location) {\n let options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};\n if (this.delegate.allowsVisitingLocationWithAction(location, options.action)) {\n if (locationIsVisitable(location, this.view.snapshot.rootLocation)) {\n this.delegate.visitProposedToLocation(location, options);\n } else {\n window.location.href = location.toString();\n }\n }\n }\n startVisit(locatable, restorationIdentifier) {\n let options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};\n this.stop();\n this.currentVisit = new Visit(this, expandURL(locatable), restorationIdentifier, Object.assign({\n referrer: this.location\n }, options));\n this.currentVisit.start();\n }\n submitForm(form, submitter) {\n this.stop();\n this.formSubmission = new FormSubmission(this, form, submitter, true);\n this.formSubmission.start();\n }\n stop() {\n if (this.formSubmission) {\n this.formSubmission.stop();\n delete this.formSubmission;\n }\n if (this.currentVisit) {\n this.currentVisit.cancel();\n delete this.currentVisit;\n }\n }\n get adapter() {\n return this.delegate.adapter;\n }\n get view() {\n return this.delegate.view;\n }\n get history() {\n return this.delegate.history;\n }\n formSubmissionStarted(formSubmission) {\n if (typeof this.adapter.formSubmissionStarted === \"function\") {\n this.adapter.formSubmissionStarted(formSubmission);\n }\n }\n async formSubmissionSucceededWithResponse(formSubmission, fetchResponse) {\n if (formSubmission == this.formSubmission) {\n const responseHTML = await fetchResponse.responseHTML;\n if (responseHTML) {\n const shouldCacheSnapshot = formSubmission.isSafe;\n if (!shouldCacheSnapshot) {\n this.view.clearSnapshotCache();\n }\n const statusCode = fetchResponse.statusCode,\n redirected = fetchResponse.redirected;\n const action = this.getActionForFormSubmission(formSubmission);\n const visitOptions = {\n action,\n shouldCacheSnapshot,\n response: {\n statusCode,\n responseHTML,\n redirected\n }\n };\n this.proposeVisit(fetchResponse.location, visitOptions);\n }\n }\n }\n async formSubmissionFailedWithResponse(formSubmission, fetchResponse) {\n const responseHTML = await fetchResponse.responseHTML;\n if (responseHTML) {\n const snapshot = PageSnapshot.fromHTMLString(responseHTML);\n if (fetchResponse.serverError) {\n await this.view.renderError(snapshot, this.currentVisit);\n } else {\n await this.view.renderPage(snapshot, false, true, this.currentVisit);\n }\n this.view.scrollToTop();\n this.view.clearSnapshotCache();\n }\n }\n formSubmissionErrored(formSubmission, error) {\n console.error(error);\n }\n formSubmissionFinished(formSubmission) {\n if (typeof this.adapter.formSubmissionFinished === \"function\") {\n this.adapter.formSubmissionFinished(formSubmission);\n }\n }\n visitStarted(visit) {\n this.delegate.visitStarted(visit);\n }\n visitCompleted(visit) {\n this.delegate.visitCompleted(visit);\n }\n locationWithActionIsSamePage(location, action) {\n const anchor = getAnchor(location);\n const currentAnchor = getAnchor(this.view.lastRenderedLocation);\n const isRestorationToTop = action === \"restore\" && typeof anchor === \"undefined\";\n return action !== \"replace\" && getRequestURL(location) === getRequestURL(this.view.lastRenderedLocation) && (isRestorationToTop || anchor != null && anchor !== currentAnchor);\n }\n visitScrolledToSamePageLocation(oldURL, newURL) {\n this.delegate.visitScrolledToSamePageLocation(oldURL, newURL);\n }\n get location() {\n return this.history.location;\n }\n get restorationIdentifier() {\n return this.history.restorationIdentifier;\n }\n getActionForFormSubmission(_ref16) {\n let submitter = _ref16.submitter,\n formElement = _ref16.formElement;\n return getVisitAction(submitter, formElement) || \"advance\";\n }\n}\nvar PageStage;\n(function (PageStage) {\n PageStage[PageStage[\"initial\"] = 0] = \"initial\";\n PageStage[PageStage[\"loading\"] = 1] = \"loading\";\n PageStage[PageStage[\"interactive\"] = 2] = \"interactive\";\n PageStage[PageStage[\"complete\"] = 3] = \"complete\";\n})(PageStage || (PageStage = {}));\nclass PageObserver {\n constructor(delegate) {\n this.stage = PageStage.initial;\n this.started = false;\n this.interpretReadyState = () => {\n const readyState = this.readyState;\n if (readyState == \"interactive\") {\n this.pageIsInteractive();\n } else if (readyState == \"complete\") {\n this.pageIsComplete();\n }\n };\n this.pageWillUnload = () => {\n this.delegate.pageWillUnload();\n };\n this.delegate = delegate;\n }\n start() {\n if (!this.started) {\n if (this.stage == PageStage.initial) {\n this.stage = PageStage.loading;\n }\n document.addEventListener(\"readystatechange\", this.interpretReadyState, false);\n addEventListener(\"pagehide\", this.pageWillUnload, false);\n this.started = true;\n }\n }\n stop() {\n if (this.started) {\n document.removeEventListener(\"readystatechange\", this.interpretReadyState, false);\n removeEventListener(\"pagehide\", this.pageWillUnload, false);\n this.started = false;\n }\n }\n pageIsInteractive() {\n if (this.stage == PageStage.loading) {\n this.stage = PageStage.interactive;\n this.delegate.pageBecameInteractive();\n }\n }\n pageIsComplete() {\n this.pageIsInteractive();\n if (this.stage == PageStage.interactive) {\n this.stage = PageStage.complete;\n this.delegate.pageLoaded();\n }\n }\n get readyState() {\n return document.readyState;\n }\n}\nclass ScrollObserver {\n constructor(delegate) {\n this.started = false;\n this.onScroll = () => {\n this.updatePosition({\n x: window.pageXOffset,\n y: window.pageYOffset\n });\n };\n this.delegate = delegate;\n }\n start() {\n if (!this.started) {\n addEventListener(\"scroll\", this.onScroll, false);\n this.onScroll();\n this.started = true;\n }\n }\n stop() {\n if (this.started) {\n removeEventListener(\"scroll\", this.onScroll, false);\n this.started = false;\n }\n }\n updatePosition(position) {\n this.delegate.scrollPositionChanged(position);\n }\n}\nclass StreamMessageRenderer {\n render(_ref17) {\n let fragment = _ref17.fragment;\n Bardo.preservingPermanentElements(this, getPermanentElementMapForFragment(fragment), () => document.documentElement.appendChild(fragment));\n }\n enteringBardo(currentPermanentElement, newPermanentElement) {\n newPermanentElement.replaceWith(currentPermanentElement.cloneNode(true));\n }\n leavingBardo() {}\n}\nfunction getPermanentElementMapForFragment(fragment) {\n const permanentElementsInDocument = queryPermanentElementsAll(document.documentElement);\n const permanentElementMap = {};\n for (const permanentElementInDocument of permanentElementsInDocument) {\n const id = permanentElementInDocument.id;\n for (const streamElement of fragment.querySelectorAll(\"turbo-stream\")) {\n const elementInStream = getPermanentElementById(streamElement.templateElement.content, id);\n if (elementInStream) {\n permanentElementMap[id] = [permanentElementInDocument, elementInStream];\n }\n }\n }\n return permanentElementMap;\n}\nclass StreamObserver {\n constructor(delegate) {\n this.sources = new Set();\n this.started = false;\n this.inspectFetchResponse = event => {\n const response = fetchResponseFromEvent(event);\n if (response && fetchResponseIsStream(response)) {\n event.preventDefault();\n this.receiveMessageResponse(response);\n }\n };\n this.receiveMessageEvent = event => {\n if (this.started && typeof event.data == \"string\") {\n this.receiveMessageHTML(event.data);\n }\n };\n this.delegate = delegate;\n }\n start() {\n if (!this.started) {\n this.started = true;\n addEventListener(\"turbo:before-fetch-response\", this.inspectFetchResponse, false);\n }\n }\n stop() {\n if (this.started) {\n this.started = false;\n removeEventListener(\"turbo:before-fetch-response\", this.inspectFetchResponse, false);\n }\n }\n connectStreamSource(source) {\n if (!this.streamSourceIsConnected(source)) {\n this.sources.add(source);\n source.addEventListener(\"message\", this.receiveMessageEvent, false);\n }\n }\n disconnectStreamSource(source) {\n if (this.streamSourceIsConnected(source)) {\n this.sources.delete(source);\n source.removeEventListener(\"message\", this.receiveMessageEvent, false);\n }\n }\n streamSourceIsConnected(source) {\n return this.sources.has(source);\n }\n async receiveMessageResponse(response) {\n const html = await response.responseHTML;\n if (html) {\n this.receiveMessageHTML(html);\n }\n }\n receiveMessageHTML(html) {\n this.delegate.receivedMessageFromStream(StreamMessage.wrap(html));\n }\n}\nfunction fetchResponseFromEvent(event) {\n var _a;\n const fetchResponse = (_a = event.detail) === null || _a === void 0 ? void 0 : _a.fetchResponse;\n if (fetchResponse instanceof FetchResponse) {\n return fetchResponse;\n }\n}\nfunction fetchResponseIsStream(response) {\n var _a;\n const contentType = (_a = response.contentType) !== null && _a !== void 0 ? _a : \"\";\n return contentType.startsWith(StreamMessage.contentType);\n}\nclass ErrorRenderer extends Renderer {\n static renderElement(currentElement, newElement) {\n const _document = document,\n documentElement = _document.documentElement,\n body = _document.body;\n documentElement.replaceChild(newElement, body);\n }\n async render() {\n this.replaceHeadAndBody();\n this.activateScriptElements();\n }\n replaceHeadAndBody() {\n const _document2 = document,\n documentElement = _document2.documentElement,\n head = _document2.head;\n documentElement.replaceChild(this.newHead, head);\n this.renderElement(this.currentElement, this.newElement);\n }\n activateScriptElements() {\n for (const replaceableElement of this.scriptElements) {\n const parentNode = replaceableElement.parentNode;\n if (parentNode) {\n const element = activateScriptElement(replaceableElement);\n parentNode.replaceChild(element, replaceableElement);\n }\n }\n }\n get newHead() {\n return this.newSnapshot.headSnapshot.element;\n }\n get scriptElements() {\n return document.documentElement.querySelectorAll(\"script\");\n }\n}\nclass PageRenderer extends Renderer {\n static renderElement(currentElement, newElement) {\n if (document.body && newElement instanceof HTMLBodyElement) {\n document.body.replaceWith(newElement);\n } else {\n document.documentElement.appendChild(newElement);\n }\n }\n get shouldRender() {\n return this.newSnapshot.isVisitable && this.trackedElementsAreIdentical;\n }\n get reloadReason() {\n if (!this.newSnapshot.isVisitable) {\n return {\n reason: \"turbo_visit_control_is_reload\"\n };\n }\n if (!this.trackedElementsAreIdentical) {\n return {\n reason: \"tracked_element_mismatch\"\n };\n }\n }\n async prepareToRender() {\n await this.mergeHead();\n }\n async render() {\n if (this.willRender) {\n await this.replaceBody();\n }\n }\n finishRendering() {\n super.finishRendering();\n if (!this.isPreview) {\n this.focusFirstAutofocusableElement();\n }\n }\n get currentHeadSnapshot() {\n return this.currentSnapshot.headSnapshot;\n }\n get newHeadSnapshot() {\n return this.newSnapshot.headSnapshot;\n }\n get newElement() {\n return this.newSnapshot.element;\n }\n async mergeHead() {\n const mergedHeadElements = this.mergeProvisionalElements();\n const newStylesheetElements = this.copyNewHeadStylesheetElements();\n this.copyNewHeadScriptElements();\n await mergedHeadElements;\n await newStylesheetElements;\n }\n async replaceBody() {\n await this.preservingPermanentElements(async () => {\n this.activateNewBody();\n await this.assignNewBody();\n });\n }\n get trackedElementsAreIdentical() {\n return this.currentHeadSnapshot.trackedElementSignature == this.newHeadSnapshot.trackedElementSignature;\n }\n async copyNewHeadStylesheetElements() {\n const loadingElements = [];\n for (const element of this.newHeadStylesheetElements) {\n loadingElements.push(waitForLoad(element));\n document.head.appendChild(element);\n }\n await Promise.all(loadingElements);\n }\n copyNewHeadScriptElements() {\n for (const element of this.newHeadScriptElements) {\n document.head.appendChild(activateScriptElement(element));\n }\n }\n async mergeProvisionalElements() {\n const newHeadElements = [...this.newHeadProvisionalElements];\n for (const element of this.currentHeadProvisionalElements) {\n if (!this.isCurrentElementInElementList(element, newHeadElements)) {\n document.head.removeChild(element);\n }\n }\n for (const element of newHeadElements) {\n document.head.appendChild(element);\n }\n }\n isCurrentElementInElementList(element, elementList) {\n for (const _ref18 of elementList.entries()) {\n var _ref19 = _slicedToArray(_ref18, 2);\n const index = _ref19[0];\n const newElement = _ref19[1];\n if (element.tagName == \"TITLE\") {\n if (newElement.tagName != \"TITLE\") {\n continue;\n }\n if (element.innerHTML == newElement.innerHTML) {\n elementList.splice(index, 1);\n return true;\n }\n }\n if (newElement.isEqualNode(element)) {\n elementList.splice(index, 1);\n return true;\n }\n }\n return false;\n }\n removeCurrentHeadProvisionalElements() {\n for (const element of this.currentHeadProvisionalElements) {\n document.head.removeChild(element);\n }\n }\n copyNewHeadProvisionalElements() {\n for (const element of this.newHeadProvisionalElements) {\n document.head.appendChild(element);\n }\n }\n activateNewBody() {\n document.adoptNode(this.newElement);\n this.activateNewBodyScriptElements();\n }\n activateNewBodyScriptElements() {\n for (const inertScriptElement of this.newBodyScriptElements) {\n const activatedScriptElement = activateScriptElement(inertScriptElement);\n inertScriptElement.replaceWith(activatedScriptElement);\n }\n }\n async assignNewBody() {\n await this.renderElement(this.currentElement, this.newElement);\n }\n get newHeadStylesheetElements() {\n return this.newHeadSnapshot.getStylesheetElementsNotInSnapshot(this.currentHeadSnapshot);\n }\n get newHeadScriptElements() {\n return this.newHeadSnapshot.getScriptElementsNotInSnapshot(this.currentHeadSnapshot);\n }\n get currentHeadProvisionalElements() {\n return this.currentHeadSnapshot.provisionalElements;\n }\n get newHeadProvisionalElements() {\n return this.newHeadSnapshot.provisionalElements;\n }\n get newBodyScriptElements() {\n return this.newElement.querySelectorAll(\"script\");\n }\n}\nclass SnapshotCache {\n constructor(size) {\n this.keys = [];\n this.snapshots = {};\n this.size = size;\n }\n has(location) {\n return toCacheKey(location) in this.snapshots;\n }\n get(location) {\n if (this.has(location)) {\n const snapshot = this.read(location);\n this.touch(location);\n return snapshot;\n }\n }\n put(location, snapshot) {\n this.write(location, snapshot);\n this.touch(location);\n return snapshot;\n }\n clear() {\n this.snapshots = {};\n }\n read(location) {\n return this.snapshots[toCacheKey(location)];\n }\n write(location, snapshot) {\n this.snapshots[toCacheKey(location)] = snapshot;\n }\n touch(location) {\n const key = toCacheKey(location);\n const index = this.keys.indexOf(key);\n if (index > -1) this.keys.splice(index, 1);\n this.keys.unshift(key);\n this.trim();\n }\n trim() {\n for (const key of this.keys.splice(this.size)) {\n delete this.snapshots[key];\n }\n }\n}\nclass PageView extends View {\n constructor() {\n super(...arguments);\n this.snapshotCache = new SnapshotCache(10);\n this.lastRenderedLocation = new URL(location.href);\n this.forceReloaded = false;\n }\n renderPage(snapshot) {\n let isPreview = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;\n let willRender = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : true;\n let visit = arguments.length > 3 ? arguments[3] : undefined;\n const renderer = new PageRenderer(this.snapshot, snapshot, PageRenderer.renderElement, isPreview, willRender);\n if (!renderer.shouldRender) {\n this.forceReloaded = true;\n } else {\n visit === null || visit === void 0 ? void 0 : visit.changeHistory();\n }\n return this.render(renderer);\n }\n renderError(snapshot, visit) {\n visit === null || visit === void 0 ? void 0 : visit.changeHistory();\n const renderer = new ErrorRenderer(this.snapshot, snapshot, ErrorRenderer.renderElement, false);\n return this.render(renderer);\n }\n clearSnapshotCache() {\n this.snapshotCache.clear();\n }\n async cacheSnapshot() {\n let snapshot = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : this.snapshot;\n if (snapshot.isCacheable) {\n this.delegate.viewWillCacheSnapshot();\n const location = this.lastRenderedLocation;\n await nextEventLoopTick();\n const cachedSnapshot = snapshot.clone();\n this.snapshotCache.put(location, cachedSnapshot);\n return cachedSnapshot;\n }\n }\n getCachedSnapshotForLocation(location) {\n return this.snapshotCache.get(location);\n }\n get snapshot() {\n return PageSnapshot.fromElement(this.element);\n }\n}\nclass Preloader {\n constructor(delegate) {\n this.selector = \"a[data-turbo-preload]\";\n this.delegate = delegate;\n }\n get snapshotCache() {\n return this.delegate.navigator.view.snapshotCache;\n }\n start() {\n if (document.readyState === \"loading\") {\n return document.addEventListener(\"DOMContentLoaded\", () => {\n this.preloadOnLoadLinksForView(document.body);\n });\n } else {\n this.preloadOnLoadLinksForView(document.body);\n }\n }\n preloadOnLoadLinksForView(element) {\n for (const link of element.querySelectorAll(this.selector)) {\n this.preloadURL(link);\n }\n }\n async preloadURL(link) {\n const location = new URL(link.href);\n if (this.snapshotCache.has(location)) {\n return;\n }\n try {\n const response = await fetch(location.toString(), {\n headers: {\n \"VND.PREFETCH\": \"true\",\n Accept: \"text/html\"\n }\n });\n const responseText = await response.text();\n const snapshot = PageSnapshot.fromHTMLString(responseText);\n this.snapshotCache.put(location, snapshot);\n } catch (_) {}\n }\n}\nclass Session {\n constructor() {\n this.navigator = new Navigator(this);\n this.history = new History(this);\n this.preloader = new Preloader(this);\n this.view = new PageView(this, document.documentElement);\n this.adapter = new BrowserAdapter(this);\n this.pageObserver = new PageObserver(this);\n this.cacheObserver = new CacheObserver();\n this.linkClickObserver = new LinkClickObserver(this, window);\n this.formSubmitObserver = new FormSubmitObserver(this, document);\n this.scrollObserver = new ScrollObserver(this);\n this.streamObserver = new StreamObserver(this);\n this.formLinkClickObserver = new FormLinkClickObserver(this, document.documentElement);\n this.frameRedirector = new FrameRedirector(this, document.documentElement);\n this.streamMessageRenderer = new StreamMessageRenderer();\n this.drive = true;\n this.enabled = true;\n this.progressBarDelay = 500;\n this.started = false;\n this.formMode = \"on\";\n }\n start() {\n if (!this.started) {\n this.pageObserver.start();\n this.cacheObserver.start();\n this.formLinkClickObserver.start();\n this.linkClickObserver.start();\n this.formSubmitObserver.start();\n this.scrollObserver.start();\n this.streamObserver.start();\n this.frameRedirector.start();\n this.history.start();\n this.preloader.start();\n this.started = true;\n this.enabled = true;\n }\n }\n disable() {\n this.enabled = false;\n }\n stop() {\n if (this.started) {\n this.pageObserver.stop();\n this.cacheObserver.stop();\n this.formLinkClickObserver.stop();\n this.linkClickObserver.stop();\n this.formSubmitObserver.stop();\n this.scrollObserver.stop();\n this.streamObserver.stop();\n this.frameRedirector.stop();\n this.history.stop();\n this.started = false;\n }\n }\n registerAdapter(adapter) {\n this.adapter = adapter;\n }\n visit(location) {\n let options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};\n const frameElement = options.frame ? document.getElementById(options.frame) : null;\n if (frameElement instanceof FrameElement) {\n frameElement.src = location.toString();\n frameElement.loaded;\n } else {\n this.navigator.proposeVisit(expandURL(location), options);\n }\n }\n connectStreamSource(source) {\n this.streamObserver.connectStreamSource(source);\n }\n disconnectStreamSource(source) {\n this.streamObserver.disconnectStreamSource(source);\n }\n renderStreamMessage(message) {\n this.streamMessageRenderer.render(StreamMessage.wrap(message));\n }\n clearCache() {\n this.view.clearSnapshotCache();\n }\n setProgressBarDelay(delay) {\n this.progressBarDelay = delay;\n }\n setFormMode(mode) {\n this.formMode = mode;\n }\n get location() {\n return this.history.location;\n }\n get restorationIdentifier() {\n return this.history.restorationIdentifier;\n }\n historyPoppedToLocationWithRestorationIdentifier(location, restorationIdentifier) {\n if (this.enabled) {\n this.navigator.startVisit(location, restorationIdentifier, {\n action: \"restore\",\n historyChanged: true\n });\n } else {\n this.adapter.pageInvalidated({\n reason: \"turbo_disabled\"\n });\n }\n }\n scrollPositionChanged(position) {\n this.history.updateRestorationData({\n scrollPosition: position\n });\n }\n willSubmitFormLinkToLocation(link, location) {\n return this.elementIsNavigatable(link) && locationIsVisitable(location, this.snapshot.rootLocation);\n }\n submittedFormLinkToLocation() {}\n willFollowLinkToLocation(link, location, event) {\n return this.elementIsNavigatable(link) && locationIsVisitable(location, this.snapshot.rootLocation) && this.applicationAllowsFollowingLinkToLocation(link, location, event);\n }\n followedLinkToLocation(link, location) {\n const action = this.getActionForLink(link);\n const acceptsStreamResponse = link.hasAttribute(\"data-turbo-stream\");\n this.visit(location.href, {\n action,\n acceptsStreamResponse\n });\n }\n allowsVisitingLocationWithAction(location, action) {\n return this.locationWithActionIsSamePage(location, action) || this.applicationAllowsVisitingLocation(location);\n }\n visitProposedToLocation(location, options) {\n extendURLWithDeprecatedProperties(location);\n this.adapter.visitProposedToLocation(location, options);\n }\n visitStarted(visit) {\n if (!visit.acceptsStreamResponse) {\n markAsBusy(document.documentElement);\n }\n extendURLWithDeprecatedProperties(visit.location);\n if (!visit.silent) {\n this.notifyApplicationAfterVisitingLocation(visit.location, visit.action);\n }\n }\n visitCompleted(visit) {\n clearBusyState(document.documentElement);\n this.notifyApplicationAfterPageLoad(visit.getTimingMetrics());\n }\n locationWithActionIsSamePage(location, action) {\n return this.navigator.locationWithActionIsSamePage(location, action);\n }\n visitScrolledToSamePageLocation(oldURL, newURL) {\n this.notifyApplicationAfterVisitingSamePageLocation(oldURL, newURL);\n }\n willSubmitForm(form, submitter) {\n const action = getAction(form, submitter);\n return this.submissionIsNavigatable(form, submitter) && locationIsVisitable(expandURL(action), this.snapshot.rootLocation);\n }\n formSubmitted(form, submitter) {\n this.navigator.submitForm(form, submitter);\n }\n pageBecameInteractive() {\n this.view.lastRenderedLocation = this.location;\n this.notifyApplicationAfterPageLoad();\n }\n pageLoaded() {\n this.history.assumeControlOfScrollRestoration();\n }\n pageWillUnload() {\n this.history.relinquishControlOfScrollRestoration();\n }\n receivedMessageFromStream(message) {\n this.renderStreamMessage(message);\n }\n viewWillCacheSnapshot() {\n var _a;\n if (!((_a = this.navigator.currentVisit) === null || _a === void 0 ? void 0 : _a.silent)) {\n this.notifyApplicationBeforeCachingSnapshot();\n }\n }\n allowsImmediateRender(_ref20, options) {\n let element = _ref20.element;\n const event = this.notifyApplicationBeforeRender(element, options);\n const defaultPrevented = event.defaultPrevented,\n render = event.detail.render;\n if (this.view.renderer && render) {\n this.view.renderer.renderElement = render;\n }\n return !defaultPrevented;\n }\n viewRenderedSnapshot(_snapshot, _isPreview) {\n this.view.lastRenderedLocation = this.history.location;\n this.notifyApplicationAfterRender();\n }\n preloadOnLoadLinksForView(element) {\n this.preloader.preloadOnLoadLinksForView(element);\n }\n viewInvalidated(reason) {\n this.adapter.pageInvalidated(reason);\n }\n frameLoaded(frame) {\n this.notifyApplicationAfterFrameLoad(frame);\n }\n frameRendered(fetchResponse, frame) {\n this.notifyApplicationAfterFrameRender(fetchResponse, frame);\n }\n applicationAllowsFollowingLinkToLocation(link, location, ev) {\n const event = this.notifyApplicationAfterClickingLinkToLocation(link, location, ev);\n return !event.defaultPrevented;\n }\n applicationAllowsVisitingLocation(location) {\n const event = this.notifyApplicationBeforeVisitingLocation(location);\n return !event.defaultPrevented;\n }\n notifyApplicationAfterClickingLinkToLocation(link, location, event) {\n return dispatch(\"turbo:click\", {\n target: link,\n detail: {\n url: location.href,\n originalEvent: event\n },\n cancelable: true\n });\n }\n notifyApplicationBeforeVisitingLocation(location) {\n return dispatch(\"turbo:before-visit\", {\n detail: {\n url: location.href\n },\n cancelable: true\n });\n }\n notifyApplicationAfterVisitingLocation(location, action) {\n return dispatch(\"turbo:visit\", {\n detail: {\n url: location.href,\n action\n }\n });\n }\n notifyApplicationBeforeCachingSnapshot() {\n return dispatch(\"turbo:before-cache\");\n }\n notifyApplicationBeforeRender(newBody, options) {\n return dispatch(\"turbo:before-render\", {\n detail: Object.assign({\n newBody\n }, options),\n cancelable: true\n });\n }\n notifyApplicationAfterRender() {\n return dispatch(\"turbo:render\");\n }\n notifyApplicationAfterPageLoad() {\n let timing = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};\n return dispatch(\"turbo:load\", {\n detail: {\n url: this.location.href,\n timing\n }\n });\n }\n notifyApplicationAfterVisitingSamePageLocation(oldURL, newURL) {\n dispatchEvent(new HashChangeEvent(\"hashchange\", {\n oldURL: oldURL.toString(),\n newURL: newURL.toString()\n }));\n }\n notifyApplicationAfterFrameLoad(frame) {\n return dispatch(\"turbo:frame-load\", {\n target: frame\n });\n }\n notifyApplicationAfterFrameRender(fetchResponse, frame) {\n return dispatch(\"turbo:frame-render\", {\n detail: {\n fetchResponse\n },\n target: frame,\n cancelable: true\n });\n }\n submissionIsNavigatable(form, submitter) {\n if (this.formMode == \"off\") {\n return false;\n } else {\n const submitterIsNavigatable = submitter ? this.elementIsNavigatable(submitter) : true;\n if (this.formMode == \"optin\") {\n return submitterIsNavigatable && form.closest('[data-turbo=\"true\"]') != null;\n } else {\n return submitterIsNavigatable && this.elementIsNavigatable(form);\n }\n }\n }\n elementIsNavigatable(element) {\n const container = findClosestRecursively(element, \"[data-turbo]\");\n const withinFrame = findClosestRecursively(element, \"turbo-frame\");\n if (this.drive || withinFrame) {\n if (container) {\n return container.getAttribute(\"data-turbo\") != \"false\";\n } else {\n return true;\n }\n } else {\n if (container) {\n return container.getAttribute(\"data-turbo\") == \"true\";\n } else {\n return false;\n }\n }\n }\n getActionForLink(link) {\n return getVisitAction(link) || \"advance\";\n }\n get snapshot() {\n return this.view.snapshot;\n }\n}\nfunction extendURLWithDeprecatedProperties(url) {\n Object.defineProperties(url, deprecatedLocationPropertyDescriptors);\n}\nconst deprecatedLocationPropertyDescriptors = {\n absoluteURL: {\n get() {\n return this.toString();\n }\n }\n};\nclass Cache {\n constructor(session) {\n this.session = session;\n }\n clear() {\n this.session.clearCache();\n }\n resetCacheControl() {\n this.setCacheControl(\"\");\n }\n exemptPageFromCache() {\n this.setCacheControl(\"no-cache\");\n }\n exemptPageFromPreview() {\n this.setCacheControl(\"no-preview\");\n }\n setCacheControl(value) {\n setMetaContent(\"turbo-cache-control\", value);\n }\n}\nconst StreamActions = {\n after() {\n this.targetElements.forEach(e => {\n var _a;\n return (_a = e.parentElement) === null || _a === void 0 ? void 0 : _a.insertBefore(this.templateContent, e.nextSibling);\n });\n },\n append() {\n this.removeDuplicateTargetChildren();\n this.targetElements.forEach(e => e.append(this.templateContent));\n },\n before() {\n this.targetElements.forEach(e => {\n var _a;\n return (_a = e.parentElement) === null || _a === void 0 ? void 0 : _a.insertBefore(this.templateContent, e);\n });\n },\n prepend() {\n this.removeDuplicateTargetChildren();\n this.targetElements.forEach(e => e.prepend(this.templateContent));\n },\n remove() {\n this.targetElements.forEach(e => e.remove());\n },\n replace() {\n this.targetElements.forEach(e => e.replaceWith(this.templateContent));\n },\n update() {\n this.targetElements.forEach(targetElement => {\n targetElement.innerHTML = \"\";\n targetElement.append(this.templateContent);\n });\n }\n};\nconst session = new Session();\nconst cache = new Cache(session);\nconst navigator$1 = session.navigator;\nfunction start() {\n session.start();\n}\nfunction registerAdapter(adapter) {\n session.registerAdapter(adapter);\n}\nfunction visit(location, options) {\n session.visit(location, options);\n}\nfunction connectStreamSource(source) {\n session.connectStreamSource(source);\n}\nfunction disconnectStreamSource(source) {\n session.disconnectStreamSource(source);\n}\nfunction renderStreamMessage(message) {\n session.renderStreamMessage(message);\n}\nfunction clearCache() {\n console.warn(\"Please replace `Turbo.clearCache()` with `Turbo.cache.clear()`. The top-level function is deprecated and will be removed in a future version of Turbo.`\");\n session.clearCache();\n}\nfunction setProgressBarDelay(delay) {\n session.setProgressBarDelay(delay);\n}\nfunction setConfirmMethod(confirmMethod) {\n FormSubmission.confirmMethod = confirmMethod;\n}\nfunction setFormMode(mode) {\n session.setFormMode(mode);\n}\nvar Turbo = /*#__PURE__*/Object.freeze({\n __proto__: null,\n navigator: navigator$1,\n session: session,\n cache: cache,\n PageRenderer: PageRenderer,\n PageSnapshot: PageSnapshot,\n FrameRenderer: FrameRenderer,\n start: start,\n registerAdapter: registerAdapter,\n visit: visit,\n connectStreamSource: connectStreamSource,\n disconnectStreamSource: disconnectStreamSource,\n renderStreamMessage: renderStreamMessage,\n clearCache: clearCache,\n setProgressBarDelay: setProgressBarDelay,\n setConfirmMethod: setConfirmMethod,\n setFormMode: setFormMode,\n StreamActions: StreamActions\n});\nclass TurboFrameMissingError extends Error {}\nclass FrameController {\n constructor(element) {\n this.fetchResponseLoaded = _fetchResponse => {};\n this.currentFetchRequest = null;\n this.resolveVisitPromise = () => {};\n this.connected = false;\n this.hasBeenLoaded = false;\n this.ignoredAttributes = new Set();\n this.action = null;\n this.visitCachedSnapshot = _ref21 => {\n let element = _ref21.element;\n const frame = element.querySelector(\"#\" + this.element.id);\n if (frame && this.previousFrameElement) {\n frame.replaceChildren(...this.previousFrameElement.children);\n }\n delete this.previousFrameElement;\n };\n this.element = element;\n this.view = new FrameView(this, this.element);\n this.appearanceObserver = new AppearanceObserver(this, this.element);\n this.formLinkClickObserver = new FormLinkClickObserver(this, this.element);\n this.linkInterceptor = new LinkInterceptor(this, this.element);\n this.restorationIdentifier = uuid();\n this.formSubmitObserver = new FormSubmitObserver(this, this.element);\n }\n connect() {\n if (!this.connected) {\n this.connected = true;\n if (this.loadingStyle == FrameLoadingStyle.lazy) {\n this.appearanceObserver.start();\n } else {\n this.loadSourceURL();\n }\n this.formLinkClickObserver.start();\n this.linkInterceptor.start();\n this.formSubmitObserver.start();\n }\n }\n disconnect() {\n if (this.connected) {\n this.connected = false;\n this.appearanceObserver.stop();\n this.formLinkClickObserver.stop();\n this.linkInterceptor.stop();\n this.formSubmitObserver.stop();\n }\n }\n disabledChanged() {\n if (this.loadingStyle == FrameLoadingStyle.eager) {\n this.loadSourceURL();\n }\n }\n sourceURLChanged() {\n if (this.isIgnoringChangesTo(\"src\")) return;\n if (this.element.isConnected) {\n this.complete = false;\n }\n if (this.loadingStyle == FrameLoadingStyle.eager || this.hasBeenLoaded) {\n this.loadSourceURL();\n }\n }\n sourceURLReloaded() {\n const src = this.element.src;\n this.ignoringChangesToAttribute(\"complete\", () => {\n this.element.removeAttribute(\"complete\");\n });\n this.element.src = null;\n this.element.src = src;\n return this.element.loaded;\n }\n completeChanged() {\n if (this.isIgnoringChangesTo(\"complete\")) return;\n this.loadSourceURL();\n }\n loadingStyleChanged() {\n if (this.loadingStyle == FrameLoadingStyle.lazy) {\n this.appearanceObserver.start();\n } else {\n this.appearanceObserver.stop();\n this.loadSourceURL();\n }\n }\n async loadSourceURL() {\n if (this.enabled && this.isActive && !this.complete && this.sourceURL) {\n this.element.loaded = this.visit(expandURL(this.sourceURL));\n this.appearanceObserver.stop();\n await this.element.loaded;\n this.hasBeenLoaded = true;\n }\n }\n async loadResponse(fetchResponse) {\n if (fetchResponse.redirected || fetchResponse.succeeded && fetchResponse.isHTML) {\n this.sourceURL = fetchResponse.response.url;\n }\n try {\n const html = await fetchResponse.responseHTML;\n if (html) {\n const document = parseHTMLDocument(html);\n const pageSnapshot = PageSnapshot.fromDocument(document);\n if (pageSnapshot.isVisitable) {\n await this.loadFrameResponse(fetchResponse, document);\n } else {\n await this.handleUnvisitableFrameResponse(fetchResponse);\n }\n }\n } finally {\n this.fetchResponseLoaded = () => {};\n }\n }\n elementAppearedInViewport(element) {\n this.proposeVisitIfNavigatedWithAction(element, element);\n this.loadSourceURL();\n }\n willSubmitFormLinkToLocation(link) {\n return this.shouldInterceptNavigation(link);\n }\n submittedFormLinkToLocation(link, _location, form) {\n const frame = this.findFrameElement(link);\n if (frame) form.setAttribute(\"data-turbo-frame\", frame.id);\n }\n shouldInterceptLinkClick(element, _location, _event) {\n return this.shouldInterceptNavigation(element);\n }\n linkClickIntercepted(element, location) {\n this.navigateFrame(element, location);\n }\n willSubmitForm(element, submitter) {\n return element.closest(\"turbo-frame\") == this.element && this.shouldInterceptNavigation(element, submitter);\n }\n formSubmitted(element, submitter) {\n if (this.formSubmission) {\n this.formSubmission.stop();\n }\n this.formSubmission = new FormSubmission(this, element, submitter);\n const fetchRequest = this.formSubmission.fetchRequest;\n this.prepareRequest(fetchRequest);\n this.formSubmission.start();\n }\n prepareRequest(request) {\n var _a;\n request.headers[\"Turbo-Frame\"] = this.id;\n if ((_a = this.currentNavigationElement) === null || _a === void 0 ? void 0 : _a.hasAttribute(\"data-turbo-stream\")) {\n request.acceptResponseType(StreamMessage.contentType);\n }\n }\n requestStarted(_request) {\n markAsBusy(this.element);\n }\n requestPreventedHandlingResponse(_request, _response) {\n this.resolveVisitPromise();\n }\n async requestSucceededWithResponse(request, response) {\n await this.loadResponse(response);\n this.resolveVisitPromise();\n }\n async requestFailedWithResponse(request, response) {\n await this.loadResponse(response);\n this.resolveVisitPromise();\n }\n requestErrored(request, error) {\n console.error(error);\n this.resolveVisitPromise();\n }\n requestFinished(_request) {\n clearBusyState(this.element);\n }\n formSubmissionStarted(_ref22) {\n let formElement = _ref22.formElement;\n markAsBusy(formElement, this.findFrameElement(formElement));\n }\n formSubmissionSucceededWithResponse(formSubmission, response) {\n const frame = this.findFrameElement(formSubmission.formElement, formSubmission.submitter);\n frame.delegate.proposeVisitIfNavigatedWithAction(frame, formSubmission.formElement, formSubmission.submitter);\n frame.delegate.loadResponse(response);\n if (!formSubmission.isSafe) {\n session.clearCache();\n }\n }\n formSubmissionFailedWithResponse(formSubmission, fetchResponse) {\n this.element.delegate.loadResponse(fetchResponse);\n session.clearCache();\n }\n formSubmissionErrored(formSubmission, error) {\n console.error(error);\n }\n formSubmissionFinished(_ref23) {\n let formElement = _ref23.formElement;\n clearBusyState(formElement, this.findFrameElement(formElement));\n }\n allowsImmediateRender(_ref24, options) {\n let newFrame = _ref24.element;\n const event = dispatch(\"turbo:before-frame-render\", {\n target: this.element,\n detail: Object.assign({\n newFrame\n }, options),\n cancelable: true\n });\n const defaultPrevented = event.defaultPrevented,\n render = event.detail.render;\n if (this.view.renderer && render) {\n this.view.renderer.renderElement = render;\n }\n return !defaultPrevented;\n }\n viewRenderedSnapshot(_snapshot, _isPreview) {}\n preloadOnLoadLinksForView(element) {\n session.preloadOnLoadLinksForView(element);\n }\n viewInvalidated() {}\n willRenderFrame(currentElement, _newElement) {\n this.previousFrameElement = currentElement.cloneNode(true);\n }\n async loadFrameResponse(fetchResponse, document) {\n const newFrameElement = await this.extractForeignFrameElement(document.body);\n if (newFrameElement) {\n const snapshot = new Snapshot(newFrameElement);\n const renderer = new FrameRenderer(this, this.view.snapshot, snapshot, FrameRenderer.renderElement, false, false);\n if (this.view.renderPromise) await this.view.renderPromise;\n this.changeHistory();\n await this.view.render(renderer);\n this.complete = true;\n session.frameRendered(fetchResponse, this.element);\n session.frameLoaded(this.element);\n this.fetchResponseLoaded(fetchResponse);\n } else if (this.willHandleFrameMissingFromResponse(fetchResponse)) {\n this.handleFrameMissingFromResponse(fetchResponse);\n }\n }\n async visit(url) {\n var _a;\n const request = new FetchRequest(this, FetchMethod.get, url, new URLSearchParams(), this.element);\n (_a = this.currentFetchRequest) === null || _a === void 0 ? void 0 : _a.cancel();\n this.currentFetchRequest = request;\n return new Promise(resolve => {\n this.resolveVisitPromise = () => {\n this.resolveVisitPromise = () => {};\n this.currentFetchRequest = null;\n resolve();\n };\n request.perform();\n });\n }\n navigateFrame(element, url, submitter) {\n const frame = this.findFrameElement(element, submitter);\n frame.delegate.proposeVisitIfNavigatedWithAction(frame, element, submitter);\n this.withCurrentNavigationElement(element, () => {\n frame.src = url;\n });\n }\n proposeVisitIfNavigatedWithAction(frame, element, submitter) {\n this.action = getVisitAction(submitter, element, frame);\n if (this.action) {\n const pageSnapshot = PageSnapshot.fromElement(frame).clone();\n const visitCachedSnapshot = frame.delegate.visitCachedSnapshot;\n frame.delegate.fetchResponseLoaded = fetchResponse => {\n if (frame.src) {\n const statusCode = fetchResponse.statusCode,\n redirected = fetchResponse.redirected;\n const responseHTML = frame.ownerDocument.documentElement.outerHTML;\n const response = {\n statusCode,\n redirected,\n responseHTML\n };\n const options = {\n response,\n visitCachedSnapshot,\n willRender: false,\n updateHistory: false,\n restorationIdentifier: this.restorationIdentifier,\n snapshot: pageSnapshot\n };\n if (this.action) options.action = this.action;\n session.visit(frame.src, options);\n }\n };\n }\n }\n changeHistory() {\n if (this.action) {\n const method = getHistoryMethodForAction(this.action);\n session.history.update(method, expandURL(this.element.src || \"\"), this.restorationIdentifier);\n }\n }\n async handleUnvisitableFrameResponse(fetchResponse) {\n console.warn(`The response (${fetchResponse.statusCode}) from is performing a full page visit due to turbo-visit-control.`);\n await this.visitResponse(fetchResponse.response);\n }\n willHandleFrameMissingFromResponse(fetchResponse) {\n var _this = this;\n this.element.setAttribute(\"complete\", \"\");\n const response = fetchResponse.response;\n const visit = async function (url) {\n let options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};\n if (url instanceof Response) {\n _this.visitResponse(url);\n } else {\n session.visit(url, options);\n }\n };\n const event = dispatch(\"turbo:frame-missing\", {\n target: this.element,\n detail: {\n response,\n visit\n },\n cancelable: true\n });\n return !event.defaultPrevented;\n }\n handleFrameMissingFromResponse(fetchResponse) {\n this.view.missing();\n this.throwFrameMissingError(fetchResponse);\n }\n throwFrameMissingError(fetchResponse) {\n const message = `The response (${fetchResponse.statusCode}) did not contain the expected and will be ignored. To perform a full page visit instead, set turbo-visit-control to reload.`;\n throw new TurboFrameMissingError(message);\n }\n async visitResponse(response) {\n const wrapped = new FetchResponse(response);\n const responseHTML = await wrapped.responseHTML;\n const location = wrapped.location,\n redirected = wrapped.redirected,\n statusCode = wrapped.statusCode;\n return session.visit(location, {\n response: {\n redirected,\n statusCode,\n responseHTML\n }\n });\n }\n findFrameElement(element, submitter) {\n var _a;\n const id = getAttribute(\"data-turbo-frame\", submitter, element) || this.element.getAttribute(\"target\");\n return (_a = getFrameElementById(id)) !== null && _a !== void 0 ? _a : this.element;\n }\n async extractForeignFrameElement(container) {\n let element;\n const id = CSS.escape(this.id);\n try {\n element = activateElement(container.querySelector(`turbo-frame#${id}`), this.sourceURL);\n if (element) {\n return element;\n }\n element = activateElement(container.querySelector(`turbo-frame[src][recurse~=${id}]`), this.sourceURL);\n if (element) {\n await element.loaded;\n return await this.extractForeignFrameElement(element);\n }\n } catch (error) {\n console.error(error);\n return new FrameElement();\n }\n return null;\n }\n formActionIsVisitable(form, submitter) {\n const action = getAction(form, submitter);\n return locationIsVisitable(expandURL(action), this.rootLocation);\n }\n shouldInterceptNavigation(element, submitter) {\n const id = getAttribute(\"data-turbo-frame\", submitter, element) || this.element.getAttribute(\"target\");\n if (element instanceof HTMLFormElement && !this.formActionIsVisitable(element, submitter)) {\n return false;\n }\n if (!this.enabled || id == \"_top\") {\n return false;\n }\n if (id) {\n const frameElement = getFrameElementById(id);\n if (frameElement) {\n return !frameElement.disabled;\n }\n }\n if (!session.elementIsNavigatable(element)) {\n return false;\n }\n if (submitter && !session.elementIsNavigatable(submitter)) {\n return false;\n }\n return true;\n }\n get id() {\n return this.element.id;\n }\n get enabled() {\n return !this.element.disabled;\n }\n get sourceURL() {\n if (this.element.src) {\n return this.element.src;\n }\n }\n set sourceURL(sourceURL) {\n this.ignoringChangesToAttribute(\"src\", () => {\n this.element.src = sourceURL !== null && sourceURL !== void 0 ? sourceURL : null;\n });\n }\n get loadingStyle() {\n return this.element.loading;\n }\n get isLoading() {\n return this.formSubmission !== undefined || this.resolveVisitPromise() !== undefined;\n }\n get complete() {\n return this.element.hasAttribute(\"complete\");\n }\n set complete(value) {\n this.ignoringChangesToAttribute(\"complete\", () => {\n if (value) {\n this.element.setAttribute(\"complete\", \"\");\n } else {\n this.element.removeAttribute(\"complete\");\n }\n });\n }\n get isActive() {\n return this.element.isActive && this.connected;\n }\n get rootLocation() {\n var _a;\n const meta = this.element.ownerDocument.querySelector(`meta[name=\"turbo-root\"]`);\n const root = (_a = meta === null || meta === void 0 ? void 0 : meta.content) !== null && _a !== void 0 ? _a : \"/\";\n return expandURL(root);\n }\n isIgnoringChangesTo(attributeName) {\n return this.ignoredAttributes.has(attributeName);\n }\n ignoringChangesToAttribute(attributeName, callback) {\n this.ignoredAttributes.add(attributeName);\n callback();\n this.ignoredAttributes.delete(attributeName);\n }\n withCurrentNavigationElement(element, callback) {\n this.currentNavigationElement = element;\n callback();\n delete this.currentNavigationElement;\n }\n}\nfunction getFrameElementById(id) {\n if (id != null) {\n const element = document.getElementById(id);\n if (element instanceof FrameElement) {\n return element;\n }\n }\n}\nfunction activateElement(element, currentURL) {\n if (element) {\n const src = element.getAttribute(\"src\");\n if (src != null && currentURL != null && urlsAreEqual(src, currentURL)) {\n throw new Error(`Matching element has a source URL which references itself`);\n }\n if (element.ownerDocument !== document) {\n element = document.importNode(element, true);\n }\n if (element instanceof FrameElement) {\n element.connectedCallback();\n element.disconnectedCallback();\n return element;\n }\n }\n}\nclass StreamElement extends HTMLElement {\n static async renderElement(newElement) {\n await newElement.performAction();\n }\n async connectedCallback() {\n try {\n await this.render();\n } catch (error) {\n console.error(error);\n } finally {\n this.disconnect();\n }\n }\n async render() {\n var _a;\n return (_a = this.renderPromise) !== null && _a !== void 0 ? _a : this.renderPromise = (async () => {\n const event = this.beforeRenderEvent;\n if (this.dispatchEvent(event)) {\n await nextAnimationFrame();\n await event.detail.render(this);\n }\n })();\n }\n disconnect() {\n try {\n this.remove();\n } catch (_a) {}\n }\n removeDuplicateTargetChildren() {\n this.duplicateChildren.forEach(c => c.remove());\n }\n get duplicateChildren() {\n var _a;\n const existingChildren = this.targetElements.flatMap(e => [...e.children]).filter(c => !!c.id);\n const newChildrenIds = [...(((_a = this.templateContent) === null || _a === void 0 ? void 0 : _a.children) || [])].filter(c => !!c.id).map(c => c.id);\n return existingChildren.filter(c => newChildrenIds.includes(c.id));\n }\n get performAction() {\n if (this.action) {\n const actionFunction = StreamActions[this.action];\n if (actionFunction) {\n return actionFunction;\n }\n this.raise(\"unknown action\");\n }\n this.raise(\"action attribute is missing\");\n }\n get targetElements() {\n if (this.target) {\n return this.targetElementsById;\n } else if (this.targets) {\n return this.targetElementsByQuery;\n } else {\n this.raise(\"target or targets attribute is missing\");\n }\n }\n get templateContent() {\n return this.templateElement.content.cloneNode(true);\n }\n get templateElement() {\n if (this.firstElementChild === null) {\n const template = this.ownerDocument.createElement(\"template\");\n this.appendChild(template);\n return template;\n } else if (this.firstElementChild instanceof HTMLTemplateElement) {\n return this.firstElementChild;\n }\n this.raise(\"first child element must be a