alchemy_cms 8.1.13 → 8.1.14
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- checksums.yaml +4 -4
- data/app/assets/builds/alchemy/alchemy_admin.min.js +4 -0
- data/app/assets/builds/alchemy/alchemy_admin.min.js.map +4 -0
- data/app/controllers/alchemy/admin/pages_controller.rb +4 -4
- data/app/controllers/alchemy/api/pages_controller.rb +8 -2
- data/app/javascript/alchemy_admin/components/element_editor.js +4 -1
- data/app/serializers/alchemy/page_tree_serializer.rb +6 -0
- data/app/services/alchemy/page_tree_preloader.rb +9 -7
- data/app/views/alchemy/admin/layoutpages/_layoutpage.html.erb +1 -1
- data/lib/alchemy/cache_digests/template_tracker.rb +0 -2
- data/lib/alchemy/configuration/collection_option.rb +1 -1
- data/lib/alchemy/version.rb +1 -1
- metadata +1 -1
|
@@ -1,6 +1,10 @@
|
|
|
1
1
|
<<<<<<< HEAD
|
|
2
|
+
<<<<<<< HEAD
|
|
2
3
|
import"handlebars";import"jquery";import"@ungap/custom-elements";import{Turbo as e}from"@hotwired/turbo-rails";import"select2";import t from"@rails/ujs";import"keymaster";import"clipboard";import s from"flatpickr";import i from"sortablejs";import"tinymce";import{setDefaultAnimation as n,registerIconLibrary as r}from"shoelace";import l from"cropperjs";const o=/\./;function a(e){const t=c(),s=Alchemy.translations;return s?o.test(e)?function(e,t){const s=t.split(o),i=e[s[0]];return i&&i[s[1]]||t}(s,e):s[e]||e:(console.warn(`Translations for locale ${t} not found!`),e)}function c(){return document.documentElement.lang?document.documentElement.lang:"en"}function d(e,t=void 0){let s=a(e);return t?s.replace(/%\{.+\}/,t):s}async function h(){const e=c();"en"!==e&&(await import(`select2/${e}.js`),$.extend($.fn.select2.defaults,$.fn.select2.locales[e]))}const u=[];function m(e){return!(!$(e.target).is("input, textarea")&&"?"===String.fromCharCode(e.which))||(_("/admin/help",{title:Alchemy.t("help"),size:"400x492"}),!1)}function p(e=document){e instanceof jQuery&&(e=e[0]),e===document&&(document.removeEventListener("keypress",m),document.addEventListener("keypress",m),u.forEach((e=>key.unbind(e))));const t=e.querySelectorAll(".search_input_field"),s=e.querySelectorAll(".search_field_clear, .js_filter_field_clear");key("alt+f",(function(){return key.setScope("search"),t.forEach((e=>e.focus({focusVisible:!0}))),!1})),u.push("alt+f"),key("esc","search",(function(){s.forEach((e=>e.click())),t.forEach((e=>e.blur()))})),u.push("esc"),e.querySelectorAll("[data-alchemy-hotkey]").forEach((function(e){const t=e.dataset.alchemyHotkey;key(t,(()=>e.click())),u.push(t)}))}function g(e){const t=document.createElement("template");return t.innerHTML=e,t.content.children[0]}let y=class{constructor(e,t="currentColor"){this.size=e,this.color=t,this.spinner=void 0}get el(){return this.spinner}spin(e){return void 0===e&&(e=document.body),this.spinner=g(`<alchemy-spinner size="${this.size}" color="${this.color}"></alchemy-spinner>`),e.append(this.spinner),this}stop(){this.spinner&&(this.spinner.remove(),this.spinner=void 0)}};const f=[],v={header_height:36,size:"400x300",padding:!0,title:"",modal:!0,overflow:"visible",ready:()=>{},closed:()=>{}};class b{constructor(e,t={}){this.url=e,this.options={...v,...t},this.$document=$(document),this.$window=$(window),this.$body=$("body");const s=this.options.size.split("x");this.width=parseInt(s[0],10),this.height=parseInt(s[1],10),this.build(),this.resize()}open(){this.dialog.trigger("Alchemy.DialogOpen"),this.bind_close_events(),window.requestAnimationFrame((()=>{if(this.dialog_container.addClass("open"),null!=this.overlay)return this.overlay.addClass("open")})),this.$body.addClass("prevent-scrolling"),f.push(this),this.load()}close(){return this.dialog.trigger("DialogClose.Alchemy"),this.$document.off("keydown"),this.dialog_container.removeClass("open"),null!=this.overlay&&this.overlay.removeClass("open"),this.$document.on("webkitTransitionEnd transitionend oTransitionEnd",(()=>{if(this.$document.off("webkitTransitionEnd transitionend oTransitionEnd"),this.dialog_container.remove(),null!=this.overlay&&this.overlay.remove(),this.$body.removeClass("prevent-scrolling"),f.pop(this),null!=this.options.closed)return this.options.closed()})),!0}load(){this.show_spinner(),$.get(this.url,(e=>{this.replace(e)})).fail((e=>{this.show_error(e)}))}reload(){this.dialog_body.empty(),this.load()}replace(e){this.remove_spinner(),this.dialog_body.hide(),this.dialog_body.html(e),this.init(),this.dialog[0].dispatchEvent(new CustomEvent("DialogReady.Alchemy",{bubbles:!0,detail:{body:this.dialog_body[0]}})),null!=this.options.ready&&this.options.ready(this.dialog_body),this.dialog_body.show()}show_spinner(){this.spinner=new y("medium"),this.spinner.spin(this.dialog_body[0])}remove_spinner(){this.spinner.stop()}init(){p(this.dialog_body),this.watch_remote_forms()}watch_remote_forms(){const e=$('[data-remote="true"]',this.dialog_body);e.on("ajax:success",(e=>{const t=e.detail[2];t.getResponseHeader("Content-Type").match(/javascript/)||(this.dialog_body.html(t.responseText),this.init())})),e.on("ajax:error",(e=>{const t=e.detail[1],s=e.detail[2];this.show_error(s,t)}))}show_error(e,t){if(422===e.status)return this.dialog_body.html(e.responseText),void this.init();const{error_body:s,error_header:i,error_type:n}=this.error_messages(e,t),r=$(`<alchemy-message type="${n}">\n <h1>${i}</h1>\n <p>${s}</p>\n </alchemy-message>`);this.dialog_body.html(r)}error_messages(e,t){let s,i,n="warning";switch(e.status){case 0:i="The server does not respond.",s="Please check server and try again.";break;case 403:i="You are not authorized!",s="Please close this window.";break;default:n="error",t?(i=t,console.error(e.responseText)):i=`${e.statusText} (${e.status})`,s="Please check log and try again."}return{error_header:i,error_body:s,error_type:n}}bind_close_events(){this.close_button.on("click",(()=>{this.close()})),this.dialog_container.addClass("closable").on("click",(e=>e.target!==this.dialog_container.get(0)||(this.close(),!1))),this.$document.keydown((e=>27!==e.which||(this.close(),!1)))}build(){this.dialog_container=$('<div class="alchemy-dialog-container" />'),this.dialog=$('<div class="alchemy-dialog" />'),this.dialog_body=$('<div class="alchemy-dialog-body" />'),this.dialog_header=$('<div class="alchemy-dialog-header" />'),this.dialog_title=$('<div class="alchemy-dialog-title" />'),this.close_button=$('<button class="alchemy-dialog-close"><alchemy-icon name="close"></alchemy-icon></button>'),this.dialog_title.text(this.options.title),this.dialog_header.append(this.dialog_title),this.dialog_header.append(this.close_button),this.dialog.append(this.dialog_header),this.dialog.append(this.dialog_body),this.dialog_container.append(this.dialog),this.options.modal&&this.dialog.addClass("modal"),this.options.padding&&this.dialog_body.addClass("padded"),this.options.modal&&(this.overlay=$('<div class="alchemy-dialog-overlay" />'),this.$body.append(this.overlay)),this.$body.append(this.dialog_container)}resize(){const{width:e,height:t}=this.getSize();this.dialog.css({width:e,"min-height":t,overflow:this.options.overflow}),"hidden"===this.options.overflow?this.dialog_body.css({height:t,overflow:"auto"}):this.dialog_body.css({"min-height":t,overflow:"visible"})}getSize(){const e=this.options.padding?16:0,t=this.$window.width(),s=this.$window.height();let i=this.width,n=this.height;return i>=t&&(i=t-e),n>=s&&(n=s-e-v.header_height),{width:i,height:n}}}function E(){const{length:e}=f;if(0!==e)return f[e-1]}function w(e){const t=E();if(null!=t)return t.options.closed=e,t.close()}function _(e,t){if(!e)throw"No url given! Please provide an url.";new b(e,t).open()}class k{constructor(e,t={}){this.message=e,this.options={...{size:"300x100",title:d("Please confirm"),ok_label:d("Yes"),cancel_label:d("No"),on_ok(){}},...t},this.#e(),this.#t()}open(){requestAnimationFrame((()=>{this.dialog.show()}))}#e(){const e=this.options.size.split("x")[0];this.dialog=g(`\n <sl-dialog label="${this.options.title}" style="--width: ${e}px">\n ${this.message}\n <button slot="footer" type="reset" class="secondary mx-1 my-0" autofocus>\n ${this.options.cancel_label}\n </button>\n <button slot="footer" type="submit" class="mx-1 my-0">\n ${this.options.ok_label}\n </button>\n </sl-dialog>\n `),document.body.append(this.dialog)}#t(){this.cancelButton.addEventListener("click",(e=>{e.preventDefault(),this.options.on_cancel(),this.dialog.hide()})),this.okButton.addEventListener("click",(e=>{e.preventDefault(),this.options.on_ok(),this.dialog.hide()})),this.dialog.addEventListener("sl-request-close",(e=>{"overlay"===e.detail.source&&(this.options.on_cancel(),e.preventDefault())})),this.dialog.addEventListener("sl-after-hide",(()=>{this.dialog.remove()}))}get cancelButton(){return this.dialog.querySelector("button[type=reset]")}get okButton(){return this.dialog.querySelector("button[type=submit]")}}function L(e,t={}){return new Promise((s=>{new k(e,{...t,on_ok(){s(!0)},on_cancel(){s(!1)}}).open()}))}function S(e=!0){document.querySelector("alchemy-overlay").show=!!e}function C(e){let t=()=>{};$(e).is("form")?t=function(){const t=$(`<form action="${e.action}" method="POST" style="display: none" />`);t.append($(e).find("input")),t.appendTo("body"),S(),t.trigger("submit")}:$(e).is("a")&&(t=()=>Turbo.visit(e.pathname));return!(document.querySelectorAll("alchemy-element-editor.dirty").length>0)||(L(d("page_dirty_notice"),{title:d("warning"),ok_label:d("ok"),cancel_label:d("cancel")}).then((e=>{e&&(window.onbeforeunload=void 0,t())})),!1)}var x={checkPageDirtyness:C,PageLeaveObserver:function(){document.querySelectorAll("#main_navi a").forEach((e=>{e.addEventListener("click",(e=>{C(e.currentTarget)||e.preventDefault()}))}))}};function T(e){const t=document.getElementById("fixed-elements"),s=`fixed-element-${e}`;t.querySelector(`sl-tab[panel="${s}"]`).remove(),t.querySelector(`sl-tab-panel[name="${s}"]`).remove(),t.show("main-content-elements")}var A=Object.freeze({__proto__:null,createTab:function(e,t){const s=document.getElementById("fixed-elements"),i=`fixed-element-${e}`,n=`<sl-tab slot="nav" panel="${i}">${t}</sl-tab>`,r=`<sl-tab-panel name="${i}" style="--padding: 0" />`;s.innerHTML+=n+r,window.requestAnimationFrame((function(){s.show(i)}))},removeTab:T});function F(e,t="notice"){!function(e,t){const s=document.getElementById("flash_notices"),i=g(`\n <alchemy-message type="${t}" dismissable>\n ${e}\n </alchemy-message>\n `);s.append(i)}(e,t)}const q=/#[\w.~-]+$/;class I extends HTMLIFrameElement{#s;#i;#n;#r;constructor(){super(),this.addEventListener("load",this),this.#r=this.#l.bind(this)}handleEvent(e){"load"===e.type&&(this.#o(),this.#a(),this.#s?.call(this,e))}#l(e){"Alchemy.previewReady"===e.data.message&&(this.#o(),this.#a(),this.#s?.call(this,e))}connectedCallback(){let e=this.url;this.#c(),window.addEventListener("message",this.#r),window.localStorage.getItem("alchemy-preview-url")&&(e=window.localStorage.getItem("alchemy-preview-url"),this.previewUrlSelect.value=e),this.refresh(e)}disconnectedCallback(){key.unbind("alt+r"),window.removeEventListener("message",this.#r)}postMessage(e){this.contentWindow.postMessage(e,"*")}resize(e){this.style.width=`${e}px`}refresh(e){return this.#d(),this.src=e||this.url,this.#o(),this.#n=setTimeout((()=>{this.#a(),F(d("Preview failed to load"),"warning")}),5e3),new Promise((e=>{this.#s=e}))}set isDragged(e){this.style.transitionProperty=e?"none":null,this.style.pointerEvents=e?"none":null}#c(){this.reloadButton?.addEventListener("click",(e=>{e.preventDefault(),this.refresh()})),key("alt+r",(()=>this.refresh())),this.sizeSelect.addEventListener("change",(e=>{const t=e.target.value;""===t?this.style.width=null:this.resize(t)})),this.previewUrlSelect?.addEventListener("change",(e=>{const t=e.target.value;window.localStorage.setItem("alchemy-preview-url",t),this.refresh(t)}))}#d(){this.reloadButton.innerHTML.includes("alchemy-spinner")||(this.#i=this.reloadButton.innerHTML),this.reloadButton.innerHTML='<alchemy-spinner size="small"></alchemy-spinner>'}#a(){this.reloadButton.innerHTML=this.#i}#o(){this.#n&&(clearTimeout(this.#n),this.#n=null)}get url(){return this.getAttribute("url")}get sizeSelect(){return document.querySelector("select#preview_size")}get previewUrlSelect(){return document.querySelector("select#preview_url")}get reloadButton(){return document.querySelector("#reload_preview_button")}}function B(){document.getElementById("alchemy_preview_window").refresh()}customElements.define("alchemy-preview-window",I,{extends:"iframe"});class M{static updateIcon(e,t=!1){const s=document.querySelector(`[data-ingredient-id="${e}"]`);if(s){s.querySelector(".edit-ingredient-anchor-link alchemy-icon").setAttribute("icon-style",t?"fill":"line")}}}class z extends HTMLElement{constructor(){super(),this.actions={closeCurrentDialog:w,reloadPreview:B,removeFixedElement:T,updateAnchorIcon:M.updateIcon,hidePleaseWaitOverlay(){S(!1)}}}connectedCallback(){const e=this.actions[this.name];e?e(...this.params):console.error(`Unknown Alchemy action: ${this.name}`),this.remove()}get name(){return this.getAttribute("name")}get params(){return this.hasAttribute("params")?JSON.parse(this.getAttribute("params")):[]}}customElements.define("alchemy-action",z);class H extends HTMLElement{static properties={};static get observedAttributes(){return Object.keys(this.properties)}constructor(e={}){super(),this.options=e,this.changeComponent=!0,this.initialContent=this.innerHTML}async connectedCallback(){Object.keys(this.constructor.properties).forEach((e=>{this[e]=this.options[e]??this.constructor.properties[e].default})),this.getAttributeNames().forEach((e=>this._updateFromAttribute(e))),this._updateComponent(),await this.connected()}disconnectedCallback(){this.disconnected()}attributeChangedCallback(e){this._updateFromAttribute(e),this._updateComponent()}async connected(){}disconnected(){}render(){return this.initialContent}afterRender(){}dispatchCustomEvent(e,t={}){const s=new CustomEvent(`Alchemy.${e}`,{bubbles:!0,detail:t});this.dispatchEvent(s)}_updateComponent(){this.changeComponent&&(this.innerHTML=this.render(),this.changeComponent=!1,this.afterRender())}_updateFromAttribute(e){const t=this.getAttribute(e),s=e.split(/-|_/).reduce(((e,t)=>e+t.charAt(0).toUpperCase()+t.slice(1)));const i=!!(0===t.length||"true"===t)||t;this[s]!==i&&(this[s]=i,this.changeComponent=!0)}}function P(e,t){return e.replace(new RegExp(t,"gi"),(e=>`<em>${e}</em>`))}class D extends H{static properties={allowClear:{default:!1},selection:{default:void 0},placeholder:{default:""},queryParams:{default:"{}"},url:{default:""}};async connected(){await h(),this.input.classList.add("alchemy_selectbox"),$(this.input).select2(this.select2Config).on("select2-open",(e=>{this.onOpen(e)})).on("change",(e=>{this.onChange(e)}))}onChange(e){this.dispatchCustomEvent("RemoteSelect.Change",{removed:e.removed,added:e.added})}onOpen(e){setTimeout((()=>{document.querySelector("#select2-drop .select2-input").focus()}),100)}get input(){return this.getElementsByTagName("input")[0]}get select2Config(){return{placeholder:this.placeholder,allowClear:this.allowClear,initSelection:(e,t)=>{this.selection&&t(JSON.parse(this.selection))},ajax:this.ajaxConfig,formatSelection:e=>this._renderResult(e),formatResult:(e,t,s)=>this._renderListEntry(e,s.term)}}get ajaxConfig(){return{url:this.url,datatype:"json",quietMillis:300,data:(e,t)=>this._searchQuery(e,t),results:e=>this._parseResponse(e)}}_searchQuery(e,t){return{q:{name_cont:e,...JSON.parse(this.queryParams)},page:t}}_parseResponse(e){const t=e.meta;return{results:e.data,more:t.page*t.per_page<t.total_count}}_renderResult(){throw new Error("You need to define a _renderResult function on your sub class!")}_renderListEntry(){throw new Error("You need to define a _renderListEntry function on your sub class!")}_hightlightTerm(e,t){return P(e,t)}}customElements.define("alchemy-attachment-select",class extends D{_renderResult(e){return this._renderListEntry(e)}_renderListEntry(e,t){return`\n <div class="attachment-select--attachment">\n <alchemy-icon name="${e.icon_css_class}"></alchemy-icon>\n <span class="attachment-select--attachment-name">${this._hightlightTerm(e.name,t)}</span>\n </div>\n `}});class N extends HTMLElement{connectedCallback(){$(this).on("change",(function(e){const t=new Event("submit",{bubbles:!0,cancelable:!0});return e.target.form.dispatchEvent(t),!1}))}}customElements.define("alchemy-auto-submit",N);class O extends HTMLButtonElement{connectedCallback(){this.form?(this.form.addEventListener("submit",this),"true"==this.form.dataset.remote&&this.form.addEventListener("ajax:complete",this),this.form.addEventListener("turbo:submit-end",this)):console.warn("No form for button found!",this)}handleEvent(e){switch(e.type){case"submit":"disabled"===this.getAttribute("disabled")?(e.preventDefault(),e.stopPropagation()):this.disable();break;case"ajax:complete":case"turbo:submit-end":this.enable()}}disable(){const e=new y("small"),t=this.getBoundingClientRect();this.dataset.initialButtonText=this.innerHTML,this.setAttribute("disabled","disabled"),this.setAttribute("tabindex","-1"),this.classList.add("disabled"),this.style.width=`${t.width}px`,this.style.height=`${t.height}px`,this.innerHTML=" ",e.spin(this)}enable(){this.classList.remove("disabled"),this.removeAttribute("disabled"),this.removeAttribute("tabindex"),this.style.width=null,this.style.height=null,this.innerHTML=this.dataset.initialButtonText}}customElements.define("alchemy-button",O,{extends:"button"});customElements.define("alchemy-char-counter",class extends H{static properties={maxChars:{default:60}};connected(){this.translation=d("allowed_chars",this.maxChars),this.formField=this.getFormField(),this.formField&&(this.createDisplayElement(),this.countCharacters(),this.formField.addEventListener("keyup",(()=>this.countCharacters())))}getFormField(){const e=this.querySelectorAll("input, textarea");return e.length>0?e[0]:void 0}createDisplayElement(){this.display=document.createElement("small"),this.display.className="alchemy-char-counter",this.formField.after(this.display)}countCharacters(){const e=this.formField.value.length;this.display.textContent=`${e} ${this.translation}`,this.display.classList.toggle("too-long",e>this.maxChars)}});class R extends HTMLElement{constructor(){super(),this.innerHTML='\n <alchemy-icon name="clipboard"></alchemy-icon>\n ',this.clipboard=new ClipboardJS(this,{text:()=>this.getAttribute("content")}),this.clipboard.on("success",(()=>{F(this.getAttribute("success-text"))}))}disconnectedCallback(){this.clipboard.destroy()}}customElements.define("alchemy-clipboard-button",R);const U=e=>{const t=e.element[0],s=t.dataset.swatch||t.value;return`\n <div class="select-color-option">\n ${"custom_color"===t.value?'<alchemy-icon name="palette"></alchemy-icon>':`<span class="color-indicator" style="--color: ${s}"></span>`}\n <span>${e.text}</span>\n </div>`};class j extends HTMLElement{connectedCallback(){this.select?(this.#h(),$(this.select).on("change",(e=>this.#u("custom_color"===e.val)))):(this.colorInput?.addEventListener("input",this),this.textInput?.addEventListener("input",this),this.#u(!0))}handleEvent(e){switch(e.target){case this.colorInput:this.textInput.value=this.colorInput.value;break;case this.textInput:this.colorInput.value=this.textInput.value}}disconnectedCallback(){this.colorInput?.removeEventListener("input",this),this.textInput?.removeEventListener("input",this)}#h(){this.select.classList.add("alchemy_selectbox");const e={minimumResultsForSearch:10,formatResult:U,formatSelection:U};$(this.select).select2(e)}#u(e=!0){this.colorInput.disabled=!e}get colorInput(){return this.querySelector("input[type='color']")}get textInput(){return this.querySelector("input[type='text']")}get select(){return this.querySelector("select")}}customElements.define("alchemy-color-select",j);const W=c();customElements.define("alchemy-datepicker",class extends H{static properties={inputType:{default:"date"}};constructor(){super(),this.flatpickr=void 0}async connected(){"en"!==W&&await import(`flatpickr/${W}.js`),this.flatpickr=s(this.inputField,this.flatpickrOptions)}disconnected(){this.flatpickr.destroy()}get flatpickrOptions(){const e=/time/.test(this.inputType),t={locale:W.slice(0,2),altInput:!0,altFormat:d(`formats.${this.inputType}`),altInputClass:"flatpickr-input",enableTime:e,noCalendar:"time"===this.inputType,time_24hr:d("formats.time_24hr"),onValueUpdate(e,t,s){s.element.closest("alchemy-element-editor")?.setDirty(this.inputField)}};return e&&(t.dateFormat="Z"),t}get inputField(){return this.querySelector("input")}});class J extends HTMLAnchorElement{constructor(){super(),this.addEventListener("click",this)}handleEvent(e){this.disabled||this.openDialog(),e.preventDefault()}openDialog(){this.dialog=new b(this.getAttribute("href"),this.dialogOptions),this.dialog.open()}get dialogOptions(){return this.dataset.dialogOptions?JSON.parse(this.dataset.dialogOptions):{}}get disabled(){return this.classList.contains("disabled")}}customElements.define("alchemy-dialog-link",J,{extends:"a"});const V="application/json",X="text/vnd.turbo-stream.html";function Q(e){return"get"===e.toLowerCase()}function Y(e,t,s){const i=function(e){return{"Content-Type":"application/json; charset=utf-8",Accept:e,"X-Requested-With":"XMLHttpRequest","X-CSRF-Token":K()}}(s),n={method:e,headers:i};return t&&!Q(e)&&(n.body=JSON.stringify(t)),n}function K(){return document.querySelector('meta[name="csrf-token"]').attributes.content.textContent}function G(e,t){return te("GET",e,t)}function Z(e,t,s){return te("PATCH",e,t,s)}function ee(e,t,s=V){return te("POST",e,t,s)}async function te(e,t,s,i=V){const n=await fetch(function(e,t,s){const i=new URL(window.location.origin+e);return t&&Q(s)&&(i.search=new URLSearchParams(t).toString()),i.toString()}(t,s,e),Y(e,s,i)),r=n.headers.get("content-type"),l=r?.includes(V),o=r?.includes(X);let a=null;if(l?a=await n.json():o&&(a=await n.text(),"undefined"!=typeof Turbo&&Turbo.renderStreamMessage(a)),n.ok)return{data:a,status:n.status};throw a||new Error("An error occurred during the transaction")}class se extends HTMLElement{dataItem(e){return{id:`#${e}`,text:`#${e}`}}get selectElement(){return this.querySelector('select[is="alchemy-select"]')}}customElements.define("alchemy-dom-id-api-select",class extends se{#m=void 0;connectedCallback(){this.page=this.getAttribute("page")}async#p(){const e=(await G(Alchemy.routes.api_ingredients_path,{page_id:this.#m})).data.ingredients.filter((e=>e.data?.dom_id)).map((e=>this.dataItem(e.data.dom_id))),t=e.length>0?d("None"):d("No anchors found");this.selectElement.setOptions(e,t),this.selectElement.enable()}#g(){requestAnimationFrame((()=>{this.selectElement.disable(),this.selectElement.setOptions([],d("Select a page first"))}))}set page(e){this.#m=e,e?this.#p():this.#g()}}),customElements.define("alchemy-dom-id-preview-select",class extends se{connectedCallback(){requestAnimationFrame((()=>{const e=document.getElementById("alchemy_preview_window"),t=e.contentDocument?.querySelectorAll("[id]")||[];if(t.length>0){const e=Array.from(t).map((e=>this.dataItem(e.id)));this.selectElement.setOptions(e,d("None"))}}))}});class ie extends HTMLElement{#y;connectedCallback(){this.#y=this.scheduleButton.getAttribute("variant"),this.publishButton.addEventListener("click",this),this.dropdown.addEventListener("sl-show",this),this.dropdown.addEventListener("sl-hide",this)}disconnectedCallback(){this.publishButton.removeEventListener("click",this),this.dropdown.removeEventListener("sl-show",this),this.dropdown.removeEventListener("sl-hide",this)}handleEvent(e){switch(e.type){case"click":this.publishButton.loading=!0;break;case"sl-show":this.scheduleButton.setAttribute("variant","primary");break;case"sl-hide":this.scheduleButton.setAttribute("variant",this.#y)}}get publishButton(){return this.querySelector("sl-button[type='submit']")}get dropdown(){return this.querySelector("sl-dropdown")}get scheduleButton(){return this.querySelector("sl-button[slot='trigger']")}}customElements.define("alchemy-publish-element-button",ie);class ne extends HTMLElement{constructor(){super(),this.button?.addEventListener("click",this)}async handleEvent(){if(await L(this.message)){const e=await te("DELETE",this.url);this.#f(e.data)}}#f(e){const t=this.closest("alchemy-element-editor");t.addEventListener("transitionend",(()=>{t.fixed&&T(t.elementId),t.remove()})),t.classList.add("dismiss"),F(e.message),e.pageHasUnpublishedChanges&&re(e),B()}get url(){return this.getAttribute("href")}get message(){return this.getAttribute("message")}get button(){return this.querySelector("button")}}function re(e){document.dispatchEvent(new CustomEvent("alchemy:page-dirty",{detail:{tooltip:e.publishButtonTooltip}}))}customElements.define("alchemy-delete-element-button",ne);class le extends HTMLElement{constructor(){super(),this.addEventListener("click",this),this.addEventListener("alchemy:element-update-title",this),this.addEventListener("ajax:complete",this),$(this.form).on("change",this.onChange),this.header?.addEventListener("dblclick",(()=>{this.toggle()})),this.toggleButton?.addEventListener("click",(e=>{e.target.closest("alchemy-element-editor")===this&&this.toggle()}))}connectedCallback(){this.classList.contains("ui-sortable-placeholder")||this.hasAttribute("created")&&(this.focusElement(),this.previewWindow?.refresh().then((()=>{this.focusElementPreview()})),this.removeAttribute("created"))}handleEvent(e){switch(e.type){case"click":e.target.closest("alchemy-element-editor")===this&&this.onClickElement();break;case"ajax:complete":if(e.target===this.body){const t=e.detail[0];e.stopPropagation(),this.onSaveElement(t)}break;case"alchemy:element-update-title":this.hasEditors||e.target!=this.firstChild||this.setTitle(e.detail.title)}}onChange(e){const t=e.target;if(!t.classList.contains("nested-elements"))return this.closest("alchemy-element-editor").setDirty(t),e.stopPropagation(),!1}async focusElement(){document.querySelector("#fixed-elements")&&await this.selectTabForElement(),await this.expand(),this.selectElement(!0)}focusElementPreview(){this.previewWindow?.postMessage({message:"Alchemy.focusElement",element_id:this.elementId})}onClickElement(){this.selectElement(),this.focusElementPreview()}onSaveElement(e){const t=JSON.parse(e.responseText);if(this.setClean(),422===e.status){const e=t.warning;t.ingredientsWithErrors.forEach((e=>{const t=this.querySelector(`[data-ingredient-id="${e.id}"]`),s=g(`<small class="error">${e.errorMessage}</small>`);t?.appendChild(s),t?.classList.add("validation_failed")})),F(e,"warn"),this.elementErrors.classList.remove("hidden")}else F(t.notice),this.previewWindow?.refresh().then((()=>{this.focusElementPreview()})),this.updateTitle(t.previewText),t.ingredientAnchors.forEach((e=>{M.updateIcon(e.ingredientId,e.active)})),t.pageHasUnpublishedChanges&&re(t)}scrollToElement(){setTimeout((()=>{this.scrollIntoView({behavior:"smooth"})}),50)}selectElement(e=!1){document.querySelectorAll("alchemy-element-editor.selected").forEach((e=>{e.classList.remove("selected")})),window.requestAnimationFrame((()=>{this.classList.add("selected")})),e&&this.scrollToElement()}selectTabForElement(){return new Promise(((e,t)=>{const s=document.querySelector("#fixed-elements"),i=this.closest("sl-tab-panel");s&&i?(s.show(i.getAttribute("name")),e()):t(new Error("No tabs present"))}))}setClean(){this.dirty=!1,window.onbeforeunload=null,this.elementErrors.classList.add("hidden"),this.hasEditors&&this.body.querySelectorAll(".ingredient-editor").forEach((e=>{e.classList.remove("dirty","validation_failed"),e.querySelectorAll("small.error").forEach((e=>e.remove()))}))}setDirty(e){this.hasEditors&&(this.dirty=!0,window.onbeforeunload||(window.onbeforeunload=e=>e.preventDefault()),e?.closest(".ingredient-editor")?.classList.add("dirty"))}setTitle(e){this.querySelector(".element-header .preview_text_quote").textContent=e}async toggle(){this.collapsed?await this.expand():await this.collapse()}collapse(){if(this.collapsed||this.compact||this.fixed)return Promise.resolve("Element is already collapsed.");const e=new Alchemy.Spinner("small");return e.spin(this.toggleButton),this.toggleIcon?.classList?.add("hidden"),ee(Alchemy.routes.collapse_admin_element_path(this.elementId)).then((e=>{const t=e.data;if(this.collapsed=!0,this.toggleButton?.setAttribute("title",t.title),t.nestedElementIds.length){const e=t.nestedElementIds.map((e=>`#element_${e}`)).join(", ");this.querySelectorAll(e).forEach((e=>{e.collapsed=!0,e.toggleButton?.setAttribute("title",t.title)}))}})).catch((e=>{F(e.message,"error"),console.error(e)})).finally((()=>{this.toggleIcon?.classList?.remove("hidden"),e.stop()}))}expand(){if(this.expanded&&!this.compact)return Promise.resolve("Element is already expanded.");if(this.compact&&this.parentElementEditor)return this.parentElementEditor.expand();{const e=new Alchemy.Spinner("small");return e.spin(this.toggleButton),this.toggleIcon?.classList.add("hidden"),new Promise(((t,s)=>{ee(Alchemy.routes.expand_admin_element_path(this.elementId)).then((e=>{const s=e.data;if(s.parentElementIds.length){const e=s.parentElementIds.map((e=>`#element_${e}`)).join(", ");document.querySelectorAll(e).forEach((e=>{e.collapsed=!1,e.toggleButton?.setAttribute("title",s.title)}))}this.collapsed=!1,this.toggleButton?.setAttribute("title",s.title),t()})).catch((e=>{F(e.message,"error"),console.error(e),s(e)})).finally((()=>{this.toggleIcon?.classList?.remove("hidden"),e.stop()}))}))}}updateTitle(e){this.setTitle(e),this.dispatchEvent(new CustomEvent("alchemy:element-update-title",{bubbles:!0,detail:{title:e}}))}set published(e){e?this.classList.remove("element-hidden"):this.classList.add("element-hidden")}get published(){return!this.classList.contains("hidden")}get compact(){return null!==this.getAttribute("compact")}get fixed(){return null!==this.getAttribute("fixed")}set collapsed(e){this.classList.toggle("folded",e),this.classList.toggle("expanded",!e),this.toggleIcon&&(this.toggleIcon.name=e?"arrow-left-s":"arrow-down-s")}get collapsed(){return this.classList.contains("folded")}get expanded(){return!this.collapsed}set dirty(e){this.classList.toggle("dirty",e)}get dirty(){return this.classList.contains("dirty")}get header(){return this.querySelector(".element-header")}get body(){return this.querySelector(this.bodySelector)}get bodySelector(){return`#${this.id} > .element-body`}get footer(){return this.querySelector(`#${this.id} > .element-footer`)}get toggleButton(){return this.querySelector(".element-toggle")}get toggleIcon(){return this.toggleButton?.querySelector("alchemy-icon")}get elementErrors(){return this.body.querySelector(".element_errors")}get elementId(){return this.dataset.elementId}get elementName(){return this.dataset.elementName}get hasEditors(){return!!this.body?.querySelector(".element-ingredient-editors")}get hasChildren(){return!!this.querySelector(".nested-elements")}get firstChild(){return this.querySelector("alchemy-element-editor")}get form(){return this.querySelector("form.element-body")}get parentElementEditor(){return this.parentElement?.closest("alchemy-element-editor")}get previewWindow(){return document.getElementById("alchemy_preview_window")}}customElements.define("alchemy-element-editor",le);const oe=e=>`\n <div class="element-select-name">\n ${e.icon}<span>${e.text}</span>\n </div>\n `;class ae extends HTMLElement{constructor(){super()}connectedCallback(){const e=this.options,t={minimumResultsForSearch:3,dropdownAutoWidth:!0,data:()=>({results:e}),formatResult:(e,t,s)=>{let i;return""===e.id?e.text:(i=""!==s.term?P(e.text,s.term):e.text,((e,t,s)=>{const i=s?`<div class="element-select-description">${s}</div>`:"";return`\n <div class="element-select-item">\n ${oe({icon:e,text:t})}\n ${i}\n </div>\n `})(e.icon,i,e.hint))},formatSelection:oe,placeholder:this.placeholder};$(this.inputField).select2(t)}get options(){return JSON.parse(this.getAttribute("options"))}get placeholder(){return this.getAttribute("placeholder")}get inputField(){return this.querySelector("input")}}customElements.define("alchemy-element-select",ae);class ce extends HTMLElement{#v=!0;#b=null;constructor(){super(),this.#c()}connectedCallback(){this.toggleButton?.addEventListener("click",(e=>{e.preventDefault(),this.toggle()})),window.location.hash&&this.focusElementEditor(window.location.hash),this.resize()}collapseAllElements(){this.querySelectorAll("alchemy-element-editor:not([compact]):not([fixed])").forEach((e=>e.collapse()))}toggle(){this.#v?this.hide():this.show()}show(){document.body.classList.add("elements-window-visible"),this.#v=!0,this.toggleButton.closest("sl-tooltip").content=Alchemy.t("Hide elements"),this.toggleButton.querySelector("alchemy-icon").setAttribute("name","menu-unfold"),this.resize()}hide(){document.body.classList.remove("elements-window-visible"),document.body.style.removeProperty("--elements-window-width"),this.#v=!1,this.toggleButton.closest("sl-tooltip").content=Alchemy.t("Show elements"),this.toggleButton.querySelector("alchemy-icon").setAttribute("name","menu-fold")}resize(e){void 0===e&&(e=this.widthFromCookie),e&&(document.body.style.setProperty("--elements-window-width",`${e}px`),document.cookie=`alchemy-elements-window-width=${e}; SameSite=Lax; Path=/;`)}focusElementEditor(e){const t=document.querySelector(e);t instanceof le&&t.focusElement()&&t.focusElementPreview()}get collapseButton(){return this.querySelector("#collapse-all-elements-button")}get toggleButton(){return document.querySelector("#element_window_button")}get previewWindow(){return document.getElementById("alchemy_preview_window")}get turboFrame(){return this.#b||(this.#b=this.closest("turbo-frame")),this.#b}get widthFromCookie(){return document.cookie.split("; ").find((e=>e.startsWith("alchemy-elements-window-width=")))?.split("=")[1]}set isDragged(e){this.turboFrame.style.transitionProperty=e?"none":null,this.turboFrame.style.pointerEvents=e?"none":null}#c(){this.collapseButton?.addEventListener("click",(()=>{this.collapseAllElements()})),window.addEventListener("message",(e=>{const t=e.data;if("Alchemy.focusElementEditor"==t?.message){const e=document.getElementById(`element_${t.element_id}`);this.show(),e?.focusElement()}})),document.body.addEventListener("click",(e=>{e.target.closest("alchemy-element-editor")||(this.querySelectorAll("alchemy-element-editor").forEach((e=>{e.classList.remove("selected")})),this.previewWindow?.postMessage({message:"Alchemy.blurElements"}))}))}}customElements.define("alchemy-elements-window",ce);class de extends HTMLElement{#E=!1;#w=null;#_=null;constructor(){super(),this.addEventListener("mousedown",this),window.addEventListener("mousemove",this),window.addEventListener("mouseup",this)}handleEvent(e){switch(e.type){case"mousedown":e.stopPropagation(),this.onMouseDown();break;case"mouseup":this.onMouseUp();break;case"mousemove":this.#E&&this.onDrag(e.pageX)}}onMouseDown(){this.#E=!0,this.elementsWindow.isDragged=!0,this.previewWindow.isDragged=!0,this.classList.add("is-dragged")}onMouseUp(){this.#E=!1,this.elementsWindow.isDragged=!1,this.previewWindow.isDragged=!1,this.classList.remove("is-dragged")}onDrag(e){const t=window.innerWidth-e;this.elementsWindow.resize(t)}get elementsWindow(){return this.#w||(this.#w=document.querySelector("alchemy-elements-window")),this.#w}get previewWindow(){return this.#_||(this.#_=document.getElementById("alchemy_preview_window")),this.#_}}customElements.define("alchemy-elements-window-handle",de);class he extends HTMLElement{constructor(){super(),this.deleteLink=this.querySelector(".remove_file_link"),this.fileIcon=this.querySelector(".file_icon"),this.fileName=this.querySelector(".file_name"),this.formFieldId=this.deleteLink?.dataset.formFieldId,this.formField=this.querySelector(`#${this.formFieldId}`),this.deleteLink?.addEventListener("click",this)}handleEvent(e){"click"===e.type&&this.removeFile(),e.stopPropagation()}removeFile(){this.formField.value="",this.fileIcon.innerHTML="",this.fileName.innerHTML="",this.deleteLink?.classList.add("hidden"),this.closest("alchemy-element-editor").setDirty(this.formField)}}customElements.define("alchemy-file-editor",he);class ue extends HTMLElement{#k;constructor(){super(),this.#c()}#c(){this.hotkey&&key(this.hotkey,(()=>(this.filterField.focus(),!1))),this.filterField.addEventListener("keyup",(()=>{clearTimeout(this.#k),this.#k=setTimeout((()=>{const e=this.filterField.value;this.clearButton.style.visibility=e?"visible":"hidden",this.filter(e)}),this.debounceTime)})),this.clearButton.addEventListener("click",(e=>{e.preventDefault(),this.clear()})),this.filterField.addEventListener("focus",(()=>key.setScope("list_filter"))),key("esc","list_filter",(()=>{this.clear(),this.filterField.blur()}))}disconnectedCallback(){this.hotkey&&key.unbind(this.hotkey),key.unbind("esc","list_filter")}filter(e){""===e&&(this.clearButton.style.visibility="hidden");const t=[],s=new Set,i=e.toLowerCase();this.items.forEach((e=>{const n=e.getAttribute(this.nameAttribute)?.toLowerCase();if(-1!==n.indexOf(i)){t.push(e),s.add(e);let i=e.parentElement?.closest(this.itemsSelector);for(;i;)s.add(i),i=i.parentElement?.closest(this.itemsSelector)}})),this.items.forEach((e=>{e.classList.toggle("hidden",!s.has(e))})),1===t.length&&t[0].scrollIntoView({behavior:"smooth",block:"nearest"})}clear(){this.filterField.value="",this.clearButton.style.visibility="hidden",this.items.forEach((e=>e.classList.remove("hidden")))}get nameAttribute(){return this.getAttribute("name-attribute")||"name"}get clearButton(){return this.querySelector('button[type="button"]')}get filterField(){return this.querySelector('input[type="text"]')}get items(){return document.querySelectorAll(this.itemsSelector)}get itemsSelector(){return this.getAttribute("items-selector")}get debounceTime(){return parseInt(this.getAttribute("debounce-time"))||150}get hotkey(){return this.getAttribute("hotkey")}}customElements.define("alchemy-list-filter",ue);class me extends HTMLElement{#L;constructor(){super(),this.#L=this.innerHTML,(this.dismissable||"error"===this.type)&&this.addEventListener("click",this)}handleEvent(e){"click"===e.type&&this.dismiss()}connectedCallback(){this.innerHTML=`\n <alchemy-icon name="${this.iconName}"></alchemy-icon>\n ${this.dismissable&&"error"===this.type?'<alchemy-icon name="close"></alchemy-icon>':""}\n ${this.#L}\n `,this.dismissable&&"error"!==this.type&&setTimeout((()=>{this.dismiss()}),this.dismissDelay)}dismiss(){this.addEventListener("transitionend",(()=>this.remove())),this.classList.add("dismissed")}get dismissable(){return this.hasAttribute("dismissable")}get icon(){return this.getAttribute("icon")}get type(){return this.getAttribute("type")||"notice"}get dismissDelay(){return parseInt(this.noticesWrapper?.dataset.autoDismissDelay||5e3)}get iconName(){switch(this.icon||this.type){case"warning":case"warn":case"alert":return"alert";case"notice":return"check";case"info":case"hint":return"information";case"error":return"bug";default:return this.type}}get noticesWrapper(){return this.closest("#flash_notices")}}customElements.define("alchemy-message",me);class pe extends HTMLElement{connectedCallback(){F(this.message,this.getAttribute("type")||"notice"),this.remove()}get message(){return this.getAttribute("message")||this.innerHTML}}customElements.define("alchemy-growl",pe);class ge extends HTMLElement{static get observedAttributes(){return["name","size","icon-style"]}constructor(){super(),this.spriteUrl=document.querySelector('link[rel="preload"][as="image"]').getAttribute("href")}connectedCallback(){this.render()}attributeChangedCallback(){this.render()}render(){const e=this.size?` icon--${this.size}`:"";this.innerHTML=`<svg class="icon${e}"><use href="${this.spriteUrl}#ri-${this.iconName}${this.style}" /></svg>`}set name(e){this.setAttribute("name",e)}get iconName(){return this.getAttribute("name")}get size(){return this.getAttribute("size")}get style(){const e=this.getAttribute("icon-style");switch(e){case"none":return"";case null:return"-line";default:return`-${e}`}}}customElements.define("alchemy-icon",ge);class ye extends HTMLDetailsElement{#S="Alchemy.expanded_ingredient_groups";constructor(){super(),this.addEventListener("toggle",this),this.isInLocalStorage&&(this.open=!0)}handleEvent(){let e=this.localStorageItem;this.open?(this.toggleIcon.name="arrow-down-s",this.isInLocalStorage||e.push(this.id)):(this.toggleIcon.name="arrow-left-s",e=e.filter((e=>e!==this.id))),localStorage.setItem(this.#S,JSON.stringify(e))}get isInLocalStorage(){return this.localStorageItem.includes(this.id)}get localStorageItem(){const e=localStorage.getItem(this.#S);if(!e)return[];try{return JSON.parse(e)}catch(e){return console.error(e),[]}}get toggleIcon(){return this.querySelector("alchemy-icon")}}customElements.define("alchemy-ingredient-group",ye,{extends:"details"});class fe extends HTMLButtonElement{constructor(){super(),this.addEventListener("click",this),this.classList.add("icon_button"),this.setAttribute("type","button"),this.innerHTML='<alchemy-icon name="link" icon-style="m"></alchemy-icon>'}handleEvent(e){new Alchemy.LinkDialog({url:this.linkUrl,title:this.linkTitle,target:this.linkTarget,type:this.linkClass}).open().then((e=>this.setLink(e))),e.preventDefault()}setLink(e){""===e.url?(this.classList.remove("linked"),this.dispatchEvent(new CustomEvent("alchemy:unlink",{bubbles:!0}))):(this.classList.add("linked"),this.dispatchEvent(new CustomEvent("alchemy:link",{bubbles:!0,detail:e})))}get linkUrl(){return this.linkButtons.linkUrlField.value}get linkTitle(){return this.linkButtons.linkTitleField.value}get linkTarget(){return this.linkButtons.linkTargetField.value}get linkClass(){return this.linkButtons.linkClassField.value}get linkButtons(){return this.closest("alchemy-link-buttons")}}customElements.define("alchemy-link-button",fe,{extends:"button"});class ve extends HTMLButtonElement{constructor(){super(),this.addEventListener("click",this),this.classList.add("icon_button"),this.setAttribute("type","button"),this.linked=this.linked,this.innerHTML='<alchemy-icon name="link-unlink" icon-style="m"></alchemy-icon>'}handleEvent(e){this.linked&&(this.linked=!1,this.blur(),this.dispatchEvent(new CustomEvent("alchemy:unlink",{bubbles:!0}))),e.preventDefault()}set linked(e){e?(this.classList.replace("disabled","linked"),this.removeAttribute("tabindex")):(this.classList.replace("linked","disabled"),this.setAttribute("tabindex","-1"))}get linked(){return this.classList.contains("linked")}}customElements.define("alchemy-unlink-button",ve,{extends:"button"});class be extends HTMLElement{constructor(){super(),this.addEventListener("alchemy:link",this),this.addEventListener("alchemy:unlink",this)}handleEvent(e){switch(e.type){case"alchemy:link":this.setLink(e.detail);break;case"alchemy:unlink":this.removeLink()}e.stopPropagation()}setLink(e){this.linkUrlField.value=e.url,this.linkUrlField.dispatchEvent(new Event("change")),this.linkTitleField.value=e.title,this.linkClassField.value=e.type,this.linkTargetField.value=e.target,this.unlinkButton.linked=!0,this.setElementDirty()}removeLink(){this.linkUrlField.value="",this.linkUrlField.dispatchEvent(new Event("change")),this.linkTitleField.value="",this.linkClassField.value="",this.linkTargetField.value="",this.linkButton.classList.remove("linked"),this.unlinkButton.linked=!1,this.setElementDirty()}setElementDirty(){this.elementEditor.setDirty(this)}get linkButton(){return this.querySelector('[is="alchemy-link-button"]')}get unlinkButton(){return this.querySelector('[is="alchemy-unlink-button"]')}get ingredientEditor(){const e=this.dataset.ingredientId;return this.parentElement.closest(`[data-ingredient-id='${e}']`)}get elementEditor(){return this.closest("alchemy-element-editor")}get linkUrlField(){return this.ingredientEditor.querySelector("[data-link-value]")}get linkTitleField(){return this.ingredientEditor.querySelector("[data-link-title]")}get linkTargetField(){return this.ingredientEditor.querySelector("[data-link-target]")}get linkClassField(){return this.ingredientEditor.querySelector("[data-link-class]")}}customElements.define("alchemy-link-buttons",be);function Ee(e){let t=0===e?0:Math.floor(Math.log(e)/Math.log(1024));return t>3&&(t=3),(e/Math.pow(1024,t)).toFixed(2)+" "+["B","kB","MB","GB"][t]}customElements.define("alchemy-node-select",class extends D{_searchQuery(e,t){return{filter:{name_or_page_name_cont:e,...JSON.parse(this.queryParams)},page:t}}_renderResult(e){return this._renderListEntry(e)}_renderListEntry(e,t){const s=e.ancestors.map((e=>e.name)),i='<alchemy-icon name="arrow-right-s"></alchemy-icon>';return`\n <div class="node-select--node">\n <alchemy-icon name="menu-2"></alchemy-icon>\n <div class="node-select--node-display_name">\n <span class="node-select--node-ancestors">\n ${s.length>0?s.join(i)+i:""}\n </span>\n <span class="node-select--node-name">\n ${this._hightlightTerm(e.name,t)}\n </span>\n </div>\n <div class="node-select--node-url">\n ${e.url||""}\n </div>\n </div>\n `}});class we extends H{constructor(){super(),this.file=null,this.request=null,this.progressEventLoaded=0,this.progressEventTotal=0,this.className="in-progress",this.valid=!0,this.value=0}initialize(e,t){this.file=e,this.request=t,this.progressEventTotal=e?e.size:0,this._validateFile(),this._addRequestEventListener()}render(){return`\n <sl-progress-bar value="${this.value}"></sl-progress-bar>\n <div class="description">\n <span class="file-name">${this.file?.name}</span>\n <span class="loaded-size">${this.loadedSize}</span>\n <span class="error-message">${this.errorMessage}</span>\n </div>\n <sl-tooltip content="${d("Abort upload")}">\n <button class="icon_button" aria-label="${d("Abort upload")}">\n <alchemy-icon name="close"></alchemy-icon>\n </button>\n </sl-tooltip>\n `}afterRender(){if(this.querySelector("button").addEventListener("click",(()=>this.cancel())),this.file?.type.includes("image")){const e=new FileReader;e.readAsDataURL(this.file),e.addEventListener("load",(()=>{const t=new Image;t.src=e.result,this.prepend(t)}))}}cancel(){this.finished||(this.status="canceled",this.request?.abort(),this.dispatchCustomEvent("FileUpload.Change"))}_validateFile(){const e=Alchemy.uploader_defaults,t=e.file_size_limit*Math.pow(1024,2);let s;this.file?.size>t&&(s=d("Uploaded bytes exceed file size"));const i=this.file?.type.includes("image")?e.allowed_filetypes.alchemy_pictures:e.allowed_filetypes.alchemy_attachments;i.includes("*")||i.includes(this.file?.type.replace(/^\w+\/(\w+)(\+\w+)?/i,"$1"))||(s=d("File type not allowed")),s&&(this.valid=!1,this.errorMessage=s)}_addRequestEventListener(){this.request&&(this.request.upload.onprogress=e=>{this.progressEvent=e},this.request.onload=()=>{this.request.status<400?(this.status="successful",F(this.responseMessage)):(this.status="failed",this.errorMessage=this.responseMessage),this.dispatchCustomEvent("FileUpload.Change")},this.request.onerror=()=>{this.errorMessage=d("An error occurred during the transaction")})}get active(){return this.valid&&"canceled"!==this.status}get errorMessage(){return this._errorMessage||""}set errorMessage(e){this._errorMessage=e;const t=this.querySelector(".error-message");t&&(t.textContent=e),F(e,"error")}get finished(){return["canceled","successful","failed"].includes(this.status)}get loadedSize(){return`${Ee(this.progressEventLoaded)} / ${Ee(this.progressEventTotal)}`}get progressElement(){return this.querySelector("sl-progress-bar")}set progressEvent(e){this.progressEventLoaded=e.loaded,this.progressEventTotal=e.total,this.value=Math.round(e.loaded/e.total*100),this.querySelector(".loaded-size").textContent=this.loadedSize}get responseMessage(){try{return JSON.parse(this.request.responseText).message}catch(e){return`${this.request.status}: ${this.request.statusText}`}}get status(){return this._status}set status(e){this._status=e,this.className=e,this.progressElement?.toggleAttribute("indeterminate","upload-finished"===e)}get valid(){return this._valid}set valid(e){this._valid=e,this.classList.toggle("invalid",!e)}get value(){return this._value}set value(e){this._value=e,this.progressElement&&(this.progressElement.value=e),100===e&&(this.status="upload-finished"),this.dispatchCustomEvent("FileUpload.Change")}}customElements.define("alchemy-file-upload",we);class _e extends H{#v=!1;constructor(){super(),this.buttonLabel=d("Cancel all uploads"),this.fileUploads=[],this.fileCount=0,this.className="in-progress",this.visible=!0,this.handleFileChange=()=>this._updateView()}initialize(e=[]){this.fileUploads=e,this.fileCount=e.length}afterRender(){this.actionButton=this.querySelector("button"),this.actionButton.addEventListener("click",(()=>{this.finished?this.onComplete(this.status):this.cancel()})),this.fileUploads.forEach((e=>{this.querySelector(".single-uploads").append(e)}))}cancel(){this._activeUploads().forEach((e=>{e.cancel()})),this._setupCloseButton()}connected(){this._updateView(),this.addEventListener("Alchemy.FileUpload.Change",this.handleFileChange)}disconnected(){this.removeEventListener("Alchemy.FileUpload.Change",this.handleFileChange)}onComplete(e){}render(){return`\n <sl-progress-bar value="0"></sl-progress-bar>\n <div class="overall-progress-value">\n <span class="value-text"></span>\n\n <sl-tooltip content="${this.buttonLabel}">\n <button class="icon_button" aria-label="${this.buttonLabel}">\n <alchemy-icon name="close"></alchemy-icon>\n </button>\n </sl-tooltip>\n </div>\n <div class="single-uploads" style="--progress-columns: ${this.fileCount>3?3:this.fileCount}"></div>\n <div class="overall-upload-value value-text"></div>\n `}_activeUploads(){return this.fileUploads.filter((e=>e.active))}_setupCloseButton(){this.buttonLabel=d("Close"),this.actionButton.ariaLabel=this.buttonLabel,this.actionButton.parentElement.content=this.buttonLabel}_sumFileProgresses(e){return this._activeUploads().reduce(((t,s)=>s[e]+t),0)}_updateView(){const e=this.status;this.className=e,this.progressElement.value=this.totalProgress,this.progressElement.toggleAttribute("indeterminate","upload-finished"===e),this.querySelector(".overall-progress-value > span").textContent=this.overallProgressValue,this.querySelector(".overall-upload-value").textContent=this.overallUploadSize,this.finished?(this._setupCloseButton(),this.onComplete(e)):this.visible=!0}get finished(){return this._activeUploads().every((e=>e.finished))}get overallUploadSize(){this._activeUploads().filter((e=>e.value>=100)).length;return this.totalProgress,this._activeUploads().length,`${Ee(this._sumFileProgresses("progressEventLoaded"))} / ${Ee(this._sumFileProgresses("progressEventTotal"))}`}get overallProgressValue(){const e=this._activeUploads().filter((e=>e.value>=100)).length;return`${this.totalProgress}% (${e} / ${this._activeUploads().length})`}get progressElement(){return this.querySelector("sl-progress-bar")}get status(){const e=this._activeUploads().map((e=>e.className));return e.includes("failed")?"failed":0===e.length?"canceled":e.every((t=>t===e[0]))?e[0]:"in-progress"}get totalProgress(){const e=this._activeUploads().reduce(((e,t)=>e+t.file.size),0);let t=Math.ceil(this._activeUploads().reduce(((t,s)=>{const i=s.file.size/e;return s.value*i+t}),0));return t>100&&(t=100),t}get visible(){return this.#v}set visible(e){this.classList.toggle("visible",e),this.#v=e}}customElements.define("alchemy-upload-progress",_e);customElements.define("alchemy-uploader",class extends H{static properties={dropzone:{default:!1}};connected(){this.fileInput.addEventListener("change",(e=>{this._uploadFiles(Array.from(e.target.files))})),this.dropzone&&this._dragAndDropBehavior(),this.addEventListener("Alchemy.upload.successful",this)}handleEvent(e){if("Alchemy.upload.successful"===e.type)this._handleUploadComplete()}_handleUploadComplete(){setTimeout((()=>{const e=this.redirectUrl,t=this.closest("turbo-frame");this.uploadProgress.visible=!1,e&&(t?(t.setAttribute("src",e),t.reload()):Turbo.visit(e))}),750)}_dragAndDropBehavior(){const e=document.querySelector(this.dropzone);let t=!1;const s=s=>{t!==s&&(t=s,e.classList.toggle("dragover"))};e.addEventListener("dragleave",(()=>s(!1))),e.addEventListener("drop",(async e=>{e.preventDefault(),s(!1);const t=[...e.dataTransfer.items].map((e=>e.getAsFile()));this._uploadFiles(t)})),e.addEventListener("dragover",(e=>{e.preventDefault(),s(!0)}))}_uploadFiles(e){let t=0;const s=e.map((e=>{const s=new XMLHttpRequest,i=new we;return i.initialize(e,s),Alchemy.uploader_defaults.upload_limit-1<t?(i.valid=!1,i.errorMessage=d("Maximum number of files exceeded")):i.valid&&(t++,this._submitFile(s,e)),i}));this._createProgress(s)}_submitFile(e,t){const s=this.querySelector("form"),i=new FormData(s);i.set(this.fileInput.name,t),e.open("POST",s.action),e.setRequestHeader("X-CSRF-Token",K()),e.setRequestHeader("X-Requested-With","XMLHttpRequest"),e.setRequestHeader("Accept","application/json"),e.send(i)}_createProgress(e){this.uploadProgress&&(this.uploadProgress.cancel(),document.body.removeChild(this.uploadProgress)),this.uploadProgress=new _e,this.uploadProgress.initialize(e),this.uploadProgress.onComplete=e=>{this.dispatchCustomEvent(`upload.${e}`)},document.body.append(this.uploadProgress)}get fileInput(){return this.querySelector("input[type='file']")}get redirectUrl(){return this.getAttribute("redirect-url")}});customElements.define("alchemy-overlay",class extends H{render(){return`\n <alchemy-spinner></alchemy-spinner>\n <div id="overlay_text_box">\n <span id="overlay_text">${this.getAttribute("text")}</span>\n </div>\n `}set show(e){this.classList.toggle("visible",e)}});const ke="BUTTON";class Le extends HTMLElement{connectedCallback(){this.pageId=this.getAttribute("page-id"),this.folded=this.hasAttribute("folded"),this.folderButton?.addEventListener("click",this)}disconnectedCallback(){this.folderButton?.removeEventListener("click",this)}async handleEvent(e){"click"===e.type&&await this.handleFolderClick(e)}async handleFolderClick(e){e.preventDefault(),e.stopPropagation();const t=e.currentTarget;t.innerHTML="";const s=new y("small");s.spin(t);try{await Z(Alchemy.routes.fold_admin_page_path(this.pageId),null,"text/vnd.turbo-stream.html"),this.folded=!this.folded,this.toggleAttribute("folded",this.folded),this.toggleChildren(),this.updateFolderIcon()}catch(e){F(e.message||e,"error"),this.updateFolderIcon()}finally{s.stop()}}toggleChildren(){const e=this.querySelector(`#page_${this.pageId}_children`);e&&e.classList.toggle("hidden",this.folded)}updateFolderIcon(){if(this.folderButton){const e=this.folded?"arrow-right-s":"arrow-down-s";this.folderButton.innerHTML=`<alchemy-icon name="${e}"></alchemy-icon>`}}updateFolderButton(){const e=this.querySelector(".page_folder");if(!e)return;const t=this.hasChildren||this.folded;if(t&&"SPAN"===e.tagName){const t=this.folded?"arrow-right-s":"arrow-down-s";e.outerHTML=`<button class="page_folder icon_button">\n <alchemy-icon name="${t}"></alchemy-icon>\n </button>`,this.folderButton?.addEventListener("click",this)}else t||e.tagName!==ke?t&&e.tagName===ke&&this.updateFolderIcon():e.outerHTML='<span class="page_folder"></span>'}get hasChildren(){const e=this.querySelector(`#page_${this.pageId}_children`);return!!e&&e.querySelectorAll(":scope > alchemy-page-node").length>0}get folderButton(){return this.querySelector("button.page_folder")}}customElements.define("alchemy-page-node",Le);class Se extends HTMLElement{connectedCallback(){const e=this.querySelector("alchemy-datepicker:has(#page_public_on)"),t=this.querySelector("alchemy-datepicker:has(#page_public_until)"),s=this.querySelector(".page-publication-date-fields"),i=this.querySelector("#page_public");i&&i.addEventListener("click",(function(i){const n=i.target,r=new Date;n.checked?(s.classList.remove("hidden"),e.flatpickr.setDate(r)):(s.classList.add("hidden"),e.flatpickr.clear()),t.flatpickr?.clear()}))}}customElements.define("alchemy-page-publication-fields",Se);customElements.define("alchemy-page-select",class extends D{get pageId(){return this.selection?JSON.parse(this.selection).id:void 0}_searchQuery(e,t){return{q:{name_cont:e,...JSON.parse(this.queryParams)},page:t}}_parseResponse(e){const t=e.meta;return{results:e.pages,more:t.page*t.per_page<t.total_count}}_renderResult(e){return e.text||e.name}_renderListEntry(e,t){return`\n <div class="page-select--page">\n <div class="page-select--top">\n <alchemy-icon name="file-3"></alchemy-icon>\n <span class="page-select--page-name">${this._hightlightTerm(e.name,t)}</span>\n <span class="page-select--site-name">${e.site.name}</span>\n </div>\n <div class="page-select--bottom">\n <span class="page-select--page-urlname">${e.url_path}</span>\n <span class="page-select--language-code">${e.language_code}</span>\n </div>\n </div>\n `}});class Ce extends HTMLElement{constructor(){super(),this.addEventListener("change",this)}handleEvent(e){if("change"===e.type)this.onChange()}onChange(){const e=new URL(this.getAttribute("url")),t=this.querySelector("select");e.searchParams.set("language_id",t.value),Turbo.visit(e,{frame:"picture_descriptions"})}}customElements.define("alchemy-picture-description-select",Ce);class xe extends HTMLElement{constructor(){super(),this.cropFromField=this.querySelector("[data-crop-from]"),this.cropSizeField=this.querySelector("[data-crop-size]"),this.pictureIdField=this.querySelector("[data-picture-id]"),this.targetSizeField=this.querySelector("[data-target-size]"),this.imageCropperField=this.querySelector("[data-image-cropper]"),this.image=this.querySelector("img"),this.pictureThumbnail=this.querySelector("alchemy-picture-thumbnail"),this.deleteButton=this.querySelector(".picture_tool.delete"),this.cropLink=this.querySelector(".crop_link"),this.targetSize=this.targetSizeField.dataset.targetSize,this.pictureId=this.pictureIdField.value,this.update=function(e,t){let s;return function(...i){const n=this;clearTimeout(s),s=setTimeout((()=>e.apply(n,i)),t)}}((()=>{this.updateImage(),this.updateCropLink()}),125),this.deleteButton?.addEventListener("click",this.removeImage.bind(this))}connectedCallback(){this.observer=new MutationObserver(this.mutationCallback.bind(this)),this.observer.observe(this.cropFromField,{attributes:!0}),this.observer.observe(this.cropSizeField,{attributes:!0}),this.observer.observe(this.pictureIdField,{attributes:!0})}disconnectedCallback(){this.observer.disconnect()}mutationCallback(e){for(const t of e)"pictureId"in t.target.dataset&&(this.cropFromField.value="",this.cropSizeField.value="",this.pictureId=t.target.value),this.update()}updateImage(){this.pictureId&&(this.pictureThumbnail.loading=!0,G(Alchemy.routes.url_admin_picture_path(this.pictureId),{crop:this.imageCropperEnabled,crop_from:this.cropFrom,crop_size:this.cropSize,flatten:!0,size:"160x120"}).then((({data:e})=>{this.pictureThumbnail.src=e.url,this.pictureThumbnail.image.alt=e.alt,this.pictureThumbnail.image.title=e.title,this.setElementDirty()})).catch((e=>{console.error(e.message||e),F(e.message||e,"error")})))}removeImage(){this.pictureThumbnail.innerHTML='<alchemy-icon name="image" size="xl"></alchemy-icon>',this.pictureIdField.value="",this.image=null,this.cropLink.classList.add("disabled"),this.setElementDirty()}setElementDirty(){this.closest(".element-editor").setDirty(this)}updateCropLink(){this.pictureId&&this.imageCropperEnabled&&(this.cropLink.classList.remove("disabled"),this.cropLink.href.match(/(picture_id=)\d+/)?this.cropLink.href=this.cropLink.href.replace(/(picture_id=)\d+/,"$1"+this.pictureId):this.cropLink.href=this.cropLink.href+`&picture_id=${this.pictureId}`)}get cropFrom(){return""===this.cropFromField.value?this.defaultCropFrom.join("x"):this.cropFromField.value}get cropSize(){return""===this.cropSizeField.value?this.defaultCropSize.join("x"):this.cropSizeField.value}get defaultCropSize(){if(!this.imageCropperEnabled)return[];const e=this.targetSize.split("x").map((e=>parseInt(e))),t=(s=e[0]/this.imageFileWidth,i=e[1]/this.imageFileHeight,s>=i?s:i);var s,i;return[Math.round(e[0]/t),Math.round(e[1]/t)]}get defaultCropFrom(){if(!this.imageCropperEnabled)return[];const e=this.defaultCropSize;return[Math.round((this.imageFileWidth-e[0])/2),Math.round((this.imageFileHeight-e[1])/2)]}get imageFileWidth(){return parseInt(this.pictureIdField.dataset.imageFileWidth)}get imageFileHeight(){return parseInt(this.pictureIdField.dataset.imageFileHeight)}get imageCropperEnabled(){return"true"===this.targetSizeField.dataset.imageCropper}}customElements.define("alchemy-picture-editor",xe);class Te extends HTMLElement{constructor(){super(),this.classList.add("thumbnail_background"),this.spinner=new y("small"),this.src&&this.start()}handleEvent(e){switch(e.type){case"load":this.#C();break;case"error":this.#x(e)}}connectedCallback(){this.#T()}disconnectedCallback(){this.image?.removeEventListener("load",this),this.image?.removeEventListener("error",this),this.stop()}createImage(e=this.src,t=this.name){this.image=new Image,this.image.src=e,t&&(this.image.alt=t)}start(e){this.createImage(e),this.image.addEventListener("load",this),this.image.addEventListener("error",this),this.load()}load(){this.image?.complete||(this.setAttribute("loading","loading"),this.innerHTML="",this.spinner.spin(this))}stop(){this.classList.remove("loading"),this.spinner.stop()}#C(){this.spinner.stop(),this.removeAttribute("loading")}#x(e){const t=`Could not load ${this.image.src}`,s=this.closest(".ingredient-editor");this.spinner.stop(),this.innerHTML=`\n <sl-tooltip content="${t}" ${s?"hoist":""}>\n <alchemy-icon name="alert" class="error"></alchemy-icon>\n </sl-tooltip>\n `,console.error(t,e)}#T(){this.image?.complete?this.replaceChildren(this.image):this.image&&this.append(this.image)}set loading(e){e?this.load():this.stop()}set src(e){this.start(e),this.#T()}get name(){return this.getAttribute("name")}get src(){return this.getAttribute("src")}}customElements.define("alchemy-picture-thumbnail",Te);class Ae extends HTMLElement{constructor(){super(),this.addEventListener("submit",this)}connectedCallback(){document.addEventListener("alchemy:page-dirty",this)}disconnectedCallback(){document.removeEventListener("alchemy:page-dirty",this)}handleEvent(e){switch(e.type){case"alchemy:page-dirty":this.markDirty(e.detail);break;case"submit":this.button.loading=!0}}markDirty(e){this.button.variant="primary",this.button.disabled=!1,this.tooltip.content=e.tooltip}get button(){return this.querySelector("sl-button")}get tooltip(){return this.querySelector("sl-tooltip")}}customElements.define("alchemy-publish-page-button",Ae);class $e extends HTMLSelectElement{#A;connectedCallback(){this.classList.add("alchemy_selectbox"),this.#A=$(this).select2({minimumResultsForSearch:5,dropdownAutoWidth:!0,allowClear:!!this.allowClear}),this.allowClear||this.multiple||this.#A.prev(".select2-container").find(".select2-search-choice-close").remove()}enable(){this.removeAttribute("disabled"),this.#$()}disable(){this.setAttribute("disabled","disabled"),this.#$()}setOptions(e,t=void 0){let s=this.value;this.innerHTML="",t&&this.add(new Option(t,"")),e.forEach((e=>{this.add(new Option(e.text,e.id,!1,e.id===s))})),this.#$()}#$(){this.#A.trigger("change")}get allowClear(){return this.dataset.hasOwnProperty("allowClear")||this.multiple}}customElements.define("alchemy-select",$e,{extends:"select"});class Fe extends HTMLElement{connectedCallback(){this.searchInput=document.querySelector(".search_input_field"),this.clearButton=document.querySelector("#search_field_clear"),this.resultCounter=document.querySelector("#page_filter_result"),this.setupSearch(),requestAnimationFrame((()=>{this.setupSortables()})),this.observer=new MutationObserver((e=>{e.forEach((e=>{e.addedNodes.forEach((e=>{e.nodeType===Node.ELEMENT_NODE&&(e.classList?.contains("children")&&this.setupSortable(e),e.querySelectorAll(".children").forEach((e=>this.setupSortable(e))))}))}))})),this.observer.observe(this,{childList:!0,subtree:!0})}disconnectedCallback(){this.teardownSearch(),this.observer?.disconnect()}setupSearch(){this.searchInput?.addEventListener("input",this),this.clearButton?.addEventListener("click",this)}teardownSearch(){this.searchInput?.removeEventListener("input",this),this.clearButton?.removeEventListener("click",this)}handleEvent(e){"input"===e.type&&e.target===this.searchInput?this.handleSearch(e):"click"===e.type&&e.target===this.clearButton&&this.handleClearSearch(e)}handleSearch(e){const t=e.target.value.toLowerCase().trim();""!==t?this.filterPages(t):this.clearFilter()}filterPages(e){const t=this.querySelectorAll(".sitemap_page");let s=0,i=null;t.forEach((t=>{(t.getAttribute("name")||"").toLowerCase().includes(e)?(t.classList.add("highlight"),t.classList.remove("no-match"),s++,i||(i=t)):(t.classList.remove("highlight"),t.classList.add("no-match"))})),1===s?(this.resultCounter.textContent=`1 ${d("page_found")}`,this.resultCounter.style.display="block"):s>1?(this.resultCounter.textContent=`${s} ${d("pages_found")}`,this.resultCounter.style.display="block"):this.resultCounter.style.display="none",i&&i.scrollIntoView({behavior:"smooth",block:"center"})}clearFilter(){this.querySelectorAll(".sitemap_page").forEach((e=>{e.classList.remove("highlight","no-match")})),this.resultCounter.style.display="none"}handleClearSearch(e){e.preventDefault(),this.searchInput.value="",this.clearFilter()}setupSortable(e){new i(e,{group:"pages",animation:150,fallbackOnBody:!0,swapThreshold:.65,handle:".page-icon.handle",draggable:"alchemy-page-node",onEnd:e=>this.handleSort(e)})}setupSortables(){this.querySelectorAll(".children").forEach((e=>this.setupSortable(e)))}async handleSort(e){if(e.from===e.to&&e.oldIndex===e.newIndex)return;const t=e.item,s=t.pageId,i=Alchemy.routes.move_admin_page_path(s),n={target_parent_id:e.to.dataset.parentId,new_position:e.newIndex};S(!0);try{const r=await Z(i,n),l=await r.data,o=t.querySelector(`#page_${s}`);if(o){const e=o.querySelector(".sitemap_url");e&&l.url_path&&(e.textContent=l.url_path)}this.updateFolderIcons(e.from,e.to),F(d("Successfully moved page"))}catch(e){F(e.message||e,"error"),window.location.reload()}finally{S(!1)}}updateFolderIcons(e,t){const s=e.closest("alchemy-page-node");if(s?.updateFolderButton(),e!==t){const e=t.closest("alchemy-page-node");e?.updateFolderButton()}}}customElements.define("alchemy-sitemap",Fe);const qe={draggable:".element-editor",handle:".element-handle.draggable",ghostClass:"dragged",animation:150,swapThreshold:.65,easing:"cubic-bezier(1, 0, 0, 1)"};function Ie(e){const t=e.item.dataset.elementName;document.querySelectorAll(`[data-droppable-elements~="${t}"]`).forEach((e=>e.classList.add("droppable-elements")))}function Be(e){const t=e.item,s=e.to.parentElement.closest(".element-editor"),i={element_id:t.dataset.elementId,position:e.newIndex+1};s&&(i.parent_element_id=s.dataset.elementId),e.target===e.to&&ee(Alchemy.routes.order_admin_elements_path,i).then((e=>{const s=e.data;F(s.message),s.pageHasUnpublishedChanges&&re(s),B(),t.updateTitle(s.preview_text)}))}function Me(){document.querySelectorAll("[data-droppable-elements]").forEach((e=>e.classList.remove("droppable-elements")))}class ze extends HTMLElement{connectedCallback(){const e={name:this.dataset.elementName,put:(e,t,s)=>e.el.dataset.droppableElements.split(" ").includes(s.dataset.elementName)};new i(this,{...qe,onStart:Ie,onSort:Be,onEnd:Me,group:e})}}customElements.define("alchemy-sortable-elements",ze);customElements.define("alchemy-spinner",class extends H{static properties={size:{default:"medium"},color:{default:"currentColor"}};render(){return this.className=`spinner spinner--${this.size}`,`\n <svg width="100%" viewBox="0 0 28 28" style="--spinner-color: ${this.color}">\n <path\n class="hex1"\n d="M5.938,18.07l-5.878-5.9l2.154-8.058l8.024-2.161l5.87,5.9l-2.144,8.058L5.938,18.07z"\n />\n <path\n class="hex2"\n d="M19.686,20.785l-4.731-4.754l1.725-6.487l6.468-1.742l4.733,4.754l-1.734,6.487L19.686,20.785z"\n />\n <path\n class="hex3"\n d="M11.708,26.294l-3.47-3.485l1.276-4.758l4.74-1.276l3.468,3.485l-1.265,4.758L11.708,26.294z"\n />\n </svg>\n `}});class He extends HTMLElement{async connectedCallback(){await h(),this.classList.add("autocomplete_tag_list"),$(this.input).select2(this.select2Config)}get input(){return this.getElementsByTagName("input")[0]}get select2Config(){return{tags:!0,tokenSeparators:[","],openOnEnter:!1,minimumInputLength:1,createSearchChoice:this.#F,ajax:{url:this.getAttribute("url"),dataType:"json",data:e=>({term:e}),results:e=>({results:e})},initSelection:this.#q}}#F(e,t){if(0===$(t).filter((function(){return 0===this.text.localeCompare(e)})).length)return{id:e,text:e}}#q(e,t){const s=[];$(e.val().split(",")).each((function(){s.push({id:this.trim(),text:this})})),t(s)}}customElements.define("alchemy-tags-autocomplete",He);const Pe="alchemy-dark",De="alchemy";customElements.define("alchemy-tinymce",class extends H{#I=null;connected(){this.className="tinymce_container";const e={root:document.getElementById("element_area"),rootMargin:"0px",threshold:[.05]};this.tinymceIntersectionObserver=new IntersectionObserver(((e,t)=>{e.forEach((e=>{e.intersectionRatio>0&&(this._initTinymceEditor(),t.unobserve(e.target))}))}),e),this.tinymceIntersectionObserver.observe(this),this._setupThemeChangeListener()}disconnected(){null!==this.tinymceIntersectionObserver&&this.tinymceIntersectionObserver.disconnect(),this._removeThemeChangeListener(),tinymce.get(this.editorId)?.remove(this.editorId)}render(){return`\n ${this.initialContent}\n <alchemy-spinner size="small"></alchemy-spinner>\n `}afterRender(){this.style.minHeight=`${this.minHeight}px`,this.editor.style.display="none"}_initTinymceEditor(){tinymce.init(this.configuration).then((e=>{e.forEach((e=>this._setupEditor(e)))}))}_setupEditor(e){e.show();const t=this.getElementsByTagName("alchemy-spinner")[0];t&&t.remove(),this.elementEditor&&(e.on("dirty",(e=>{this.elementEditor.setDirty(e.target.editorContainer)})),e.on("click",(()=>this.elementEditor.onClickElement(!1))))}_setupThemeChangeListener(){this.darkModeMediaQuery=window.matchMedia("(prefers-color-scheme: dark)"),this.themeChangeHandler=e=>this._handleThemeChange(e),this.darkModeMediaQuery.addEventListener("change",this.themeChangeHandler)}_removeThemeChangeListener(){this.darkModeMediaQuery&&this.themeChangeHandler&&this.darkModeMediaQuery.removeEventListener("change",this.themeChangeHandler)}_handleThemeChange(e){const t=tinymce.get(this.editorId);if(t){const s=e.matches?Pe:De,i=e.matches?Pe:De;t.remove(),tinymce.init({content_css:i,...this.configuration,skin:s}).then((e=>{e.forEach((e=>this._setupEditor(e)))}))}}get configuration(){const e={};this.getAttributeNames().forEach((t=>{if(!["class","id","is","name","style"].includes(t)){const s=this.getAttribute(t),i=t.replaceAll("-","_");if(s===t||""===s)e[i]=!0;else try{e[i]=JSON.parse(s)}catch(t){e[i]=s}}}));const t={content_css:this.preferredTheme,...Alchemy.TinymceDefaults,...e,language:c(),selector:`#${this.editorId}`,skin:this.preferredTheme};return t.height=t.min_height,t}get preferredTheme(){return window.matchMedia("(prefers-color-scheme: dark)").matches?Pe:De}get editorId(){return this.editor.id}get editor(){return this.getElementsByTagName("textarea")[0]}get elementEditor(){return document.getElementById(this.editorId).closest("alchemy-element-editor")}get minHeight(){return this.#I||this.configuration.min_height}set minHeight(e){this.#I=e}});class Ne extends HTMLElement{async connectedCallback(){const e=new y("small");e.spin(this);try{const e=await fetch(this.url,{credentials:"include"}),t=await e.json();e.ok?this.showStatus(t):this.showError(e)}catch(e){this.showError(e)}finally{e.stop()}}get url(){return this.getAttribute("url")}showStatus(e){"true"==e.status?this.querySelector(".update_available").classList.remove("hidden"):this.querySelector(".up_to_date").classList.remove("hidden")}showError(e){this.querySelector(".error").classList.remove("hidden"),console.error("[alchemy] Error fetching update status",e)}}var Oe;customElements.define("alchemy-update-check",Ne),Oe=Handlebars.template,(Handlebars.templates=Handlebars.templates||{})["node_folder.hbs"]=Oe({0:function(e,t,s,i,n){return"right"},1:function(e,t,s,i,n){return"down"},compiler:[8,">= 4.3.0"],main:function(e,t,s,i,n){var r,l=e.lambda,o=e.escapeExpression,a=e.lookupProperty||function(e,t){if(Object.prototype.hasOwnProperty.call(e,t))return e[t]};return'<a class="node_folder" data-record-id="'+o(l(null!=(r=null!=t?a(t,"node"):t)?a(r,"id"):r,t))+'" data-record-type="'+o(l(null!=(r=null!=t?a(t,"node"):t)?a(r,"type"):r,t))+'">\n <alchemy-icon name="arrow-'+(null!=(r=a(s,"if").call(null!=t?t:e.nullContext||{},null!=(r=null!=t?a(t,"node"):t)?a(r,"folded"):r,{name:"if",hash:{},fn:e.program(0,n,0),inverse:e.program(1,n,0),data:n,loc:{start:{line:2,column:28},end:{line:2,column:72}}}))?r:"")+'-s"></alchemy-icon>\n</a>\n'},useData:!0}),n("tooltip.show",{keyframes:[{transform:"translateY(10px)",opacity:"0"},{transform:"translateY(0)",opacity:"1"}],options:{duration:100}}),n("tooltip.hide",{keyframes:[{transform:"translateY(0)",opacity:"1"},{transform:"translateY(10px)",opacity:"0"}],options:{duration:100}}),n("dialog.show",{keyframes:[{transform:"scale(0.98)",opacity:"0"},{transform:"scale(1)",opacity:"1"}],options:{duration:150}}),n("dialog.hide",{keyframes:[{transform:"scale(1)",opacity:"1"},{transform:"scale(0.98)",opacity:"0"}],options:{duration:150}});const Re=document.querySelector('link[rel="preload"][as="image"]').getAttribute("href"),Ue={"x-lg":"close",caret:"arrow-down-s"},je={resolver:e=>`${Re}#ri-${Ue[e]||e}-line`,mutator:e=>{e.setAttribute("fill","currentColor"),e.setAttribute("viewBox","0 0 24 24")},spriteSheet:!0};function We(e,t,s,i){document.querySelectorAll(t).forEach((t=>{t.addEventListener(e,(e=>{const n=Array.from(t.querySelectorAll(s));let r=e.target;for(;r!==t;){if(n.includes(r))return void i.call(r,e);r=r.parentElement}}))}))}r("default",je),r("system",je);class Je{#B=!1;#M=null;#z=null;#H=null;constructor(e,t){this.image=e,this.defaultBox=t.default_box,this.aspectRatio=t.ratio,this.#z=document.getElementById(t.crop_from_form_field_id),this.#H=document.getElementById(t.crop_size_form_field_id),this.elementId=t.element_id,this.dialog=Alchemy.currentDialog(),this.dialog&&(this.dialog.options.closed=()=>this.destroy(),this.bind()),this.init()}get cropperOptions(){return{aspectRatio:this.aspectRatio,viewMode:1,zoomable:!1,checkCrossOrigin:!1,checkOrientation:!1,data:this.box,cropend:()=>{const e=this.#M.getData(!0);this.update(e)}}}get cropFrom(){if(this.#z?.value)return this.#z.value.split("x").map((e=>parseInt(e)))}get cropSize(){if(this.#H?.value)return this.#H.value.split("x").map((e=>parseInt(e)))}get box(){return this.cropFrom&&this.cropSize?{x:this.cropFrom[0],y:this.cropFrom[1],width:this.cropSize[0],height:this.cropSize[1]}:this.defaultBoxSize}get defaultBoxSize(){return{x:this.defaultBox[0],y:this.defaultBox[1],width:this.defaultBox[2],height:this.defaultBox[3]}}init(){this.#B||(this.#M=new l(this.image,this.cropperOptions),this.#B=!0)}update(e){this.#z.value=`${e.x}x${e.y}`,this.#z.dispatchEvent(new Event("change")),this.#H.value=`${e.width}x${e.height}`,this.#H.dispatchEvent(new Event("change"))}reset(){this.#M.setData(this.defaultBoxSize),this.update(this.defaultBoxSize)}destroy(){return this.#M&&this.#M.destroy(),this.#B=!1,!0}bind(){this.dialog.dialog_body.find('button[type="submit"]').on("click",(()=>(document.querySelector(`[data-element-id='${this.elementId}']`).setDirty(),this.dialog.close(),!1))),this.dialog.dialog_body.find('button[type="reset"]').on("click",(()=>(this.reset(),!1)))}}class Ve extends b{constructor(e,t={}){super(e,t)}init(){$(".zoomed-picture-background").on("click",(e=>{if(e.stopPropagation(),"IMG"!==e.target.nodeName)return this.close(),!1})),$(".picture-overlay-handle").on("click",(e=>(this.dialog.toggleClass("hide-form"),!1))),this.$previous=$(".previous-picture"),this.$next=$(".next-picture"),this.#P(),super.init()}previous(){null!=this.$previous[0]&&this.$previous[0].click()}next(){null!=this.$next[0]&&this.$next[0].click()}build(){this.dialog_container=$('<div class="alchemy-image-overlay-container" />'),this.dialog=$('<div class="alchemy-image-overlay-dialog" />'),this.dialog_body=$('<div class="alchemy-image-overlay-body" />'),this.close_button=$('<a class="alchemy-image-overlay-close">\n <alchemy-icon name="close" size="xl"></alchemy-icon>\n </a>'),this.dialog.append(this.close_button),this.dialog.append(this.dialog_body),this.dialog_container.append(this.dialog),this.overlay=$('<div class="alchemy-image-overlay" />'),this.$body.append(this.overlay),this.$body.append(this.dialog_container)}#P(){this.$document.keydown((e=>{if("INPUT"===e.target.nodeName||"TEXTAREA"===e.target.nodeName)return!0;switch(e.which){case 37:return this.previous(),!1;case 39:return this.next(),!1;default:return!0}}))}}function Xe(){return document.querySelectorAll("#picture_archive input:checked")}function Qe(){const e=document.querySelector("#select_all_pictures"),t=document.querySelector(".selected_item_tools");We("click",".toolbar_buttons","a#select_all_pictures",(s=>{s.preventDefault(),e.classList.toggle("active");const i=e.classList.contains("active");!function(e){document.querySelectorAll(".picture_tool.select input[type='checkbox']").forEach((t=>{t.checked=e,t.closest(".picture_thumbnail").classList.toggle("active",e)}))}(i),t.classList.toggle("hidden",!i)})),We("change",".picture_tool.select","input",(e=>{t.classList.toggle("hidden",0===Xe().length);const s=e.target.parentElement.classList,i=e.target.checked;s.toggle("visible",i)})),We("click",".selected_item_tools","a#edit_multiple_pictures",(e=>{e.preventDefault();_(function(e){const t=new URL(e);return Xe().forEach((e=>t.searchParams.append(e.name,e.value))),t.toString()}(e.target.href),{title:e.target.title,size:"400x295"})}))}function Ye(){document.querySelectorAll("li.menu-item").forEach((e=>{const t=e.querySelector(".nodes_tree-left_images"),s=e.querySelector(".children"),i={folded:"true"===e.dataset.folded,id:e.dataset.id,type:e.dataset.type};s.children.length>0||i.folded?t.innerHTML=Handlebars.templates["node_folder.hbs"]({node:i}):t.innerHTML=" "}))}function Ke(e){Z(Alchemy.routes[e.item.dataset.type].move_api_path(e.item.dataset.id),{target_parent_id:e.to.dataset.recordId,new_position:e.newIndex}).then((()=>{F(Alchemy.t("Successfully moved menu item")),Ye()})).catch((e=>{F(e.message||e,"error")}))}function Ge(){We("click",".nodes_tree",".node_folder",(function(){const e=this.dataset.recordId,t=this.closest("li.menu-item"),s=Alchemy.routes[this.dataset.recordType].toggle_folded_api_path(e),i=t.querySelector(".children");Z(s).then((()=>{i.classList.toggle("folded"),t.dataset.folded="true"==t.dataset.folded?"false":"true",Ye()})).catch((e=>{F(e.message||e)}))})),Ye(),document.querySelectorAll(".nodes_tree ul.children").forEach((e=>{new i(e,{group:"nodes",animation:150,fallbackOnBody:!0,swapThreshold:.65,handle:".node_name",invertSwap:!0,onEnd:Ke})}))}void 0===window.Alchemy&&(window.Alchemy={}),Object.assign(Alchemy,{closeCurrentDialog:w,currentDialog:E,...x,t:d,FixedElements:A,growl:F,LinkDialog:class extends b{#D;constructor(e){const t=new URL(Alchemy.routes.link_admin_pages_path,window.location),s={url:e.url,selected_tab:e.type,link_title:e.title,link_target:e.target};Object.keys(s).forEach((e=>{s[e]&&t.searchParams.set(e,s[e])})),super(t.href,{size:"600x320",title:d("Link")})}replace(e){super.replace(e),this.#c()}open(){return super.open(),new Promise((e=>this.#D=e))}#c(){const e=document.querySelector('[data-link-form-type="internal"]'),t=document.querySelector('[data-link-form-type="file"] alchemy-attachment-select');e.addEventListener("Alchemy.RemoteSelect.Change",(e=>{this.#N(e.detail.added)})),t.addEventListener("Alchemy.RemoteSelect.Change",(e=>{const t=e.detail.added;document.getElementById("file_link").value=t?t.url:""})),document.querySelectorAll("[data-link-form-type]").forEach((e=>{e.addEventListener("submit",(e=>{e.preventDefault(),this.#O(e.target.dataset.linkFormType)}))}))}#N(e=null){const t=document.getElementById("internal_link"),s=document.querySelector('[data-link-form-type="internal"] alchemy-dom-id-api-select');t.value=e?e.url_path:"",s.page=e?e.id:void 0}#O(e){const t=document.getElementById("element_anchor");let s=document.getElementById(`${e}_link`).value;if("internal"===e&&""!==t.value)s=s.replace(q,"")+t.value;else if("external"===e&&!s.match(Alchemy.link_url_regexp))return void this.#R();this.#D({url:s.trim(),title:document.getElementById(`${e}_link_title`).value,target:document.getElementById(`${e}_link_target`)?.value,type:e}),this.close()}#R(){const e=document.getElementById("errors");e.querySelector("ul").innerHTML=`<li>${Alchemy.t("url_validation_failed")}</li>`,e.style.display="block"}},pleaseWaitOverlay:S,Spinner:y,reloadPreview:B}),t.start(),e.config.forms.confirm=L,document.addEventListener("turbo:load",(function(){document.documentElement.classList.remove("no-js"),p(),document.querySelectorAll(".please_wait").forEach((e=>{e.addEventListener("click",S)})),document.querySelectorAll("a.button").forEach((e=>{e.setAttribute("tabindex",0)})),key.filter=function(e){let t=(e.target||e.srcElement).tagName;return key.isPressed("esc")||!("INPUT"===t||"SELECT"===t||"TEXTAREA"===t)}}));export{Je as ImageCropper,Ve as ImageOverlay,Ge as NodeTree,D as RemoteSelect,We as on,Qe as pictureSelector};
|
|
3
4
|
=======
|
|
4
5
|
import"handlebars";import"jquery";import"@ungap/custom-elements";import{Turbo as e}from"@hotwired/turbo-rails";import"select2";import t from"@rails/ujs";import"keymaster";import"clipboard";import s from"flatpickr";import i from"sortablejs";import"tinymce";import{setDefaultAnimation as n,registerIconLibrary as l}from"shoelace";import o from"cropperjs";const r=/\./;function a(e){const t=c(),s=Alchemy.translations;return s?r.test(e)?function(e,t){const s=t.split(r),i=e[s[0]];return i&&i[s[1]]||t}(s,e):s[e]||e:(console.warn(`Translations for locale ${t} not found!`),e)}function c(){return document.documentElement.lang?document.documentElement.lang:"en"}function h(e,t=void 0){let s=a(e);return t?s.replace(/%\{.+\}/,t):s}async function d(){const e=c();"en"!==e&&(await import(`select2/${e}.js`),$.extend($.fn.select2.defaults,$.fn.select2.locales[e]))}const u=[];function m(e){return!(!$(e.target).is("input, textarea")&&"?"===String.fromCharCode(e.which))||(k("/admin/help",{title:Alchemy.t("help"),size:"400x492"}),!1)}function p(e=document){e instanceof jQuery&&(e=e[0]),e===document&&(document.removeEventListener("keypress",m),document.addEventListener("keypress",m),u.forEach((e=>key.unbind(e))));const t=e.querySelectorAll(".search_input_field"),s=e.querySelectorAll(".search_field_clear, .js_filter_field_clear");key("alt+f",(function(){return key.setScope("search"),t.forEach((e=>e.focus({focusVisible:!0}))),!1})),u.push("alt+f"),key("esc","search",(function(){s.forEach((e=>e.click())),t.forEach((e=>e.blur()))})),u.push("esc"),e.querySelectorAll("[data-alchemy-hotkey]").forEach((function(e){const t=e.dataset.alchemyHotkey;key(t,(()=>e.click())),u.push(t)}))}function g(e){const t=document.createElement("template");return t.innerHTML=e,t.content.children[0]}let y=class{constructor(e,t="currentColor"){this.size=e,this.color=t,this.spinner=void 0}get el(){return this.spinner}spin(e){return void 0===e&&(e=document.body),this.spinner=g(`<alchemy-spinner size="${this.size}" color="${this.color}"></alchemy-spinner>`),e.append(this.spinner),this}stop(){this.spinner&&(this.spinner.remove(),this.spinner=void 0)}};const v=[],b={header_height:36,size:"400x300",padding:!0,title:"",modal:!0,overflow:"visible",ready:()=>{},closed:()=>{}};class f{constructor(e,t={}){this.url=e,this.options={...b,...t},this.$document=$(document),this.$window=$(window),this.$body=$("body");const s=this.options.size.split("x");this.width=parseInt(s[0],10),this.height=parseInt(s[1],10),this.build(),this.resize()}open(){this.dialog.trigger("Alchemy.DialogOpen"),this.bind_close_events(),window.requestAnimationFrame((()=>{if(this.dialog_container.addClass("open"),null!=this.overlay)return this.overlay.addClass("open")})),this.$body.addClass("prevent-scrolling"),v.push(this),this.load()}close(){return this.dialog.trigger("DialogClose.Alchemy"),this.$document.off("keydown"),this.dialog_container.removeClass("open"),null!=this.overlay&&this.overlay.removeClass("open"),this.$document.on("webkitTransitionEnd transitionend oTransitionEnd",(()=>{if(this.$document.off("webkitTransitionEnd transitionend oTransitionEnd"),this.dialog_container.remove(),null!=this.overlay&&this.overlay.remove(),this.$body.removeClass("prevent-scrolling"),v.pop(this),null!=this.options.closed)return this.options.closed()})),!0}load(){this.show_spinner(),$.get(this.url,(e=>{this.replace(e)})).fail((e=>{this.show_error(e)}))}reload(){this.dialog_body.empty(),this.load()}replace(e){this.remove_spinner(),this.dialog_body.hide(),this.dialog_body.html(e),this.init(),this.dialog[0].dispatchEvent(new CustomEvent("DialogReady.Alchemy",{bubbles:!0,detail:{body:this.dialog_body[0]}})),null!=this.options.ready&&this.options.ready(this.dialog_body),this.dialog_body.show()}show_spinner(){this.spinner=new y("medium"),this.spinner.spin(this.dialog_body[0])}remove_spinner(){this.spinner.stop()}init(){p(this.dialog_body),this.watch_remote_forms()}watch_remote_forms(){const e=$('[data-remote="true"]',this.dialog_body);e.on("ajax:success",(e=>{const t=e.detail[2];t.getResponseHeader("Content-Type").match(/javascript/)||(this.dialog_body.html(t.responseText),this.init())})),e.on("ajax:error",(e=>{const t=e.detail[1],s=e.detail[2];this.show_error(s,t)}))}show_error(e,t){if(422===e.status)return this.dialog_body.html(e.responseText),void this.init();const{error_body:s,error_header:i,error_type:n}=this.error_messages(e,t),l=$(`<alchemy-message type="${n}">\n <h1>${i}</h1>\n <p>${s}</p>\n </alchemy-message>`);this.dialog_body.html(l)}error_messages(e,t){let s,i,n="warning";switch(e.status){case 0:i="The server does not respond.",s="Please check server and try again.";break;case 403:i="You are not authorized!",s="Please close this window.";break;default:n="error",t?(i=t,console.error(e.responseText)):i=`${e.statusText} (${e.status})`,s="Please check log and try again."}return{error_header:i,error_body:s,error_type:n}}bind_close_events(){this.close_button.on("click",(()=>{this.close()})),this.dialog_container.addClass("closable").on("click",(e=>e.target!==this.dialog_container.get(0)||(this.close(),!1))),this.$document.keydown((e=>27!==e.which||(this.close(),!1)))}build(){this.dialog_container=$('<div class="alchemy-dialog-container" />'),this.dialog=$('<div class="alchemy-dialog" />'),this.dialog_body=$('<div class="alchemy-dialog-body" />'),this.dialog_header=$('<div class="alchemy-dialog-header" />'),this.dialog_title=$('<div class="alchemy-dialog-title" />'),this.close_button=$('<button class="alchemy-dialog-close"><alchemy-icon name="close"></alchemy-icon></button>'),this.dialog_title.text(this.options.title),this.dialog_header.append(this.dialog_title),this.dialog_header.append(this.close_button),this.dialog.append(this.dialog_header),this.dialog.append(this.dialog_body),this.dialog_container.append(this.dialog),this.options.modal&&this.dialog.addClass("modal"),this.options.padding&&this.dialog_body.addClass("padded"),this.options.modal&&(this.overlay=$('<div class="alchemy-dialog-overlay" />'),this.$body.append(this.overlay)),this.$body.append(this.dialog_container)}resize(){const{width:e,height:t}=this.getSize();this.dialog.css({width:e,"min-height":t,overflow:this.options.overflow}),"hidden"===this.options.overflow?this.dialog_body.css({height:t,overflow:"auto"}):this.dialog_body.css({"min-height":t,overflow:"visible"})}getSize(){const e=this.options.padding?16:0,t=this.$window.width(),s=this.$window.height();let i=this.width,n=this.height;return i>=t&&(i=t-e),n>=s&&(n=s-e-b.header_height),{width:i,height:n}}}function E(){const{length:e}=v;if(0!==e)return v[e-1]}function w(e){const t=E();if(null!=t)return t.options.closed=e,t.close()}function k(e,t){if(!e)throw"No url given! Please provide an url.";new f(e,t).open()}class L{constructor(e,t={}){this.message=e,this.options={...{size:"300x100",title:h("Please confirm"),ok_label:h("Yes"),cancel_label:h("No"),on_ok(){}},...t},this.#e(),this.#t()}open(){requestAnimationFrame((()=>{this.dialog.show()}))}#e(){const e=this.options.size.split("x")[0];this.dialog=g(`\n <sl-dialog label="${this.options.title}" style="--width: ${e}px">\n ${this.message}\n <button slot="footer" type="reset" class="secondary mx-1 my-0" autofocus>\n ${this.options.cancel_label}\n </button>\n <button slot="footer" type="submit" class="mx-1 my-0">\n ${this.options.ok_label}\n </button>\n </sl-dialog>\n `),document.body.append(this.dialog)}#t(){this.cancelButton.addEventListener("click",(e=>{e.preventDefault(),this.options.on_cancel(),this.dialog.hide()})),this.okButton.addEventListener("click",(e=>{e.preventDefault(),this.options.on_ok(),this.dialog.hide()})),this.dialog.addEventListener("sl-request-close",(e=>{"overlay"===e.detail.source&&(this.options.on_cancel(),e.preventDefault())})),this.dialog.addEventListener("sl-after-hide",(()=>{this.dialog.remove()}))}get cancelButton(){return this.dialog.querySelector("button[type=reset]")}get okButton(){return this.dialog.querySelector("button[type=submit]")}}function _(e,t={}){return new Promise((s=>{new L(e,{...t,on_ok(){s(!0)},on_cancel(){s(!1)}}).open()}))}function C(e=!0){document.querySelector("alchemy-overlay").show=!!e}function S(e){let t=()=>{};$(e).is("form")?t=function(){const t=$(`<form action="${e.action}" method="POST" style="display: none" />`);t.append($(e).find("input")),t.appendTo("body"),C(),t.trigger("submit")}:$(e).is("a")&&(t=()=>Turbo.visit(e.pathname));return!(document.querySelectorAll("alchemy-element-editor.dirty").length>0)||(_(h("page_dirty_notice"),{title:h("warning"),ok_label:h("ok"),cancel_label:h("cancel")}).then((e=>{e&&(window.onbeforeunload=void 0,t())})),!1)}var x={checkPageDirtyness:S,PageLeaveObserver:function(){document.querySelectorAll("#main_navi a").forEach((e=>{e.addEventListener("click",(e=>{S(e.currentTarget)||e.preventDefault()}))}))}};function T(e){const t=document.getElementById("fixed-elements"),s=`fixed-element-${e}`;t.querySelector(`sl-tab[panel="${s}"]`).remove(),t.querySelector(`sl-tab-panel[name="${s}"]`).remove(),t.show("main-content-elements")}var A=Object.freeze({__proto__:null,createTab:function(e,t){const s=document.getElementById("fixed-elements"),i=`fixed-element-${e}`,n=`<sl-tab slot="nav" panel="${i}">${t}</sl-tab>`,l=`<sl-tab-panel name="${i}" style="--padding: 0" />`;s.innerHTML+=n+l,window.requestAnimationFrame((function(){s.show(i)}))},removeTab:T});function F(e,t="notice"){!function(e,t){const s=document.getElementById("flash_notices"),i=g(`\n <alchemy-message type="${t}" dismissable>\n ${e}\n </alchemy-message>\n `);s.append(i)}(e,t)}const I=/#[\w.~-]+$/;class q extends HTMLIFrameElement{#s;#i;#n;handleEvent(e){"load"===e.type&&(this.#l(),this.#o(),this.#s?.call(this,e))}#r=e=>{"Alchemy.previewReady"===e.data.message&&(this.#l(),this.#o(),this.#s?.call(this,e))};connectedCallback(){let e=this.url;this.addEventListener("load",this),this.#a(),window.addEventListener("message",this.#r),window.localStorage.getItem("alchemy-preview-url")&&(e=window.localStorage.getItem("alchemy-preview-url"),this.previewUrlSelect.value=e),this.refresh(e)}disconnectedCallback(){this.removeEventListener("load",this),key.unbind("alt+r"),window.removeEventListener("message",this.#r)}postMessage(e){this.contentWindow.postMessage(e,"*")}resize(e){this.style.width=`${e}px`}refresh(e){return this.#c(),this.src=e||this.url,this.#l(),this.#n=setTimeout((()=>{this.#o(),F(h("Preview failed to load"),"warning")}),5e3),new Promise((e=>{this.#s=e}))}set isDragged(e){this.style.transitionProperty=e?"none":null,this.style.pointerEvents=e?"none":null}#a(){this.reloadButton?.addEventListener("click",(e=>{e.preventDefault(),this.refresh()})),key("alt+r",(()=>this.refresh())),this.sizeSelect.addEventListener("change",(e=>{const t=e.target.value;""===t?this.style.width=null:this.resize(t)})),this.previewUrlSelect?.addEventListener("change",(e=>{const t=e.target.value;window.localStorage.setItem("alchemy-preview-url",t),this.refresh(t)}))}#c(){this.reloadButton.innerHTML.includes("alchemy-spinner")||(this.#i=this.reloadButton.innerHTML),this.reloadButton.innerHTML='<alchemy-spinner size="small"></alchemy-spinner>'}#o(){this.reloadButton.innerHTML=this.#i}#l(){this.#n&&(clearTimeout(this.#n),this.#n=null)}get url(){return this.getAttribute("url")}get sizeSelect(){return document.querySelector("select#preview_size")}get previewUrlSelect(){return document.querySelector("select#preview_url")}get reloadButton(){return document.querySelector("#reload_preview_button")}}function B(){document.getElementById("alchemy_preview_window").refresh()}customElements.define("alchemy-preview-window",q,{extends:"iframe"});class M{static updateIcon(e,t=!1){const s=document.querySelector(`[data-ingredient-id="${e}"]`);if(s){s.querySelector(".edit-ingredient-anchor-link alchemy-icon").setAttribute("icon-style",t?"fill":"line")}}}class z extends HTMLElement{constructor(){super(),this.actions={closeCurrentDialog:w,reloadPreview:B,removeFixedElement:T,updateAnchorIcon:M.updateIcon,hidePleaseWaitOverlay(){C(!1)}}}connectedCallback(){const e=this.actions[this.name];e?e(...this.params):console.error(`Unknown Alchemy action: ${this.name}`),this.remove()}get name(){return this.getAttribute("name")}get params(){return this.hasAttribute("params")?JSON.parse(this.getAttribute("params")):[]}}function D(e,t){return e.replace(new RegExp(t,"gi"),(e=>`<em>${e}</em>`))}customElements.define("alchemy-action",z);class H extends HTMLElement{#h=null;async connectedCallback(){await d(),this.isConnected&&(this.input.classList.add("alchemy_selectbox"),this.#h=$(this.input).select2(this.select2Config).on("select2-open",this.#d).on("change",this.#u))}disconnectedCallback(){this.#h&&(this.#h.off("select2-open",this.#d),this.#h.off("change",this.#u),this.#h.select2("destroy"),this.#h=null)}#d=e=>this.onOpen(e);#u=e=>this.onChange(e);onChange(e){e.added&&this.setAttribute("selection",JSON.stringify(e.added)),this.dispatchCustomEvent("RemoteSelect.Change",{removed:e.removed,added:e.added})}onOpen(e){setTimeout((()=>{document.querySelector("#select2-drop .select2-input").focus()}),100)}dispatchCustomEvent(e,t={}){this.dispatchEvent(new CustomEvent(`Alchemy.${e}`,{bubbles:!0,detail:t}))}get allowClear(){return this.hasAttribute("allow-clear")}get selection(){return this.getAttribute("selection")}get placeholder(){return this.getAttribute("placeholder")??""}get queryParams(){return this.getAttribute("query-params")??"{}"}get url(){return this.getAttribute("url")??""}get input(){return this.getElementsByTagName("input")[0]}get select2Config(){return{placeholder:this.placeholder,allowClear:this.allowClear,initSelection:(e,t)=>{this.selection&&t(JSON.parse(this.selection))},ajax:this.ajaxConfig,formatSelection:e=>this._renderResult(e),formatResult:(e,t,s)=>this._renderListEntry(e,s.term)}}get ajaxConfig(){return{url:this.url,datatype:"json",quietMillis:300,data:(e,t)=>this._searchQuery(e,t),results:e=>this._parseResponse(e)}}_searchQuery(e,t){return{q:{name_cont:e,...JSON.parse(this.queryParams)},page:t}}_parseResponse(e){const t=e.meta;return{results:e.data,more:t.page*t.per_page<t.total_count}}_renderResult(){throw new Error("You need to define a _renderResult function on your sub class!")}_renderListEntry(){throw new Error("You need to define a _renderListEntry function on your sub class!")}_hightlightTerm(e,t){return D(e,t)}}customElements.define("alchemy-attachment-select",class extends H{_renderResult(e){return this._renderListEntry(e)}_renderListEntry(e,t){return`\n <div class="attachment-select--attachment">\n <alchemy-icon name="${e.icon_css_class}"></alchemy-icon>\n <span class="attachment-select--attachment-name">${this._hightlightTerm(e.name,t)}</span>\n </div>\n `}});class P extends HTMLElement{connectedCallback(){$(this).on("change",this.#u)}disconnectedCallback(){$(this).off("change",this.#u)}#u=e=>{const t=new Event("submit",{bubbles:!0,cancelable:!0});return e.target.form.dispatchEvent(t),!1}}customElements.define("alchemy-auto-submit",P);class O extends HTMLButtonElement{connectedCallback(){this.form?(this.form.addEventListener("submit",this),"true"==this.form.dataset.remote&&this.form.addEventListener("ajax:complete",this),this.form.addEventListener("turbo:submit-end",this)):console.warn("No form for button found!",this)}handleEvent(e){switch(e.type){case"submit":"disabled"===this.getAttribute("disabled")?(e.preventDefault(),e.stopPropagation()):this.disable();break;case"ajax:complete":case"turbo:submit-end":this.enable()}}disable(){const e=new y("small"),t=this.getBoundingClientRect();this.dataset.initialButtonText=this.innerHTML,this.setAttribute("disabled","disabled"),this.setAttribute("tabindex","-1"),this.classList.add("disabled"),this.style.width=`${t.width}px`,this.style.height=`${t.height}px`,this.innerHTML=" ",e.spin(this)}enable(){this.classList.remove("disabled"),this.removeAttribute("disabled"),this.removeAttribute("tabindex"),this.style.width=null,this.style.height=null,this.innerHTML=this.dataset.initialButtonText}}customElements.define("alchemy-button",O,{extends:"button"});class N extends HTMLElement{connectedCallback(){this.translation=h("allowed_chars",this.maxChars),this.formField=this.getFormField(),this.formField&&(this.createDisplayElement(),this.countCharacters(),this.formField.addEventListener("keyup",this))}disconnectedCallback(){this.formField?.removeEventListener("keyup",this)}handleEvent(e){"keyup"===e.type&&this.countCharacters()}getFormField(){const e=this.querySelectorAll("input, textarea");return e.length>0?e[0]:void 0}createDisplayElement(){this.display=this.querySelector(":scope > .alchemy-char-counter"),this.display||(this.display=document.createElement("small"),this.display.className="alchemy-char-counter",this.formField.after(this.display))}countCharacters(){const e=this.formField.value.length;this.display.textContent=`${e} ${this.translation}`,this.display.classList.toggle("too-long",e>this.maxChars)}get maxChars(){return this.getAttribute("max-chars")??60}}customElements.define("alchemy-char-counter",N);class U extends HTMLElement{connectedCallback(){this.innerHTML='<alchemy-icon name="clipboard"></alchemy-icon>',this.clipboard=new ClipboardJS(this,{text:()=>this.getAttribute("content")}),this.clipboard.on("success",(()=>{F(this.getAttribute("success-text"))}))}disconnectedCallback(){this.clipboard.destroy()}}customElements.define("alchemy-clipboard-button",U);const R=e=>{const t=e.element[0],s=t.dataset.swatch||t.value;return`\n <div class="select-color-option">\n ${"custom_color"===t.value?'<alchemy-icon name="palette"></alchemy-icon>':`<span class="color-indicator" style="--color: ${s}"></span>`}\n <span>${e.text}</span>\n </div>`};class W extends HTMLElement{#h=null;connectedCallback(){this.select?(this.#m(),this.#h.on("change",this.#p)):(this.colorInput?.addEventListener("input",this),this.textInput?.addEventListener("input",this),this.#g(!0))}handleEvent(e){switch(e.target){case this.colorInput:this.textInput.value=this.colorInput.value;break;case this.textInput:this.colorInput.value=this.textInput.value}}disconnectedCallback(){this.colorInput?.removeEventListener("input",this),this.textInput?.removeEventListener("input",this),this.#h&&(this.#h.off("change",this.#p),this.#h.select2("destroy"),this.#h=null)}#p=e=>{this.#g("custom_color"===e.val)};#m(){this.select.classList.add("alchemy_selectbox");const e={minimumResultsForSearch:10,formatResult:R,formatSelection:R};this.#h=$(this.select).select2(e)}#g(e=!0){this.colorInput.disabled=!e}get colorInput(){return this.querySelector("input[type='color']")}get textInput(){return this.querySelector("input[type='text']")}get select(){return this.querySelector("select")}}customElements.define("alchemy-color-select",W);const j=c();class J extends HTMLElement{async connectedCallback(){"en"!==j&&await import(`flatpickr/${j}.js`),this.isConnected&&(this.flatpickr=s(this.inputField,this.flatpickrOptions))}disconnectedCallback(){this.flatpickr?.destroy()}get flatpickrOptions(){const e=/time/.test(this.inputType),t={locale:j.slice(0,2),altInput:!0,altFormat:h(`formats.${this.inputType}`),altInputClass:"flatpickr-input",enableTime:e,noCalendar:"time"===this.inputType,time_24hr:h("formats.time_24hr"),onValueUpdate(e,t,s){s.element.closest("alchemy-element-editor")?.setDirty(this.inputField)}};return e&&(t.dateFormat="Z"),t}get inputField(){return this.querySelector("input")}get inputType(){return this.getAttribute("input-type")||"date"}}customElements.define("alchemy-datepicker",J);class V extends HTMLAnchorElement{connectedCallback(){this.addEventListener("click",this)}disconnectedCallback(){this.removeEventListener("click",this)}handleEvent(e){this.disabled||this.openDialog(),e.preventDefault()}openDialog(){this.dialog=new f(this.getAttribute("href"),this.dialogOptions),this.dialog.open()}get dialogOptions(){return this.dataset.dialogOptions?JSON.parse(this.dataset.dialogOptions):{}}get disabled(){return this.classList.contains("disabled")}}customElements.define("alchemy-dialog-link",V,{extends:"a"});const X="application/json",Q="text/vnd.turbo-stream.html";function K(e){return"get"===e.toLowerCase()}function Y(e,t,s){const i=function(e){return{"Content-Type":"application/json; charset=utf-8",Accept:e,"X-Requested-With":"XMLHttpRequest","X-CSRF-Token":G()}}(s),n={method:e,headers:i};return t&&!K(e)&&(n.body=JSON.stringify(t)),n}function G(){return document.querySelector('meta[name="csrf-token"]').attributes.content.textContent}function Z(e,t){return se("GET",e,t)}function ee(e,t,s){return se("PATCH",e,t,s)}function te(e,t,s=X){return se("POST",e,t,s)}async function se(e,t,s,i=X){const n=await fetch(function(e,t,s){const i=new URL(window.location.origin+e);return t&&K(s)&&(i.search=new URLSearchParams(t).toString()),i.toString()}(t,s,e),Y(e,s,i)),l=n.headers.get("content-type"),o=l?.includes(X),r=l?.includes(Q);let a=null;if(o?a=await n.json():r&&(a=await n.text(),"undefined"!=typeof Turbo&&Turbo.renderStreamMessage(a)),n.ok)return{data:a,status:n.status};throw a||new Error("An error occurred during the transaction")}class ie extends HTMLElement{dataItem(e){return{id:`#${e}`,text:`#${e}`}}get selectElement(){return this.querySelector('select[is="alchemy-select"]')}}customElements.define("alchemy-dom-id-api-select",class extends ie{#y=void 0;connectedCallback(){this.page=this.getAttribute("page")}async#v(){const e=(await Z(Alchemy.routes.api_ingredients_path,{page_id:this.#y})).data.ingredients.filter((e=>e.data?.dom_id)).map((e=>this.dataItem(e.data.dom_id))),t=e.length>0?h("None"):h("No anchors found");this.selectElement.setOptions(e,t),this.selectElement.enable()}#b(){requestAnimationFrame((()=>{this.selectElement.disable(),this.selectElement.setOptions([],h("Select a page first"))}))}set page(e){this.#y=e,e?this.#v():this.#b()}}),customElements.define("alchemy-dom-id-preview-select",class extends ie{connectedCallback(){requestAnimationFrame((()=>{const e=document.getElementById("alchemy_preview_window"),t=e.contentDocument?.querySelectorAll("[id]")||[];if(t.length>0){const e=Array.from(t).map((e=>this.dataItem(e.id)));this.selectElement.setOptions(e,h("None"))}}))}});class ne extends HTMLElement{#f;connectedCallback(){this.#f=this.scheduleButton.getAttribute("variant"),this.publishButton.addEventListener("click",this),this.dropdown.addEventListener("sl-show",this),this.dropdown.addEventListener("sl-hide",this)}disconnectedCallback(){this.publishButton.removeEventListener("click",this),this.dropdown.removeEventListener("sl-show",this),this.dropdown.removeEventListener("sl-hide",this)}handleEvent(e){switch(e.type){case"click":this.publishButton.loading=!0;break;case"sl-show":this.scheduleButton.setAttribute("variant","primary");break;case"sl-hide":this.scheduleButton.setAttribute("variant",this.#f)}}get publishButton(){return this.querySelector("sl-button[type='submit']")}get dropdown(){return this.querySelector("sl-dropdown")}get scheduleButton(){return this.querySelector("sl-button[slot='trigger']")}}customElements.define("alchemy-publish-element-button",ne);class le extends HTMLElement{connectedCallback(){this.button?.addEventListener("click",this)}disconnectedCallback(){this.button?.removeEventListener("click",this)}async handleEvent(){if(await _(this.message)){const e=await se("DELETE",this.url);this.#E(e.data)}}#E(e){const t=this.closest("alchemy-element-editor");t.addEventListener("transitionend",(()=>{t.fixed&&T(t.elementId),t.remove()})),t.classList.add("dismiss"),F(e.message),e.pageHasUnpublishedChanges&&oe(e),B()}get url(){return this.getAttribute("href")}get message(){return this.getAttribute("message")}get button(){return this.querySelector("button")}}function oe(e){document.dispatchEvent(new CustomEvent("alchemy:page-dirty",{detail:{tooltip:e.publishButtonTooltip}}))}customElements.define("alchemy-delete-element-button",le);class re extends HTMLElement{#w=null;#k=null;#L=null;connectedCallback(){this.classList.contains("ui-sortable-placeholder")||(this.addEventListener("click",this),this.addEventListener("alchemy:element-update-title",this),this.addEventListener("ajax:complete",this),this.#w=this.form,this.#w&&$(this.#w).on("change",this.onChange),this.#k=this.header,this.#k?.addEventListener("dblclick",this.#_),this.#L=this.toggleButton,this.#L?.addEventListener("click",this.#C),this.hasAttribute("created")&&(this.focusElement(),this.previewWindow?.refresh().then((()=>{this.focusElementPreview()})),this.removeAttribute("created")))}disconnectedCallback(){this.removeEventListener("click",this),this.removeEventListener("alchemy:element-update-title",this),this.removeEventListener("ajax:complete",this),this.#w&&($(this.#w).off("change",this.onChange),this.#w=null),this.#k?.removeEventListener("dblclick",this.#_),this.#k=null,this.#L?.removeEventListener("click",this.#C),this.#L=null}handleEvent(e){switch(e.type){case"click":e.target.closest("alchemy-element-editor")===this&&this.onClickElement();break;case"ajax:complete":if(e.target===this.body){const t=e.detail[0];e.stopPropagation(),this.onSaveElement(t)}break;case"alchemy:element-update-title":this.hasEditors||e.target!=this.firstChild||this.setTitle(e.detail.title)}}onChange=e=>{const t=e.target;if(!t.classList.contains("nested-elements"))return this.setDirty(t),e.stopPropagation(),!1};async focusElement(){document.querySelector("#fixed-elements")&&await this.selectTabForElement(),await this.expand(),this.selectElement(!0)}focusElementPreview(){this.previewWindow?.postMessage({message:"Alchemy.focusElement",element_id:this.elementId})}onClickElement(){this.selectElement(),this.focusElementPreview()}onSaveElement(e){const t=JSON.parse(e.responseText);if(this.setClean(),422===e.status){const e=t.warning;t.ingredientsWithErrors.forEach((e=>{const t=this.querySelector(`[data-ingredient-id="${e.id}"]`),s=g(`<small class="error">${e.errorMessage}</small>`);t?.appendChild(s),t?.classList.add("validation_failed")})),F(e,"warn"),this.elementErrors.classList.remove("hidden")}else F(t.notice),this.previewWindow?.refresh().then((()=>{this.focusElementPreview()})),this.updateTitle(t.previewText),t.ingredientAnchors.forEach((e=>{M.updateIcon(e.ingredientId,e.active)})),t.pageHasUnpublishedChanges&&oe(t)}scrollToElement(){setTimeout((()=>{this.scrollIntoView({behavior:"smooth"})}),50)}selectElement(e=!1){document.querySelectorAll("alchemy-element-editor.selected").forEach((e=>{e.classList.remove("selected")})),window.requestAnimationFrame((()=>{this.classList.add("selected")})),e&&this.scrollToElement()}selectTabForElement(){return new Promise(((e,t)=>{const s=document.querySelector("#fixed-elements"),i=this.closest("sl-tab-panel");s&&i?(s.show(i.getAttribute("name")),e()):t(new Error("No tabs present"))}))}setClean(){this.dirty=!1,window.onbeforeunload=null,this.elementErrors.classList.add("hidden"),this.hasEditors&&this.body.querySelectorAll(".ingredient-editor").forEach((e=>{e.classList.remove("dirty","validation_failed"),e.querySelectorAll("small.error").forEach((e=>e.remove()))}))}setDirty(e){this.hasEditors&&(this.dirty=!0,window.onbeforeunload||(window.onbeforeunload=e=>e.preventDefault()),e?.closest(".ingredient-editor")?.classList.add("dirty"))}setTitle(e){this.querySelector(".element-header .preview_text_quote").textContent=e}async toggle(){this.collapsed?await this.expand():await this.collapse()}collapse(){if(this.collapsed||this.compact||this.fixed)return Promise.resolve("Element is already collapsed.");const e=new Alchemy.Spinner("small");return e.spin(this.toggleButton),this.toggleIcon?.classList?.add("hidden"),te(Alchemy.routes.collapse_admin_element_path(this.elementId)).then((e=>{const t=e.data;if(this.collapsed=!0,this.toggleButton?.setAttribute("title",t.title),t.nestedElementIds.length){const e=t.nestedElementIds.map((e=>`#element_${e}`)).join(", ");this.querySelectorAll(e).forEach((e=>{e.collapsed=!0,e.toggleButton?.setAttribute("title",t.title)}))}})).catch((e=>{F(e.message,"error"),console.error(e)})).finally((()=>{this.toggleIcon?.classList?.remove("hidden"),e.stop()}))}expand(){if(this.expanded&&!this.compact)return Promise.resolve("Element is already expanded.");if(this.compact&&this.parentElementEditor)return this.parentElementEditor.expand();{const e=new Alchemy.Spinner("small");return e.spin(this.toggleButton),this.toggleIcon?.classList.add("hidden"),new Promise(((t,s)=>{te(Alchemy.routes.expand_admin_element_path(this.elementId)).then((e=>{const s=e.data;if(s.parentElementIds.length){const e=s.parentElementIds.map((e=>`#element_${e}`)).join(", ");document.querySelectorAll(e).forEach((e=>{e.collapsed=!1,e.toggleButton?.setAttribute("title",s.title)}))}this.collapsed=!1,this.toggleButton?.setAttribute("title",s.title),t()})).catch((e=>{F(e.message,"error"),console.error(e),s(e)})).finally((()=>{this.toggleIcon?.classList?.remove("hidden"),e.stop()}))}))}}updateTitle(e){this.setTitle(e),this.dispatchEvent(new CustomEvent("alchemy:element-update-title",{bubbles:!0,detail:{title:e}}))}set published(e){e?this.classList.remove("element-hidden"):this.classList.add("element-hidden")}get published(){return!this.classList.contains("hidden")}get compact(){return null!==this.getAttribute("compact")}get fixed(){return null!==this.getAttribute("fixed")}set collapsed(e){this.classList.toggle("folded",e),this.classList.toggle("expanded",!e),this.toggleIcon&&(this.toggleIcon.name=e?"arrow-left-s":"arrow-down-s")}get collapsed(){return this.classList.contains("folded")}get expanded(){return!this.collapsed}set dirty(e){this.classList.toggle("dirty",e)}get dirty(){return this.classList.contains("dirty")}get header(){return this.querySelector(".element-header")}get body(){return this.querySelector(this.bodySelector)}get bodySelector(){return`#${this.id} > .element-body`}get footer(){return this.querySelector(`#${this.id} > .element-footer`)}get toggleButton(){return this.querySelector(".element-toggle")}get toggleIcon(){return this.toggleButton?.querySelector("alchemy-icon")}get elementErrors(){return this.body.querySelector(".element_errors")}get elementId(){return this.dataset.elementId}get elementName(){return this.dataset.elementName}get hasEditors(){return!!this.body?.querySelector(".element-ingredient-editors")}get hasChildren(){return!!this.querySelector(".nested-elements")}get firstChild(){return this.querySelector("alchemy-element-editor")}get form(){return this.querySelector("form.element-body")}get parentElementEditor(){return this.parentElement?.closest("alchemy-element-editor")}get previewWindow(){return document.getElementById("alchemy_preview_window")}#_=()=>{this.toggle()};#C=e=>{e.target.closest("alchemy-element-editor")===this&&this.toggle()}}customElements.define("alchemy-element-editor",re);const ae=e=>`\n <div class="element-select-name">\n ${e.icon}<span>${e.text}</span>\n </div>\n `;class ce extends HTMLElement{#h=null;connectedCallback(){const e=this.options,t={minimumResultsForSearch:3,dropdownAutoWidth:!0,data:()=>({results:e}),formatResult:(e,t,s)=>{let i;return""===e.id?e.text:(i=""!==s.term?D(e.text,s.term):e.text,((e,t,s)=>{const i=s?`<div class="element-select-description">${s}</div>`:"";return`\n <div class="element-select-item">\n ${ae({icon:e,text:t})}\n ${i}\n </div>\n `})(e.icon,i,e.hint))},formatSelection:ae,placeholder:this.placeholder};this.#h=$(this.inputField).select2(t)}disconnectedCallback(){this.#h?.select2("destroy"),this.#h=null}get options(){return JSON.parse(this.getAttribute("options"))}get placeholder(){return this.getAttribute("placeholder")}get inputField(){return this.querySelector("input")}}customElements.define("alchemy-element-select",ce);class he extends HTMLElement{#S=!0;#x=null;connectedCallback(){this.toggleButton?.addEventListener("click",this.#C),this.collapseButton?.addEventListener("click",this.#T),window.addEventListener("message",this.#A),document.body.addEventListener("click",this.#F),window.location.hash&&this.focusElementEditor(window.location.hash),this.resize()}disconnectedCallback(){this.toggleButton?.removeEventListener("click",this.#C),this.collapseButton?.removeEventListener("click",this.#T),window.removeEventListener("message",this.#A),document.body.removeEventListener("click",this.#F)}#C=e=>{e.preventDefault(),this.toggle()};#T=()=>{this.collapseAllElements()};#A=e=>{const t=e.data;if("Alchemy.focusElementEditor"==t?.message){const e=document.getElementById(`element_${t.element_id}`);this.show(),e?.focusElement()}};#F=e=>{e.target.closest("alchemy-element-editor")||(this.querySelectorAll("alchemy-element-editor").forEach((e=>{e.classList.remove("selected")})),this.previewWindow?.postMessage({message:"Alchemy.blurElements"}))};collapseAllElements(){this.querySelectorAll("alchemy-element-editor:not([compact]):not([fixed])").forEach((e=>e.collapse()))}toggle(){this.#S?this.hide():this.show()}show(){document.body.classList.add("elements-window-visible"),this.#S=!0,this.toggleButton.closest("sl-tooltip").content=Alchemy.t("Hide elements"),this.toggleButton.querySelector("alchemy-icon").setAttribute("name","menu-unfold"),this.resize()}hide(){document.body.classList.remove("elements-window-visible"),document.body.style.removeProperty("--elements-window-width"),this.#S=!1,this.toggleButton.closest("sl-tooltip").content=Alchemy.t("Show elements"),this.toggleButton.querySelector("alchemy-icon").setAttribute("name","menu-fold")}resize(e){void 0===e&&(e=this.widthFromCookie),e&&(document.body.style.setProperty("--elements-window-width",`${e}px`),document.cookie=`alchemy-elements-window-width=${e}; SameSite=Lax; Path=/;`)}focusElementEditor(e){const t=document.querySelector(e);t instanceof re&&t.focusElement()&&t.focusElementPreview()}get collapseButton(){return this.querySelector("#collapse-all-elements-button")}get toggleButton(){return document.querySelector("#element_window_button")}get previewWindow(){return document.getElementById("alchemy_preview_window")}get turboFrame(){return this.#x||(this.#x=this.closest("turbo-frame")),this.#x}get widthFromCookie(){return document.cookie.split("; ").find((e=>e.startsWith("alchemy-elements-window-width=")))?.split("=")[1]}set isDragged(e){this.turboFrame.style.transitionProperty=e?"none":null,this.turboFrame.style.pointerEvents=e?"none":null}}customElements.define("alchemy-elements-window",he);class de extends HTMLElement{#$=!1;#I=null;#q=null;connectedCallback(){this.addEventListener("mousedown",this),window.addEventListener("mousemove",this),window.addEventListener("mouseup",this)}disconnectedCallback(){this.removeEventListener("mousedown",this),window.removeEventListener("mousemove",this),window.removeEventListener("mouseup",this)}handleEvent(e){switch(e.type){case"mousedown":e.stopPropagation(),this.onMouseDown();break;case"mouseup":this.onMouseUp();break;case"mousemove":this.#$&&this.onDrag(e.pageX)}}onMouseDown(){this.#$=!0,this.elementsWindow.isDragged=!0,this.previewWindow.isDragged=!0,this.classList.add("is-dragged")}onMouseUp(){this.#$=!1,this.elementsWindow.isDragged=!1,this.previewWindow.isDragged=!1,this.classList.remove("is-dragged")}onDrag(e){const t=window.innerWidth-e;this.elementsWindow.resize(t)}get elementsWindow(){return this.#I||(this.#I=document.querySelector("alchemy-elements-window")),this.#I}get previewWindow(){return this.#q||(this.#q=document.getElementById("alchemy_preview_window")),this.#q}}customElements.define("alchemy-elements-window-handle",de);class ue extends HTMLElement{connectedCallback(){this.deleteLink=this.querySelector(".remove_file_link"),this.fileIcon=this.querySelector(".file_icon"),this.fileName=this.querySelector(".file_name"),this.formFieldId=this.deleteLink?.dataset.formFieldId,this.formField=this.querySelector(`#${this.formFieldId}`),this.deleteLink?.addEventListener("click",this)}disconnectedCallback(){this.deleteLink?.removeEventListener("click",this)}handleEvent(e){"click"===e.type&&this.removeFile(),e.stopPropagation()}removeFile(){this.formField.value="",this.fileIcon.innerHTML="",this.fileName.innerHTML="",this.deleteLink?.classList.add("hidden"),this.closest("alchemy-element-editor").setDirty(this.formField)}}customElements.define("alchemy-file-editor",ue);class me extends HTMLElement{#B;#M=null;#z=null;connectedCallback(){this.hotkey&&key(this.hotkey,this.#D),this.#M=this.filterField,this.#M.addEventListener("keyup",this.#H),this.#M.addEventListener("focus",this.#P),this.#z=this.clearButton,this.#z.addEventListener("click",this.#O),key("esc","list_filter",this.#N)}disconnectedCallback(){clearTimeout(this.#B),this.#M?.removeEventListener("keyup",this.#H),this.#M?.removeEventListener("focus",this.#P),this.#M=null,this.#z?.removeEventListener("click",this.#O),this.#z=null,this.hotkey&&key.unbind(this.hotkey),key.unbind("esc","list_filter")}filter(e){""===e&&(this.clearButton.style.visibility="hidden");const t=[],s=new Set,i=e.toLowerCase();this.items.forEach((e=>{const n=e.getAttribute(this.nameAttribute)?.toLowerCase();if(-1!==n.indexOf(i)){t.push(e),s.add(e);let i=e.parentElement?.closest(this.itemsSelector);for(;i;)s.add(i),i=i.parentElement?.closest(this.itemsSelector)}})),this.items.forEach((e=>{e.classList.toggle("hidden",!s.has(e))})),1===t.length&&t[0].scrollIntoView({behavior:"smooth",block:"nearest"})}clear(){this.filterField.value="",this.clearButton.style.visibility="hidden",this.items.forEach((e=>e.classList.remove("hidden")))}get nameAttribute(){return this.getAttribute("name-attribute")||"name"}get clearButton(){return this.querySelector('button[type="button"]')}get filterField(){return this.querySelector('input[type="text"]')}get items(){return document.querySelectorAll(this.itemsSelector)}get itemsSelector(){return this.getAttribute("items-selector")}get debounceTime(){return parseInt(this.getAttribute("debounce-time"))||150}get hotkey(){return this.getAttribute("hotkey")}#D=()=>(this.filterField.focus(),!1);#H=()=>{clearTimeout(this.#B),this.#B=setTimeout((()=>{const e=this.filterField.value;this.clearButton.style.visibility=e?"visible":"hidden",this.filter(e)}),this.debounceTime)};#P=()=>key.setScope("list_filter");#O=e=>{e.preventDefault(),this.clear()};#N=()=>{this.clear(),this.filterField.blur()}}customElements.define("alchemy-list-filter",me);class pe extends HTMLElement{#U=null;handleEvent(e){"click"===e.type&&this.dismiss()}connectedCallback(){if(!this.querySelector(":scope > alchemy-icon")){const e=this.dismissable&&"error"===this.type?'<alchemy-icon name="close"></alchemy-icon>':"";this.insertAdjacentHTML("afterbegin",`<alchemy-icon name="${this.iconName}"></alchemy-icon>${e}`)}(this.dismissable||"error"===this.type)&&this.addEventListener("click",this),this.dismissable&&"error"!==this.type&&(this.#U=setTimeout((()=>{this.dismiss()}),this.dismissDelay))}disconnectedCallback(){null!==this.#U&&(clearTimeout(this.#U),this.#U=null)}dismiss(){this.addEventListener("transitionend",(()=>this.remove())),this.classList.add("dismissed")}get dismissable(){return this.hasAttribute("dismissable")}get icon(){return this.getAttribute("icon")}get type(){return this.getAttribute("type")||"notice"}get dismissDelay(){return parseInt(this.noticesWrapper?.dataset.autoDismissDelay||5e3)}get iconName(){switch(this.icon||this.type){case"warning":case"warn":case"alert":return"alert";case"notice":return"check";case"info":case"hint":return"information";case"error":return"bug";default:return this.type}}get noticesWrapper(){return this.closest("#flash_notices")}}customElements.define("alchemy-message",pe);class ge extends HTMLElement{connectedCallback(){F(this.message,this.getAttribute("type")||"notice"),this.remove()}get message(){return this.getAttribute("message")||this.innerHTML}}customElements.define("alchemy-growl",ge);class ye extends HTMLElement{static get observedAttributes(){return["name","size","icon-style"]}constructor(){super(),this.spriteUrl=document.querySelector('link[rel="preload"][as="image"]').getAttribute("href")}connectedCallback(){this.render()}attributeChangedCallback(){this.render()}render(){const e=this.size?` icon--${this.size}`:"";this.innerHTML=`<svg class="icon${e}"><use href="${this.spriteUrl}#ri-${this.iconName}${this.style}" /></svg>`}set name(e){this.setAttribute("name",e)}get iconName(){return this.getAttribute("name")}get size(){return this.getAttribute("size")}get style(){const e=this.getAttribute("icon-style");switch(e){case"none":return"";case null:return"-line";default:return`-${e}`}}}customElements.define("alchemy-icon",ye);class ve extends HTMLDetailsElement{#R="Alchemy.expanded_ingredient_groups";connectedCallback(){this.addEventListener("toggle",this),this.isInLocalStorage&&(this.open=!0)}disconnectedCallback(){this.removeEventListener("toggle",this)}handleEvent(){let e=this.localStorageItem;this.open?(this.toggleIcon.name="arrow-down-s",this.isInLocalStorage||e.push(this.id)):(this.toggleIcon.name="arrow-left-s",e=e.filter((e=>e!==this.id))),localStorage.setItem(this.#R,JSON.stringify(e))}get isInLocalStorage(){return this.localStorageItem.includes(this.id)}get localStorageItem(){const e=localStorage.getItem(this.#R);if(!e)return[];try{return JSON.parse(e)}catch(e){return console.error(e),[]}}get toggleIcon(){return this.querySelector("alchemy-icon")}}customElements.define("alchemy-ingredient-group",ve,{extends:"details"});class be extends HTMLButtonElement{connectedCallback(){this.addEventListener("click",this),this.classList.add("icon_button"),this.setAttribute("type","button"),this.innerHTML='<alchemy-icon name="link" icon-style="m"></alchemy-icon>'}handleEvent(e){new Alchemy.LinkDialog({url:this.linkUrl,title:this.linkTitle,target:this.linkTarget,type:this.linkClass}).open().then((e=>this.setLink(e))),e.preventDefault()}setLink(e){""===e.url?(this.classList.remove("linked"),this.dispatchEvent(new CustomEvent("alchemy:unlink",{bubbles:!0}))):(this.classList.add("linked"),this.dispatchEvent(new CustomEvent("alchemy:link",{bubbles:!0,detail:e})))}get linkUrl(){return this.linkButtons.linkUrlField.value}get linkTitle(){return this.linkButtons.linkTitleField.value}get linkTarget(){return this.linkButtons.linkTargetField.value}get linkClass(){return this.linkButtons.linkClassField.value}get linkButtons(){return this.closest("alchemy-link-buttons")}}customElements.define("alchemy-link-button",be,{extends:"button"});class fe extends HTMLButtonElement{connectedCallback(){this.addEventListener("click",this),this.classList.add("icon_button"),this.setAttribute("type","button"),this.linked=this.linked,this.innerHTML='<alchemy-icon name="link-unlink" icon-style="m"></alchemy-icon>'}handleEvent(e){this.linked&&(this.linked=!1,this.blur(),this.dispatchEvent(new CustomEvent("alchemy:unlink",{bubbles:!0}))),e.preventDefault()}set linked(e){e?(this.classList.replace("disabled","linked"),this.removeAttribute("tabindex")):(this.classList.replace("linked","disabled"),this.setAttribute("tabindex","-1"))}get linked(){return this.classList.contains("linked")}}customElements.define("alchemy-unlink-button",fe,{extends:"button"});class Ee extends HTMLElement{connectedCallback(){this.addEventListener("alchemy:link",this),this.addEventListener("alchemy:unlink",this)}disconnectedCallback(){this.removeEventListener("alchemy:link",this),this.removeEventListener("alchemy:unlink",this)}handleEvent(e){switch(e.type){case"alchemy:link":this.setLink(e.detail);break;case"alchemy:unlink":this.removeLink()}e.stopPropagation()}setLink(e){this.linkUrlField.value=e.url,this.linkUrlField.dispatchEvent(new Event("change")),this.linkTitleField.value=e.title,this.linkClassField.value=e.type,this.linkTargetField.value=e.target,this.unlinkButton.linked=!0,this.setElementDirty()}removeLink(){this.linkUrlField.value="",this.linkUrlField.dispatchEvent(new Event("change")),this.linkTitleField.value="",this.linkClassField.value="",this.linkTargetField.value="",this.linkButton.classList.remove("linked"),this.unlinkButton.linked=!1,this.setElementDirty()}setElementDirty(){this.elementEditor.setDirty(this)}get linkButton(){return this.querySelector('[is="alchemy-link-button"]')}get unlinkButton(){return this.querySelector('[is="alchemy-unlink-button"]')}get ingredientEditor(){const e=this.dataset.ingredientId;return this.parentElement.closest(`[data-ingredient-id='${e}']`)}get elementEditor(){return this.closest("alchemy-element-editor")}get linkUrlField(){return this.ingredientEditor.querySelector("[data-link-value]")}get linkTitleField(){return this.ingredientEditor.querySelector("[data-link-title]")}get linkTargetField(){return this.ingredientEditor.querySelector("[data-link-target]")}get linkClassField(){return this.ingredientEditor.querySelector("[data-link-class]")}}customElements.define("alchemy-link-buttons",Ee);function we(e){let t=0===e?0:Math.floor(Math.log(e)/Math.log(1024));return t>3&&(t=3),(e/Math.pow(1024,t)).toFixed(2)+" "+["B","kB","MB","GB"][t]}customElements.define("alchemy-node-select",class extends H{_searchQuery(e,t){return{filter:{name_or_page_name_cont:e,...JSON.parse(this.queryParams)},page:t}}_renderResult(e){return this._renderListEntry(e)}_renderListEntry(e,t){const s=e.ancestors.map((e=>e.name)),i='<alchemy-icon name="arrow-right-s"></alchemy-icon>';return`\n <div class="node-select--node">\n <alchemy-icon name="menu-2"></alchemy-icon>\n <div class="node-select--node-display_name">\n <span class="node-select--node-ancestors">\n ${s.length>0?s.join(i)+i:""}\n </span>\n <span class="node-select--node-name">\n ${this._hightlightTerm(e.name,t)}\n </span>\n </div>\n <div class="node-select--node-url">\n ${e.url||""}\n </div>\n </div>\n `}});class ke extends HTMLElement{file=null;request=null;progressEventLoaded=0;progressEventTotal=0;#W=!0;#j=0;#J=void 0;#V="";connectedCallback(){if(this.innerHTML=`\n <sl-progress-bar value="${this.value}"></sl-progress-bar>\n <div class="description">\n <span class="file-name">${this.file?.name}</span>\n <span class="loaded-size">${this.loadedSize}</span>\n <span class="error-message">${this.errorMessage}</span>\n </div>\n <sl-tooltip content="${h("Abort upload")}">\n <button class="icon_button" aria-label="${h("Abort upload")}">\n <alchemy-icon name="close"></alchemy-icon>\n </button>\n </sl-tooltip>\n `,this.querySelector("button").addEventListener("click",(()=>this.cancel())),this.file?.type.includes("image")){const e=new FileReader;e.readAsDataURL(this.file),e.addEventListener("load",(()=>{const t=new Image;t.src=e.result,this.prepend(t)}))}}initialize(e,t){this.file=e,this.request=t,this.progressEventTotal=e?e.size:0,this.status="in-progress",this.#X(),this.#Q()}cancel(){this.finished||(this.status="canceled",this.request?.abort(),this.dispatchCustomEvent("FileUpload.Change"))}dispatchCustomEvent(e){this.dispatchEvent(new CustomEvent(`Alchemy.${e}`,{bubbles:!0}))}#X(){const e=Alchemy.uploader_defaults,t=e.file_size_limit*Math.pow(1024,2);let s;this.file?.size>t&&(s=h("Uploaded bytes exceed file size"));const i=this.file?.type.includes("image")?e.allowed_filetypes.alchemy_pictures:e.allowed_filetypes.alchemy_attachments;i.includes("*")||i.includes(this.file?.type.replace(/^\w+\/(\w+)(\+\w+)?/i,"$1"))||(s=h("File type not allowed")),s&&(this.valid=!1,this.errorMessage=s)}#Q(){this.request&&(this.request.upload.onprogress=e=>{this.progressEvent=e},this.request.onload=()=>{this.request.status<400?(this.status="successful",F(this.responseMessage)):(this.status="failed",this.errorMessage=this.responseMessage),this.dispatchCustomEvent("FileUpload.Change")},this.request.onerror=()=>{this.errorMessage=h("An error occurred during the transaction")})}get active(){return this.valid&&"canceled"!==this.status}get errorMessage(){return this.#V||""}set errorMessage(e){this.#V=e;const t=this.querySelector(".error-message");t&&(t.textContent=e),F(e,"error")}get finished(){return["canceled","successful","failed"].includes(this.status)}get loadedSize(){return`${we(this.progressEventLoaded)} / ${we(this.progressEventTotal)}`}get progressElement(){return this.querySelector("sl-progress-bar")}set progressEvent(e){this.progressEventLoaded=e.loaded,this.progressEventTotal=e.total,this.value=Math.round(e.loaded/e.total*100),this.querySelector(".loaded-size").textContent=this.loadedSize}get responseMessage(){try{return JSON.parse(this.request.responseText).message}catch(e){return`${this.request.status}: ${this.request.statusText}`}}get status(){return this.#J}set status(e){this.#J=e,this.className=e,this.progressElement?.toggleAttribute("indeterminate","upload-finished"===e)}get valid(){return this.#W}set valid(e){this.#W=e,this.classList.toggle("invalid",!e)}get value(){return this.#j}set value(e){this.#j=e,this.progressElement&&(this.progressElement.value=e),100===e&&(this.status="upload-finished"),this.dispatchCustomEvent("FileUpload.Change")}}customElements.define("alchemy-file-upload",ke);class Le extends HTMLElement{fileCount=0;#K=[];#Y=h("Cancel all uploads");#G=null;#S=!1;#Z=()=>this.#ee();connectedCallback(){var e,t;this.innerHTML=(e=this.#Y,t=this.fileCount,`\n <sl-progress-bar value="0"></sl-progress-bar>\n <div class="overall-progress-value">\n <span class="value-text"></span>\n\n <sl-tooltip content="${e}">\n <button class="icon_button" aria-label="${e}">\n <alchemy-icon name="close"></alchemy-icon>\n </button>\n </sl-tooltip>\n </div>\n <div class="single-uploads" style="--progress-columns: ${t>3?3:t}"></div>\n <div class="overall-upload-value value-text"></div>\n`),this.visible=!0,this.#G=this.querySelector("button"),this.#G.addEventListener("click",(()=>{this.finished?this.onComplete(this.status):this.cancel()})),this.#K.forEach((e=>{this.querySelector(".single-uploads").append(e)})),this.#ee(),this.addEventListener("Alchemy.FileUpload.Change",this.#Z)}disconnectedCallback(){this.removeEventListener("Alchemy.FileUpload.Change",this.#Z)}initialize(e=[]){this.#K=e,this.fileCount=e.length}cancel(){this.#te().forEach((e=>{e.cancel()})),this.#se()}onComplete(e){}#te(){return this.#K.filter((e=>e.active))}#se(){this.#Y=h("Close"),this.#G.ariaLabel=this.#Y,this.#G.parentElement.content=this.#Y}#ie(e){return this.#te().reduce(((t,s)=>s[e]+t),0)}#ee(){const e=this.status;this.className=e,this.progressElement.value=this.totalProgress,this.progressElement.toggleAttribute("indeterminate","upload-finished"===e),this.querySelector(".overall-progress-value > span").textContent=this.overallProgressValue,this.querySelector(".overall-upload-value").textContent=this.overallUploadSize,this.finished?(this.#se(),this.onComplete(e)):this.visible=!0}get finished(){return this.#te().every((e=>e.finished))}get overallUploadSize(){this.#te().filter((e=>e.value>=100)).length;return this.totalProgress,this.#te().length,`${we(this.#ie("progressEventLoaded"))} / ${we(this.#ie("progressEventTotal"))}`}get overallProgressValue(){const e=this.#te().filter((e=>e.value>=100)).length;return`${this.totalProgress}% (${e} / ${this.#te().length})`}get progressElement(){return this.querySelector("sl-progress-bar")}get status(){const e=this.#te().map((e=>e.className));return e.includes("failed")?"failed":0===e.length?"canceled":e.every((t=>t===e[0]))?e[0]:"in-progress"}get totalProgress(){const e=this.#te().reduce(((e,t)=>e+t.file.size),0);let t=Math.ceil(this.#te().reduce(((t,s)=>{const i=s.file.size/e;return s.value*i+t}),0));return t>100&&(t=100),t}get visible(){return this.#S}set visible(e){this.classList.toggle("visible",e),this.#S=e}}customElements.define("alchemy-upload-progress",Le);class _e extends HTMLElement{#ne=null;#le=!1;connectedCallback(){this.fileInput.addEventListener("change",this.#oe),this.dropzone&&this.#re(),this.addEventListener("Alchemy.upload.successful",this)}disconnectedCallback(){this.fileInput?.removeEventListener("change",this.#oe),this.#ne&&(this.#ne.removeEventListener("dragleave",this.#ae),this.#ne.removeEventListener("drop",this.#ce),this.#ne.removeEventListener("dragover",this.#he),this.#ne=null)}handleEvent(e){if("Alchemy.upload.successful"===e.type)this.#de()}#oe=e=>{this.uploadFiles(Array.from(e.target.files))};#ue=e=>{this.#le!==e&&(this.#le=e,this.#ne.classList.toggle("dragover"))};#ae=()=>this.#ue(!1);#ce=async e=>{e.preventDefault(),this.#ue(!1);const t=[...e.dataTransfer.items].map((e=>e.getAsFile()));this.uploadFiles(t)};#he=e=>{e.preventDefault(),this.#ue(!0)};#de(){setTimeout((()=>{const e=this.redirectUrl,t=this.closest("turbo-frame");this.uploadProgress.visible=!1,e&&(t?(t.setAttribute("src",e),t.reload()):Turbo.visit(e))}),750)}#re(){this.#ne=document.querySelector(this.dropzone),this.#ne&&(this.#ne.addEventListener("dragleave",this.#ae),this.#ne.addEventListener("drop",this.#ce),this.#ne.addEventListener("dragover",this.#he))}uploadFiles(e){let t=0;const s=e.map((e=>{const s=new XMLHttpRequest,i=new ke;return i.initialize(e,s),Alchemy.uploader_defaults.upload_limit-1<t?(i.valid=!1,i.errorMessage=h("Maximum number of files exceeded")):i.valid&&(t++,this.#me(s,e)),i}));this.#pe(s)}#me(e,t){const s=this.querySelector("form"),i=new FormData(s);i.set(this.fileInput.name,t),e.open("POST",s.action),e.setRequestHeader("X-CSRF-Token",G()),e.setRequestHeader("X-Requested-With","XMLHttpRequest"),e.setRequestHeader("Accept","application/json"),e.send(i)}#pe(e){this.uploadProgress&&(this.uploadProgress.cancel(),document.body.removeChild(this.uploadProgress)),this.uploadProgress=new Le,this.uploadProgress.initialize(e),this.uploadProgress.onComplete=e=>{this.dispatchEvent(new CustomEvent(`Alchemy.upload.${e}`,{bubbles:!0}))},document.body.append(this.uploadProgress)}get dropzone(){return this.getAttribute("dropzone")}get fileInput(){return this.querySelector("input[type='file']")}get redirectUrl(){return this.getAttribute("redirect-url")}}customElements.define("alchemy-uploader",_e);class Ce extends HTMLElement{connectedCallback(){this.innerHTML=`\n <alchemy-spinner></alchemy-spinner>\n <div id="overlay_text_box">\n <span id="overlay_text">${this.getAttribute("text")??""}</span>\n </div>\n `}set show(e){this.classList.toggle("visible",e)}}customElements.define("alchemy-overlay",Ce);const Se="BUTTON";class xe extends HTMLElement{connectedCallback(){this.pageId=this.getAttribute("page-id"),this.folded=this.hasAttribute("folded"),this.folderButton?.addEventListener("click",this)}disconnectedCallback(){this.folderButton?.removeEventListener("click",this)}async handleEvent(e){"click"===e.type&&await this.handleFolderClick(e)}async handleFolderClick(e){e.preventDefault(),e.stopPropagation();const t=e.currentTarget;t.innerHTML="";const s=new y("small");s.spin(t);try{await ee(Alchemy.routes.fold_admin_page_path(this.pageId),null,"text/vnd.turbo-stream.html"),this.folded=!this.folded,this.toggleAttribute("folded",this.folded),this.toggleChildren(),this.updateFolderIcon()}catch(e){F(e.message||e,"error"),this.updateFolderIcon()}finally{s.stop()}}toggleChildren(){const e=this.querySelector(`#page_${this.pageId}_children`);e&&e.classList.toggle("hidden",this.folded)}updateFolderIcon(){if(this.folderButton){const e=this.folded?"arrow-right-s":"arrow-down-s";this.folderButton.innerHTML=`<alchemy-icon name="${e}"></alchemy-icon>`}}updateFolderButton(){const e=this.querySelector(".page_folder");if(!e)return;const t=this.hasChildren||this.folded;if(t&&"SPAN"===e.tagName){const t=this.folded?"arrow-right-s":"arrow-down-s";e.outerHTML=`<button class="page_folder icon_button">\n <alchemy-icon name="${t}"></alchemy-icon>\n </button>`,this.folderButton?.addEventListener("click",this)}else t||e.tagName!==Se?t&&e.tagName===Se&&this.updateFolderIcon():e.outerHTML='<span class="page_folder"></span>'}get hasChildren(){const e=this.querySelector(`#page_${this.pageId}_children`);return!!e&&e.querySelectorAll(":scope > alchemy-page-node").length>0}get folderButton(){return this.querySelector("button.page_folder")}}customElements.define("alchemy-page-node",xe);class Te extends HTMLElement{connectedCallback(){this.publicField?.addEventListener("click",this.#ge)}disconnectedCallback(){this.publicField?.removeEventListener("click",this.#ge)}#ge=e=>{const t=e.target,s=new Date;t.checked?(this.publicationDateFields.classList.remove("hidden"),this.publicOnPicker.flatpickr.setDate(s)):(this.publicationDateFields.classList.add("hidden"),this.publicOnPicker.flatpickr.clear()),this.publicUntilPicker.flatpickr?.clear()};get publicField(){return this.querySelector("#page_public")}get publicOnPicker(){return this.querySelector("alchemy-datepicker:has(#page_public_on)")}get publicUntilPicker(){return this.querySelector("alchemy-datepicker:has(#page_public_until)")}get publicationDateFields(){return this.querySelector(".page-publication-date-fields")}}customElements.define("alchemy-page-publication-fields",Te);customElements.define("alchemy-page-select",class extends H{get pageId(){return this.selection?JSON.parse(this.selection).id:void 0}_searchQuery(e,t){return{q:{name_cont:e,...JSON.parse(this.queryParams)},page:t}}_parseResponse(e){const t=e.meta;return{results:e.pages,more:t.page*t.per_page<t.total_count}}_renderResult(e){return e.text||e.name}_renderListEntry(e,t){return`\n <div class="page-select--page">\n <div class="page-select--top">\n <alchemy-icon name="file-3"></alchemy-icon>\n <span class="page-select--page-name">${this._hightlightTerm(e.name,t)}</span>\n <span class="page-select--site-name">${e.site.name}</span>\n </div>\n <div class="page-select--bottom">\n <span class="page-select--page-urlname">${e.url_path}</span>\n <span class="page-select--language-code">${e.language_code}</span>\n </div>\n </div>\n `}});class Ae extends HTMLElement{connectedCallback(){this.addEventListener("change",this)}disconnectedCallback(){this.removeEventListener("change",this)}handleEvent(e){if("change"===e.type)this.onChange()}onChange(){const e=new URL(this.getAttribute("url")),t=this.querySelector("select");e.searchParams.set("language_id",t.value),Turbo.visit(e,{frame:"picture_descriptions"})}}customElements.define("alchemy-picture-description-select",Ae);class Fe extends HTMLElement{connectedCallback(){this.cropFromField=this.querySelector("[data-crop-from]"),this.cropSizeField=this.querySelector("[data-crop-size]"),this.pictureIdField=this.querySelector("[data-picture-id]"),this.targetSizeField=this.querySelector("[data-target-size]"),this.imageCropperField=this.querySelector("[data-image-cropper]"),this.image=this.querySelector("img"),this.pictureThumbnail=this.querySelector("alchemy-picture-thumbnail"),this.deleteButton=this.querySelector(".picture_tool.delete"),this.cropLink=this.querySelector(".crop_link"),this.targetSize=this.targetSizeField.dataset.targetSize,this.pictureId=this.pictureIdField.value,this.update=function(e,t){let s;return function(...i){const n=this;clearTimeout(s),s=setTimeout((()=>e.apply(n,i)),t)}}((()=>{this.updateImage(),this.updateCropLink()}),125),this.deleteButton?.addEventListener("click",this.removeImage),this.observer=new MutationObserver(this.mutationCallback),this.observer.observe(this.cropFromField,{attributes:!0}),this.observer.observe(this.cropSizeField,{attributes:!0}),this.observer.observe(this.pictureIdField,{attributes:!0})}disconnectedCallback(){this.observer.disconnect()}mutationCallback=e=>{for(const t of e)"pictureId"in t.target.dataset&&(this.cropFromField.value="",this.cropSizeField.value="",this.pictureId=t.target.value),this.update()};updateImage(){this.pictureId&&(this.pictureThumbnail.loading=!0,Z(Alchemy.routes.url_admin_picture_path(this.pictureId),{crop:this.imageCropperEnabled,crop_from:this.cropFrom,crop_size:this.cropSize,flatten:!0,size:"160x120"}).then((({data:e})=>{this.pictureThumbnail.src=e.url,this.pictureThumbnail.image.alt=e.alt,this.pictureThumbnail.image.title=e.title,this.setElementDirty()})).catch((e=>{console.error(e.message||e),F(e.message||e,"error")})))}removeImage=()=>{this.pictureThumbnail.innerHTML='<alchemy-icon name="image" size="xl"></alchemy-icon>',this.pictureIdField.value="",this.image=null,this.cropLink.classList.add("disabled"),this.setElementDirty()};setElementDirty(){this.closest(".element-editor").setDirty(this)}updateCropLink(){this.pictureId&&this.imageCropperEnabled&&(this.cropLink.classList.remove("disabled"),this.cropLink.href.match(/(picture_id=)\d+/)?this.cropLink.href=this.cropLink.href.replace(/(picture_id=)\d+/,"$1"+this.pictureId):this.cropLink.href=this.cropLink.href+`&picture_id=${this.pictureId}`)}get cropFrom(){return""===this.cropFromField.value?this.defaultCropFrom.join("x"):this.cropFromField.value}get cropSize(){return""===this.cropSizeField.value?this.defaultCropSize.join("x"):this.cropSizeField.value}get defaultCropSize(){if(!this.imageCropperEnabled)return[];const e=this.targetSize.split("x").map((e=>parseInt(e))),t=(s=e[0]/this.imageFileWidth,i=e[1]/this.imageFileHeight,s>=i?s:i);var s,i;return[Math.round(e[0]/t),Math.round(e[1]/t)]}get defaultCropFrom(){if(!this.imageCropperEnabled)return[];const e=this.defaultCropSize;return[Math.round((this.imageFileWidth-e[0])/2),Math.round((this.imageFileHeight-e[1])/2)]}get imageFileWidth(){return parseInt(this.pictureIdField.dataset.imageFileWidth)}get imageFileHeight(){return parseInt(this.pictureIdField.dataset.imageFileHeight)}get imageCropperEnabled(){return"true"===this.targetSizeField.dataset.imageCropper}}customElements.define("alchemy-picture-editor",Fe);class $e extends HTMLElement{constructor(){super(),this.spinner=new y("small")}handleEvent(e){switch(e.type){case"load":this.#ye();break;case"error":this.#ve(e)}}connectedCallback(){this.classList.add("thumbnail_background"),this.src&&!this.image&&this.start(),this.#be()}disconnectedCallback(){this.image?.removeEventListener("load",this),this.image?.removeEventListener("error",this),this.stop()}createImage(e=this.src,t=this.name){this.image=new Image,this.image.src=e,t&&(this.image.alt=t)}start(e){this.createImage(e),this.image.addEventListener("load",this),this.image.addEventListener("error",this),this.load()}load(){this.image?.complete||(this.setAttribute("loading","loading"),this.innerHTML="",this.spinner.spin(this))}stop(){this.classList.remove("loading"),this.spinner.stop()}#ye(){this.spinner.stop(),this.removeAttribute("loading")}#ve(e){const t=`Could not load ${this.image.src}`,s=this.closest(".ingredient-editor");this.spinner.stop(),this.innerHTML=`\n <sl-tooltip content="${t}" ${s?"hoist":""}>\n <alchemy-icon name="alert" class="error"></alchemy-icon>\n </sl-tooltip>\n `,console.error(t,e)}#be(){this.image?.complete?this.replaceChildren(this.image):this.image&&this.append(this.image)}set loading(e){e?this.load():this.stop()}set src(e){this.start(e),this.#be()}get name(){return this.getAttribute("name")}get src(){return this.getAttribute("src")}}customElements.define("alchemy-picture-thumbnail",$e);class Ie extends HTMLElement{connectedCallback(){this.addEventListener("submit",this),document.addEventListener("alchemy:page-dirty",this)}disconnectedCallback(){this.removeEventListener("submit",this),document.removeEventListener("alchemy:page-dirty",this)}handleEvent(e){switch(e.type){case"alchemy:page-dirty":this.markDirty(e.detail);break;case"submit":this.button.loading=!0}}markDirty(e){this.button.variant="primary",this.button.disabled=!1,this.tooltip.content=e.tooltip}get button(){return this.querySelector("sl-button")}get tooltip(){return this.querySelector("sl-tooltip")}}customElements.define("alchemy-publish-page-button",Ie);class qe extends HTMLSelectElement{#fe;connectedCallback(){this.classList.add("alchemy_selectbox"),this.#fe=$(this).select2({minimumResultsForSearch:5,dropdownAutoWidth:!0,allowClear:!!this.allowClear}),this.allowClear||this.multiple||this.#fe.prev(".select2-container").find(".select2-search-choice-close").remove()}disconnectedCallback(){this.#fe?.select2("destroy"),this.#fe=null}enable(){this.removeAttribute("disabled"),this.#Ee()}disable(){this.setAttribute("disabled","disabled"),this.#Ee()}setOptions(e,t=void 0){let s=this.value;this.innerHTML="",t&&this.add(new Option(t,"")),e.forEach((e=>{this.add(new Option(e.text,e.id,!1,e.id===s))})),this.#Ee()}#Ee(){this.#fe.trigger("change")}get allowClear(){return this.dataset.hasOwnProperty("allowClear")||this.multiple}}customElements.define("alchemy-select",qe,{extends:"select"});class Be extends HTMLElement{connectedCallback(){this.searchInput=document.querySelector(".search_input_field"),this.clearButton=document.querySelector("#search_field_clear"),this.resultCounter=document.querySelector("#page_filter_result"),this.setupSearch(),requestAnimationFrame((()=>{this.setupSortables()})),this.observer=new MutationObserver((e=>{e.forEach((e=>{e.addedNodes.forEach((e=>{e.nodeType===Node.ELEMENT_NODE&&(e.classList?.contains("children")&&this.setupSortable(e),e.querySelectorAll(".children").forEach((e=>this.setupSortable(e))))}))}))})),this.observer.observe(this,{childList:!0,subtree:!0})}disconnectedCallback(){this.teardownSearch(),this.observer?.disconnect()}setupSearch(){this.searchInput?.addEventListener("input",this),this.clearButton?.addEventListener("click",this)}teardownSearch(){this.searchInput?.removeEventListener("input",this),this.clearButton?.removeEventListener("click",this)}handleEvent(e){"input"===e.type&&e.target===this.searchInput?this.handleSearch(e):"click"===e.type&&e.target===this.clearButton&&this.handleClearSearch(e)}handleSearch(e){const t=e.target.value.toLowerCase().trim();""!==t?this.filterPages(t):this.clearFilter()}filterPages(e){const t=this.querySelectorAll(".sitemap_page");let s=0,i=null;t.forEach((t=>{(t.getAttribute("name")||"").toLowerCase().includes(e)?(t.classList.add("highlight"),t.classList.remove("no-match"),s++,i||(i=t)):(t.classList.remove("highlight"),t.classList.add("no-match"))})),1===s?(this.resultCounter.textContent=`1 ${h("page_found")}`,this.resultCounter.style.display="block"):s>1?(this.resultCounter.textContent=`${s} ${h("pages_found")}`,this.resultCounter.style.display="block"):this.resultCounter.style.display="none",i&&i.scrollIntoView({behavior:"smooth",block:"center"})}clearFilter(){this.querySelectorAll(".sitemap_page").forEach((e=>{e.classList.remove("highlight","no-match")})),this.resultCounter.style.display="none"}handleClearSearch(e){e.preventDefault(),this.searchInput.value="",this.clearFilter()}setupSortable(e){new i(e,{group:"pages",animation:150,fallbackOnBody:!0,swapThreshold:.65,handle:".page-icon.handle",draggable:"alchemy-page-node",onEnd:e=>this.handleSort(e)})}setupSortables(){this.querySelectorAll(".children").forEach((e=>this.setupSortable(e)))}async handleSort(e){if(e.from===e.to&&e.oldIndex===e.newIndex)return;const t=e.item,s=t.pageId,i=Alchemy.routes.move_admin_page_path(s),n={target_parent_id:e.to.dataset.parentId,new_position:e.newIndex};C(!0);try{const l=await ee(i,n),o=await l.data,r=t.querySelector(`#page_${s}`);if(r){const e=r.querySelector(".sitemap_url");e&&o.url_path&&(e.textContent=o.url_path)}this.updateFolderIcons(e.from,e.to),F(h("Successfully moved page"))}catch(e){F(e.message||e,"error"),window.location.reload()}finally{C(!1)}}updateFolderIcons(e,t){const s=e.closest("alchemy-page-node");if(s?.updateFolderButton(),e!==t){const e=t.closest("alchemy-page-node");e?.updateFolderButton()}}}customElements.define("alchemy-sitemap",Be);const Me={draggable:".element-editor",handle:".element-handle.draggable",ghostClass:"dragged",animation:150,swapThreshold:.65,easing:"cubic-bezier(1, 0, 0, 1)"};function ze(e){const t=e.item.dataset.elementName;document.querySelectorAll(`[data-droppable-elements~="${t}"]`).forEach((e=>e.classList.add("droppable-elements")))}function De(e){const t=e.item,s=e.to.parentElement.closest(".element-editor"),i={element_id:t.dataset.elementId,position:e.newIndex+1};s&&(i.parent_element_id=s.dataset.elementId),e.target===e.to&&te(Alchemy.routes.order_admin_elements_path,i).then((e=>{const s=e.data;F(s.message),s.pageHasUnpublishedChanges&&oe(s),B(),t.updateTitle(s.preview_text)}))}function He(){document.querySelectorAll("[data-droppable-elements]").forEach((e=>e.classList.remove("droppable-elements")))}class Pe extends HTMLElement{connectedCallback(){const e={name:this.dataset.elementName,put:(e,t,s)=>e.el.dataset.droppableElements.split(" ").includes(s.dataset.elementName)};new i(this,{...Me,onStart:ze,onSort:De,onEnd:He,group:e})}}customElements.define("alchemy-sortable-elements",Pe);class Oe extends HTMLElement{connectedCallback(){this.className=`spinner spinner--${this.size}`,this.innerHTML=`\n <svg width="100%" viewBox="0 0 28 28" style="--spinner-color: ${this.color}">\n <path\n class="hex1"\n d="M5.938,18.07l-5.878-5.9l2.154-8.058l8.024-2.161l5.87,5.9l-2.144,8.058L5.938,18.07z"\n />\n <path\n class="hex2"\n d="M19.686,20.785l-4.731-4.754l1.725-6.487l6.468-1.742l4.733,4.754l-1.734,6.487L19.686,20.785z"\n />\n <path\n class="hex3"\n d="M11.708,26.294l-3.47-3.485l1.276-4.758l4.74-1.276l3.468,3.485l-1.265,4.758L11.708,26.294z"\n />\n </svg>\n `}get size(){return this.getAttribute("size")||"medium"}get color(){return this.getAttribute("color")||"currentColor"}}customElements.define("alchemy-spinner",Oe);class Ne extends HTMLElement{#h=null;async connectedCallback(){await d(),this.isConnected&&(this.classList.add("autocomplete_tag_list"),this.#h=$(this.input).select2(this.select2Config))}disconnectedCallback(){this.#h?.select2("destroy"),this.#h=null}get input(){return this.getElementsByTagName("input")[0]}get select2Config(){return{tags:!0,tokenSeparators:[","],openOnEnter:!1,minimumInputLength:1,createSearchChoice:this.#we,ajax:{url:this.getAttribute("url"),dataType:"json",data:e=>({term:e}),results:e=>({results:e})},initSelection:this.#ke}}#we(e,t){if(0===$(t).filter((function(){return 0===this.text.localeCompare(e)})).length)return{id:e,text:e}}#ke(e,t){const s=[];$(e.val().split(",")).each((function(){s.push({id:this.trim(),text:this})})),t(s)}}customElements.define("alchemy-tags-autocomplete",Ne);const Ue="alchemy-dark",Re="alchemy";class We extends HTMLElement{#Le=null;connectedCallback(){this.className="tinymce_container",this.querySelector(":scope > alchemy-spinner")||this.insertAdjacentHTML("beforeend",'<alchemy-spinner size="small"></alchemy-spinner>'),this.style.minHeight=`${this.minHeight}px`,this.editor.style.display="none";const e={root:document.getElementById("element_area"),rootMargin:"0px",threshold:[.05]};this.tinymceIntersectionObserver=new IntersectionObserver(((e,t)=>{e.forEach((e=>{e.intersectionRatio>0&&(this._initTinymceEditor(),t.unobserve(e.target))}))}),e),this.tinymceIntersectionObserver.observe(this),this._setupThemeChangeListener()}disconnectedCallback(){this.tinymceIntersectionObserver?.disconnect(),this._removeThemeChangeListener(),tinymce.get(this.editorId)?.remove(this.editorId)}_initTinymceEditor(){tinymce.init(this.configuration).then((e=>{e.forEach((e=>this._setupEditor(e)))}))}_setupEditor(e){e.show();const t=this.getElementsByTagName("alchemy-spinner")[0];t&&t.remove(),this.elementEditor&&(e.on("dirty",(e=>{this.elementEditor.setDirty(e.target.editorContainer)})),e.on("click",(()=>this.elementEditor.onClickElement(!1))))}_setupThemeChangeListener(){this.darkModeMediaQuery=window.matchMedia("(prefers-color-scheme: dark)"),this.themeChangeHandler=e=>this._handleThemeChange(e),this.darkModeMediaQuery.addEventListener("change",this.themeChangeHandler)}_removeThemeChangeListener(){this.darkModeMediaQuery&&this.themeChangeHandler&&this.darkModeMediaQuery.removeEventListener("change",this.themeChangeHandler)}_handleThemeChange(e){const t=tinymce.get(this.editorId);if(t){const s=e.matches?Ue:Re,i=e.matches?Ue:Re;t.remove(),tinymce.init({content_css:i,...this.configuration,skin:s}).then((e=>{e.forEach((e=>this._setupEditor(e)))}))}}get configuration(){const e={};this.getAttributeNames().forEach((t=>{if(!["class","id","is","name","style"].includes(t)){const s=this.getAttribute(t),i=t.replaceAll("-","_");if(s===t||""===s)e[i]=!0;else try{e[i]=JSON.parse(s)}catch(t){e[i]=s}}}));const t={content_css:this.preferredTheme,...Alchemy.TinymceDefaults,...e,language:c(),selector:`#${this.editorId}`,skin:this.preferredTheme};return t.height=t.min_height,t}get preferredTheme(){return window.matchMedia("(prefers-color-scheme: dark)").matches?Ue:Re}get editorId(){return this.editor.id}get editor(){return this.getElementsByTagName("textarea")[0]}get elementEditor(){return document.getElementById(this.editorId).closest("alchemy-element-editor")}get minHeight(){return this.#Le||this.configuration.min_height}set minHeight(e){this.#Le=e}}customElements.define("alchemy-tinymce",We);class je extends HTMLElement{async connectedCallback(){const e=new y("small");e.spin(this);try{const e=await fetch(this.url,{credentials:"include"}),t=await e.json();e.ok?this.showStatus(t):this.showError(e)}catch(e){this.showError(e)}finally{e.stop()}}get url(){return this.getAttribute("url")}showStatus(e){"true"==e.status?this.querySelector(".update_available").classList.remove("hidden"):this.querySelector(".up_to_date").classList.remove("hidden")}showError(e){this.querySelector(".error").classList.remove("hidden"),console.error("[alchemy] Error fetching update status",e)}}var Je;customElements.define("alchemy-update-check",je),Je=Handlebars.template,(Handlebars.templates=Handlebars.templates||{})["node_folder.hbs"]=Je({0:function(e,t,s,i,n){return"right"},1:function(e,t,s,i,n){return"down"},compiler:[8,">= 4.3.0"],main:function(e,t,s,i,n){var l,o=e.lambda,r=e.escapeExpression,a=e.lookupProperty||function(e,t){if(Object.prototype.hasOwnProperty.call(e,t))return e[t]};return'<a class="node_folder" data-record-id="'+r(o(null!=(l=null!=t?a(t,"node"):t)?a(l,"id"):l,t))+'" data-record-type="'+r(o(null!=(l=null!=t?a(t,"node"):t)?a(l,"type"):l,t))+'">\n <alchemy-icon name="arrow-'+(null!=(l=a(s,"if").call(null!=t?t:e.nullContext||{},null!=(l=null!=t?a(t,"node"):t)?a(l,"folded"):l,{name:"if",hash:{},fn:e.program(0,n,0),inverse:e.program(1,n,0),data:n,loc:{start:{line:2,column:28},end:{line:2,column:72}}}))?l:"")+'-s"></alchemy-icon>\n</a>\n'},useData:!0}),n("tooltip.show",{keyframes:[{transform:"translateY(10px)",opacity:"0"},{transform:"translateY(0)",opacity:"1"}],options:{duration:100}}),n("tooltip.hide",{keyframes:[{transform:"translateY(0)",opacity:"1"},{transform:"translateY(10px)",opacity:"0"}],options:{duration:100}}),n("dialog.show",{keyframes:[{transform:"scale(0.98)",opacity:"0"},{transform:"scale(1)",opacity:"1"}],options:{duration:150}}),n("dialog.hide",{keyframes:[{transform:"scale(1)",opacity:"1"},{transform:"scale(0.98)",opacity:"0"}],options:{duration:150}});const Ve=document.querySelector('link[rel="preload"][as="image"]').getAttribute("href"),Xe={"x-lg":"close",caret:"arrow-down-s"},Qe={resolver:e=>`${Ve}#ri-${Xe[e]||e}-line`,mutator:e=>{e.setAttribute("fill","currentColor"),e.setAttribute("viewBox","0 0 24 24")},spriteSheet:!0};function Ke(e,t,s,i){document.querySelectorAll(t).forEach((t=>{t.addEventListener(e,(e=>{const n=Array.from(t.querySelectorAll(s));let l=e.target;for(;l!==t;){if(n.includes(l))return void i.call(l,e);l=l.parentElement}}))}))}l("default",Qe),l("system",Qe);class Ye{#_e=!1;#Ce=null;#Se=null;#xe=null;constructor(e,t){this.image=e,this.defaultBox=t.default_box,this.aspectRatio=t.ratio,this.#Se=document.getElementById(t.crop_from_form_field_id),this.#xe=document.getElementById(t.crop_size_form_field_id),this.elementId=t.element_id,this.dialog=Alchemy.currentDialog(),this.dialog&&(this.dialog.options.closed=()=>this.destroy(),this.bind()),this.init()}get cropperOptions(){return{aspectRatio:this.aspectRatio,viewMode:1,zoomable:!1,checkCrossOrigin:!1,checkOrientation:!1,data:this.box,cropend:()=>{const e=this.#Ce.getData(!0);this.update(e)}}}get cropFrom(){if(this.#Se?.value)return this.#Se.value.split("x").map((e=>parseInt(e)))}get cropSize(){if(this.#xe?.value)return this.#xe.value.split("x").map((e=>parseInt(e)))}get box(){return this.cropFrom&&this.cropSize?{x:this.cropFrom[0],y:this.cropFrom[1],width:this.cropSize[0],height:this.cropSize[1]}:this.defaultBoxSize}get defaultBoxSize(){return{x:this.defaultBox[0],y:this.defaultBox[1],width:this.defaultBox[2],height:this.defaultBox[3]}}init(){this.#_e||(this.#Ce=new o(this.image,this.cropperOptions),this.#_e=!0)}update(e){this.#Se.value=`${e.x}x${e.y}`,this.#Se.dispatchEvent(new Event("change")),this.#xe.value=`${e.width}x${e.height}`,this.#xe.dispatchEvent(new Event("change"))}reset(){this.#Ce.setData(this.defaultBoxSize),this.update(this.defaultBoxSize)}destroy(){return this.#Ce&&this.#Ce.destroy(),this.#_e=!1,!0}bind(){this.dialog.dialog_body.find('button[type="submit"]').on("click",(()=>(document.querySelector(`[data-element-id='${this.elementId}']`).setDirty(),this.dialog.close(),!1))),this.dialog.dialog_body.find('button[type="reset"]').on("click",(()=>(this.reset(),!1)))}}class Ge extends f{constructor(e,t={}){super(e,t)}init(){$(".zoomed-picture-background").on("click",(e=>{if(e.stopPropagation(),"IMG"!==e.target.nodeName)return this.close(),!1})),$(".picture-overlay-handle").on("click",(e=>(this.dialog.toggleClass("hide-form"),!1))),this.$previous=$(".previous-picture"),this.$next=$(".next-picture"),this.#Te(),super.init()}previous(){null!=this.$previous[0]&&this.$previous[0].click()}next(){null!=this.$next[0]&&this.$next[0].click()}build(){this.dialog_container=$('<div class="alchemy-image-overlay-container" />'),this.dialog=$('<div class="alchemy-image-overlay-dialog" />'),this.dialog_body=$('<div class="alchemy-image-overlay-body" />'),this.close_button=$('<a class="alchemy-image-overlay-close">\n <alchemy-icon name="close" size="xl"></alchemy-icon>\n </a>'),this.dialog.append(this.close_button),this.dialog.append(this.dialog_body),this.dialog_container.append(this.dialog),this.overlay=$('<div class="alchemy-image-overlay" />'),this.$body.append(this.overlay),this.$body.append(this.dialog_container)}#Te(){this.$document.keydown((e=>{if("INPUT"===e.target.nodeName||"TEXTAREA"===e.target.nodeName)return!0;switch(e.which){case 37:return this.previous(),!1;case 39:return this.next(),!1;default:return!0}}))}}function Ze(){return document.querySelectorAll("#picture_archive input:checked")}function et(){const e=document.querySelector("#select_all_pictures"),t=document.querySelector(".selected_item_tools");Ke("click",".toolbar_buttons","a#select_all_pictures",(s=>{s.preventDefault(),e.classList.toggle("active");const i=e.classList.contains("active");!function(e){document.querySelectorAll(".picture_tool.select input[type='checkbox']").forEach((t=>{t.checked=e,t.closest(".picture_thumbnail").classList.toggle("active",e)}))}(i),t.classList.toggle("hidden",!i)})),Ke("change",".picture_tool.select","input",(e=>{t.classList.toggle("hidden",0===Ze().length);const s=e.target.parentElement.classList,i=e.target.checked;s.toggle("visible",i)})),Ke("click",".selected_item_tools","a#edit_multiple_pictures",(e=>{e.preventDefault();k(function(e){const t=new URL(e);return Ze().forEach((e=>t.searchParams.append(e.name,e.value))),t.toString()}(e.target.href),{title:e.target.title,size:"400x295"})}))}function tt(){document.querySelectorAll("li.menu-item").forEach((e=>{const t=e.querySelector(".nodes_tree-left_images"),s=e.querySelector(".children"),i={folded:"true"===e.dataset.folded,id:e.dataset.id,type:e.dataset.type};s.children.length>0||i.folded?t.innerHTML=Handlebars.templates["node_folder.hbs"]({node:i}):t.innerHTML=" "}))}function st(e){ee(Alchemy.routes[e.item.dataset.type].move_api_path(e.item.dataset.id),{target_parent_id:e.to.dataset.recordId,new_position:e.newIndex}).then((()=>{F(Alchemy.t("Successfully moved menu item")),tt()})).catch((e=>{F(e.message||e,"error")}))}function it(){Ke("click",".nodes_tree",".node_folder",(function(){const e=this.dataset.recordId,t=this.closest("li.menu-item"),s=Alchemy.routes[this.dataset.recordType].toggle_folded_api_path(e),i=t.querySelector(".children");ee(s).then((()=>{i.classList.toggle("folded"),t.dataset.folded="true"==t.dataset.folded?"false":"true",tt()})).catch((e=>{F(e.message||e)}))})),tt(),document.querySelectorAll(".nodes_tree ul.children").forEach((e=>{new i(e,{group:"nodes",animation:150,fallbackOnBody:!0,swapThreshold:.65,handle:".node_name",invertSwap:!0,onEnd:st})}))}void 0===window.Alchemy&&(window.Alchemy={}),Object.assign(Alchemy,{closeCurrentDialog:w,currentDialog:E,...x,t:h,FixedElements:A,growl:F,LinkDialog:class extends f{#Ae;constructor(e){const t=new URL(Alchemy.routes.link_admin_pages_path,window.location),s={url:e.url,selected_tab:e.type,link_title:e.title,link_target:e.target};Object.keys(s).forEach((e=>{s[e]&&t.searchParams.set(e,s[e])})),super(t.href,{size:"600x320",title:h("Link")})}replace(e){super.replace(e),this.#a()}open(){return super.open(),new Promise((e=>this.#Ae=e))}#a(){const e=document.querySelector('[data-link-form-type="internal"]'),t=document.querySelector('[data-link-form-type="file"] alchemy-attachment-select');e.addEventListener("Alchemy.RemoteSelect.Change",(e=>{this.#Fe(e.detail.added)})),t.addEventListener("Alchemy.RemoteSelect.Change",(e=>{const t=e.detail.added;document.getElementById("file_link").value=t?t.url:""})),document.querySelectorAll("[data-link-form-type]").forEach((e=>{e.addEventListener("submit",(e=>{e.preventDefault(),this.#$e(e.target.dataset.linkFormType)}))}))}#Fe(e=null){const t=document.getElementById("internal_link"),s=document.querySelector('[data-link-form-type="internal"] alchemy-dom-id-api-select');t.value=e?e.url_path:"",s.page=e?e.id:void 0}#$e(e){const t=document.getElementById("element_anchor");let s=document.getElementById(`${e}_link`).value;if("internal"===e&&""!==t.value)s=s.replace(I,"")+t.value;else if("external"===e&&!s.match(Alchemy.link_url_regexp))return void this.#Ie();this.#Ae({url:s.trim(),title:document.getElementById(`${e}_link_title`).value,target:document.getElementById(`${e}_link_target`)?.value,type:e}),this.close()}#Ie(){const e=document.getElementById("errors");e.querySelector("ul").innerHTML=`<li>${Alchemy.t("url_validation_failed")}</li>`,e.style.display="block"}},pleaseWaitOverlay:C,Spinner:y,reloadPreview:B}),t.start(),e.config.forms.confirm=_,document.addEventListener("turbo:load",(function(){document.documentElement.classList.remove("no-js"),p(),document.querySelectorAll(".please_wait").forEach((e=>{e.addEventListener("click",C)})),document.querySelectorAll("a.button").forEach((e=>{e.setAttribute("tabindex",0)})),key.filter=function(e){let t=(e.target||e.srcElement).tagName;return key.isPressed("esc")||!("INPUT"===t||"SELECT"===t||"TEXTAREA"===t)}}));export{Ye as ImageCropper,Ge as ImageOverlay,it as NodeTree,H as RemoteSelect,Ke as on,et as pictureSelector};
|
|
5
6
|
>>>>>>> 314d20b16 (fix(RemoteSelect): Persist selection on change)
|
|
7
|
+
=======
|
|
8
|
+
import"handlebars";import"jquery";import"@ungap/custom-elements";import{Turbo as e}from"@hotwired/turbo-rails";import"select2";import t from"@rails/ujs";import"keymaster";import"clipboard";import i from"flatpickr";import s from"sortablejs";import"tinymce";import{setDefaultAnimation as n,registerIconLibrary as o}from"shoelace";import r from"cropperjs";const l=/\./;function a(e){const t=c(),i=Alchemy.translations;return i?l.test(e)?function(e,t){const i=t.split(l),s=e[i[0]];return s&&s[i[1]]||t}(i,e):i[e]||e:(console.warn(`Translations for locale ${t} not found!`),e)}function c(){return document.documentElement.lang?document.documentElement.lang:"en"}function d(e,t=void 0){let i=a(e);return t?i.replace(/%\{.+\}/,t):i}async function h(){const e=c();"en"!==e&&(await import(`select2/${e}.js`),$.extend($.fn.select2.defaults,$.fn.select2.locales[e]))}const u=[];function p(e){return!(!$(e.target).is("input, textarea")&&"?"===String.fromCharCode(e.which))||(k("/admin/help",{title:Alchemy.t("help"),size:"400x492"}),!1)}function m(e=document){e instanceof jQuery&&(e=e[0]),e===document&&(document.removeEventListener("keypress",p),document.addEventListener("keypress",p),u.forEach(e=>key.unbind(e)));const t=e.querySelectorAll(".search_input_field"),i=e.querySelectorAll(".search_field_clear, .js_filter_field_clear");key("alt+f",function(){return key.setScope("search"),t.forEach(e=>e.focus({focusVisible:!0})),!1}),u.push("alt+f"),key("esc","search",function(){i.forEach(e=>e.click()),t.forEach(e=>e.blur())}),u.push("esc"),e.querySelectorAll("[data-alchemy-hotkey]").forEach(function(e){const t=e.dataset.alchemyHotkey;key(t,()=>e.click()),u.push(t)})}function g(e){const t=document.createElement("template");return t.innerHTML=e,t.content.children[0]}let f=class{constructor(e,t="currentColor"){this.size=e,this.color=t,this.spinner=void 0}get el(){return this.spinner}spin(e){return void 0===e&&(e=document.body),this.spinner=g(`<alchemy-spinner size="${this.size}" color="${this.color}"></alchemy-spinner>`),e.append(this.spinner),this}stop(){this.spinner&&(this.spinner.remove(),this.spinner=void 0)}};const v=[],y={header_height:36,size:"400x300",padding:!0,title:"",modal:!0,overflow:"visible",ready:()=>{},closed:()=>{}};class b{constructor(e,t={}){this.url=e,this.options={...y,...t},this.$document=$(document),this.$window=$(window),this.$body=$("body");const i=this.options.size.split("x");this.width=parseInt(i[0],10),this.height=parseInt(i[1],10),this.build(),this.resize()}open(){this.dialog.trigger("Alchemy.DialogOpen"),this.bind_close_events(),window.requestAnimationFrame(()=>{if(this.dialog_container.addClass("open"),null!=this.overlay)return this.overlay.addClass("open")}),this.$body.addClass("prevent-scrolling"),v.push(this),this.load()}close(){return this.dialog.trigger("DialogClose.Alchemy"),this.$document.off("keydown"),this.dialog_container.removeClass("open"),null!=this.overlay&&this.overlay.removeClass("open"),this.$document.on("webkitTransitionEnd transitionend oTransitionEnd",()=>{if(this.$document.off("webkitTransitionEnd transitionend oTransitionEnd"),this.dialog_container.remove(),null!=this.overlay&&this.overlay.remove(),this.$body.removeClass("prevent-scrolling"),v.pop(this),null!=this.options.closed)return this.options.closed()}),!0}load(){this.show_spinner(),$.get(this.url,e=>{this.replace(e)}).fail(e=>{this.show_error(e)})}reload(){this.dialog_body.empty(),this.load()}replace(e){this.remove_spinner(),this.dialog_body.hide(),this.dialog_body.html(e),this.init(),this.dialog[0].dispatchEvent(new CustomEvent("DialogReady.Alchemy",{bubbles:!0,detail:{body:this.dialog_body[0]}})),null!=this.options.ready&&this.options.ready(this.dialog_body),this.dialog_body.show()}show_spinner(){this.spinner=new f("medium"),this.spinner.spin(this.dialog_body[0])}remove_spinner(){this.spinner.stop()}init(){m(this.dialog_body),this.watch_remote_forms(),window.requestAnimationFrame(()=>{this.dialog_body.find("[autofocus]").focus()})}watch_remote_forms(){const e=$('[data-remote="true"]',this.dialog_body);e.on("ajax:success",e=>{const t=e.detail[2];t.getResponseHeader("Content-Type").match(/javascript/)||(this.dialog_body.html(t.responseText),this.init())}),e.on("ajax:error",e=>{const t=e.detail[1],i=e.detail[2];this.show_error(i,t)})}show_error(e,t){if(422===e.status)return this.dialog_body.html(e.responseText),void this.init();const{error_body:i,error_header:s,error_type:n}=this.error_messages(e,t),o=$(`<alchemy-message type="${n}">\n <h1>${s}</h1>\n <p>${i}</p>\n </alchemy-message>`);this.dialog_body.html(o)}error_messages(e,t){let i,s,n="warning";switch(e.status){case 0:s="The server does not respond.",i="Please check server and try again.";break;case 403:s="You are not authorized!",i="Please close this window.";break;default:n="error",t?(s=t,console.error(e.responseText)):s=`${e.statusText} (${e.status})`,i="Please check log and try again."}return{error_header:s,error_body:i,error_type:n}}bind_close_events(){this.close_button.on("click",()=>{this.close()}),this.dialog_container.addClass("closable").on("click",e=>e.target!==this.dialog_container.get(0)||(this.close(),!1)),this.$document.keydown(e=>27!==e.which||(this.close(),!1))}build(){this.dialog_container=$('<div class="alchemy-dialog-container" />'),this.dialog=$('<div class="alchemy-dialog" />'),this.dialog_body=$('<div class="alchemy-dialog-body" />'),this.dialog_header=$('<div class="alchemy-dialog-header" />'),this.dialog_title=$('<div class="alchemy-dialog-title" />'),this.close_button=$('<button class="alchemy-dialog-close"><alchemy-icon name="close"></alchemy-icon></button>'),this.dialog_title.text(this.options.title),this.dialog_header.append(this.dialog_title),this.dialog_header.append(this.close_button),this.dialog.append(this.dialog_header),this.dialog.append(this.dialog_body),this.dialog_container.append(this.dialog),this.options.modal&&this.dialog.addClass("modal"),this.options.padding&&this.dialog_body.addClass("padded"),this.options.modal&&(this.overlay=$('<div class="alchemy-dialog-overlay" />'),this.$body.append(this.overlay)),this.$body.append(this.dialog_container)}resize(){const{width:e,height:t}=this.getSize();this.dialog.css({width:e,"min-height":t,overflow:this.options.overflow}),"hidden"===this.options.overflow?this.dialog_body.css({height:t,overflow:"auto"}):this.dialog_body.css({"min-height":t,overflow:"visible"})}getSize(){const e=this.options.padding?16:0,t=this.$window.width(),i=this.$window.height();let s=this.width,n=this.height;return s>=t&&(s=t-e),n>=i&&(n=i-e-y.header_height),{width:s,height:n}}}function w(){const{length:e}=v;if(0!==e)return v[e-1]}function E(e){const t=w();if(null!=t)return t.options.closed=e,t.close()}function k(e,t){if(!e)throw"No url given! Please provide an url.";new b(e,t).open()}class _{constructor(e,t={}){this.message=e,this.options={...{size:"300x100",title:d("Please confirm"),ok_label:d("Yes"),cancel_label:d("No"),on_ok(){}},...t},this.#e(),this.#t()}open(){requestAnimationFrame(()=>{this.dialog.show()})}#e(){const e=this.options.size.split("x")[0];this.dialog=g(`\n <sl-dialog label="${this.options.title}" style="--width: ${e}px">\n ${this.message}\n <button slot="footer" type="reset" class="secondary mx-1 my-0" autofocus>\n ${this.options.cancel_label}\n </button>\n <button slot="footer" type="submit" class="mx-1 my-0">\n ${this.options.ok_label}\n </button>\n </sl-dialog>\n `),document.body.append(this.dialog)}#t(){this.cancelButton.addEventListener("click",e=>{e.preventDefault(),this.options.on_cancel(),this.dialog.hide()}),this.okButton.addEventListener("click",e=>{e.preventDefault(),this.options.on_ok(),this.dialog.hide()}),this.dialog.addEventListener("sl-request-close",e=>{"overlay"===e.detail.source&&(this.options.on_cancel(),e.preventDefault())}),this.dialog.addEventListener("sl-after-hide",()=>{this.dialog.remove()})}get cancelButton(){return this.dialog.querySelector("button[type=reset]")}get okButton(){return this.dialog.querySelector("button[type=submit]")}}function L(e,t={}){return new Promise(i=>{new _(e,{...t,on_ok(){i(!0)},on_cancel(){i(!1)}}).open()})}function S(e=!0){document.querySelector("alchemy-overlay").show=!!e}function x(e){let t=()=>{};$(e).is("form")?t=function(){const t=$(`<form action="${e.action}" method="POST" style="display: none" />`);t.append($(e).find("input")),t.appendTo("body"),S(),t.trigger("submit")}:$(e).is("a")&&(t=()=>Turbo.visit(e.pathname));return!(document.querySelectorAll("alchemy-element-editor.dirty").length>0)||(L(d("page_dirty_notice"),{title:d("warning"),ok_label:d("ok"),cancel_label:d("cancel")}).then(e=>{e&&(window.onbeforeunload=void 0,t())}),!1)}var C={checkPageDirtyness:x,PageLeaveObserver:function(){document.querySelectorAll("#main_navi a").forEach(e=>{e.addEventListener("click",e=>{x(e.currentTarget)||e.preventDefault()})})}};function A(e){const t=document.getElementById("fixed-elements"),i=`fixed-element-${e}`;t.querySelector(`sl-tab[panel="${i}"]`).remove(),t.querySelector(`sl-tab-panel[name="${i}"]`).remove(),t.show("main-content-elements")}var T=Object.freeze({__proto__:null,createTab:function(e,t){const i=document.getElementById("fixed-elements"),s=`fixed-element-${e}`,n=`<sl-tab slot="nav" panel="${s}">${t}</sl-tab>`,o=`<sl-tab-panel name="${s}" style="--padding: 0" />`;i.innerHTML+=n+o,window.requestAnimationFrame(function(){i.show(s)})},removeTab:A});function O(e,t="notice"){!function(e,t){const i=document.getElementById("flash_notices"),s=g(`\n <alchemy-message type="${t}" dismissable>\n ${e}\n </alchemy-message>\n `);i.append(s)}(e,t)}const I=/#[\w.~-]+$/;class F extends HTMLIFrameElement{#i;#s;#n;handleEvent(e){"load"===e.type&&(this.#o(),this.#r(),this.#i?.call(this,e))}#l=e=>{"Alchemy.previewReady"===e.data.message&&(this.#o(),this.#r(),this.#i?.call(this,e))};connectedCallback(){let e=this.url;this.addEventListener("load",this),this.#a(),window.addEventListener("message",this.#l),window.localStorage.getItem("alchemy-preview-url")&&(e=window.localStorage.getItem("alchemy-preview-url"),this.previewUrlSelect.value=e),this.refresh(e)}disconnectedCallback(){this.removeEventListener("load",this),key.unbind("alt+r"),window.removeEventListener("message",this.#l)}postMessage(e){this.contentWindow.postMessage(e,"*")}resize(e){this.style.width=`${e}px`}refresh(e){return this.#c(),this.src=e||this.url,this.#o(),this.#n=setTimeout(()=>{this.#r(),O(d("Preview failed to load"),"warning")},5e3),new Promise(e=>{this.#i=e})}set isDragged(e){this.style.transitionProperty=e?"none":null,this.style.pointerEvents=e?"none":null}#a(){this.reloadButton?.addEventListener("click",e=>{e.preventDefault(),this.refresh()}),key("alt+r",()=>this.refresh()),this.sizeSelect.addEventListener("change",e=>{const t=e.target.value;""===t?this.style.width=null:this.resize(t)}),this.previewUrlSelect?.addEventListener("change",e=>{const t=e.target.value;window.localStorage.setItem("alchemy-preview-url",t),this.refresh(t)})}#c(){this.reloadButton.innerHTML.includes("alchemy-spinner")||(this.#s=this.reloadButton.innerHTML),this.reloadButton.innerHTML='<alchemy-spinner size="small"></alchemy-spinner>'}#r(){this.reloadButton.innerHTML=this.#s}#o(){this.#n&&(clearTimeout(this.#n),this.#n=null)}get url(){return this.getAttribute("url")}get sizeSelect(){return document.querySelector("select#preview_size")}get previewUrlSelect(){return document.querySelector("select#preview_url")}get reloadButton(){return document.querySelector("#reload_preview_button")}}function q(){document.getElementById("alchemy_preview_window").refresh()}customElements.define("alchemy-preview-window",F,{extends:"iframe"});class D{static updateIcon(e,t=!1){const i=document.querySelector(`[data-ingredient-id="${e}"]`);if(i){i.querySelector(".edit-ingredient-anchor-link alchemy-icon").setAttribute("icon-style",t?"fill":"line")}}}class M extends HTMLElement{constructor(){super(),this.actions={closeCurrentDialog:E,reloadPreview:q,removeFixedElement:A,updateAnchorIcon:D.updateIcon,hidePleaseWaitOverlay(){S(!1)}}}connectedCallback(){const e=this.actions[this.name];e?e(...this.params):console.error(`Unknown Alchemy action: ${this.name}`),this.remove()}get name(){return this.getAttribute("name")}get params(){return this.hasAttribute("params")?JSON.parse(this.getAttribute("params")):[]}}function B(e,t){return e.replace(new RegExp(t,"gi"),e=>`<em>${e}</em>`)}customElements.define("alchemy-action",M);class P extends HTMLElement{#d=null;async connectedCallback(){await h(),this.isConnected&&(this.input.classList.add("alchemy_selectbox"),this.#d=$(this.input).select2(this.select2Config).on("select2-open",this.#h).on("change",this.#u))}disconnectedCallback(){this.#d&&(this.#d.off("select2-open",this.#h),this.#d.off("change",this.#u),this.#d.select2("destroy"),this.#d=null)}#h=e=>this.onOpen(e);#u=e=>this.onChange(e);onChange(e){e.added&&this.setAttribute("selection",JSON.stringify(e.added)),this.dispatchCustomEvent("RemoteSelect.Change",{removed:e.removed,added:e.added})}onOpen(e){setTimeout(()=>{document.querySelector("#select2-drop .select2-input").focus()},100)}dispatchCustomEvent(e,t={}){this.dispatchEvent(new CustomEvent(`Alchemy.${e}`,{bubbles:!0,detail:t}))}get allowClear(){return this.hasAttribute("allow-clear")}get selection(){return this.getAttribute("selection")}get placeholder(){return this.getAttribute("placeholder")??""}get queryParams(){return this.getAttribute("query-params")??"{}"}get url(){return this.getAttribute("url")??""}get input(){return this.getElementsByTagName("input")[0]}get select2Config(){return{placeholder:this.placeholder,allowClear:this.allowClear,initSelection:(e,t)=>{this.selection&&t(JSON.parse(this.selection))},ajax:this.ajaxConfig,formatSelection:e=>this._renderResult(e),formatResult:(e,t,i)=>this._renderListEntry(e,i.term)}}get ajaxConfig(){return{url:this.url,datatype:"json",quietMillis:300,data:(e,t)=>this._searchQuery(e,t),results:e=>this._parseResponse(e)}}_searchQuery(e,t){return{q:{name_cont:e,...JSON.parse(this.queryParams)},page:t}}_parseResponse(e){const t=e.meta;return{results:e.data,more:t.page*t.per_page<t.total_count}}_renderResult(){throw new Error("You need to define a _renderResult function on your sub class!")}_renderListEntry(){throw new Error("You need to define a _renderListEntry function on your sub class!")}_hightlightTerm(e,t){return B(e,t)}}customElements.define("alchemy-attachment-select",class extends P{_renderResult(e){return this._renderListEntry(e)}_renderListEntry(e,t){return`\n <div class="attachment-select--attachment">\n <alchemy-icon name="${e.icon_css_class}"></alchemy-icon>\n <span class="attachment-select--attachment-name">${this._hightlightTerm(e.name,t)}</span>\n </div>\n `}});class z extends HTMLElement{connectedCallback(){$(this).on("change",this.#u)}disconnectedCallback(){$(this).off("change",this.#u)}#u=e=>{const t=new Event("submit",{bubbles:!0,cancelable:!0});return e.target.form.dispatchEvent(t),!1}}customElements.define("alchemy-auto-submit",z);class H extends HTMLButtonElement{connectedCallback(){this.form?(this.form.addEventListener("submit",this),"true"==this.form.dataset.remote&&this.form.addEventListener("ajax:complete",this),this.form.addEventListener("turbo:submit-end",this)):console.warn("No form for button found!",this)}handleEvent(e){switch(e.type){case"submit":"disabled"===this.getAttribute("disabled")?(e.preventDefault(),e.stopPropagation()):this.disable();break;case"ajax:complete":case"turbo:submit-end":this.enable()}}disable(){const e=new f("small"),t=this.getBoundingClientRect();this.dataset.initialButtonText=this.innerHTML,this.setAttribute("disabled","disabled"),this.setAttribute("tabindex","-1"),this.classList.add("disabled"),this.style.width=`${t.width}px`,this.style.height=`${t.height}px`,this.innerHTML=" ",e.spin(this)}enable(){this.classList.remove("disabled"),this.removeAttribute("disabled"),this.removeAttribute("tabindex"),this.style.width=null,this.style.height=null,this.innerHTML=this.dataset.initialButtonText}}customElements.define("alchemy-button",H,{extends:"button"});class R extends HTMLElement{connectedCallback(){this.translation=d("allowed_chars",this.maxChars),this.formField=this.getFormField(),this.formField&&(this.createDisplayElement(),this.countCharacters(),this.formField.addEventListener("keyup",this))}disconnectedCallback(){this.formField?.removeEventListener("keyup",this)}handleEvent(e){"keyup"===e.type&&this.countCharacters()}getFormField(){const e=this.querySelectorAll("input, textarea");return e.length>0?e[0]:void 0}createDisplayElement(){this.display=this.querySelector(":scope > .alchemy-char-counter"),this.display||(this.display=document.createElement("small"),this.display.className="alchemy-char-counter",this.formField.after(this.display))}countCharacters(){const e=this.formField.value.length;this.display.textContent=`${e} ${this.translation}`,this.display.classList.toggle("too-long",e>this.maxChars)}get maxChars(){return this.getAttribute("max-chars")??60}}customElements.define("alchemy-char-counter",R);class N extends HTMLElement{connectedCallback(){this.innerHTML='<alchemy-icon name="clipboard"></alchemy-icon>',this.clipboard=new ClipboardJS(this,{text:()=>this.getAttribute("content")}),this.clipboard.on("success",()=>{O(this.getAttribute("success-text"))})}disconnectedCallback(){this.clipboard.destroy()}}customElements.define("alchemy-clipboard-button",N);const j=e=>{const t=e.element[0],i=t.dataset.swatch||t.value;return`\n <div class="select-color-option">\n ${"custom_color"===t.value?'<alchemy-icon name="palette"></alchemy-icon>':`<span class="color-indicator" style="--color: ${i}"></span>`}\n <span>${e.text}</span>\n </div>`};class V extends HTMLElement{#d=null;connectedCallback(){this.select?(this.#p(),this.#d.on("change",this.#m)):(this.colorInput?.addEventListener("input",this),this.textInput?.addEventListener("input",this),this.#g(!0))}handleEvent(e){switch(e.target){case this.colorInput:this.textInput.value=this.colorInput.value;break;case this.textInput:this.colorInput.value=this.textInput.value}}disconnectedCallback(){this.colorInput?.removeEventListener("input",this),this.textInput?.removeEventListener("input",this),this.#d&&(this.#d.off("change",this.#m),this.#d.select2("destroy"),this.#d=null)}#m=e=>{this.#g("custom_color"===e.val)};#p(){this.select.classList.add("alchemy_selectbox");const e={minimumResultsForSearch:10,formatResult:j,formatSelection:j};this.#d=$(this.select).select2(e)}#g(e=!0){this.colorInput.disabled=!e}get colorInput(){return this.querySelector("input[type='color']")}get textInput(){return this.querySelector("input[type='text']")}get select(){return this.querySelector("select")}}customElements.define("alchemy-color-select",V);const W=c();class U extends HTMLElement{async connectedCallback(){"en"!==W&&await import(`flatpickr/${W}.js`),this.isConnected&&(this.flatpickr=i(this.inputField,this.flatpickrOptions))}disconnectedCallback(){this.flatpickr?.destroy()}get flatpickrOptions(){const e=/time/.test(this.inputType),t={locale:W.slice(0,2),altInput:!0,altFormat:d(`formats.${this.inputType}`),altInputClass:"flatpickr-input",enableTime:e,noCalendar:"time"===this.inputType,time_24hr:d("formats.time_24hr"),onValueUpdate(e,t,i){i.element.closest("alchemy-element-editor")?.setDirty(this.inputField)}};return e&&(t.dateFormat="Z"),t}get inputField(){return this.querySelector("input")}get inputType(){return this.getAttribute("input-type")||"date"}}customElements.define("alchemy-datepicker",U);class K extends HTMLAnchorElement{connectedCallback(){this.addEventListener("click",this)}disconnectedCallback(){this.removeEventListener("click",this)}handleEvent(e){this.disabled||this.openDialog(),e.preventDefault()}openDialog(){this.dialog=new b(this.getAttribute("href"),this.dialogOptions),this.dialog.open()}get dialogOptions(){return this.dataset.dialogOptions?JSON.parse(this.dataset.dialogOptions):{}}get disabled(){return this.classList.contains("disabled")}}customElements.define("alchemy-dialog-link",K,{extends:"a"});const J="application/json";function G(e){return"get"===e.toLowerCase()}function Q(e,t,i){const s=function(e){return{"Content-Type":"application/json; charset=utf-8",Accept:e,"X-Requested-With":"XMLHttpRequest","X-CSRF-Token":X()}}(i),n={method:e,headers:s};return t&&!G(e)&&(n.body=JSON.stringify(t)),n}function X(){return document.querySelector('meta[name="csrf-token"]').attributes.content.textContent}function Y(e,t){return te("GET",e,t)}function Z(e,t,i){return te("PATCH",e,t,i)}function ee(e,t,i=J){return te("POST",e,t,i)}async function te(e,t,i,s=J){const n=await fetch(function(e,t,i){const s=new URL(window.location.origin+e);return t&&G(i)&&(s.search=new URLSearchParams(t).toString()),s.toString()}(t,i,e),Q(e,i,s)),o=n.headers.get("content-type"),r=o?.includes(J),l=o?.includes("text/vnd.turbo-stream.html");let a=null;if(r?a=await n.json():l&&(a=await n.text(),"undefined"!=typeof Turbo&&Turbo.renderStreamMessage(a)),n.ok)return{data:a,status:n.status};throw a||new Error("An error occurred during the transaction")}class ie extends HTMLElement{dataItem(e){return{id:`#${e}`,text:`#${e}`}}get selectElement(){return this.querySelector('select[is="alchemy-select"]')}}customElements.define("alchemy-dom-id-api-select",class extends ie{#f=void 0;connectedCallback(){this.page=this.getAttribute("page")}async#v(){const e=(await Y(Alchemy.routes.api_ingredients_path,{page_id:this.#f})).data.ingredients.filter(e=>e.data?.dom_id).map(e=>this.dataItem(e.data.dom_id)),t=e.length>0?d("None"):d("No anchors found");this.selectElement.setOptions(e,t),this.selectElement.enable()}#y(){requestAnimationFrame(()=>{this.selectElement.disable(),this.selectElement.setOptions([],d("Select a page first"))})}set page(e){this.#f=e,e?this.#v():this.#y()}}),customElements.define("alchemy-dom-id-preview-select",class extends ie{connectedCallback(){requestAnimationFrame(()=>{const e=document.getElementById("alchemy_preview_window"),t=e.contentDocument?.querySelectorAll("[id]")||[];if(t.length>0){const e=Array.from(t).map(e=>this.dataItem(e.id));this.selectElement.setOptions(e,d("None"))}})}});class se extends HTMLElement{#b;connectedCallback(){this.#b=this.scheduleButton.getAttribute("variant"),this.publishButton.addEventListener("click",this),this.dropdown.addEventListener("sl-show",this),this.dropdown.addEventListener("sl-hide",this)}disconnectedCallback(){this.publishButton.removeEventListener("click",this),this.dropdown.removeEventListener("sl-show",this),this.dropdown.removeEventListener("sl-hide",this)}handleEvent(e){switch(e.type){case"click":this.publishButton.loading=!0;break;case"sl-show":this.scheduleButton.setAttribute("variant","primary");break;case"sl-hide":this.scheduleButton.setAttribute("variant",this.#b)}}get publishButton(){return this.querySelector("sl-button[type='submit']")}get dropdown(){return this.querySelector("sl-dropdown")}get scheduleButton(){return this.querySelector("sl-button[slot='trigger']")}}customElements.define("alchemy-publish-element-button",se);class ne extends HTMLElement{connectedCallback(){this.button?.addEventListener("click",this)}disconnectedCallback(){this.button?.removeEventListener("click",this)}async handleEvent(){if(await L(this.message)){const e=await te("DELETE",this.url);this.#w(e.data)}}#w(e){const t=this.closest("alchemy-element-editor");t.addEventListener("transitionend",()=>{t.fixed&&A(t.elementId),t.remove()}),t.classList.add("dismiss"),O(e.message),e.pageHasUnpublishedChanges&&oe(e),q()}get url(){return this.getAttribute("href")}get message(){return this.getAttribute("message")}get button(){return this.querySelector("button")}}function oe(e){document.dispatchEvent(new CustomEvent("alchemy:page-dirty",{detail:{tooltip:e.publishButtonTooltip}}))}customElements.define("alchemy-delete-element-button",ne);class re extends HTMLElement{#E=null;#k=null;#_=null;connectedCallback(){this.classList.contains("ui-sortable-placeholder")||(this.addEventListener("click",this),this.addEventListener("alchemy:element-update-title",this),this.addEventListener("ajax:complete",this),this.#E=this.form,this.#E&&$(this.#E).on("change",this.onChange),this.#k=this.header,this.#k?.addEventListener("dblclick",this.#L),this.#_=this.toggleButton,this.#_?.addEventListener("click",this.#S),this.hasAttribute("created")&&(this.focusElement(),this.previewWindow?.refresh().then(()=>{this.focusElementPreview()}),this.removeAttribute("created")))}disconnectedCallback(){this.removeEventListener("click",this),this.removeEventListener("alchemy:element-update-title",this),this.removeEventListener("ajax:complete",this),this.#E&&($(this.#E).off("change",this.onChange),this.#E=null),this.#k?.removeEventListener("dblclick",this.#L),this.#k=null,this.#_?.removeEventListener("click",this.#S),this.#_=null}handleEvent(e){switch(e.type){case"click":e.target.closest("alchemy-element-editor")===this&&this.onClickElement();break;case"ajax:complete":if(e.target===this.body){const t=e.detail[0];e.stopPropagation(),this.onSaveElement(t)}break;case"alchemy:element-update-title":this.hasEditors||e.target!=this.firstChild||this.setTitle(e.detail.title)}}onChange=e=>{const t=e.target;if(!t.classList.contains("nested-elements"))return this.setDirty(t),e.stopPropagation(),!1};async focusElement(){document.querySelector("#fixed-elements")&&await this.selectTabForElement(),await this.expand(),this.selectElement(!0)}focusElementPreview(){this.previewWindow?.postMessage({message:"Alchemy.focusElement",element_id:this.elementId})}onClickElement(){this.selectElement(),this.focusElementPreview()}onSaveElement(e){const t=JSON.parse(e.responseText);if(this.setClean(),422===e.status){const e=t.warning;t.ingredientsWithErrors.forEach(e=>{const t=this.querySelector(`[data-ingredient-id="${e.id}"]`),i=g(`<small class="error">${e.errorMessage}</small>`);t?.appendChild(i),t?.classList.add("validation_failed")}),O(e,"warn"),this.elementErrors.classList.remove("hidden")}else O(t.notice),this.previewWindow?.refresh().then(()=>{this.focusElementPreview()}),this.updateTitle(t.previewText),t.ingredientAnchors.forEach(e=>{D.updateIcon(e.ingredientId,e.active)}),t.pageHasUnpublishedChanges&&oe(t)}scrollToElement(){setTimeout(()=>{this.scrollIntoView({behavior:"smooth"})},50)}selectElement(e=!1){document.querySelectorAll("alchemy-element-editor.selected").forEach(e=>{e.classList.remove("selected")}),window.requestAnimationFrame(()=>{this.classList.add("selected")}),e&&this.scrollToElement()}selectTabForElement(){return new Promise((e,t)=>{const i=document.querySelector("#fixed-elements"),s=this.closest("sl-tab-panel");i&&s?(i.show(s.getAttribute("name")),e()):t(new Error("No tabs present"))})}setClean(){this.dirty=!1,window.onbeforeunload=null,this.elementErrors.classList.add("hidden"),this.hasEditors&&this.body.querySelectorAll(".ingredient-editor").forEach(e=>{e.classList.remove("dirty","validation_failed"),e.querySelectorAll("small.error").forEach(e=>e.remove())})}setDirty(e){this.hasEditors&&(this.dirty=!0,window.onbeforeunload||(window.onbeforeunload=e=>e.preventDefault()),e?.closest(".ingredient-editor")?.classList.add("dirty"))}setTitle(e){const t=this.querySelector(".element-header .preview_text_quote");t&&(t.textContent=e)}async toggle(){this.collapsed?await this.expand():await this.collapse()}collapse(){if(this.collapsed||this.compact||this.fixed)return Promise.resolve("Element is already collapsed.");const e=new Alchemy.Spinner("small");return e.spin(this.toggleButton),this.toggleIcon?.classList?.add("hidden"),ee(Alchemy.routes.collapse_admin_element_path(this.elementId)).then(e=>{const t=e.data;if(this.collapsed=!0,this.toggleButton?.setAttribute("title",t.title),t.nestedElementIds.length){const e=t.nestedElementIds.map(e=>`#element_${e}`).join(", ");this.querySelectorAll(e).forEach(e=>{e.collapsed=!0,e.toggleButton?.setAttribute("title",t.title)})}}).catch(e=>{O(e.message,"error"),console.error(e)}).finally(()=>{this.toggleIcon?.classList?.remove("hidden"),e.stop()})}expand(){if(this.expanded&&!this.compact)return Promise.resolve("Element is already expanded.");if(this.compact&&this.parentElementEditor)return this.parentElementEditor.expand();{const e=new Alchemy.Spinner("small");return e.spin(this.toggleButton),this.toggleIcon?.classList.add("hidden"),new Promise((t,i)=>{ee(Alchemy.routes.expand_admin_element_path(this.elementId)).then(e=>{const i=e.data;if(i.parentElementIds.length){const e=i.parentElementIds.map(e=>`#element_${e}`).join(", ");document.querySelectorAll(e).forEach(e=>{e.collapsed=!1,e.toggleButton?.setAttribute("title",i.title)})}this.collapsed=!1,this.toggleButton?.setAttribute("title",i.title),t()}).catch(e=>{O(e.message,"error"),console.error(e),i(e)}).finally(()=>{this.toggleIcon?.classList?.remove("hidden"),e.stop()})})}}updateTitle(e){this.setTitle(e),this.dispatchEvent(new CustomEvent("alchemy:element-update-title",{bubbles:!0,detail:{title:e}}))}set published(e){e?this.classList.remove("element-hidden"):this.classList.add("element-hidden")}get published(){return!this.classList.contains("hidden")}get compact(){return null!==this.getAttribute("compact")}get fixed(){return null!==this.getAttribute("fixed")}set collapsed(e){this.classList.toggle("folded",e),this.classList.toggle("expanded",!e),this.toggleIcon&&(this.toggleIcon.name=e?"arrow-left-s":"arrow-down-s")}get collapsed(){return this.classList.contains("folded")}get expanded(){return!this.collapsed}set dirty(e){this.classList.toggle("dirty",e)}get dirty(){return this.classList.contains("dirty")}get header(){return this.querySelector(".element-header")}get body(){return this.querySelector(this.bodySelector)}get bodySelector(){return`#${this.id} > .element-body`}get footer(){return this.querySelector(`#${this.id} > .element-footer`)}get toggleButton(){return this.querySelector(".element-toggle")}get toggleIcon(){return this.toggleButton?.querySelector("alchemy-icon")}get elementErrors(){return this.body.querySelector(".element_errors")}get elementId(){return this.dataset.elementId}get elementName(){return this.dataset.elementName}get hasEditors(){return!!this.body?.querySelector(".element-ingredient-editors")}get hasChildren(){return!!this.querySelector(".nested-elements")}get firstChild(){return this.querySelector("alchemy-element-editor")}get form(){return this.querySelector("form.element-body")}get parentElementEditor(){return this.parentElement?.closest("alchemy-element-editor")}get previewWindow(){return document.getElementById("alchemy_preview_window")}#L=()=>{this.toggle()};#S=e=>{e.target.closest("alchemy-element-editor")===this&&this.toggle()}}customElements.define("alchemy-element-editor",re);const le=e=>`\n <div class="element-select-name">\n ${e.icon}<span>${e.text}</span>\n </div>\n `;class ae extends HTMLElement{#d=null;connectedCallback(){const e=this.options,t={minimumResultsForSearch:3,dropdownAutoWidth:!0,data:()=>({results:e}),formatResult:(e,t,i)=>{let s;return""===e.id?e.text:(s=""!==i.term?B(e.text,i.term):e.text,((e,t,i)=>{const s=i?`<div class="element-select-description">${i}</div>`:"";return`\n <div class="element-select-item">\n ${le({icon:e,text:t})}\n ${s}\n </div>\n `})(e.icon,s,e.hint))},formatSelection:le,placeholder:this.placeholder};this.#d=$(this.inputField).select2(t)}disconnectedCallback(){this.#d?.select2("destroy"),this.#d=null}get options(){return JSON.parse(this.getAttribute("options"))}get placeholder(){return this.getAttribute("placeholder")}get inputField(){return this.querySelector("input")}}customElements.define("alchemy-element-select",ae);class ce extends HTMLElement{#x=!0;#C=null;connectedCallback(){this.toggleButton?.addEventListener("click",this.#S),this.collapseButton?.addEventListener("click",this.#A),window.addEventListener("message",this.#T),document.body.addEventListener("click",this.#O),window.location.hash&&this.focusElementEditor(window.location.hash),this.resize()}disconnectedCallback(){this.toggleButton?.removeEventListener("click",this.#S),this.collapseButton?.removeEventListener("click",this.#A),window.removeEventListener("message",this.#T),document.body.removeEventListener("click",this.#O)}#S=e=>{e.preventDefault(),this.toggle()};#A=()=>{this.collapseAllElements()};#T=e=>{const t=e.data;if("Alchemy.focusElementEditor"==t?.message){const e=document.getElementById(`element_${t.element_id}`);this.show(),e?.focusElement()}};#O=e=>{e.target.closest("alchemy-element-editor")||(this.querySelectorAll("alchemy-element-editor").forEach(e=>{e.classList.remove("selected")}),this.previewWindow?.postMessage({message:"Alchemy.blurElements"}))};collapseAllElements(){this.querySelectorAll("alchemy-element-editor:not([compact]):not([fixed])").forEach(e=>e.collapse())}toggle(){this.#x?this.hide():this.show()}show(){document.body.classList.add("elements-window-visible"),this.#x=!0,this.toggleButton.closest("sl-tooltip").content=Alchemy.t("Hide elements"),this.toggleButton.querySelector("alchemy-icon").setAttribute("name","menu-unfold"),this.resize()}hide(){document.body.classList.remove("elements-window-visible"),document.body.style.removeProperty("--elements-window-width"),this.#x=!1,this.toggleButton.closest("sl-tooltip").content=Alchemy.t("Show elements"),this.toggleButton.querySelector("alchemy-icon").setAttribute("name","menu-fold")}resize(e){void 0===e&&(e=this.widthFromCookie),e&&(document.body.style.setProperty("--elements-window-width",`${e}px`),document.cookie=`alchemy-elements-window-width=${e}; SameSite=Lax; Path=/;`)}focusElementEditor(e){const t=document.querySelector(e);t instanceof re&&t.focusElement()&&t.focusElementPreview()}get collapseButton(){return this.querySelector("#collapse-all-elements-button")}get toggleButton(){return document.querySelector("#element_window_button")}get previewWindow(){return document.getElementById("alchemy_preview_window")}get turboFrame(){return this.#C||(this.#C=this.closest("turbo-frame")),this.#C}get widthFromCookie(){return document.cookie.split("; ").find(e=>e.startsWith("alchemy-elements-window-width="))?.split("=")[1]}set isDragged(e){this.turboFrame.style.transitionProperty=e?"none":null,this.turboFrame.style.pointerEvents=e?"none":null}}customElements.define("alchemy-elements-window",ce);class de extends HTMLElement{#I=!1;#F=null;#$=null;#q=400;#D=1e3;connectedCallback(){this.addEventListener("mousedown",this),window.addEventListener("mousemove",this),window.addEventListener("mouseup",this)}disconnectedCallback(){this.removeEventListener("mousedown",this),window.removeEventListener("mousemove",this),window.removeEventListener("mouseup",this)}handleEvent(e){switch(e.type){case"mousedown":e.stopPropagation(),this.onMouseDown();break;case"mouseup":this.onMouseUp();break;case"mousemove":this.#I&&this.onDrag(e.pageX)}}onMouseDown(){this.#I=!0;const e=getComputedStyle(this.elementsWindow);this.#q=parseFloat(e.minWidth)||400,this.#D="none"===e.maxWidth?1e3:parseFloat(e.maxWidth),this.elementsWindow.isDragged=!0,this.previewWindow.isDragged=!0,this.classList.add("is-dragged")}onMouseUp(){this.#I=!1,this.elementsWindow.isDragged=!1,this.previewWindow.isDragged=!1,this.classList.remove("is-dragged")}onDrag(e){const t=window.innerWidth-e,i=Math.min(Math.max(t,this.#q),this.#D);this.elementsWindow.resize(i)}get elementsWindow(){return this.#F||(this.#F=document.querySelector("alchemy-elements-window")),this.#F}get previewWindow(){return this.#$||(this.#$=document.getElementById("alchemy_preview_window")),this.#$}}customElements.define("alchemy-elements-window-handle",de);class he extends HTMLElement{connectedCallback(){this.deleteLink=this.querySelector(".remove_file_link"),this.fileIcon=this.querySelector(".file_icon"),this.fileName=this.querySelector(".file_name"),this.formFieldId=this.deleteLink?.dataset.formFieldId,this.formField=this.querySelector(`#${this.formFieldId}`),this.deleteLink?.addEventListener("click",this)}disconnectedCallback(){this.deleteLink?.removeEventListener("click",this)}handleEvent(e){"click"===e.type&&this.removeFile(),e.stopPropagation()}removeFile(){this.formField.value="",this.fileIcon.innerHTML="",this.fileName.innerHTML="",this.deleteLink?.classList.add("hidden"),this.closest("alchemy-element-editor").setDirty(this.formField)}}customElements.define("alchemy-file-editor",he);class ue extends HTMLElement{#M;#B=null;#P=null;connectedCallback(){this.hotkey&&key(this.hotkey,this.#z),this.#B=this.filterField,this.#B.addEventListener("keyup",this.#H),this.#B.addEventListener("focus",this.#R),this.#P=this.clearButton,this.#P.addEventListener("click",this.#N),key("esc","list_filter",this.#j)}disconnectedCallback(){clearTimeout(this.#M),this.#B?.removeEventListener("keyup",this.#H),this.#B?.removeEventListener("focus",this.#R),this.#B=null,this.#P?.removeEventListener("click",this.#N),this.#P=null,this.hotkey&&key.unbind(this.hotkey),key.unbind("esc","list_filter")}filter(e){""===e&&(this.clearButton.style.visibility="hidden");const t=[],i=new Set,s=e.toLowerCase();this.items.forEach(e=>{const n=e.getAttribute(this.nameAttribute)?.toLowerCase();if(-1!==n.indexOf(s)){t.push(e),i.add(e);let s=e.parentElement?.closest(this.itemsSelector);for(;s;)i.add(s),s=s.parentElement?.closest(this.itemsSelector)}}),this.items.forEach(e=>{e.classList.toggle("hidden",!i.has(e))}),1===t.length&&t[0].scrollIntoView({behavior:"smooth",block:"nearest"})}clear(){this.filterField.value="",this.clearButton.style.visibility="hidden",this.items.forEach(e=>e.classList.remove("hidden"))}get nameAttribute(){return this.getAttribute("name-attribute")||"name"}get clearButton(){return this.querySelector('button[type="button"]')}get filterField(){return this.querySelector('input[type="text"]')}get items(){return document.querySelectorAll(this.itemsSelector)}get itemsSelector(){return this.getAttribute("items-selector")}get debounceTime(){return parseInt(this.getAttribute("debounce-time"))||150}get hotkey(){return this.getAttribute("hotkey")}#z=()=>(this.filterField.focus(),!1);#H=()=>{clearTimeout(this.#M),this.#M=setTimeout(()=>{const e=this.filterField.value;this.clearButton.style.visibility=e?"visible":"hidden",this.filter(e)},this.debounceTime)};#R=()=>key.setScope("list_filter");#N=e=>{e.preventDefault(),this.clear()};#j=()=>{this.clear(),this.filterField.blur()}}customElements.define("alchemy-list-filter",ue);class pe extends HTMLElement{#V=null;handleEvent(e){"click"===e.type&&this.dismiss()}connectedCallback(){if(!this.querySelector(":scope > alchemy-icon")){const e=this.dismissable&&"error"===this.type?'<alchemy-icon name="close"></alchemy-icon>':"";this.insertAdjacentHTML("afterbegin",`<alchemy-icon name="${this.iconName}"></alchemy-icon>${e}`)}(this.dismissable||"error"===this.type)&&this.addEventListener("click",this),this.dismissable&&"error"!==this.type&&(this.#V=setTimeout(()=>{this.dismiss()},this.dismissDelay))}disconnectedCallback(){null!==this.#V&&(clearTimeout(this.#V),this.#V=null)}dismiss(){this.addEventListener("transitionend",()=>this.remove()),this.classList.add("dismissed")}get dismissable(){return this.hasAttribute("dismissable")}get icon(){return this.getAttribute("icon")}get type(){return this.getAttribute("type")||"notice"}get dismissDelay(){return parseInt(this.noticesWrapper?.dataset.autoDismissDelay||5e3)}get iconName(){switch(this.icon||this.type){case"warning":case"warn":case"alert":return"alert";case"notice":return"check";case"info":case"hint":return"information";case"error":return"bug";default:return this.type}}get noticesWrapper(){return this.closest("#flash_notices")}}customElements.define("alchemy-message",pe);class me extends HTMLElement{connectedCallback(){O(this.message,this.getAttribute("type")||"notice"),this.remove()}get message(){return this.getAttribute("message")||this.innerHTML}}customElements.define("alchemy-growl",me);class ge extends HTMLElement{static get observedAttributes(){return["name","size","icon-style"]}constructor(){super(),this.spriteUrl=document.querySelector('link[rel="preload"][as="image"]').getAttribute("href")}connectedCallback(){this.render()}attributeChangedCallback(){this.render()}render(){const e=this.size?` icon--${this.size}`:"";this.innerHTML=`<svg class="icon${e}"><use href="${this.spriteUrl}#ri-${this.iconName}${this.style}" /></svg>`}set name(e){this.setAttribute("name",e)}get iconName(){return this.getAttribute("name")}get size(){return this.getAttribute("size")}get style(){const e=this.getAttribute("icon-style");switch(e){case"none":return"";case null:return"-line";default:return`-${e}`}}}customElements.define("alchemy-icon",ge);class fe extends HTMLDetailsElement{#W="Alchemy.expanded_ingredient_groups";connectedCallback(){this.addEventListener("toggle",this),this.isInLocalStorage&&(this.open=!0)}disconnectedCallback(){this.removeEventListener("toggle",this)}handleEvent(){let e=this.localStorageItem;this.open?(this.toggleIcon.name="arrow-down-s",this.isInLocalStorage||e.push(this.id)):(this.toggleIcon.name="arrow-right-s",e=e.filter(e=>e!==this.id)),localStorage.setItem(this.#W,JSON.stringify(e))}get isInLocalStorage(){return this.localStorageItem.includes(this.id)}get localStorageItem(){const e=localStorage.getItem(this.#W);if(!e)return[];try{return JSON.parse(e)}catch(e){return console.error(e),[]}}get toggleIcon(){return this.querySelector("alchemy-icon")}}customElements.define("alchemy-ingredient-group",fe,{extends:"details"});class ve extends HTMLButtonElement{connectedCallback(){this.addEventListener("click",this),this.classList.add("icon_button"),this.setAttribute("type","button"),this.innerHTML='<alchemy-icon name="link" icon-style="m"></alchemy-icon>'}handleEvent(e){new Alchemy.LinkDialog({url:this.linkUrl,title:this.linkTitle,target:this.linkTarget,type:this.linkClass}).open().then(e=>this.setLink(e)),e.preventDefault()}setLink(e){""===e.url?(this.classList.remove("linked"),this.dispatchEvent(new CustomEvent("alchemy:unlink",{bubbles:!0}))):(this.classList.add("linked"),this.dispatchEvent(new CustomEvent("alchemy:link",{bubbles:!0,detail:e})))}get linkUrl(){return this.linkButtons.linkUrlField.value}get linkTitle(){return this.linkButtons.linkTitleField.value}get linkTarget(){return this.linkButtons.linkTargetField.value}get linkClass(){return this.linkButtons.linkClassField.value}get linkButtons(){return this.closest("alchemy-link-buttons")}}customElements.define("alchemy-link-button",ve,{extends:"button"});class ye extends HTMLButtonElement{connectedCallback(){this.addEventListener("click",this),this.classList.add("icon_button"),this.setAttribute("type","button"),this.linked=this.linked,this.innerHTML='<alchemy-icon name="link-unlink" icon-style="m"></alchemy-icon>'}handleEvent(e){this.linked&&(this.linked=!1,this.blur(),this.dispatchEvent(new CustomEvent("alchemy:unlink",{bubbles:!0}))),e.preventDefault()}set linked(e){e?(this.classList.replace("disabled","linked"),this.removeAttribute("tabindex")):(this.classList.replace("linked","disabled"),this.setAttribute("tabindex","-1"))}get linked(){return this.classList.contains("linked")}}customElements.define("alchemy-unlink-button",ye,{extends:"button"});class be extends HTMLElement{connectedCallback(){this.addEventListener("alchemy:link",this),this.addEventListener("alchemy:unlink",this)}disconnectedCallback(){this.removeEventListener("alchemy:link",this),this.removeEventListener("alchemy:unlink",this)}handleEvent(e){switch(e.type){case"alchemy:link":this.setLink(e.detail);break;case"alchemy:unlink":this.removeLink()}e.stopPropagation()}setLink(e){this.linkUrlField.value=e.url,this.linkUrlField.dispatchEvent(new Event("change")),this.linkTitleField.value=e.title,this.linkClassField.value=e.type,this.linkTargetField.value=e.target,this.unlinkButton.linked=!0,this.setElementDirty()}removeLink(){this.linkUrlField.value="",this.linkUrlField.dispatchEvent(new Event("change")),this.linkTitleField.value="",this.linkClassField.value="",this.linkTargetField.value="",this.linkButton.classList.remove("linked"),this.unlinkButton.linked=!1,this.setElementDirty()}setElementDirty(){this.elementEditor.setDirty(this)}get linkButton(){return this.querySelector('[is="alchemy-link-button"]')}get unlinkButton(){return this.querySelector('[is="alchemy-unlink-button"]')}get ingredientEditor(){const e=this.dataset.ingredientId;return this.parentElement.closest(`[data-ingredient-id='${e}']`)}get elementEditor(){return this.closest("alchemy-element-editor")}get linkUrlField(){return this.ingredientEditor.querySelector("[data-link-value]")}get linkTitleField(){return this.ingredientEditor.querySelector("[data-link-title]")}get linkTargetField(){return this.ingredientEditor.querySelector("[data-link-target]")}get linkClassField(){return this.ingredientEditor.querySelector("[data-link-class]")}}customElements.define("alchemy-link-buttons",be);function we(e){let t=0===e?0:Math.floor(Math.log(e)/Math.log(1024));return t>3&&(t=3),(e/Math.pow(1024,t)).toFixed(2)+" "+["B","kB","MB","GB"][t]}customElements.define("alchemy-node-select",class extends P{_searchQuery(e,t){return{filter:{name_or_page_name_cont:e,...JSON.parse(this.queryParams)},page:t}}_renderResult(e){return this._renderListEntry(e)}_renderListEntry(e,t){const i=e.ancestors.map(e=>e.name),s='<alchemy-icon name="arrow-right-s"></alchemy-icon>';return`\n <div class="node-select--node">\n <alchemy-icon name="menu-2"></alchemy-icon>\n <div class="node-select--node-display_name">\n <span class="node-select--node-ancestors">\n ${i.length>0?i.join(s)+s:""}\n </span>\n <span class="node-select--node-name">\n ${this._hightlightTerm(e.name,t)}\n </span>\n </div>\n <div class="node-select--node-url">\n ${e.url||""}\n </div>\n </div>\n `}});class Ee extends HTMLElement{file=null;request=null;progressEventLoaded=0;progressEventTotal=0;#U=!0;#K=0;#J=void 0;#G="";connectedCallback(){if(this.innerHTML=`\n <sl-progress-bar value="${this.value}"></sl-progress-bar>\n <div class="description">\n <span class="file-name">${this.file?.name}</span>\n <span class="loaded-size">${this.loadedSize}</span>\n <span class="error-message">${this.errorMessage}</span>\n </div>\n <sl-tooltip content="${d("Abort upload")}">\n <button class="icon_button" aria-label="${d("Abort upload")}">\n <alchemy-icon name="close"></alchemy-icon>\n </button>\n </sl-tooltip>\n `,this.querySelector("button").addEventListener("click",()=>this.cancel()),this.file?.type.includes("image")){const e=new FileReader;e.readAsDataURL(this.file),e.addEventListener("load",()=>{const t=new Image;t.src=e.result,this.prepend(t)})}}initialize(e,t){this.file=e,this.request=t,this.progressEventTotal=e?e.size:0,this.status="in-progress",this.#Q(),this.#X()}cancel(){this.finished||(this.status="canceled",this.request?.abort(),this.dispatchCustomEvent("FileUpload.Change"))}dispatchCustomEvent(e){this.dispatchEvent(new CustomEvent(`Alchemy.${e}`,{bubbles:!0}))}#Q(){const e=Alchemy.uploader_defaults,t=e.file_size_limit*Math.pow(1024,2);let i;this.file?.size>t&&(i=d("Uploaded bytes exceed file size"));const s=this.file?.type.includes("image")?e.allowed_filetypes.alchemy_pictures:e.allowed_filetypes.alchemy_attachments;s.includes("*")||s.includes(this.file?.type.replace(/^\w+\/(\w+)(\+\w+)?/i,"$1"))||(i=d("File type not allowed")),i&&(this.valid=!1,this.errorMessage=i)}#X(){this.request&&(this.request.upload.onprogress=e=>{this.progressEvent=e},this.request.onload=()=>{this.request.status<400?(this.status="successful",O(this.responseMessage)):(this.status="failed",this.errorMessage=this.responseMessage),this.dispatchCustomEvent("FileUpload.Change")},this.request.onerror=()=>{this.errorMessage=d("An error occurred during the transaction")})}get active(){return this.valid&&"canceled"!==this.status}get errorMessage(){return this.#G||""}set errorMessage(e){this.#G=e;const t=this.querySelector(".error-message");t&&(t.textContent=e),O(e,"error")}get finished(){return["canceled","successful","failed"].includes(this.status)}get loadedSize(){return`${we(this.progressEventLoaded)} / ${we(this.progressEventTotal)}`}get progressElement(){return this.querySelector("sl-progress-bar")}set progressEvent(e){this.progressEventLoaded=e.loaded,this.progressEventTotal=e.total,this.value=Math.round(e.loaded/e.total*100),this.querySelector(".loaded-size").textContent=this.loadedSize}get responseMessage(){try{return JSON.parse(this.request.responseText).message}catch(e){return`${this.request.status}: ${this.request.statusText}`}}get status(){return this.#J}set status(e){this.#J=e,this.className=e,this.progressElement?.toggleAttribute("indeterminate","upload-finished"===e)}get valid(){return this.#U}set valid(e){this.#U=e,this.classList.toggle("invalid",!e)}get value(){return this.#K}set value(e){this.#K=e,this.progressElement&&(this.progressElement.value=e),100===e&&(this.status="upload-finished"),this.dispatchCustomEvent("FileUpload.Change")}}customElements.define("alchemy-file-upload",Ee);class ke extends HTMLElement{fileCount=0;#Y=[];#Z=d("Cancel all uploads");#ee=null;#x=!1;#te=()=>this.#ie();connectedCallback(){var e,t;this.innerHTML=(e=this.#Z,t=this.fileCount,`\n <sl-progress-bar value="0"></sl-progress-bar>\n <div class="overall-progress-value">\n <span class="value-text"></span>\n\n <sl-tooltip content="${e}">\n <button class="icon_button" aria-label="${e}">\n <alchemy-icon name="close"></alchemy-icon>\n </button>\n </sl-tooltip>\n </div>\n <div class="single-uploads" style="--progress-columns: ${t>3?3:t}"></div>\n <div class="overall-upload-value value-text"></div>\n`),this.visible=!0,this.#ee=this.querySelector("button"),this.#ee.addEventListener("click",()=>{this.finished?this.onComplete(this.status):this.cancel()}),this.#Y.forEach(e=>{this.querySelector(".single-uploads").append(e)}),this.#ie(),this.addEventListener("Alchemy.FileUpload.Change",this.#te)}disconnectedCallback(){this.removeEventListener("Alchemy.FileUpload.Change",this.#te)}initialize(e=[]){this.#Y=e,this.fileCount=e.length}cancel(){this.#se().forEach(e=>{e.cancel()}),this.#ne()}onComplete(e){}#se(){return this.#Y.filter(e=>e.active)}#ne(){this.#Z=d("Close"),this.#ee.ariaLabel=this.#Z,this.#ee.parentElement.content=this.#Z}#oe(e){return this.#se().reduce((t,i)=>i[e]+t,0)}#ie(){const e=this.status;this.className=e,this.progressElement.value=this.totalProgress,this.progressElement.toggleAttribute("indeterminate","upload-finished"===e),this.querySelector(".overall-progress-value > span").textContent=this.overallProgressValue,this.querySelector(".overall-upload-value").textContent=this.overallUploadSize,this.finished?(this.#ne(),this.onComplete(e)):this.visible=!0}get finished(){return this.#se().every(e=>e.finished)}get overallUploadSize(){this.#se().filter(e=>e.value>=100).length;return this.totalProgress,this.#se().length,`${we(this.#oe("progressEventLoaded"))} / ${we(this.#oe("progressEventTotal"))}`}get overallProgressValue(){const e=this.#se().filter(e=>e.value>=100).length;return`${this.totalProgress}% (${e} / ${this.#se().length})`}get progressElement(){return this.querySelector("sl-progress-bar")}get status(){const e=this.#se().map(e=>e.className);return e.includes("failed")?"failed":0===e.length?"canceled":e.every(t=>t===e[0])?e[0]:"in-progress"}get totalProgress(){const e=this.#se().reduce((e,t)=>e+t.file.size,0);let t=Math.ceil(this.#se().reduce((t,i)=>{const s=i.file.size/e;return i.value*s+t},0));return t>100&&(t=100),t}get visible(){return this.#x}set visible(e){this.classList.toggle("visible",e),this.#x=e}}customElements.define("alchemy-upload-progress",ke);class _e extends HTMLElement{#re=null;#le=!1;connectedCallback(){this.fileInput.addEventListener("change",this.#ae),this.dropzone&&this.#ce(),this.addEventListener("Alchemy.upload.successful",this)}disconnectedCallback(){this.fileInput?.removeEventListener("change",this.#ae),this.#re&&(this.#re.removeEventListener("dragleave",this.#de),this.#re.removeEventListener("drop",this.#he),this.#re.removeEventListener("dragover",this.#ue),this.#re=null)}handleEvent(e){if("Alchemy.upload.successful"===e.type)this.#pe()}#ae=e=>{this.uploadFiles(Array.from(e.target.files))};#me=e=>{this.#le!==e&&(this.#le=e,this.#re.classList.toggle("dragover"))};#de=()=>this.#me(!1);#he=async e=>{e.preventDefault(),this.#me(!1);const t=[...e.dataTransfer.items].map(e=>e.getAsFile());this.uploadFiles(t)};#ue=e=>{e.preventDefault(),this.#me(!0)};#pe(){setTimeout(()=>{const e=this.redirectUrl,t=this.closest("turbo-frame");this.uploadProgress.visible=!1,e&&(t?(t.setAttribute("src",e),t.reload()):Turbo.visit(e))},750)}#ce(){this.#re=document.querySelector(this.dropzone),this.#re&&(this.#re.addEventListener("dragleave",this.#de),this.#re.addEventListener("drop",this.#he),this.#re.addEventListener("dragover",this.#ue))}uploadFiles(e){let t=0;const i=e.map(e=>{const i=new XMLHttpRequest,s=new Ee;return s.initialize(e,i),Alchemy.uploader_defaults.upload_limit-1<t?(s.valid=!1,s.errorMessage=d("Maximum number of files exceeded")):s.valid&&(t++,this.#ge(i,e)),s});this.#fe(i)}#ge(e,t){const i=this.querySelector("form"),s=new FormData(i);s.set(this.fileInput.name,t),e.open("POST",i.action),e.setRequestHeader("X-CSRF-Token",X()),e.setRequestHeader("X-Requested-With","XMLHttpRequest"),e.setRequestHeader("Accept","application/json"),e.send(s)}#fe(e){this.uploadProgress&&(this.uploadProgress.cancel(),document.body.removeChild(this.uploadProgress)),this.uploadProgress=new ke,this.uploadProgress.initialize(e),this.uploadProgress.onComplete=e=>{this.dispatchEvent(new CustomEvent(`Alchemy.upload.${e}`,{bubbles:!0}))},document.body.append(this.uploadProgress)}get dropzone(){return this.getAttribute("dropzone")}get fileInput(){return this.querySelector("input[type='file']")}get redirectUrl(){return this.getAttribute("redirect-url")}}customElements.define("alchemy-uploader",_e);class Le extends HTMLElement{connectedCallback(){this.innerHTML=`\n <alchemy-spinner></alchemy-spinner>\n <div id="overlay_text_box">\n <span id="overlay_text">${this.getAttribute("text")??""}</span>\n </div>\n `}set show(e){this.classList.toggle("visible",e)}}customElements.define("alchemy-overlay",Le);const Se="BUTTON";class xe extends HTMLElement{connectedCallback(){this.pageId=this.getAttribute("page-id"),this.folded=this.hasAttribute("folded"),this.folderButton?.addEventListener("click",this)}disconnectedCallback(){this.folderButton?.removeEventListener("click",this)}async handleEvent(e){"click"===e.type&&await this.handleFolderClick(e)}async handleFolderClick(e){e.preventDefault(),e.stopPropagation();const t=e.currentTarget;t.innerHTML="";const i=new f("small");i.spin(t);try{await Z(Alchemy.routes.fold_admin_page_path(this.pageId),null,"text/vnd.turbo-stream.html"),this.folded=!this.folded,this.toggleAttribute("folded",this.folded),this.toggleChildren(),this.updateFolderIcon()}catch(e){O(e.message||e,"error"),this.updateFolderIcon()}finally{i.stop()}}toggleChildren(){const e=this.querySelector(`#page_${this.pageId}_children`);e&&e.classList.toggle("hidden",this.folded)}updateFolderIcon(){if(this.folderButton){const e=this.folded?"arrow-right-s":"arrow-down-s";this.folderButton.innerHTML=`<alchemy-icon name="${e}"></alchemy-icon>`}}updateFolderButton(){const e=this.querySelector(".page_folder");if(!e)return;const t=this.hasChildren||this.folded;if(t&&"SPAN"===e.tagName){const t=this.folded?"arrow-right-s":"arrow-down-s";e.outerHTML=`<button class="page_folder icon_button">\n <alchemy-icon name="${t}"></alchemy-icon>\n </button>`,this.folderButton?.addEventListener("click",this)}else t||e.tagName!==Se?t&&e.tagName===Se&&this.updateFolderIcon():e.outerHTML='<span class="page_folder"></span>'}get hasChildren(){const e=this.querySelector(`#page_${this.pageId}_children`);return!!e&&e.querySelectorAll(":scope > alchemy-page-node").length>0}get folderButton(){return this.querySelector("button.page_folder")}}customElements.define("alchemy-page-node",xe);class Ce extends HTMLElement{connectedCallback(){this.publicField?.addEventListener("click",this.#ve)}disconnectedCallback(){this.publicField?.removeEventListener("click",this.#ve)}#ve=e=>{const t=e.target,i=new Date,s=new Date(i.getTime()-6e4*i.getTimezoneOffset()).toISOString();t.checked?(this.publicationDateFields.classList.remove("hidden"),this.publicOnPicker.value=s.substring(0,s.indexOf("T")+6)):(this.publicationDateFields.classList.add("hidden"),this.publicOnPicker.value=""),this.publicUntilPicker.value=""};get publicField(){return this.querySelector("#page_public")}get publicOnPicker(){return this.querySelector("input#page_public_on")}get publicUntilPicker(){return this.querySelector("input#page_public_until")}get publicationDateFields(){return this.querySelector(".page-publication-date-fields")}}customElements.define("alchemy-page-publication-fields",Ce);customElements.define("alchemy-page-select",class extends P{get pageId(){return this.selection?JSON.parse(this.selection).id:void 0}_searchQuery(e,t){return{q:{name_cont:e,...JSON.parse(this.queryParams)},page:t}}_parseResponse(e){const t=e.meta;return{results:e.pages,more:t.page*t.per_page<t.total_count}}_renderResult(e){return e.text||e.name}_renderListEntry(e,t){return`\n <div class="page-select--page">\n <div class="page-select--top">\n <alchemy-icon name="file-3"></alchemy-icon>\n <span class="page-select--page-name">${this._hightlightTerm(e.name,t)}</span>\n <span class="page-select--site-name">${e.site.name}</span>\n </div>\n <div class="page-select--bottom">\n <span class="page-select--page-urlname">${e.url_path}</span>\n <span class="page-select--language-code">${e.language_code}</span>\n </div>\n </div>\n `}});class Ae extends HTMLElement{connectedCallback(){this.addEventListener("change",this)}disconnectedCallback(){this.removeEventListener("change",this)}handleEvent(e){if("change"===e.type)this.onChange()}onChange(){const e=new URL(this.getAttribute("url")),t=this.querySelector("select");e.searchParams.set("language_id",t.value),Turbo.visit(e,{frame:"picture_descriptions"})}}customElements.define("alchemy-picture-description-select",Ae);class Te extends HTMLElement{connectedCallback(){this.cropFromField=this.querySelector("[data-crop-from]"),this.cropSizeField=this.querySelector("[data-crop-size]"),this.pictureIdField=this.querySelector("[data-picture-id]"),this.targetSizeField=this.querySelector("[data-target-size]"),this.imageCropperField=this.querySelector("[data-image-cropper]"),this.image=this.querySelector("img"),this.pictureThumbnail=this.querySelector("alchemy-picture-thumbnail"),this.deleteButton=this.querySelector(".picture_tool.delete"),this.cropLink=this.querySelector(".crop_link"),this.targetSize=this.targetSizeField.dataset.targetSize,this.pictureId=this.pictureIdField.value,this.update=function(e,t){let i;return function(...s){const n=this;clearTimeout(i),i=setTimeout(()=>e.apply(n,s),t)}}(()=>{this.updateImage(),this.updateCropLink()},125),this.deleteButton?.addEventListener("click",this.removeImage),this.observer=new MutationObserver(this.mutationCallback),this.observer.observe(this.cropFromField,{attributes:!0}),this.observer.observe(this.cropSizeField,{attributes:!0}),this.observer.observe(this.pictureIdField,{attributes:!0})}disconnectedCallback(){this.observer.disconnect()}mutationCallback=e=>{for(const t of e)"pictureId"in t.target.dataset&&(this.cropFromField.value="",this.cropSizeField.value="",this.pictureId=t.target.value),this.update()};updateImage(){this.pictureId&&(this.pictureThumbnail.loading=!0,Y(Alchemy.routes.url_admin_picture_path(this.pictureId),{crop:this.imageCropperEnabled,crop_from:this.cropFrom,crop_size:this.cropSize,flatten:!0,size:"160x120"}).then(({data:e})=>{this.pictureThumbnail.src=e.url,this.pictureThumbnail.image.alt=e.alt,this.pictureThumbnail.image.title=e.title,this.setElementDirty()}).catch(e=>{console.error(e.message||e),O(e.message||e,"error")}))}removeImage=()=>{this.pictureThumbnail.innerHTML='<alchemy-icon name="image" size="xl"></alchemy-icon>',this.pictureIdField.value="",this.image=null,this.cropLink.classList.add("disabled"),this.setElementDirty()};setElementDirty(){this.closest(".element-editor").setDirty(this)}updateCropLink(){this.pictureId&&this.imageCropperEnabled&&(this.cropLink.classList.remove("disabled"),this.cropLink.href.match(/(picture_id=)\d+/)?this.cropLink.href=this.cropLink.href.replace(/(picture_id=)\d+/,"$1"+this.pictureId):this.cropLink.href=this.cropLink.href+`&picture_id=${this.pictureId}`)}get cropFrom(){return""===this.cropFromField.value?this.defaultCropFrom.join("x"):this.cropFromField.value}get cropSize(){return""===this.cropSizeField.value?this.defaultCropSize.join("x"):this.cropSizeField.value}get defaultCropSize(){if(!this.imageCropperEnabled)return[];const e=this.targetSize.split("x").map(e=>parseInt(e)),t=(i=e[0]/this.imageFileWidth,s=e[1]/this.imageFileHeight,i>=s?i:s);var i,s;return[Math.round(e[0]/t),Math.round(e[1]/t)]}get defaultCropFrom(){if(!this.imageCropperEnabled)return[];const e=this.defaultCropSize;return[Math.round((this.imageFileWidth-e[0])/2),Math.round((this.imageFileHeight-e[1])/2)]}get imageFileWidth(){return parseInt(this.pictureIdField.dataset.imageFileWidth)}get imageFileHeight(){return parseInt(this.pictureIdField.dataset.imageFileHeight)}get imageCropperEnabled(){return"true"===this.targetSizeField.dataset.imageCropper}}customElements.define("alchemy-picture-editor",Te);class Oe extends HTMLElement{constructor(){super(),this.spinner=new f("small")}handleEvent(e){switch(e.type){case"load":this.#ye();break;case"error":this.#be(e)}}connectedCallback(){this.classList.add("thumbnail_background"),this.src&&!this.image&&this.start(),this.#we()}disconnectedCallback(){this.image?.removeEventListener("load",this),this.image?.removeEventListener("error",this),this.stop()}createImage(e=this.src,t=this.name){this.image=new Image,this.image.src=e,t&&(this.image.alt=t)}start(e){this.createImage(e),this.image.addEventListener("load",this),this.image.addEventListener("error",this),this.load()}load(){this.image?.complete||(this.setAttribute("loading","loading"),this.innerHTML="",this.spinner.spin(this))}stop(){this.classList.remove("loading"),this.spinner.stop()}#ye(){this.spinner.stop(),this.removeAttribute("loading")}#be(e){const t=`Could not load ${this.image.src}`,i=this.closest(".ingredient-editor");this.spinner.stop(),this.innerHTML=`\n <sl-tooltip content="${t}" ${i?"hoist":""}>\n <alchemy-icon name="alert" class="error"></alchemy-icon>\n </sl-tooltip>\n `,console.error(t,e)}#we(){this.image?.complete?this.replaceChildren(this.image):this.image&&this.append(this.image)}set loading(e){e?this.load():this.stop()}set src(e){this.start(e),this.#we()}get name(){return this.getAttribute("name")}get src(){return this.getAttribute("src")}}customElements.define("alchemy-picture-thumbnail",Oe);class Ie extends HTMLElement{connectedCallback(){this.addEventListener("submit",this),document.addEventListener("alchemy:page-dirty",this)}disconnectedCallback(){this.removeEventListener("submit",this),document.removeEventListener("alchemy:page-dirty",this)}handleEvent(e){switch(e.type){case"alchemy:page-dirty":this.markDirty(e.detail);break;case"submit":this.button.loading=!0}}markDirty(e){this.button.variant="primary",this.button.disabled=!1,this.tooltip.content=e.tooltip}get button(){return this.querySelector("sl-button")}get tooltip(){return this.querySelector("sl-tooltip")}}function Fe(e,t){e.split(/\s+/).forEach(e=>{t(e)})}customElements.define("alchemy-publish-page-button",Ie);class $e{constructor(){this._events={}}on(e,t){Fe(e,e=>{const i=this._events[e]||[];i.push(t),this._events[e]=i})}off(e,t){var i=arguments.length;0!==i?Fe(e,e=>{if(1===i)return void delete this._events[e];const s=this._events[e];void 0!==s&&(s.splice(s.indexOf(t),1),this._events[e]=s)}):this._events={}}trigger(e,...t){var i=this;Fe(e,e=>{const s=i._events[e];void 0!==s&&s.forEach(e=>{e.apply(i,t)})})}}const qe=e=>(e=e.filter(Boolean)).length<2?e[0]||"":1==ze(e)?"["+e.join("")+"]":"(?:"+e.join("|")+")",De=e=>{if(!Be(e))return e.join("");let t="",i=0;const s=()=>{i>1&&(t+="{"+i+"}")};return e.forEach((n,o)=>{n!==e[o-1]?(s(),t+=n,i=1):i++}),s(),t},Me=e=>{let t=Array.from(e);return qe(t)},Be=e=>new Set(e).size!==e.length,Pe=e=>(e+"").replace(/([\$\(\)\*\+\.\?\[\]\^\{\|\}\\])/gu,"\\$1"),ze=e=>e.reduce((e,t)=>Math.max(e,He(t)),0),He=e=>Array.from(e).length,Re=e=>{if(1===e.length)return[[e]];let t=[];const i=e.substring(1);return Re(i).forEach(function(i){let s=i.slice(0);s[0]=e.charAt(0)+s[0],t.push(s),s=i.slice(0),s.unshift(e.charAt(0)),t.push(s)}),t},Ne=[[0,65535]];let je,Ve;const We={},Ue={"/":"⁄∕",0:"߀",a:"ⱥɐɑ",aa:"ꜳ",ae:"æǽǣ",ao:"ꜵ",au:"ꜷ",av:"ꜹꜻ",ay:"ꜽ",b:"ƀɓƃ",c:"ꜿƈȼↄ",d:"đɗɖᴅƌꮷԁɦ",e:"ɛǝᴇɇ",f:"ꝼƒ",g:"ǥɠꞡᵹꝿɢ",h:"ħⱨⱶɥ",i:"ɨı",j:"ɉȷ",k:"ƙⱪꝁꝃꝅꞣ",l:"łƚɫⱡꝉꝇꞁɭ",m:"ɱɯϻ",n:"ꞥƞɲꞑᴎлԉ",o:"øǿɔɵꝋꝍᴑ",oe:"œ",oi:"ƣ",oo:"ꝏ",ou:"ȣ",p:"ƥᵽꝑꝓꝕρ",q:"ꝗꝙɋ",r:"ɍɽꝛꞧꞃ",s:"ßȿꞩꞅʂ",t:"ŧƭʈⱦꞇ",th:"þ",tz:"ꜩ",u:"ʉ",v:"ʋꝟʌ",vy:"ꝡ",w:"ⱳ",y:"ƴɏỿ",z:"ƶȥɀⱬꝣ",hv:"ƕ"};for(let e in Ue){let t=Ue[e]||"";for(let i=0;i<t.length;i++){let s=t.substring(i,i+1);We[s]=e}}const Ke=new RegExp(Object.keys(We).join("|")+"|[̀-ͯ·ʾʼ]","gu"),Je=(e,t="NFKD")=>e.normalize(t),Ge=e=>Array.from(e).reduce((e,t)=>e+Qe(t),""),Qe=e=>(e=Je(e).toLowerCase().replace(Ke,e=>We[e]||""),Je(e,"NFC"));const Xe=e=>{const t={},i=(e,i)=>{const s=t[e]||new Set,n=new RegExp("^"+Me(s)+"$","iu");i.match(n)||(s.add(Pe(i)),t[e]=s)};for(let t of function*(e){for(const[t,i]of e)for(let e=t;e<=i;e++){let t=String.fromCharCode(e),i=Ge(t);i!=t.toLowerCase()&&(i.length>3||0!=i.length&&(yield{folded:i,composed:t,code_point:e}))}}(e))i(t.folded,t.folded),i(t.folded,t.composed);return t},Ye=e=>{const t=Xe(e),i={};let s=[];for(let e in t){let n=t[e];n&&(i[e]=Me(n)),e.length>1&&s.push(Pe(e))}s.sort((e,t)=>t.length-e.length);const n=qe(s);return Ve=new RegExp("^"+n,"u"),i},Ze=(e,t=1)=>(t=Math.max(t,e.length-1),qe(Re(e).map(e=>((e,t=1)=>{let i=0;return e=e.map(e=>(je[e]&&(i+=e.length),je[e]||e)),i>=t?De(e):""})(e,t)))),et=(e,t=!0)=>{let i=e.length>1?1:0;return qe(e.map(e=>{let s=[];const n=t?e.length():e.length()-1;for(let t=0;t<n;t++)s.push(Ze(e.substrs[t]||"",i));return De(s)}))},tt=(e,t)=>{for(const i of t){if(i.start!=e.start||i.end!=e.end)continue;if(i.substrs.join("")!==e.substrs.join(""))continue;let t=e.parts;const s=e=>{for(const i of t){if(i.start===e.start&&i.substr===e.substr)return!1;if(1!=e.length&&1!=i.length){if(e.start<i.start&&e.end>i.start)return!0;if(i.start<e.start&&i.end>e.start)return!0}}return!1};if(!(i.parts.filter(s).length>0))return!0}return!1};class it{parts;substrs;start;end;constructor(){this.parts=[],this.substrs=[],this.start=0,this.end=0}add(e){e&&(this.parts.push(e),this.substrs.push(e.substr),this.start=Math.min(e.start,this.start),this.end=Math.max(e.end,this.end))}last(){return this.parts[this.parts.length-1]}length(){return this.parts.length}clone(e,t){let i=new it,s=JSON.parse(JSON.stringify(this.parts)),n=s.pop();for(const e of s)i.add(e);let o=t.substr.substring(0,e-n.start),r=o.length;return i.add({start:n.start,end:n.start+r,length:r,substr:o}),i}}const st=e=>{void 0===je&&(je=Ye(Ne)),e=Ge(e);let t="",i=[new it];for(let s=0;s<e.length;s++){let n=e.substring(s).match(Ve);const o=e.substring(s,s+1),r=n?n[0]:null;let l=[],a=new Set;for(const e of i){const t=e.last();if(!t||1==t.length||t.end<=s)if(r){const t=r.length;e.add({start:s,end:s+t,length:t,substr:r}),a.add("1")}else e.add({start:s,end:s+1,length:1,substr:o}),a.add("2");else if(r){let i=e.clone(s,t);const n=r.length;i.add({start:s,end:s+n,length:n,substr:r}),l.push(i)}else a.add("3")}if(l.length>0){l=l.sort((e,t)=>e.length()-t.length());for(let e of l)tt(e,i)||i.push(e)}else if(s>0&&1==a.size&&!a.has("3")){t+=et(i,!1);let e=new it;const s=i[0];s&&e.add(s.last()),i=[e]}}return t+=et(i,!0),t},nt=(e,t)=>{if(e)return e[t]},ot=(e,t)=>{if(e){for(var i,s=t.split(".");(i=s.shift())&&(e=e[i]););return e}},rt=(e,t,i)=>{var s,n;return e?(e+="",null==t.regex||-1===(n=e.search(t.regex))?0:(s=t.string.length/e.length,0===n&&(s+=.5),s*i)):0},lt=(e,t)=>{var i=e[t];if("function"==typeof i)return i;i&&!Array.isArray(i)&&(e[t]=[i])},at=(e,t)=>{if(Array.isArray(e))e.forEach(t);else for(var i in e)e.hasOwnProperty(i)&&t(e[i],i)},ct=(e,t)=>"number"==typeof e&&"number"==typeof t?e>t?1:e<t?-1:0:(e=Ge(e+"").toLowerCase())>(t=Ge(t+"").toLowerCase())?1:t>e?-1:0;class dt{items;settings;constructor(e,t){this.items=e,this.settings=t||{diacritics:!0}}tokenize(e,t,i){if(!e||!e.length)return[];const s=[],n=e.split(/\s+/);var o;return i&&(o=new RegExp("^("+Object.keys(i).map(Pe).join("|")+"):(.*)$")),n.forEach(e=>{let i,n=null,r=null;o&&(i=e.match(o))&&(n=i[1],e=i[2]),e.length>0&&(r=this.settings.diacritics?st(e)||null:Pe(e),r&&t&&(r="\\b"+r)),s.push({string:e,regex:r?new RegExp(r,"iu"):null,field:n})}),s}getScoreFunction(e,t){var i=this.prepareSearch(e,t);return this._getScoreFunction(i)}_getScoreFunction(e){const t=e.tokens,i=t.length;if(!i)return function(){return 0};const s=e.options.fields,n=e.weights,o=s.length,r=e.getAttrFn;if(!o)return function(){return 1};const l=1===o?function(e,t){const i=s[0].field;return rt(r(t,i),e,n[i]||1)}:function(e,t){var i=0;if(e.field){const s=r(t,e.field);!e.regex&&s?i+=1/o:i+=rt(s,e,1)}else at(n,(s,n)=>{i+=rt(r(t,n),e,s)});return i/o};return 1===i?function(e){return l(t[0],e)}:"and"===e.options.conjunction?function(e){var s,n=0;for(let i of t){if((s=l(i,e))<=0)return 0;n+=s}return n/i}:function(e){var s=0;return at(t,t=>{s+=l(t,e)}),s/i}}getSortFunction(e,t){var i=this.prepareSearch(e,t);return this._getSortFunction(i)}_getSortFunction(e){var t,i=[];const s=this,n=e.options,o=!e.query&&n.sort_empty?n.sort_empty:n.sort;if("function"==typeof o)return o.bind(this);const r=function(t,i){return"$score"===t?i.score:e.getAttrFn(s.items[i.id],t)};if(o)for(let t of o)(e.query||"$score"!==t.field)&&i.push(t);if(e.query){t=!0;for(let e of i)if("$score"===e.field){t=!1;break}t&&i.unshift({field:"$score",direction:"desc"})}else i=i.filter(e=>"$score"!==e.field);return i.length?function(e,t){var s,n;for(let o of i){if(n=o.field,s=("desc"===o.direction?-1:1)*ct(r(n,e),r(n,t)))return s}return 0}:null}prepareSearch(e,t){const i={};var s=Object.assign({},t);if(lt(s,"sort"),lt(s,"sort_empty"),s.fields){lt(s,"fields");const e=[];s.fields.forEach(t=>{"string"==typeof t&&(t={field:t,weight:1}),e.push(t),i[t.field]="weight"in t?t.weight:1}),s.fields=e}return{options:s,query:e.toLowerCase().trim(),tokens:this.tokenize(e,s.respect_word_boundaries,i),total:0,items:[],weights:i,getAttrFn:s.nesting?ot:nt}}search(e,t){var i,s,n=this;s=this.prepareSearch(e,t),t=s.options,e=s.query;const o=t.score||n._getScoreFunction(s);e.length?at(n.items,(e,n)=>{i=o(e),(!1===t.filter||i>0)&&s.items.push({score:i,id:n})}):at(n.items,(e,t)=>{s.items.push({score:1,id:t})});const r=n._getSortFunction(s);return r&&s.items.sort(r),s.total=s.items.length,"number"==typeof t.limit&&(s.items=s.items.slice(0,t.limit)),s}}const ht=e=>null==e?null:ut(e),ut=e=>"boolean"==typeof e?e?"1":"0":e+"",pt=e=>(e+"").replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,"""),mt=(e,t)=>{var i;return function(s,n){var o=this;i&&(o.loading=Math.max(o.loading-1,0),clearTimeout(i)),i=setTimeout(function(){i=null,o.loadedSearches[s]=!0,e.call(o,s,n)},t)}},gt=(e,t,i)=>{var s,n=e.trigger,o={};for(s of(e.trigger=function(){var i=arguments[0];if(-1===t.indexOf(i))return n.apply(e,arguments);o[i]=arguments},i.apply(e,[]),e.trigger=n,t))s in o&&n.apply(e,o[s])},ft=(e,t=!1)=>{e&&(e.preventDefault(),t&&e.stopPropagation())},vt=(e,t,i,s)=>{e.addEventListener(t,i,s)},yt=(e,t)=>!!t&&(!!t[e]&&1===(t.altKey?1:0)+(t.ctrlKey?1:0)+(t.shiftKey?1:0)+(t.metaKey?1:0)),bt=(e,t)=>{const i=e.getAttribute("id");return i||(e.setAttribute("id",t),t)},wt=e=>e.replace(/[\\"']/g,"\\$&"),Et=(e,t)=>{t&&e.append(t)},kt=(e,t)=>{if(Array.isArray(e))e.forEach(t);else for(var i in e)e.hasOwnProperty(i)&&t(e[i],i)},_t=e=>{if(e.jquery)return e[0];if(e instanceof HTMLElement)return e;if(Lt(e)){var t=document.createElement("template");return t.innerHTML=e.trim(),t.content.firstChild}return document.querySelector(e)},Lt=e=>"string"==typeof e&&e.indexOf("<")>-1,St=(e,t)=>{var i=document.createEvent("HTMLEvents");i.initEvent(t,!0,!1),e.dispatchEvent(i)},xt=(e,t)=>{Object.assign(e.style,t)},Ct=(e,...t)=>{var i=Tt(t);(e=Ot(e)).map(e=>{i.map(t=>{e.classList.add(t)})})},At=(e,...t)=>{var i=Tt(t);(e=Ot(e)).map(e=>{i.map(t=>{e.classList.remove(t)})})},Tt=e=>{var t=[];return kt(e,e=>{"string"==typeof e&&(e=e.trim().split(/[\t\n\f\r\s]/)),Array.isArray(e)&&(t=t.concat(e))}),t.filter(Boolean)},Ot=e=>(Array.isArray(e)||(e=[e]),e),It=(e,t,i)=>{if(!i||i.contains(e))for(;e&&e.matches;){if(e.matches(t))return e;e=e.parentNode}},Ft=(e,t=0)=>t>0?e[e.length-1]:e[0],$t=(e,t)=>{if(!e)return-1;t=t||e.nodeName;for(var i=0;e=e.previousElementSibling;)e.matches(t)&&i++;return i},qt=(e,t)=>{kt(t,(t,i)=>{null==t?e.removeAttribute(i):e.setAttribute(i,""+t)})},Dt=(e,t)=>{e.parentNode&&e.parentNode.replaceChild(t,e)},Mt=(e,t)=>{if(null===t)return;if("string"==typeof t){if(!t.length)return;t=new RegExp(t,"i")}const i=e=>3===e.nodeType?(e=>{var i=e.data.match(t);if(i&&e.data.length>0){var s=document.createElement("span");s.className="highlight";var n=e.splitText(i.index);n.splitText(i[0].length);var o=n.cloneNode(!0);return s.appendChild(o),Dt(n,s),1}return 0})(e):((e=>{1!==e.nodeType||!e.childNodes||/(script|style)/i.test(e.tagName)||"highlight"===e.className&&"SPAN"===e.tagName||Array.from(e.childNodes).forEach(e=>{i(e)})})(e),0);i(e)},Bt="undefined"!=typeof navigator&&/Mac/.test(navigator.userAgent)?"metaKey":"ctrlKey";var Pt={options:[],optgroups:[],plugins:[],delimiter:",",splitOn:null,persist:!0,diacritics:!0,create:null,createOnBlur:!1,createFilter:null,clearAfterSelect:!1,highlight:!0,openOnFocus:!0,shouldOpen:null,maxOptions:50,maxItems:null,hideSelected:null,duplicates:!1,addPrecedence:!1,selectOnTab:!1,preload:null,allowEmptyOption:!1,refreshThrottle:300,loadThrottle:300,loadingClass:"loading",dataAttr:null,optgroupField:"optgroup",valueField:"value",labelField:"text",disabledField:"disabled",optgroupLabelField:"label",optgroupValueField:"value",lockOptgroupOrder:!1,sortField:"$order",searchField:["text"],searchConjunction:"and",mode:null,wrapperClass:"ts-wrapper",controlClass:"ts-control",dropdownClass:"ts-dropdown",dropdownContentClass:"ts-dropdown-content",itemClass:"item",optionClass:"option",dropdownParent:null,controlInput:'<input type="text" autocomplete="off" size="1" />',copyClassesToDropdown:!1,placeholder:null,hidePlaceholder:null,shouldLoad:function(e){return e.length>0},render:{}};function zt(e,t){var i=Object.assign({},Pt,t),s=i.dataAttr,n=i.labelField,o=i.valueField,r=i.disabledField,l=i.optgroupField,a=i.optgroupLabelField,c=i.optgroupValueField,d=e.tagName.toLowerCase(),h=e.getAttribute("placeholder")||e.getAttribute("data-placeholder");if(!h&&!i.allowEmptyOption){let t=e.querySelector('option[value=""]');t&&(h=t.textContent)}var u={placeholder:h,options:[],optgroups:[],items:[],maxItems:null};return"select"===d?(()=>{var t,d=u.options,h={},p=1;let m=0;var g=e=>{var t=Object.assign({},e.dataset),i=s&&t[s];return"string"==typeof i&&i.length&&(t=Object.assign(t,JSON.parse(i))),t},f=(e,t)=>{var s=ht(e.value);if(null!=s&&(s||i.allowEmptyOption)){if(h.hasOwnProperty(s)){if(t){var a=h[s][l];a?Array.isArray(a)?a.push(t):h[s][l]=[a,t]:h[s][l]=t}}else{var c=g(e);c[n]=c[n]||e.textContent,c[o]=c[o]||s,c[r]=c[r]||e.disabled,c[l]=c[l]||t,c.$option=e,c.$order=c.$order||++m,h[s]=c,d.push(c)}e.selected&&u.items.push(s)}};u.maxItems=e.hasAttribute("multiple")?null:1,kt(e.children,e=>{var i,s,n;"optgroup"===(t=e.tagName.toLowerCase())?((n=g(i=e))[a]=n[a]||i.getAttribute("label")||"",n[c]=n[c]||p++,n[r]=n[r]||i.disabled,n.$order=n.$order||++m,u.optgroups.push(n),s=n[c],kt(i.children,e=>{f(e,s)})):"option"===t&&f(e)})})():(()=>{var t,r;const l=e.getAttribute(s);if(l)u.options=JSON.parse(l),kt(u.options,e=>{u.items.push(e[o])});else{var a=null!==(r=null===(t=null==e?void 0:e.value)||void 0===t?void 0:t.trim())&&void 0!==r?r:"";if(!i.allowEmptyOption&&!a.length)return;const s=a.split(i.delimiter);kt(s,e=>{const t={};t[n]=e,t[o]=e,u.options.push(t)}),u.items=s}})(),Object.assign({},Pt,u,t)}var Ht=0;class Rt extends(function(e){return e.plugins={},class extends e{constructor(){super(...arguments),this.plugins={names:[],settings:{},requested:{},loaded:{}}}static define(t,i){e.plugins[t]={name:t,fn:i}}initializePlugins(e){var t,i;const s=this,n=[];if(Array.isArray(e))e.forEach(e=>{"string"==typeof e?n.push(e):(s.plugins.settings[e.name]=e.options,n.push(e.name))});else if(e)for(t in e)e.hasOwnProperty(t)&&(s.plugins.settings[t]=e[t],n.push(t));for(;i=n.shift();)s.require(i)}loadPlugin(t){var i=this,s=i.plugins,n=e.plugins[t];if(!e.plugins.hasOwnProperty(t))throw new Error('Unable to find "'+t+'" plugin');s.requested[t]=!0,s.loaded[t]=n.fn.apply(i,[i.plugins.settings[t]||{}]),s.names.push(t)}require(e){var t=this,i=t.plugins;if(!t.plugins.loaded.hasOwnProperty(e)){if(i.requested[e])throw new Error('Plugin has circular dependency ("'+e+'")');t.loadPlugin(e)}return i.loaded[e]}}}($e)){constructor(e,t){var i;super(),this.order=0,this.isOpen=!1,this.isDisabled=!1,this.isReadOnly=!1,this.isInvalid=!1,this.isValid=!0,this.isLocked=!1,this.isFocused=!1,this.isInputHidden=!1,this.isSetup=!1,this.isDropdownContentStale=!0,this.ignoreFocus=!1,this.ignoreHover=!1,this.hasOptions=!1,this.lastValue="",this.caretPos=0,this.loading=0,this.loadedSearches={},this.activeOption=null,this.activeItems=[],this.optgroups={},this.options={},this.userOptions={},this.items=[],this.refreshTimeout=null,Ht++;var s=_t(e);if(s.tomselect)throw new Error("Tom Select already initialized on this element");s.tomselect=this,i=(window.getComputedStyle&&window.getComputedStyle(s,null)).getPropertyValue("direction");const n=zt(s,t);this.settings=n,this.input=s,this.tabIndex=s.tabIndex||0,this.is_select_tag="select"===s.tagName.toLowerCase(),this.rtl=/rtl/i.test(i),this.inputId=bt(s,"tomselect-"+Ht),this.isRequired=s.required,this.sifter=new dt(this.options,{diacritics:n.diacritics}),n.mode=n.mode||(1===n.maxItems?"single":"multi"),"boolean"!=typeof n.hideSelected&&(n.hideSelected="multi"===n.mode),"boolean"!=typeof n.hidePlaceholder&&(n.hidePlaceholder="multi"!==n.mode);var o=n.createFilter;"function"!=typeof o&&("string"==typeof o&&(o=new RegExp(o)),o instanceof RegExp?n.createFilter=e=>o.test(e):n.createFilter=e=>this.settings.duplicates||!this.options[e]),this.initializePlugins(n.plugins),this.setupCallbacks(),this.setupTemplates();const r=_t("<div>"),l=_t("<div>"),a=this._render("dropdown"),c=_t('<div role="listbox" tabindex="-1">'),d=this.input.getAttribute("class")||"",h=n.mode;var u;if(Ct(r,n.wrapperClass,d,h),Ct(l,n.controlClass),Et(r,l),Ct(a,n.dropdownClass,h),n.copyClassesToDropdown&&Ct(a,d),Ct(c,n.dropdownContentClass),Et(a,c),_t(n.dropdownParent||r).appendChild(a),Lt(n.controlInput)){u=_t(n.controlInput);kt(["autocorrect","autocapitalize","autocomplete","spellcheck","aria-label"],e=>{s.getAttribute(e)&&qt(u,{[e]:s.getAttribute(e)})}),u.tabIndex=-1,l.appendChild(u),this.focus_node=u}else n.controlInput?(u=_t(n.controlInput),this.focus_node=u):(u=_t("<input/>"),this.focus_node=l);this.wrapper=r,this.dropdown=a,this.dropdown_content=c,this.control=l,this.control_input=u,this.setup()}setup(){const e=this,t=e.settings,i=e.control_input,s=e.dropdown,n=e.dropdown_content,o=e.wrapper,r=e.control,l=e.input,a=e.focus_node,c={passive:!0},d=e.inputId+"-ts-dropdown";qt(n,{id:d}),qt(a,{role:"combobox","aria-haspopup":"listbox","aria-expanded":"false","aria-controls":d});const h=bt(a,e.inputId+"-ts-control"),u="label[for='"+(e=>e.replace(/['"\\]/g,"\\$&"))(e.inputId)+"']",p=document.querySelector(u),m=e.focus.bind(e);if(p){vt(p,"click",m),qt(p,{for:h});const t=bt(p,e.inputId+"-ts-label");qt(a,{"aria-labelledby":t}),qt(n,{"aria-labelledby":t})}if(o.style.width=l.style.width,o.style.minWidth=l.style.minWidth,o.style.maxWidth=l.style.maxWidth,e.plugins.names.length){const t="plugin-"+e.plugins.names.join(" plugin-");Ct([o,s],t)}(null===t.maxItems||t.maxItems>1)&&e.is_select_tag&&qt(l,{multiple:"multiple"}),t.placeholder&&qt(i,{placeholder:t.placeholder}),!t.splitOn&&t.delimiter&&(t.splitOn=new RegExp("\\s*"+Pe(t.delimiter)+"+\\s*")),t.load&&t.loadThrottle&&(t.load=mt(t.load,t.loadThrottle)),vt(s,"mousemove",()=>{e.ignoreHover=!1}),vt(s,"mouseenter",t=>{var i=It(t.target,"[data-selectable]",s);i&&e.onOptionHover(t,i)},{capture:!0}),vt(s,"click",t=>{const i=It(t.target,"[data-selectable]");i&&(e.onOptionSelect(t,i),ft(t,!0))}),vt(r,"click",t=>{var s=It(t.target,"[data-ts-item]",r);s&&e.onItemSelect(t,s)?ft(t,!0):""==i.value&&(e.onClick(),ft(t,!0))}),vt(a,"keydown",t=>e.onKeyDown(t)),vt(i,"keypress",t=>e.onKeyPress(t)),vt(i,"input",t=>e.onInput(t)),vt(a,"blur",t=>e.onBlur(t)),vt(a,"focus",t=>e.onFocus(t)),vt(i,"paste",t=>e.onPaste(t));const g=t=>{const n=t.composedPath()[0];if(!o.contains(n)&&!s.contains(n))return e.isFocused&&e.blur(),void e.inputState();n==i&&e.isOpen?t.stopPropagation():ft(t,!0)},f=()=>{e.isOpen&&e.positionDropdown()},v=()=>{e.isValid&&(e.isValid=!1,e.isInvalid=!0,e.refreshState())};vt(l,"invalid",v),vt(document,"mousedown",g),vt(window,"scroll",f,c),vt(window,"resize",f,c),this._destroy=()=>{l.removeEventListener("invalid",v),document.removeEventListener("mousedown",g),window.removeEventListener("scroll",f),window.removeEventListener("resize",f),p&&p.removeEventListener("click",m)},this.revertSettings={innerHTML:l.innerHTML,tabIndex:l.tabIndex},l.tabIndex=-1,l.insertAdjacentElement("afterend",e.wrapper),e.sync(!1),t.items=[],delete t.optgroups,delete t.options,e.refreshItems(),e.close(!1),e.inputState(),e.isSetup=!0,e.on("change",this.onChange),Ct(l,"tomselected","ts-hidden-accessible"),e.trigger("initialize"),!0===t.preload&&e.preload()}setupOptions(e=[],t=[]){this.addOptions(e),kt(t,e=>{this.registerOptionGroup(e)})}setupTemplates(){var e=this,t=e.settings.labelField,i=e.settings.optgroupLabelField,s={optgroup:e=>{let t=document.createElement("div");return t.className="optgroup",t.appendChild(e.options),t},optgroup_header:(e,t)=>'<div class="optgroup-header">'+t(e[i])+"</div>",option:(e,i)=>"<div>"+i(e[t])+"</div>",item:(e,i)=>"<div>"+i(e[t])+"</div>",option_create:(e,t)=>'<div class="create">Add <strong>'+t(e.input)+"</strong>…</div>",no_results:()=>'<div class="no-results">No results found</div>',loading:()=>'<div class="spinner"></div>',not_loading:()=>{},dropdown:()=>"<div></div>"};e.settings.render=Object.assign({},s,e.settings.render)}setupCallbacks(){var e,t,i={initialize:"onInitialize",change:"onChange",item_add:"onItemAdd",item_remove:"onItemRemove",item_select:"onItemSelect",clear:"onClear",option_add:"onOptionAdd",option_remove:"onOptionRemove",option_clear:"onOptionClear",optgroup_add:"onOptionGroupAdd",optgroup_remove:"onOptionGroupRemove",optgroup_clear:"onOptionGroupClear",dropdown_open:"onDropdownOpen",dropdown_close:"onDropdownClose",type:"onType",load:"onLoad",focus:"onFocus",blur:"onBlur"};for(e in i)(t=this.settings[i[e]])&&this.on(e,t)}sync(e=!0){const t=this,i=e?zt(t.input,{delimiter:t.settings.delimiter,allowEmptyOption:t.settings.allowEmptyOption}):t.settings;t.setupOptions(i.options,i.optgroups),t.setValue(i.items||[],!0),t.input.disabled?t.disable():t.input.readOnly?t.setReadOnly(!0):t.enable(),t.lastQuery=null}onClick(){var e=this;if(e.activeItems.length>0)return e.clearActiveItems(),void e.focus();e.isFocused&&e.isOpen?e.blur():e.focus()}onMouseDown(){}onChange(){St(this.input,"input"),St(this.input,"change")}onPaste(e){var t=this;t.isInputHidden||t.isLocked?ft(e):t.settings.splitOn&&setTimeout(()=>{var e=t.inputValue();if(e.match(t.settings.splitOn)){var i=e.trim().split(t.settings.splitOn);kt(i,e=>{ht(e)&&(this.options[e]?t.addItem(e):t.createItem(e))})}},0)}onKeyPress(e){var t=this;if(!t.isLocked){var i=String.fromCharCode(e.keyCode||e.which);return t.settings.create&&"multi"===t.settings.mode&&i===t.settings.delimiter?(t.createItem(),void ft(e)):void 0}ft(e)}onKeyDown(e){var t=this;if(t.ignoreHover=!0,t.isLocked)9!==e.keyCode&&ft(e);else{switch(e.keyCode){case 65:if(yt(Bt,e)&&""==t.control_input.value)return ft(e),void t.selectAll();break;case 27:return t.isOpen&&(ft(e,!0),t.close()),void t.clearActiveItems();case 40:if(!t.isOpen&&t.hasOptions)t.open();else if(t.activeOption){let e=t.getAdjacent(t.activeOption,1);e&&t.setActiveOption(e)}return void ft(e);case 38:if(t.activeOption){let e=t.getAdjacent(t.activeOption,-1);e&&t.setActiveOption(e)}return void ft(e);case 13:return void(t.canSelect(t.activeOption)?(t.onOptionSelect(e,t.activeOption),ft(e)):(t.settings.create&&t.createItem()||document.activeElement==t.control_input&&t.isOpen)&&ft(e));case 37:return void t.advanceSelection(-1,e);case 39:return void t.advanceSelection(1,e);case 9:return void(t.settings.selectOnTab&&(t.canSelect(t.activeOption)?(t.onOptionSelect(e,t.activeOption),ft(e)):t.settings.create&&t.createItem()&&ft(e)));case 8:case 46:return void t.deleteSelection(e)}t.isInputHidden&&!yt(Bt,e)&&ft(e)}}onInput(e){if(this.isLocked)return;const t=this.inputValue();this.lastValue!==t&&(this.lastValue=t,""!=t?(this.refreshTimeout&&window.clearTimeout(this.refreshTimeout),this.refreshTimeout=((e,t)=>t>0?window.setTimeout(e,t):(e.call(null),null))(()=>{this.refreshTimeout=null,this._onInput()},this.settings.refreshThrottle)):this._onInput())}_onInput(){const e=this.lastValue;this.settings.shouldLoad.call(this,e)&&this.load(e),this.refreshOptions(),this.trigger("type",e)}onOptionHover(e,t){this.ignoreHover||this.setActiveOption(t,!1)}onFocus(e){var t=this,i=t.isFocused;if(t.isDisabled||t.isReadOnly)return t.blur(),void ft(e);t.ignoreFocus||(t.isFocused=!0,"focus"===t.settings.preload&&t.preload(),i||t.trigger("focus"),t.activeItems.length||(t.inputState(),t.refreshOptions(!!t.settings.openOnFocus)),t.refreshState())}onBlur(e){if(!1!==document.hasFocus()){var t=this;if(t.isFocused){t.isFocused=!1,t.ignoreFocus=!1;var i=()=>{t.close(),t.setActiveItem(),t.setCaret(t.items.length),t.trigger("blur")};t.settings.create&&t.settings.createOnBlur?t.createItem(null,i):i()}}}onOptionSelect(e,t){var i,s=this;t.parentElement&&t.parentElement.matches("[data-disabled]")||(t.classList.contains("create")?s.createItem(null,()=>{s.settings.closeAfterSelect?s.close():s.settings.clearAfterSelect&&s.setTextboxValue()}):void 0!==(i=t.dataset.value)&&(s.isDropdownContentStale=s.settings.hideSelected,s.addItem(i),s.settings.closeAfterSelect?s.close():s.settings.clearAfterSelect&&s.setTextboxValue(),!s.settings.hideSelected&&e.type&&/click/.test(e.type)&&s.setActiveOption(t)))}canSelect(e){return!!(this.isOpen&&e&&this.dropdown_content.contains(e))}onItemSelect(e,t){var i=this;return!i.isLocked&&"multi"===i.settings.mode&&(ft(e),i.setActiveItem(t,e),!0)}canLoad(e){return!!this.settings.load&&!this.loadedSearches.hasOwnProperty(e)}load(e){const t=this;if(!t.canLoad(e))return;Ct(t.wrapper,t.settings.loadingClass),t.loading++;const i=t.loadCallback.bind(t);t.settings.load.call(t,e,i)}loadCallback(e,t){const i=this;i.loading=Math.max(i.loading-1,0),i.isDropdownContentStale=!0,i.clearActiveOption(),i.setupOptions(e,t),i.refreshOptions(i.isFocused&&!i.isInputHidden),i.loading||At(i.wrapper,i.settings.loadingClass),i.trigger("load",e,t)}preload(){var e=this.wrapper.classList;e.contains("preloaded")||(e.add("preloaded"),this.load(""))}setTextboxValue(e=""){var t=this.control_input;t.value!==e&&(t.value=e,St(t,"update"),this.lastValue=e)}getValue(){return this.is_select_tag&&this.input.hasAttribute("multiple")?this.items:this.items.join(this.settings.delimiter)}setValue(e,t){gt(this,t?[]:["change"],()=>{this.clear(t),this.addItems(e,t)})}setMaxItems(e){0===e&&(e=null),this.settings.maxItems=e,this.refreshState()}setActiveItem(e,t){var i,s,n,o,r,l,a=this;if("single"!==a.settings.mode){if(!e)return a.clearActiveItems(),void(a.isFocused&&a.inputState());if("click"===(i=t&&t.type.toLowerCase())&&yt("shiftKey",t)&&a.activeItems.length){for(l=a.getLastActive(),(n=Array.prototype.indexOf.call(a.control.children,l))>(o=Array.prototype.indexOf.call(a.control.children,e))&&(r=n,n=o,o=r),s=n;s<=o;s++)e=a.control.children[s],-1===a.activeItems.indexOf(e)&&a.setActiveItemClass(e);ft(t)}else"click"===i&&yt(Bt,t)||"keydown"===i&&yt("shiftKey",t)?e.classList.contains("active")?a.removeActiveItem(e):a.setActiveItemClass(e):(a.clearActiveItems(),a.setActiveItemClass(e));a.inputState(),a.isFocused||a.focus()}}setActiveItemClass(e){const t=this,i=t.control.querySelector(".last-active");i&&At(i,"last-active"),Ct(e,"active last-active"),t.trigger("item_select",e),-1==t.activeItems.indexOf(e)&&t.activeItems.push(e)}removeActiveItem(e){var t=this.activeItems.indexOf(e);this.activeItems.splice(t,1),At(e,"active")}clearActiveItems(){At(this.activeItems,"active"),this.activeItems=[]}setActiveOption(e,t=!0){e!==this.activeOption&&(this.clearActiveOption(),e&&(this.activeOption=e,qt(this.focus_node,{"aria-activedescendant":e.getAttribute("id")}),qt(e,{"aria-selected":"true"}),Ct(e,"active"),t&&this.scrollToOption(e)))}scrollToOption(e,t){if(!e)return;const i=this.dropdown_content,s=i.clientHeight,n=i.scrollTop||0,o=e.offsetHeight,r=e.getBoundingClientRect().top-i.getBoundingClientRect().top+n;r+o>s+n?this.scroll(r-s+o,t):r<n&&this.scroll(r,t)}scroll(e,t){const i=this.dropdown_content;t&&(i.style.scrollBehavior=t),i.scrollTop=e,i.style.scrollBehavior=""}clearActiveOption(){this.activeOption&&(At(this.activeOption,"active"),qt(this.activeOption,{"aria-selected":null})),this.activeOption=null,qt(this.focus_node,{"aria-activedescendant":null})}selectAll(){const e=this;if("single"===e.settings.mode)return;const t=e.controlChildren();t.length&&(e.inputState(),e.close(),e.activeItems=t,kt(t,t=>{e.setActiveItemClass(t)}))}inputState(){var e=this;e.control.contains(e.control_input)&&(qt(e.control_input,{placeholder:e.settings.placeholder}),e.activeItems.length>0||!e.isFocused&&e.settings.hidePlaceholder&&e.items.length>0?(e.setTextboxValue(),e.isInputHidden=!0):(e.settings.hidePlaceholder&&e.items.length>0&&qt(e.control_input,{placeholder:""}),e.isInputHidden=!1),e.wrapper.classList.toggle("input-hidden",e.isInputHidden))}inputValue(){return this.control_input.value.trim()}focus(){var e=this;if(e.isDisabled||e.isReadOnly)return;e.ignoreFocus=!0;const t=this.control_input.offsetWidth?this.control_input:this.focus_node;t.focus(),setTimeout(()=>{e.ignoreFocus=!1;t.getRootNode().activeElement===t&&this.onFocus()},0)}blur(){this.focus_node.blur(),this.onBlur()}getScoreFunction(e){return this.sifter.getScoreFunction(e,this.getSearchOptions())}getSearchOptions(){var e=this.settings,t=e.sortField;return"string"==typeof e.sortField&&(t=[{field:e.sortField}]),{fields:e.searchField,conjunction:e.searchConjunction,sort:t,nesting:e.nesting}}search(e){var t,i,s=this,n=this.getSearchOptions();if(s.settings.score&&"function"!=typeof(i=s.settings.score.call(s,e)))throw new Error('Tom Select "score" setting must be a function that returns a function');return s.isDropdownContentStale||e!==s.lastQuery?(s.lastQuery=e,/(.)\1{15,}/.test(e)&&(e=""),t=s.sifter.search(e,Object.assign(n,{score:i})),s.currentResults=t):t=Object.assign({},s.currentResults),s.settings.hideSelected&&(t.items=t.items.filter(e=>{let t=ht(e.id);return!(null!==t&&-1!==s.items.indexOf(t))})),t}refreshOptions(e=!0){var t,i,s,n,o,r,l,a,c,d;const h={},u=[];var p=this,m=p.inputValue();const g=m===p.lastQuery||""==m&&null==p.lastQuery;var f=p.search(m),v=null,y=p.settings.shouldOpen||!1,b=p.dropdown_content;g&&(v=p.activeOption)&&(c=v.closest("[data-group]")),n=f.items.length,"number"==typeof p.settings.maxOptions&&(n=Math.min(n,p.settings.maxOptions)),n>0&&(y=!0);const w=(e,t)=>{let i=h[e];if(void 0!==i){let e=u[i];if(void 0!==e)return[i,e.fragment]}let s=document.createDocumentFragment();return i=u.length,u.push({fragment:s,order:t,optgroup:e}),[i,s]};for(t=0;t<n;t++){let e=f.items[t];if(!e)continue;let n=e.id,l=p.options[n];if(void 0===l)continue;let a=ut(n),d=p.getOption(a,!0);for(p.settings.hideSelected||d.classList.toggle("selected",p.items.includes(a)),o=l[p.settings.optgroupField]||"",i=0,s=(r=Array.isArray(o)?o:[o])&&r.length;i<s;i++){o=r[i];let e=l.$order,t=p.optgroups[o];var E;if(void 0===t&&"function"==typeof p.settings.optionGroupRegister)(E=p.settings.optionGroupRegister.apply(p,[o]))&&p.registerOptionGroup(E);t=p.optgroups[o],void 0===t?o="":e=t.$order;const[s,a]=w(o,e);i>0&&(d=d.cloneNode(!0),qt(d,{id:l.$id+"-clone-"+i,"aria-selected":null}),d.classList.add("ts-cloned"),At(d,"active"),p.activeOption&&p.activeOption.dataset.value==n&&c&&c.dataset.group===o.toString()&&(v=d)),a.appendChild(d),""!=o&&(h[o]=s)}}var k;p.settings.lockOptgroupOrder&&u.sort((e,t)=>e.order-t.order),l=document.createDocumentFragment(),kt(u,e=>{let t=e.fragment,i=e.optgroup;if(!t||!t.children.length)return;let s=p.optgroups[i];if(void 0!==s){let e=document.createDocumentFragment(),i=p.render("optgroup_header",s);Et(e,i),Et(e,t);let n=p.render("optgroup",{group:s,options:e});Et(l,n)}else Et(l,t)}),b.innerHTML="",Et(b,l),p.isDropdownContentStale=!1,p.settings.highlight&&(k=b.querySelectorAll("span.highlight"),Array.prototype.forEach.call(k,function(e){var t=e.parentNode;t.replaceChild(e.firstChild,e),t.normalize()}),f.query.length&&f.tokens.length&&kt(f.tokens,e=>{Mt(b,e.regex)}));var _=e=>{let t=p.render(e,{input:m});return t&&(y=!0,b.insertBefore(t,b.firstChild)),t};if(p.loading?_("loading"):p.settings.shouldLoad.call(p,m)?0===f.items.length&&_("no_results"):_("not_loading"),(a=p.canCreate(m))&&(d=_("option_create")),p.hasOptions=f.items.length>0||a,y){if(f.items.length>0){if(v||"single"!==p.settings.mode||null==p.items[0]||(v=p.getOption(p.items[0])),!b.contains(v)){let e=0;d&&!p.settings.addPrecedence&&(e=1),v=p.selectable()[e]}}else d&&(v=d);e&&!p.isOpen&&(p.open(),p.scrollToOption(v,"auto")),p.setActiveOption(v)}else p.clearActiveOption(),e&&p.isOpen&&p.close(!1)}selectable(){return this.dropdown_content.querySelectorAll("[data-selectable]")}addOption(e,t=!1){const i=this;if(Array.isArray(e))return i.addOptions(e,t),!1;const s=ht(e[i.settings.valueField]);return null===s||i.options.hasOwnProperty(s)?(i.updateOption(e[i.settings.valueField],e),!1):(e.$order=e.$order||++i.order,e.$id=i.inputId+"-opt-"+e.$order,i.options[s]=e,i.isDropdownContentStale=!0,t&&(i.userOptions[s]=t,i.trigger("option_add",s,e)),s)}addOptions(e,t=!1){kt(e,e=>{this.addOption(e,t)})}registerOption(e){return this.addOption(e)}registerOptionGroup(e){var t=ht(e[this.settings.optgroupValueField]);return null!==t&&(e.$order=e.$order||++this.order,this.optgroups[t]=e,t)}addOptionGroup(e,t){var i;t[this.settings.optgroupValueField]=e,(i=this.registerOptionGroup(t))&&this.trigger("optgroup_add",i,t)}removeOptionGroup(e){this.optgroups.hasOwnProperty(e)&&(delete this.optgroups[e],this.clearCache(),this.trigger("optgroup_remove",e))}clearOptionGroups(){this.optgroups={},this.clearCache(),this.trigger("optgroup_clear")}updateOption(e,t){const i=this;var s,n;const o=ht(e),r=ht(t[i.settings.valueField]);if(null===o)return;const l=i.options[o];if(null==l)return;if("string"!=typeof r)throw new Error("Value must be set in option data");const a=i.getOption(o),c=i.getItem(o);if(t.$order=t.$order||l.$order,delete i.options[o],i.uncacheValue(r),i.options[r]=t,a){if(i.dropdown_content.contains(a)){const e=i._render("option",t);Dt(a,e),i.activeOption===a&&i.setActiveOption(e)}a.remove()}c&&(-1!==(n=i.items.indexOf(o))&&i.items.splice(n,1,r),s=i._render("item",t),c.classList.contains("active")&&Ct(s,"active"),Dt(c,s)),i.isDropdownContentStale=!0}removeOption(e,t){const i=this;e=ut(e),i.uncacheValue(e),delete i.userOptions[e],delete i.options[e],i.isDropdownContentStale=!0,i.trigger("option_remove",e),i.removeItem(e,t)}clearOptions(e){const t=(e||this.clearFilter).bind(this);this.loadedSearches={},this.userOptions={},this.clearCache();const i={};kt(this.options,(e,s)=>{t(e,s)&&(i[s]=e)}),this.options=this.sifter.items=i,this.isDropdownContentStale=!0,this.trigger("option_clear")}clearFilter(e,t){return this.items.indexOf(t)>=0}getOption(e,t=!1){const i=ht(e);if(null===i)return null;const s=this.options[i];if(null!=s){if(s.$div)return s.$div;if(t)return this._render("option",s)}return null}getAdjacent(e,t,i="option"){var s;if(!e)return null;s="item"==i?this.controlChildren():this.dropdown_content.querySelectorAll("[data-selectable]");for(let i=0;i<s.length;i++)if(s[i]==e)return t>0?s[i+1]:s[i-1];return null}getItem(e){if("object"==typeof e)return e;var t=ht(e);return null!==t?this.control.querySelector(`[data-value="${wt(t)}"]`):null}addItems(e,t){var i=this,s=Array.isArray(e)?e:[e];const n=(s=s.filter(e=>-1===i.items.indexOf(e)))[s.length-1];s.forEach(e=>{i.isPending=e!==n,i.addItem(e,t)})}addItem(e,t){gt(this,t?[]:["change","dropdown_close"],()=>{var i,s;const n=this,o=n.settings.mode,r=ht(e);if((!r||-1===n.items.indexOf(r)||("single"===o&&n.close(),"single"!==o&&n.settings.duplicates))&&null!==r&&n.options.hasOwnProperty(r)&&("single"===o&&n.clear(t),"multi"!==o||!n.isFull())){if(i=n._render("item",n.options[r]),n.control.contains(i)&&(i=i.cloneNode(!0)),s=n.isFull(),n.items.splice(n.caretPos,0,r),n.insertAtCaret(i),n.isSetup){if(!n.isPending&&n.settings.hideSelected){let e=n.getOption(r),t=n.getAdjacent(e,1);t&&n.setActiveOption(t)}n.settings.clearAfterSelect&&n.setTextboxValue(),n.isPending||n.settings.closeAfterSelect||n.refreshOptions(n.isFocused&&"single"!==o),0!=n.settings.closeAfterSelect&&n.isFull()?n.close():n.isPending||n.positionDropdown(),n.trigger("item_add",r,i),n.isPending||n.updateOriginalInput({silent:t})}(!n.isPending||!s&&n.isFull())&&(n.inputState(),n.refreshState())}})}removeItem(e=null,t){const i=this;if(!(e=i.getItem(e)))return;var s,n;const o=e.dataset.value;s=$t(e),e.remove(),e.classList.contains("active")&&(n=i.activeItems.indexOf(e),i.activeItems.splice(n,1),At(e,"active")),i.items.splice(s,1),i.isDropdownContentStale=!0,!i.settings.persist&&i.userOptions.hasOwnProperty(o)&&i.removeOption(o,t),s<i.caretPos&&i.setCaret(i.caretPos-1),i.updateOriginalInput({silent:t}),i.refreshState(),i.positionDropdown(),i.trigger("item_remove",o,e)}createItem(e=null,t=()=>{}){3===arguments.length&&(t=arguments[2]),"function"!=typeof t&&(t=()=>{});var i,s=this,n=s.caretPos;if(e=e||s.inputValue(),!s.canCreate(e)){return ht(e)&&this.options[e]&&s.addItem(e),t(),!1}s.lock();var o=!1,r=e=>{if(s.unlock(),!e||"object"!=typeof e)return t();var i=ht(e[s.settings.valueField]);if("string"!=typeof i)return t();s.setTextboxValue(),s.addOption(e,!0),s.setCaret(n),s.addItem(i),t(e),o=!0};return i="function"==typeof s.settings.create?s.settings.create.call(this,e,r):{[s.settings.labelField]:e,[s.settings.valueField]:e},o||r(i),!0}refreshItems(){var e=this;e.isDropdownContentStale=!0,e.isSetup&&e.addItems(e.items),e.updateOriginalInput(),e.refreshState()}refreshState(){const e=this;e.refreshValidityState();const t=e.isFull(),i=e.isLocked;e.wrapper.classList.toggle("rtl",e.rtl);const s=e.wrapper.classList;var n;s.toggle("focus",e.isFocused),s.toggle("disabled",e.isDisabled),s.toggle("readonly",e.isReadOnly),s.toggle("required",e.isRequired),s.toggle("invalid",!e.isValid),s.toggle("locked",i),s.toggle("full",t),s.toggle("input-active",e.isFocused&&!e.isInputHidden),s.toggle("dropdown-active",e.isOpen),s.toggle("has-options",(n=e.options,0===Object.keys(n).length)),s.toggle("has-items",e.items.length>0)}refreshValidityState(){var e=this;e.input.validity&&(e.isValid=e.input.validity.valid,e.isInvalid=!e.isValid)}isFull(){return null!==this.settings.maxItems&&this.items.length>=this.settings.maxItems}updateOriginalInput(e={}){const t=this;var i,s;const n=t.input.querySelector('option[value=""]');if(t.is_select_tag){const o=[],r=t.input.querySelectorAll("option:checked").length;function l(e,i,s){return e||(e=_t('<option value="'+pt(i)+'">'+pt(s)+"</option>")),e!=n&&t.input.append(e),o.push(e),(e!=n||r>0)&&(e.selected=!0),e}t.input.querySelectorAll("option:checked").forEach(e=>{e.selected=!1}),0==t.items.length&&"single"==t.settings.mode?l(n,"",""):t.items.forEach(e=>{if(i=t.options[e],s=i[t.settings.labelField]||"",o.includes(i.$option)){l(t.input.querySelector(`option[value="${wt(e)}"]:not(:checked)`),e,s)}else i.$option=l(i.$option,e,s)})}else t.input.value=t.getValue();t.isSetup&&(e.silent||t.trigger("change",t.getValue()))}open(){var e=this;e.isLocked||e.isOpen||"multi"===e.settings.mode&&e.isFull()||(e.isOpen=!0,qt(e.focus_node,{"aria-expanded":"true"}),e.refreshState(),xt(e.dropdown,{visibility:"hidden",display:"block"}),e.positionDropdown(),xt(e.dropdown,{visibility:"visible",display:"block"}),e.focus(),e.trigger("dropdown_open",e.dropdown))}close(e=!0){var t=this,i=t.isOpen;e&&(t.setTextboxValue(),"single"===t.settings.mode&&t.items.length&&t.inputState()),t.isOpen=!1,qt(t.focus_node,{"aria-expanded":"false"}),xt(t.dropdown,{display:"none"}),t.settings.hideSelected&&t.clearActiveOption(),t.refreshState(),i&&t.trigger("dropdown_close",t.dropdown)}positionDropdown(){if("body"===this.settings.dropdownParent){var e=this.control,t=e.getBoundingClientRect(),i=e.offsetHeight+t.top+window.scrollY,s=t.left+window.scrollX;xt(this.dropdown,{width:t.width+"px",top:i+"px",left:s+"px"})}}clear(e){var t=this;if(t.items.length){var i=t.controlChildren();kt(i,e=>{t.removeItem(e,!0)}),t.inputState(),e||t.updateOriginalInput(),t.trigger("clear")}}insertAtCaret(e){const t=this,i=t.caretPos,s=t.control;s.insertBefore(e,s.children[i]||null),t.setCaret(i+1)}deleteSelection(e){var t,i,s,n,o,r=this;t=e&&8===e.keyCode?-1:1,i={start:(o=r.control_input).selectionStart||0,length:(o.selectionEnd||0)-(o.selectionStart||0)};const l=[];if(r.activeItems.length)n=Ft(r.activeItems,t),s=$t(n),t>0&&s++,kt(r.activeItems,e=>l.push(e));else if((r.isFocused||"single"===r.settings.mode)&&r.items.length){const e=r.controlChildren();let s;t<0&&0===i.start&&0===i.length?s=e[r.caretPos-1]:t>0&&i.start===r.inputValue().length&&(s=e[r.caretPos]),void 0!==s&&l.push(s)}if(!r.shouldDelete(l,e))return!1;for(ft(e,!0),void 0!==s&&r.setCaret(s);l.length;)r.removeItem(l.pop());return r.inputState(),r.positionDropdown(),r.refreshOptions(!1),!0}shouldDelete(e,t){const i=e.map(e=>e.dataset.value);return!(!i.length||"function"==typeof this.settings.onDelete&&!1===this.settings.onDelete.call(this,i,t))}advanceSelection(e,t){var i,s,n=this;n.rtl&&(e*=-1),n.inputValue().length||(yt(Bt,t)||yt("shiftKey",t)?(s=(i=n.getLastActive(e))?i.classList.contains("active")?n.getAdjacent(i,e,"item"):i:e>0?n.control_input.nextElementSibling:n.control_input.previousElementSibling)&&(s.classList.contains("active")&&n.removeActiveItem(i),n.setActiveItemClass(s)):n.moveCaret(e))}moveCaret(e){}getLastActive(e){let t=this.control.querySelector(".last-active");if(t)return t;var i=this.control.querySelectorAll(".active");return i?Ft(i,e):void 0}setCaret(e){this.caretPos=this.items.length}controlChildren(){return Array.from(this.control.querySelectorAll("[data-ts-item]"))}lock(){this.setLocked(!0)}unlock(){this.setLocked(!1)}setLocked(e=this.isReadOnly||this.isDisabled){this.isLocked=e,this.refreshState()}disable(){this.setDisabled(!0),this.close()}enable(){this.setDisabled(!1)}setDisabled(e){this.focus_node.tabIndex=e?-1:this.tabIndex,this.isDisabled=e,this.input.disabled=e,this.control_input.disabled=e,this.setLocked()}setReadOnly(e){this.isReadOnly=e,this.input.readOnly=e,this.control_input.readOnly=e,this.setLocked()}destroy(){var e=this,t=e.revertSettings;e.trigger("destroy"),e.off(),e.wrapper.remove(),e.dropdown.remove(),e.input.innerHTML=t.innerHTML,e.input.tabIndex=t.tabIndex,At(e.input,"tomselected","ts-hidden-accessible"),e._destroy(),delete e.input.tomselect}render(e,t){var i,s;const n=this;if("function"!=typeof this.settings.render[e])return null;if(!(s=n.settings.render[e].call(this,t,pt)))return null;if(s=_t(s),"option"===e||"option_create"===e?t[n.settings.disabledField]?qt(s,{"aria-disabled":"true"}):qt(s,{"data-selectable":""}):"optgroup"===e&&(i=t.group[n.settings.optgroupValueField],qt(s,{"data-group":i}),t.group[n.settings.disabledField]&&qt(s,{"data-disabled":""})),"option"===e||"item"===e){const i=ut(t[n.settings.valueField]);qt(s,{"data-value":i}),"item"===e?(Ct(s,n.settings.itemClass),qt(s,{"data-ts-item":""})):(Ct(s,n.settings.optionClass),qt(s,{role:"option",id:t.$id}),t.$div=s,n.options[i]=t)}return s}_render(e,t){const i=this.render(e,t);if(null==i)throw"HTMLElement expected";return i}clearCache(){kt(this.options,e=>{e.$div&&(e.$div.remove(),delete e.$div)})}uncacheValue(e){const t=this.getOption(e);t&&t.remove()}canCreate(e){return this.settings.create&&e.length>0&&this.settings.createFilter.call(this,e)}hook(e,t,i){var s=this,n=s[t];s[t]=function(){var t,o;return"after"===e&&(t=n.apply(s,arguments)),o=i.apply(s,arguments),"instead"===e?o:("before"===e&&(t=n.apply(s,arguments)),t)}}}const Nt=e=>"boolean"==typeof e?e?"1":"0":e+"",jt=(e,t=!1)=>{e&&(e.preventDefault(),t&&e.stopPropagation())},Vt=e=>"string"==typeof e&&e.indexOf("<")>-1;const Wt=e=>"string"==typeof e&&e.indexOf("<")>-1;const Ut=(e,t,i,s)=>{e.addEventListener(t,i,s)},Kt=e=>"string"==typeof e&&e.indexOf("<")>-1,Jt=(e,t)=>{((e,t)=>{if(Array.isArray(e))e.forEach(t);else for(var i in e)e.hasOwnProperty(i)&&t(e[i],i)})(t,(t,i)=>{null==t?e.removeAttribute(i):e.setAttribute(i,""+t)})};const Gt=e=>"string"==typeof e&&e.indexOf("<")>-1;const Qt=e=>{var t=[];return((e,t)=>{if(Array.isArray(e))e.forEach(t);else for(var i in e)e.hasOwnProperty(i)&&t(e[i],i)})(e,e=>{"string"==typeof e&&(e=e.trim().split(/[\t\n\f\r\s]/)),Array.isArray(e)&&(t=t.concat(e))}),t.filter(Boolean)},Xt=e=>(Array.isArray(e)||(e=[e]),e);const Yt=e=>{if(e.jquery)return e[0];if(e instanceof HTMLElement)return e;if(Zt(e)){var t=document.createElement("template");return t.innerHTML=e.trim(),t.content.firstChild}return document.querySelector(e)},Zt=e=>"string"==typeof e&&e.indexOf("<")>-1,ei=e=>{var t=[];return((e,t)=>{if(Array.isArray(e))e.forEach(t);else for(var i in e)e.hasOwnProperty(i)&&t(e[i],i)})(e,e=>{"string"==typeof e&&(e=e.trim().split(/[\t\n\f\r\s]/)),Array.isArray(e)&&(t=t.concat(e))}),t.filter(Boolean)},ti=e=>(Array.isArray(e)||(e=[e]),e);const ii=(e,t,i,s)=>{e.addEventListener(t,i,s)};const si=(e,t=!1)=>{e&&(e.preventDefault(),t&&e.stopPropagation())},ni=(e,t,i,s)=>{e.addEventListener(t,i,s)},oi=e=>{if(e.jquery)return e[0];if(e instanceof HTMLElement)return e;if(ri(e)){var t=document.createElement("template");return t.innerHTML=e.trim(),t.content.firstChild}return document.querySelector(e)},ri=e=>"string"==typeof e&&e.indexOf("<")>-1;const li=e=>{var t=[];return((e,t)=>{if(Array.isArray(e))e.forEach(t);else for(var i in e)e.hasOwnProperty(i)&&t(e[i],i)})(e,e=>{"string"==typeof e&&(e=e.trim().split(/[\t\n\f\r\s]/)),Array.isArray(e)&&(t=t.concat(e))}),t.filter(Boolean)},ai=e=>(Array.isArray(e)||(e=[e]),e);Rt.define("change_listener",function(){((e,t,i,s)=>{e.addEventListener(t,i,s)})(this.input,"change",()=>{this.sync()})}),Rt.define("checkbox_options",function(e){var t=this,i=t.onOptionSelect;t.settings.hideSelected=!1;const s=Object.assign({className:"tomselect-checkbox",checkedClassNames:void 0,uncheckedClassNames:void 0},e);var n=function(e,t){t?(e.checked=!0,s.uncheckedClassNames&&e.classList.remove(...s.uncheckedClassNames),s.checkedClassNames&&e.classList.add(...s.checkedClassNames)):(e.checked=!1,s.checkedClassNames&&e.classList.remove(...s.checkedClassNames),s.uncheckedClassNames&&e.classList.add(...s.uncheckedClassNames))},o=function(e){setTimeout(()=>{var t=e.querySelector("input."+s.className);t instanceof HTMLInputElement&&n(t,e.classList.contains("selected"))},1)};t.hook("after","setupTemplates",()=>{var e=t.settings.render.option;t.settings.render.option=(i,o)=>{var r=(e=>{if(e.jquery)return e[0];if(e instanceof HTMLElement)return e;if(Vt(e)){var t=document.createElement("template");return t.innerHTML=e.trim(),t.content.firstChild}return document.querySelector(e)})(e.call(t,i,o)),l=document.createElement("input");s.className&&l.classList.add(s.className),l.addEventListener("click",function(e){jt(e)}),l.type="checkbox";const a=null==(c=i[t.settings.valueField])?null:Nt(c);var c;return n(l,!!(a&&t.items.indexOf(a)>-1)),r.prepend(l),r}}),t.on("item_remove",e=>{var i=t.getOption(e);i&&(i.classList.remove("selected"),o(i))}),t.on("item_add",e=>{var i=t.getOption(e);i&&o(i)}),t.hook("instead","onOptionSelect",(e,s)=>{if(s.classList.contains("selected"))return s.classList.remove("selected"),t.removeItem(s.dataset.value),t.refreshOptions(),void jt(e,!0);i.call(t,e,s),o(s)})}),Rt.define("clear_button",function(e){const t=this,i=Object.assign({className:"clear-button",title:"Clear All",role:"button",tabindex:0,html:e=>`<div class="${e.className}" title="${e.title}" role="${e.role}" tabindex="${e.tabindex}">×</div>`},e);t.on("initialize",()=>{var e=(e=>{if(e.jquery)return e[0];if(e instanceof HTMLElement)return e;if(Wt(e)){var t=document.createElement("template");return t.innerHTML=e.trim(),t.content.firstChild}return document.querySelector(e)})(i.html(i));e.addEventListener("click",e=>{t.isLocked||(t.clear(),"single"===t.settings.mode&&t.settings.allowEmptyOption&&t.addItem(""),t.refreshOptions(!1),e.preventDefault(),e.stopPropagation())}),t.control.appendChild(e)})}),Rt.define("drag_drop",function(){var e=this;if("multi"!==e.settings.mode)return;var t=e.lock,i=e.unlock;let s,n=!0;e.hook("after","setupTemplates",()=>{var t=e.settings.render.item;e.settings.render.item=(i,o)=>{const r=(e=>{if(e.jquery)return e[0];if(e instanceof HTMLElement)return e;if(Kt(e)){var t=document.createElement("template");return t.innerHTML=e.trim(),t.content.firstChild}return document.querySelector(e)})(t.call(e,i,o));Jt(r,{draggable:"true"});const l=e=>{e.preventDefault(),r.classList.add("ts-drag-over"),a(r,s)},a=(e,t)=>{var i,s,n;void 0!==t&&(((e,t)=>{do{var i;if(e==(t=null==(i=t)?void 0:i.previousElementSibling))return!0}while(t&&t.previousElementSibling);return!1})(t,r)?(s=t,null==(n=(i=e).parentNode)||n.insertBefore(s,i.nextSibling)):((e,t)=>{var i;null==(i=e.parentNode)||i.insertBefore(t,e)})(e,t))};return Ut(r,"mousedown",e=>{n||((e,t=!1)=>{e&&(e.preventDefault(),t&&e.stopPropagation())})(e),e.stopPropagation()}),Ut(r,"dragstart",e=>{s=r,setTimeout(()=>{r.classList.add("ts-dragging")},0)}),Ut(r,"dragenter",l),Ut(r,"dragover",l),Ut(r,"dragleave",()=>{r.classList.remove("ts-drag-over")}),Ut(r,"dragend",()=>{var t;document.querySelectorAll(".ts-drag-over").forEach(e=>e.classList.remove("ts-drag-over")),null==(t=s)||t.classList.remove("ts-dragging"),s=void 0;var i=[];e.control.querySelectorAll("[data-value]").forEach(e=>{if(e.dataset.value){let t=e.dataset.value;t&&i.push(t)}}),e.setValue(i)}),r}}),e.hook("instead","lock",()=>(n=!1,t.call(e))),e.hook("instead","unlock",()=>(n=!0,i.call(e)))}),Rt.define("dropdown_header",function(e){const t=this,i=Object.assign({title:"Untitled",headerClass:"dropdown-header",titleRowClass:"dropdown-header-title",labelClass:"dropdown-header-label",closeClass:"dropdown-header-close",html:e=>'<div class="'+e.headerClass+'"><div class="'+e.titleRowClass+'"><span class="'+e.labelClass+'">'+e.title+'</span><a class="'+e.closeClass+'">×</a></div></div>'},e);t.on("initialize",()=>{var e=(e=>{if(e.jquery)return e[0];if(e instanceof HTMLElement)return e;if(Gt(e)){var t=document.createElement("template");return t.innerHTML=e.trim(),t.content.firstChild}return document.querySelector(e)})(i.html(i)),s=e.querySelector("."+i.closeClass);s&&s.addEventListener("click",e=>{((e,t=!1)=>{e&&(e.preventDefault(),t&&e.stopPropagation())})(e,!0),t.close()}),t.dropdown.insertBefore(e,t.dropdown.firstChild)})}),Rt.define("caret_position",function(){var e=this;e.hook("instead","setCaret",t=>{"single"!==e.settings.mode&&e.control.contains(e.control_input)?(t=Math.max(0,Math.min(e.items.length,t)))==e.caretPos||e.isPending||e.controlChildren().forEach((i,s)=>{s<t?e.control_input.insertAdjacentElement("beforebegin",i):e.control.appendChild(i)}):t=e.items.length,e.caretPos=t}),e.hook("instead","moveCaret",t=>{if(!e.isFocused)return;const i=e.getLastActive(t);if(i){const s=((e,t)=>{if(!e)return-1;t=t||e.nodeName;for(var i=0;e=e.previousElementSibling;)e.matches(t)&&i++;return i})(i);e.setCaret(t>0?s+1:s),e.setActiveItem(),((e,...t)=>{var i=Qt(t);(e=Xt(e)).map(e=>{i.map(t=>{e.classList.remove(t)})})})(i,"last-active")}else e.setCaret(e.caretPos+t)})}),Rt.define("dropdown_input",function(){const e=this;e.settings.shouldOpen=!0,e.hook("before","setup",()=>{var t;e.focus_node=e.control,((e,...t)=>{var i=ei(t);(e=ti(e)).map(e=>{i.map(t=>{e.classList.add(t)})})})(e.control_input,"dropdown-input");const i=Yt('<div class="dropdown-input-wrap">');i.append(e.control_input),e.dropdown.insertBefore(i,e.dropdown.firstChild);const s=Yt('<input class="items-placeholder" tabindex="-1" />');s.placeholder=e.settings.placeholder||"",e.control.append(s);const n=null==(t=e.input)?void 0:t.getAttribute("aria-label");n&&s.setAttribute("aria-label",n)}),e.on("initialize",()=>{e.control_input.addEventListener("keydown",t=>{switch(t.keyCode){case 27:return e.isOpen&&(((e,t=!1)=>{e&&(e.preventDefault(),t&&e.stopPropagation())})(t,!0),e.close()),void e.clearActiveItems();case 9:e.focus_node.tabIndex=-1}return e.onKeyDown.call(e,t)}),e.on("blur",()=>{e.focus_node.tabIndex=e.isDisabled?-1:e.tabIndex}),e.on("dropdown_open",()=>{e.control_input.focus()});const t=e.onBlur;e.hook("instead","onBlur",i=>{if(!i||i.relatedTarget!=e.control_input)return t.call(e)}),((e,t,i,s)=>{e.addEventListener(t,i,s)})(e.control_input,"blur",()=>e.onBlur()),e.hook("before","close",()=>{e.isOpen&&e.focus_node.focus({preventScroll:!0})})})}),Rt.define("input_autogrow",function(){var e=this;e.on("initialize",()=>{var t=document.createElement("span"),i=e.control_input;t.style.cssText="position:absolute; top:-99999px; left:-99999px; width:auto; padding:0; white-space:pre; ",e.wrapper.appendChild(t);for(const e of["letterSpacing","fontSize","fontFamily","fontWeight","textTransform"])t.style[e]=i.style[e];var s=()=>{t.textContent=i.value,i.style.width=t.clientWidth+"px"};s(),e.on("update item_add item_remove",s),ii(i,"input",s),ii(i,"keyup",s),ii(i,"blur",s),ii(i,"update",s)})}),Rt.define("no_backspace_delete",function(){var e=this,t=e.deleteSelection;this.hook("instead","deleteSelection",i=>!!e.activeItems.length&&t.call(e,i))}),Rt.define("no_active_items",function(){this.hook("instead","setActiveItem",()=>{}),this.hook("instead","selectAll",()=>{})}),Rt.define("optgroup_columns",function(){var e=this,t=e.onKeyDown;e.hook("instead","onKeyDown",i=>{var s,n,o,r;if(!e.isOpen||37!==i.keyCode&&39!==i.keyCode)return t.call(e,i);e.ignoreHover=!0,r=((e,t)=>{for(;e&&e.matches;){if(e.matches(t))return e;e=e.parentNode}})(e.activeOption,"[data-group]"),s=((e,t)=>{if(!e)return-1;t=t||e.nodeName;for(var i=0;e=e.previousElementSibling;)e.matches(t)&&i++;return i})(e.activeOption,"[data-selectable]"),r&&(r=37===i.keyCode?r.previousSibling:r.nextSibling)&&(n=(o=r.querySelectorAll("[data-selectable]"))[Math.min(o.length-1,s)])&&e.setActiveOption(n)})}),Rt.define("remove_button",function(e){const t=Object.assign({label:"×",title:"Remove",className:"remove",append:!0},e);var i=this;if(t.append){var s='<a href="javascript:void(0)" class="'+t.className+'" tabindex="-1" title="'+((t.title+"").replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""")+'">')+t.label+"</a>";i.hook("after","setupTemplates",()=>{var e=i.settings.render.item;i.settings.render.item=(t,n)=>{var o=oi(e.call(i,t,n)),r=oi(s);return o.appendChild(r),ni(r,"mousedown",e=>{si(e,!0)}),ni(r,"click",e=>{i.isLocked||(si(e,!0),i.isLocked||i.shouldDelete([o],e)&&(i.removeItem(o),i.refreshOptions(!1),i.inputState()))}),o}})}}),Rt.define("restore_on_backspace",function(e){const t=this,i=Object.assign({text:e=>e[t.settings.labelField]},e);t.on("item_remove",function(e){if(t.isFocused&&""===t.control_input.value.trim()){var s=t.options[e];s&&t.setTextboxValue(i.text.call(t,s))}})}),Rt.define("virtual_scroll",function(){const e=this,t=e.canLoad,i=e.clearActiveOption,s=e.loadCallback;var n,o,r,l={},a=!1,c=[],d=!1;if(e.settings.shouldLoadMore||(e.settings.shouldLoadMore=()=>{if(n.clientHeight/(n.scrollHeight-n.scrollTop)>.9)return!0;if(e.activeOption){var t=e.selectable();if(Array.from(t).indexOf(e.activeOption)>=t.length-2)return!0}return!1}),!e.settings.firstUrl)throw"virtual_scroll plugin requires a firstUrl() method";e.settings.sortField=[{field:"$order"},{field:"$score"}];const h=t=>!("number"==typeof e.settings.maxOptions&&n.children.length>=e.settings.maxOptions)&&!(!(t in l)||!l[t]),u=(t,i)=>e.items.indexOf(i)>=0||c.indexOf(i)>=0;e.setNextUrl=(e,t)=>{l[e]=t},e.getUrl=t=>{if(t in l){const e=l[t];return l[t]=!1,e}return e.clearPagination(),e.settings.firstUrl.call(e,t)},e.clearPagination=()=>{l={}},e.hook("instead","clearActiveOption",()=>{if(!a)return i.call(e)}),e.hook("instead","canLoad",i=>i in l?h(i):t.call(e,i)),e.hook("instead","loadCallback",(t,i)=>{if(a){if(o){const i=t[0];void 0!==i&&(o.dataset.value=i[e.settings.valueField])}}else e.clearOptions(u);s.call(e,t,i),a||d||(d=!0,""===e.lastValue&&(c=Object.keys(e.options),r=l[""])),a=!1}),e.hook("before","refreshOptions",()=>{e.activeOption&&"option"!==e.activeOption.getAttribute("role")&&e.setActiveOption(e.activeOption.previousElementSibling)}),e.hook("after","refreshOptions",()=>{const t=e.lastValue;var i;h(t)?(i=e.render("loading_more",{query:t}))&&(i.setAttribute("data-selectable",""),o=i):t in l&&!n.querySelector(".no-results")&&(i=e.render("no_more_results",{query:t})),i&&(((e,...t)=>{var i=li(t);(e=ai(e)).map(e=>{i.map(t=>{e.classList.add(t)})})})(i,e.settings.optionClass),n.append(i))});const p=()=>{d&&(e.clearOptions(u),r&&(l[""]=r))};e.on("type",t=>{""===t&&(p(),e.refreshOptions(!1))}),e.on("dropdown_close",p),e.on("initialize",()=>{c=Object.keys(e.options),n=e.dropdown_content,e.settings.render=Object.assign({},{loading_more:()=>'<div class="loading-more-results">Loading more results ... </div>',no_more_results:()=>'<div class="no-more-results">No more results</div>'},e.settings.render),n.addEventListener("scroll",()=>{e.settings.shouldLoadMore.call(e)&&h(e.lastValue)&&(a||(a=!0,e.load.call(e,e.lastValue)))})})});const ci=Math.min,di=Math.max,hi=Math.round,ui=Math.floor,pi=e=>({x:e,y:e}),mi={left:"right",right:"left",bottom:"top",top:"bottom"};function gi(e,t){return"function"==typeof e?e(t):e}function fi(e){return e.split("-")[0]}function vi(e){return e.split("-")[1]}function yi(e){return"y"===e?"height":"width"}function bi(e){const t=e[0];return"t"===t||"b"===t?"y":"x"}function wi(e){return"x"===bi(e)?"y":"x"}function Ei(e){return e.includes("start")?e.replace("start","end"):e.replace("end","start")}const ki=["left","right"],_i=["right","left"],Li=["top","bottom"],Si=["bottom","top"];function xi(e,t,i,s){const n=vi(e);let o=function(e,t,i){switch(e){case"top":case"bottom":return i?t?_i:ki:t?ki:_i;case"left":case"right":return t?Li:Si;default:return[]}}(fi(e),"start"===i,s);return n&&(o=o.map(e=>e+"-"+n),t&&(o=o.concat(o.map(Ei)))),o}function Ci(e){const t=fi(e);return mi[t]+e.slice(t.length)}function Ai(e){const{x:t,y:i,width:s,height:n}=e;return{width:s,height:n,top:i,left:t,right:t+s,bottom:i+n,x:t,y:i}}function Ti(e,t,i){let{reference:s,floating:n}=e;const o=bi(t),r=wi(t),l=yi(r),a=fi(t),c="y"===o,d=s.x+s.width/2-n.width/2,h=s.y+s.height/2-n.height/2,u=s[l]/2-n[l]/2;let p;switch(a){case"top":p={x:d,y:s.y-n.height};break;case"bottom":p={x:d,y:s.y+s.height};break;case"right":p={x:s.x+s.width,y:h};break;case"left":p={x:s.x-n.width,y:h};break;default:p={x:s.x,y:s.y}}switch(vi(t)){case"start":p[r]-=u*(i&&c?-1:1);break;case"end":p[r]+=u*(i&&c?-1:1)}return p}async function Oi(e,t){var i;void 0===t&&(t={});const{x:s,y:n,platform:o,rects:r,elements:l,strategy:a}=e,{boundary:c="clippingAncestors",rootBoundary:d="viewport",elementContext:h="floating",altBoundary:u=!1,padding:p=0}=gi(t,e),m=function(e){return"number"!=typeof e?function(e){return{top:0,right:0,bottom:0,left:0,...e}}(e):{top:e,right:e,bottom:e,left:e}}(p),g=l[u?"floating"===h?"reference":"floating":h],f=Ai(await o.getClippingRect({element:null==(i=await(null==o.isElement?void 0:o.isElement(g)))||i?g:g.contextElement||await(null==o.getDocumentElement?void 0:o.getDocumentElement(l.floating)),boundary:c,rootBoundary:d,strategy:a})),v="floating"===h?{x:s,y:n,width:r.floating.width,height:r.floating.height}:r.reference,y=await(null==o.getOffsetParent?void 0:o.getOffsetParent(l.floating)),b=await(null==o.isElement?void 0:o.isElement(y))&&await(null==o.getScale?void 0:o.getScale(y))||{x:1,y:1},w=Ai(o.convertOffsetParentRelativeRectToViewportRelativeRect?await o.convertOffsetParentRelativeRectToViewportRelativeRect({elements:l,rect:v,offsetParent:y,strategy:a}):v);return{top:(f.top-w.top+m.top)/b.y,bottom:(w.bottom-f.bottom+m.bottom)/b.y,left:(f.left-w.left+m.left)/b.x,right:(w.right-f.right+m.right)/b.x}}const Ii=new Set(["left","top"]);function Fi(){return"undefined"!=typeof window}function $i(e){return Mi(e)?(e.nodeName||"").toLowerCase():"#document"}function qi(e){var t;return(null==e||null==(t=e.ownerDocument)?void 0:t.defaultView)||window}function Di(e){var t;return null==(t=(Mi(e)?e.ownerDocument:e.document)||window.document)?void 0:t.documentElement}function Mi(e){return!!Fi()&&(e instanceof Node||e instanceof qi(e).Node)}function Bi(e){return!!Fi()&&(e instanceof Element||e instanceof qi(e).Element)}function Pi(e){return!!Fi()&&(e instanceof HTMLElement||e instanceof qi(e).HTMLElement)}function zi(e){return!(!Fi()||"undefined"==typeof ShadowRoot)&&(e instanceof ShadowRoot||e instanceof qi(e).ShadowRoot)}function Hi(e){const{overflow:t,overflowX:i,overflowY:s,display:n}=Qi(e);return/auto|scroll|overlay|hidden|clip/.test(t+s+i)&&"inline"!==n&&"contents"!==n}function Ri(e){return/^(table|td|th)$/.test($i(e))}function Ni(e){try{if(e.matches(":popover-open"))return!0}catch(e){}try{return e.matches(":modal")}catch(e){return!1}}const ji=/transform|translate|scale|rotate|perspective|filter/,Vi=/paint|layout|strict|content/,Wi=e=>!!e&&"none"!==e;let Ui;function Ki(e){const t=Bi(e)?Qi(e):e;return Wi(t.transform)||Wi(t.translate)||Wi(t.scale)||Wi(t.rotate)||Wi(t.perspective)||!Ji()&&(Wi(t.backdropFilter)||Wi(t.filter))||ji.test(t.willChange||"")||Vi.test(t.contain||"")}function Ji(){return null==Ui&&(Ui="undefined"!=typeof CSS&&CSS.supports&&CSS.supports("-webkit-backdrop-filter","none")),Ui}function Gi(e){return/^(html|body|#document)$/.test($i(e))}function Qi(e){return qi(e).getComputedStyle(e)}function Xi(e){return Bi(e)?{scrollLeft:e.scrollLeft,scrollTop:e.scrollTop}:{scrollLeft:e.scrollX,scrollTop:e.scrollY}}function Yi(e){if("html"===$i(e))return e;const t=e.assignedSlot||e.parentNode||zi(e)&&e.host||Di(e);return zi(t)?t.host:t}function Zi(e){const t=Yi(e);return Gi(t)?e.ownerDocument?e.ownerDocument.body:e.body:Pi(t)&&Hi(t)?t:Zi(t)}function es(e,t,i){var s;void 0===t&&(t=[]),void 0===i&&(i=!0);const n=Zi(e),o=n===(null==(s=e.ownerDocument)?void 0:s.body),r=qi(n);if(o){const e=ts(r);return t.concat(r,r.visualViewport||[],Hi(n)?n:[],e&&i?es(e):[])}return t.concat(n,es(n,[],i))}function ts(e){return e.parent&&Object.getPrototypeOf(e.parent)?e.frameElement:null}function is(e){const t=Qi(e);let i=parseFloat(t.width)||0,s=parseFloat(t.height)||0;const n=Pi(e),o=n?e.offsetWidth:i,r=n?e.offsetHeight:s,l=hi(i)!==o||hi(s)!==r;return l&&(i=o,s=r),{width:i,height:s,$:l}}function ss(e){return Bi(e)?e:e.contextElement}function ns(e){const t=ss(e);if(!Pi(t))return pi(1);const i=t.getBoundingClientRect(),{width:s,height:n,$:o}=is(t);let r=(o?hi(i.width):i.width)/s,l=(o?hi(i.height):i.height)/n;return r&&Number.isFinite(r)||(r=1),l&&Number.isFinite(l)||(l=1),{x:r,y:l}}const os=pi(0);function rs(e){const t=qi(e);return Ji()&&t.visualViewport?{x:t.visualViewport.offsetLeft,y:t.visualViewport.offsetTop}:os}function ls(e,t,i,s){void 0===t&&(t=!1),void 0===i&&(i=!1);const n=e.getBoundingClientRect(),o=ss(e);let r=pi(1);t&&(s?Bi(s)&&(r=ns(s)):r=ns(e));const l=function(e,t,i){return void 0===t&&(t=!1),!(!i||t&&i!==qi(e))&&t}(o,i,s)?rs(o):pi(0);let a=(n.left+l.x)/r.x,c=(n.top+l.y)/r.y,d=n.width/r.x,h=n.height/r.y;if(o){const e=qi(o),t=s&&Bi(s)?qi(s):s;let i=e,n=ts(i);for(;n&&s&&t!==i;){const e=ns(n),t=n.getBoundingClientRect(),s=Qi(n),o=t.left+(n.clientLeft+parseFloat(s.paddingLeft))*e.x,r=t.top+(n.clientTop+parseFloat(s.paddingTop))*e.y;a*=e.x,c*=e.y,d*=e.x,h*=e.y,a+=o,c+=r,i=qi(n),n=ts(i)}}return Ai({width:d,height:h,x:a,y:c})}function as(e,t){const i=Xi(e).scrollLeft;return t?t.left+i:ls(Di(e)).left+i}function cs(e,t){const i=e.getBoundingClientRect();return{x:i.left+t.scrollLeft-as(e,i),y:i.top+t.scrollTop}}function ds(e,t,i){let s;if("viewport"===t)s=function(e,t){const i=qi(e),s=Di(e),n=i.visualViewport;let o=s.clientWidth,r=s.clientHeight,l=0,a=0;if(n){o=n.width,r=n.height;const e=Ji();(!e||e&&"fixed"===t)&&(l=n.offsetLeft,a=n.offsetTop)}const c=as(s);if(c<=0){const e=s.ownerDocument,t=e.body,i=getComputedStyle(t),n="CSS1Compat"===e.compatMode&&parseFloat(i.marginLeft)+parseFloat(i.marginRight)||0,r=Math.abs(s.clientWidth-t.clientWidth-n);r<=25&&(o-=r)}else c<=25&&(o+=c);return{width:o,height:r,x:l,y:a}}(e,i);else if("document"===t)s=function(e){const t=Di(e),i=Xi(e),s=e.ownerDocument.body,n=di(t.scrollWidth,t.clientWidth,s.scrollWidth,s.clientWidth),o=di(t.scrollHeight,t.clientHeight,s.scrollHeight,s.clientHeight);let r=-i.scrollLeft+as(e);const l=-i.scrollTop;return"rtl"===Qi(s).direction&&(r+=di(t.clientWidth,s.clientWidth)-n),{width:n,height:o,x:r,y:l}}(Di(e));else if(Bi(t))s=function(e,t){const i=ls(e,!0,"fixed"===t),s=i.top+e.clientTop,n=i.left+e.clientLeft,o=Pi(e)?ns(e):pi(1);return{width:e.clientWidth*o.x,height:e.clientHeight*o.y,x:n*o.x,y:s*o.y}}(t,i);else{const i=rs(e);s={x:t.x-i.x,y:t.y-i.y,width:t.width,height:t.height}}return Ai(s)}function hs(e,t){const i=Yi(e);return!(i===t||!Bi(i)||Gi(i))&&("fixed"===Qi(i).position||hs(i,t))}function us(e,t,i){const s=Pi(t),n=Di(t),o="fixed"===i,r=ls(e,!0,o,t);let l={scrollLeft:0,scrollTop:0};const a=pi(0);function c(){a.x=as(n)}if(s||!s&&!o)if(("body"!==$i(t)||Hi(n))&&(l=Xi(t)),s){const e=ls(t,!0,o,t);a.x=e.x+t.clientLeft,a.y=e.y+t.clientTop}else n&&c();o&&!s&&n&&c();const d=!n||s||o?pi(0):cs(n,l);return{x:r.left+l.scrollLeft-a.x-d.x,y:r.top+l.scrollTop-a.y-d.y,width:r.width,height:r.height}}function ps(e){return"static"===Qi(e).position}function ms(e,t){if(!Pi(e)||"fixed"===Qi(e).position)return null;if(t)return t(e);let i=e.offsetParent;return Di(e)===i&&(i=i.ownerDocument.body),i}function gs(e,t){const i=qi(e);if(Ni(e))return i;if(!Pi(e)){let t=Yi(e);for(;t&&!Gi(t);){if(Bi(t)&&!ps(t))return t;t=Yi(t)}return i}let s=ms(e,t);for(;s&&Ri(s)&&ps(s);)s=ms(s,t);return s&&Gi(s)&&ps(s)&&!Ki(s)?i:s||function(e){let t=Yi(e);for(;Pi(t)&&!Gi(t);){if(Ki(t))return t;if(Ni(t))return null;t=Yi(t)}return null}(e)||i}const fs={convertOffsetParentRelativeRectToViewportRelativeRect:function(e){let{elements:t,rect:i,offsetParent:s,strategy:n}=e;const o="fixed"===n,r=Di(s),l=!!t&&Ni(t.floating);if(s===r||l&&o)return i;let a={scrollLeft:0,scrollTop:0},c=pi(1);const d=pi(0),h=Pi(s);if((h||!h&&!o)&&(("body"!==$i(s)||Hi(r))&&(a=Xi(s)),h)){const e=ls(s);c=ns(s),d.x=e.x+s.clientLeft,d.y=e.y+s.clientTop}const u=!r||h||o?pi(0):cs(r,a);return{width:i.width*c.x,height:i.height*c.y,x:i.x*c.x-a.scrollLeft*c.x+d.x+u.x,y:i.y*c.y-a.scrollTop*c.y+d.y+u.y}},getDocumentElement:Di,getClippingRect:function(e){let{element:t,boundary:i,rootBoundary:s,strategy:n}=e;const o=[..."clippingAncestors"===i?Ni(t)?[]:function(e,t){const i=t.get(e);if(i)return i;let s=es(e,[],!1).filter(e=>Bi(e)&&"body"!==$i(e)),n=null;const o="fixed"===Qi(e).position;let r=o?Yi(e):e;for(;Bi(r)&&!Gi(r);){const t=Qi(r),i=Ki(r);i||"fixed"!==t.position||(n=null),(o?!i&&!n:!i&&"static"===t.position&&n&&("absolute"===n.position||"fixed"===n.position)||Hi(r)&&!i&&hs(e,r))?s=s.filter(e=>e!==r):n=t,r=Yi(r)}return t.set(e,s),s}(t,this._c):[].concat(i),s],r=ds(t,o[0],n);let l=r.top,a=r.right,c=r.bottom,d=r.left;for(let e=1;e<o.length;e++){const i=ds(t,o[e],n);l=di(i.top,l),a=ci(i.right,a),c=ci(i.bottom,c),d=di(i.left,d)}return{width:a-d,height:c-l,x:d,y:l}},getOffsetParent:gs,getElementRects:async function(e){const t=this.getOffsetParent||gs,i=this.getDimensions,s=await i(e.floating);return{reference:us(e.reference,await t(e.floating),e.strategy),floating:{x:0,y:0,width:s.width,height:s.height}}},getClientRects:function(e){return Array.from(e.getClientRects())},getDimensions:function(e){const{width:t,height:i}=is(e);return{width:t,height:i}},getScale:ns,isElement:Bi,isRTL:function(e){return"rtl"===Qi(e).direction}};function vs(e,t){return e.x===t.x&&e.y===t.y&&e.width===t.width&&e.height===t.height}function ys(e,t,i,s){void 0===s&&(s={});const{ancestorScroll:n=!0,ancestorResize:o=!0,elementResize:r="function"==typeof ResizeObserver,layoutShift:l="function"==typeof IntersectionObserver,animationFrame:a=!1}=s,c=ss(e),d=n||o?[...c?es(c):[],...t?es(t):[]]:[];d.forEach(e=>{n&&e.addEventListener("scroll",i,{passive:!0}),o&&e.addEventListener("resize",i)});const h=c&&l?function(e,t){let i,s=null;const n=Di(e);function o(){var e;clearTimeout(i),null==(e=s)||e.disconnect(),s=null}return function r(l,a){void 0===l&&(l=!1),void 0===a&&(a=1),o();const c=e.getBoundingClientRect(),{left:d,top:h,width:u,height:p}=c;if(l||t(),!u||!p)return;const m={rootMargin:-ui(h)+"px "+-ui(n.clientWidth-(d+u))+"px "+-ui(n.clientHeight-(h+p))+"px "+-ui(d)+"px",threshold:di(0,ci(1,a))||1};let g=!0;function f(t){const s=t[0].intersectionRatio;if(s!==a){if(!g)return r();s?r(!1,s):i=setTimeout(()=>{r(!1,1e-7)},1e3)}1!==s||vs(c,e.getBoundingClientRect())||r(),g=!1}try{s=new IntersectionObserver(f,{...m,root:n.ownerDocument})}catch(e){s=new IntersectionObserver(f,m)}s.observe(e)}(!0),o}(c,i):null;let u,p=-1,m=null;r&&(m=new ResizeObserver(e=>{let[s]=e;s&&s.target===c&&m&&t&&(m.unobserve(t),cancelAnimationFrame(p),p=requestAnimationFrame(()=>{var e;null==(e=m)||e.observe(t)})),i()}),c&&!a&&m.observe(c),t&&m.observe(t));let g=a?ls(e):null;return a&&function t(){const s=ls(e);g&&!vs(g,s)&&i();g=s,u=requestAnimationFrame(t)}(),i(),()=>{var e;d.forEach(e=>{n&&e.removeEventListener("scroll",i),o&&e.removeEventListener("resize",i)}),null==h||h(),null==(e=m)||e.disconnect(),m=null,a&&cancelAnimationFrame(u)}}const bs=function(e){return void 0===e&&(e=0),{name:"offset",options:e,async fn(t){var i,s;const{x:n,y:o,placement:r,middlewareData:l}=t,a=await async function(e,t){const{placement:i,platform:s,elements:n}=e,o=await(null==s.isRTL?void 0:s.isRTL(n.floating)),r=fi(i),l=vi(i),a="y"===bi(i),c=Ii.has(r)?-1:1,d=o&&a?-1:1,h=gi(t,e);let{mainAxis:u,crossAxis:p,alignmentAxis:m}="number"==typeof h?{mainAxis:h,crossAxis:0,alignmentAxis:null}:{mainAxis:h.mainAxis||0,crossAxis:h.crossAxis||0,alignmentAxis:h.alignmentAxis};return l&&"number"==typeof m&&(p="end"===l?-1*m:m),a?{x:p*d,y:u*c}:{x:u*c,y:p*d}}(t,e);return r===(null==(i=l.offset)?void 0:i.placement)&&null!=(s=l.arrow)&&s.alignmentOffset?{}:{x:n+a.x,y:o+a.y,data:{...a,placement:r}}}}},ws=function(e){return void 0===e&&(e={}),{name:"flip",options:e,async fn(t){var i,s;const{placement:n,middlewareData:o,rects:r,initialPlacement:l,platform:a,elements:c}=t,{mainAxis:d=!0,crossAxis:h=!0,fallbackPlacements:u,fallbackStrategy:p="bestFit",fallbackAxisSideDirection:m="none",flipAlignment:g=!0,...f}=gi(e,t);if(null!=(i=o.arrow)&&i.alignmentOffset)return{};const v=fi(n),y=bi(l),b=fi(l)===l,w=await(null==a.isRTL?void 0:a.isRTL(c.floating)),E=u||(b||!g?[Ci(l)]:function(e){const t=Ci(e);return[Ei(e),t,Ei(t)]}(l)),k="none"!==m;!u&&k&&E.push(...xi(l,g,m,w));const _=[l,...E],L=await a.detectOverflow(t,f),S=[];let x=(null==(s=o.flip)?void 0:s.overflows)||[];if(d&&S.push(L[v]),h){const e=function(e,t,i){void 0===i&&(i=!1);const s=vi(e),n=wi(e),o=yi(n);let r="x"===n?s===(i?"end":"start")?"right":"left":"start"===s?"bottom":"top";return t.reference[o]>t.floating[o]&&(r=Ci(r)),[r,Ci(r)]}(n,r,w);S.push(L[e[0]],L[e[1]])}if(x=[...x,{placement:n,overflows:S}],!S.every(e=>e<=0)){var C,A;const e=((null==(C=o.flip)?void 0:C.index)||0)+1,t=_[e];if(t){if(!("alignment"===h&&y!==bi(t))||x.every(e=>bi(e.placement)!==y||e.overflows[0]>0))return{data:{index:e,overflows:x},reset:{placement:t}}}let i=null==(A=x.filter(e=>e.overflows[0]<=0).sort((e,t)=>e.overflows[1]-t.overflows[1])[0])?void 0:A.placement;if(!i)switch(p){case"bestFit":{var T;const e=null==(T=x.filter(e=>{if(k){const t=bi(e.placement);return t===y||"y"===t}return!0}).map(e=>[e.placement,e.overflows.filter(e=>e>0).reduce((e,t)=>e+t,0)]).sort((e,t)=>e[1]-t[1])[0])?void 0:T[0];e&&(i=e);break}case"initialPlacement":i=l}if(n!==i)return{reset:{placement:i}}}return{}}}},Es=function(e){return void 0===e&&(e={}),{name:"size",options:e,async fn(t){var i,s;const{placement:n,rects:o,platform:r,elements:l}=t,{apply:a=()=>{},...c}=gi(e,t),d=await r.detectOverflow(t,c),h=fi(n),u=vi(n),p="y"===bi(n),{width:m,height:g}=o.floating;let f,v;"top"===h||"bottom"===h?(f=h,v=u===(await(null==r.isRTL?void 0:r.isRTL(l.floating))?"start":"end")?"left":"right"):(v=h,f="end"===u?"top":"bottom");const y=g-d.top-d.bottom,b=m-d.left-d.right,w=ci(g-d[f],y),E=ci(m-d[v],b),k=!t.middlewareData.shift;let _=w,L=E;if(null!=(i=t.middlewareData.shift)&&i.enabled.x&&(L=b),null!=(s=t.middlewareData.shift)&&s.enabled.y&&(_=y),k&&!u){const e=di(d.left,0),t=di(d.right,0),i=di(d.top,0),s=di(d.bottom,0);p?L=m-2*(0!==e||0!==t?e+t:di(d.left,d.right)):_=g-2*(0!==i||0!==s?i+s:di(d.top,d.bottom))}await a({...t,availableWidth:L,availableHeight:_});const S=await r.getDimensions(l.floating);return m!==S.width||g!==S.height?{reset:{rects:!0}}:{}}}},ks=(e,t,i)=>{const s=new Map,n={platform:fs,...i},o={...n.platform,_c:s};return(async(e,t,i)=>{const{placement:s="bottom",strategy:n="absolute",middleware:o=[],platform:r}=i,l=r.detectOverflow?r:{...r,detectOverflow:Oi},a=await(null==r.isRTL?void 0:r.isRTL(t));let c=await r.getElementRects({reference:e,floating:t,strategy:n}),{x:d,y:h}=Ti(c,s,a),u=s,p=0;const m={};for(let i=0;i<o.length;i++){const g=o[i];if(!g)continue;const{name:f,fn:v}=g,{x:y,y:b,data:w,reset:E}=await v({x:d,y:h,initialPlacement:s,placement:u,strategy:n,middlewareData:m,rects:c,platform:l,elements:{reference:e,floating:t}});d=null!=y?y:d,h=null!=b?b:h,m[f]={...m[f],...w},E&&p<50&&(p++,"object"==typeof E&&(E.placement&&(u=E.placement),E.rects&&(c=!0===E.rects?await r.getElementRects({reference:e,floating:t,strategy:n}):E.rects),({x:d,y:h}=Ti(c,u,a))),i=-1)}return{x:d,y:h,placement:u,strategy:n,middlewareData:m}})(e,t,{...n,platform:o})};class _s extends HTMLSelectElement{#Ee=null;connectedCallback(){this.classList.add("alchemy_selectbox"),this.#ke()}disconnectedCallback(){this.#_e()}enable(){this.removeAttribute("disabled"),this.#Ee?.enable()}disable(){this.setAttribute("disabled","disabled"),this.#Ee?.disable()}setOptions(e,t=void 0){const i=this.value;this.#_e(),this.innerHTML="",t&&this.add(new Option(t,"")),e.forEach(e=>{this.add(new Option(e.text,e.id,!1,e.id===i))}),this.#ke()}get allowClear(){return this.dataset.hasOwnProperty("allowClear")||this.multiple}get placeholder(){return this.getAttribute("placeholder")}#ke(){const e={},t=!!this.placeholder,i=!!this.querySelector("option[selected]"),s=document.createElement("div");s.className="ts-dropdown-mask";let n=()=>{};this.multiple&&(e.remove_button={title:d("Remove")}),this.allowClear&&(e.clear_button={html:()=>`<button type="button" class="clear-button" aria-label="${d("Clear selection")}">\n <alchemy-icon name="close" size="1x"></alchemy-icon>\n </button>`});const o={plugins:e,closeAfterSelect:!this.multiple,onInitialize:function(){this.input.autofocus&&this.focus(),t&&!i&&this.clear()},onType(e){this.control_input.classList.toggle("has-value",e.length>0)},refreshThrottle:0,onDropdownOpen:async function(){const e={minWidth:`${this.control.offsetWidth}px`};this.control.closest(".alchemy-dialog-body, .alchemy-popover")&&(e.zIndex="101"),Object.assign(this.dropdown.style,e),document.body.append(s),document.body.append(this.dropdown);n=ys(this.control,this.dropdown,async()=>{const{x:e,y:t}=await ks(this.control,this.dropdown,{middleware:[ws(),bs(2),Es({apply({availableHeight:e,elements:t}){Object.assign(t.floating.querySelector(".ts-dropdown-content").style,{maxHeight:`${Math.max(120,e-16)}px`})}})]});Object.assign(this.dropdown.style,{left:`${e}px`,top:`${t}px`})})},onDropdownClose:function(){this.control_input.classList.remove("has-value"),this.dropdown.remove(),s.remove(),n()},allowEmptyOption:!0,openOnFocus:!1,sortField:"$order",maxOptions:null,render:{option_create:(e,t)=>`<div class="create">\n ${d("Add")}<strong>${t(e.input)}</strong>…\n </div>`,no_results:()=>`<div class="no-results">${d("No results found")}</div>`}};this.#Ee=new Rt(this,o),this.#Ee.control.addEventListener("click",this.#Ee.open.bind(this.#Ee))}#_e(){this.#Ee?.destroy(),this.#Ee=null}}customElements.define("alchemy-select",_s,{extends:"select"});class Ls extends HTMLElement{connectedCallback(){this.searchInput=document.querySelector(".search_input_field"),this.clearButton=document.querySelector("#search_field_clear"),this.resultCounter=document.querySelector("#page_filter_result"),this.setupSearch(),requestAnimationFrame(()=>{this.setupSortables()}),this.observer=new MutationObserver(e=>{e.forEach(e=>{e.addedNodes.forEach(e=>{e.nodeType===Node.ELEMENT_NODE&&(e.classList?.contains("children")&&this.setupSortable(e),e.querySelectorAll(".children").forEach(e=>this.setupSortable(e)))})})}),this.observer.observe(this,{childList:!0,subtree:!0})}disconnectedCallback(){this.teardownSearch(),this.observer?.disconnect()}setupSearch(){this.searchInput?.addEventListener("input",this),this.clearButton?.addEventListener("click",this)}teardownSearch(){this.searchInput?.removeEventListener("input",this),this.clearButton?.removeEventListener("click",this)}handleEvent(e){"input"===e.type&&e.target===this.searchInput?this.handleSearch(e):"click"===e.type&&e.target===this.clearButton&&this.handleClearSearch(e)}handleSearch(e){const t=e.target.value.toLowerCase().trim();""!==t?this.filterPages(t):this.clearFilter()}filterPages(e){const t=this.querySelectorAll(".sitemap_page");let i=0,s=null;t.forEach(t=>{(t.getAttribute("name")||"").toLowerCase().includes(e)?(t.classList.add("highlight"),t.classList.remove("no-match"),i++,s||(s=t)):(t.classList.remove("highlight"),t.classList.add("no-match"))}),1===i?(this.resultCounter.textContent=`1 ${d("page_found")}`,this.resultCounter.style.display="block"):i>1?(this.resultCounter.textContent=`${i} ${d("pages_found")}`,this.resultCounter.style.display="block"):this.resultCounter.style.display="none",s&&s.scrollIntoView({behavior:"smooth",block:"center"})}clearFilter(){this.querySelectorAll(".sitemap_page").forEach(e=>{e.classList.remove("highlight","no-match")}),this.resultCounter.style.display="none"}handleClearSearch(e){e.preventDefault(),this.searchInput.value="",this.clearFilter()}setupSortable(e){new s(e,{group:"pages",animation:150,fallbackOnBody:!0,swapThreshold:.65,handle:".page-icon.handle",draggable:"alchemy-page-node",onEnd:e=>this.handleSort(e)})}setupSortables(){this.querySelectorAll(".children").forEach(e=>this.setupSortable(e))}async handleSort(e){if(e.from===e.to&&e.oldIndex===e.newIndex)return;const t=e.item,i=t.pageId,s=Alchemy.routes.move_admin_page_path(i),n={target_parent_id:e.to.dataset.parentId,new_position:e.newIndex};S(!0);try{const o=await Z(s,n),r=await o.data,l=t.querySelector(`#page_${i}`);if(l){const e=l.querySelector(".sitemap_url");e&&r.url_path&&(e.textContent=r.url_path)}this.updateFolderIcons(e.from,e.to),O(d("Successfully moved page"))}catch(e){O(e.message||e,"error"),window.location.reload()}finally{S(!1)}}updateFolderIcons(e,t){const i=e.closest("alchemy-page-node");if(i?.updateFolderButton(),e!==t){const e=t.closest("alchemy-page-node");e?.updateFolderButton()}}}customElements.define("alchemy-sitemap",Ls);const Ss={draggable:".element-editor",handle:".element-handle.draggable",ghostClass:"dragged",animation:150,swapThreshold:.65,easing:"cubic-bezier(1, 0, 0, 1)"};function xs(e){const t=e.item.dataset.elementName;document.querySelectorAll(`[data-droppable-elements~="${t}"]`).forEach(e=>e.classList.add("droppable-elements"))}function Cs(e){const t=e.item,i=e.to.parentElement.closest(".element-editor"),s={element_id:t.dataset.elementId,position:e.newIndex+1};i&&(s.parent_element_id=i.dataset.elementId),e.target===e.to&&ee(Alchemy.routes.order_admin_elements_path,s).then(e=>{const i=e.data;O(i.message),i.pageHasUnpublishedChanges&&oe(i),q(),t.updateTitle(i.preview_text)})}function As(){document.querySelectorAll("[data-droppable-elements]").forEach(e=>e.classList.remove("droppable-elements"))}class Ts extends HTMLElement{connectedCallback(){const e={name:this.dataset.elementName,put:(e,t,i)=>e.el.dataset.droppableElements.split(" ").includes(i.dataset.elementName)};new s(this,{...Ss,onStart:xs,onSort:Cs,onEnd:As,group:e})}}customElements.define("alchemy-sortable-elements",Ts);class Os extends HTMLElement{connectedCallback(){this.className=`spinner spinner--${this.size}`,this.innerHTML=`\n <svg width="100%" viewBox="0 0 28 28" style="--spinner-color: ${this.color}">\n <path\n class="hex1"\n d="M5.938,18.07l-5.878-5.9l2.154-8.058l8.024-2.161l5.87,5.9l-2.144,8.058L5.938,18.07z"\n />\n <path\n class="hex2"\n d="M19.686,20.785l-4.731-4.754l1.725-6.487l6.468-1.742l4.733,4.754l-1.734,6.487L19.686,20.785z"\n />\n <path\n class="hex3"\n d="M11.708,26.294l-3.47-3.485l1.276-4.758l4.74-1.276l3.468,3.485l-1.265,4.758L11.708,26.294z"\n />\n </svg>\n `}get size(){return this.getAttribute("size")||"medium"}get color(){return this.getAttribute("color")||"currentColor"}}customElements.define("alchemy-spinner",Os);class Is extends HTMLElement{#d=null;async connectedCallback(){await h(),this.isConnected&&(this.classList.add("autocomplete_tag_list"),this.#d=$(this.input).select2(this.select2Config))}disconnectedCallback(){this.#d?.select2("destroy"),this.#d=null}get input(){return this.getElementsByTagName("input")[0]}get select2Config(){return{tags:!0,tokenSeparators:[","],openOnEnter:!1,minimumInputLength:1,createSearchChoice:this.#Le,ajax:{url:this.getAttribute("url"),dataType:"json",data:e=>({term:e}),results:e=>({results:e})},initSelection:this.#Se}}#Le(e,t){if(0===$(t).filter(function(){return 0===this.text.localeCompare(e)}).length)return{id:e,text:e}}#Se(e,t){const i=[];$(e.val().split(",")).each(function(){i.push({id:this.trim(),text:this})}),t(i)}}customElements.define("alchemy-tags-autocomplete",Is);const Fs="alchemy-dark",$s="alchemy";class qs extends HTMLElement{#xe=null;connectedCallback(){this.className="tinymce_container",this.querySelector(":scope > alchemy-spinner")||this.insertAdjacentHTML("beforeend",'<alchemy-spinner size="small"></alchemy-spinner>'),this.style.minHeight=`${this.minHeight}px`,this.editor.style.display="none";const e={root:document.getElementById("element_area"),rootMargin:"0px",threshold:[.05]};this.tinymceIntersectionObserver=new IntersectionObserver((e,t)=>{e.forEach(e=>{e.intersectionRatio>0&&(this._initTinymceEditor(),t.unobserve(e.target))})},e),this.tinymceIntersectionObserver.observe(this),this._setupThemeChangeListener()}disconnectedCallback(){this.tinymceIntersectionObserver?.disconnect(),this._removeThemeChangeListener(),tinymce.get(this.editorId)?.remove(this.editorId)}_initTinymceEditor(){tinymce.init(this.configuration).then(e=>{e.forEach(e=>this._setupEditor(e))})}_setupEditor(e){e.show();const t=this.getElementsByTagName("alchemy-spinner")[0];t&&t.remove(),this.elementEditor&&(e.on("dirty",e=>{this.elementEditor.setDirty(e.target.editorContainer)}),e.on("click",()=>this.elementEditor.onClickElement(!1)))}_setupThemeChangeListener(){this.darkModeMediaQuery=window.matchMedia("(prefers-color-scheme: dark)"),this.themeChangeHandler=e=>this._handleThemeChange(e),this.darkModeMediaQuery.addEventListener("change",this.themeChangeHandler)}_removeThemeChangeListener(){this.darkModeMediaQuery&&this.themeChangeHandler&&this.darkModeMediaQuery.removeEventListener("change",this.themeChangeHandler)}_handleThemeChange(e){const t=tinymce.get(this.editorId);if(t){const i=e.matches?Fs:$s,s=e.matches?Fs:$s;t.remove(),tinymce.init({content_css:s,...this.configuration,skin:i}).then(e=>{e.forEach(e=>this._setupEditor(e))})}}get configuration(){const e={};this.getAttributeNames().forEach(t=>{if(!["class","id","is","name","style"].includes(t)){const i=this.getAttribute(t),s=t.replaceAll("-","_");if(i===t||""===i)e[s]=!0;else try{e[s]=JSON.parse(i)}catch(t){e[s]=i}}});const t={content_css:this.preferredTheme,...Alchemy.TinymceDefaults,...e,language:c(),selector:`#${this.editorId}`,skin:this.preferredTheme};return t.height=t.min_height,t}get preferredTheme(){return window.matchMedia("(prefers-color-scheme: dark)").matches?Fs:$s}get editorId(){return this.editor.id}get editor(){return this.getElementsByTagName("textarea")[0]}get elementEditor(){return document.getElementById(this.editorId).closest("alchemy-element-editor")}get minHeight(){return this.#xe||this.configuration.min_height}set minHeight(e){this.#xe=e}}customElements.define("alchemy-tinymce",qs);class Ds extends HTMLElement{async connectedCallback(){const e=new f("small");e.spin(this);try{const e=await fetch(this.url,{credentials:"include"}),t=await e.json();e.ok?this.showStatus(t):this.showError(e)}catch(e){this.showError(e)}finally{e.stop()}}get url(){return this.getAttribute("url")}showStatus(e){"true"==e.status?this.querySelector(".update_available").classList.remove("hidden"):this.querySelector(".up_to_date").classList.remove("hidden")}showError(e){this.querySelector(".error").classList.remove("hidden"),console.error("[alchemy] Error fetching update status",e)}}var Ms;customElements.define("alchemy-update-check",Ds),Ms=Handlebars.template,(Handlebars.templates=Handlebars.templates||{})["node_folder.hbs"]=Ms({0:function(e,t,i,s,n){return"right"},1:function(e,t,i,s,n){return"down"},compiler:[8,">= 4.3.0"],main:function(e,t,i,s,n){var o,r=e.lambda,l=e.escapeExpression,a=e.lookupProperty||function(e,t){if(Object.prototype.hasOwnProperty.call(e,t))return e[t]};return'<a class="node_folder" data-record-id="'+l(r(null!=(o=null!=t?a(t,"node"):t)?a(o,"id"):o,t))+'" data-record-type="'+l(r(null!=(o=null!=t?a(t,"node"):t)?a(o,"type"):o,t))+'">\n <alchemy-icon name="arrow-'+(null!=(o=a(i,"if").call(null!=t?t:e.nullContext||{},null!=(o=null!=t?a(t,"node"):t)?a(o,"folded"):o,{name:"if",hash:{},fn:e.program(0,n,0),inverse:e.program(1,n,0),data:n,loc:{start:{line:2,column:28},end:{line:2,column:72}}}))?o:"")+'-s"></alchemy-icon>\n</a>\n'},useData:!0}),n("tooltip.show",{keyframes:[{transform:"translateY(10px)",opacity:"0"},{transform:"translateY(0)",opacity:"1"}],options:{duration:100}}),n("tooltip.hide",{keyframes:[{transform:"translateY(0)",opacity:"1"},{transform:"translateY(10px)",opacity:"0"}],options:{duration:100}}),n("dialog.show",{keyframes:[{transform:"scale(0.98)",opacity:"0"},{transform:"scale(1)",opacity:"1"}],options:{duration:150}}),n("dialog.hide",{keyframes:[{transform:"scale(1)",opacity:"1"},{transform:"scale(0.98)",opacity:"0"}],options:{duration:150}});const Bs=document.querySelector('link[rel="preload"][as="image"]').getAttribute("href"),Ps={"x-lg":"close",caret:"arrow-down-s"},zs={resolver:e=>`${Bs}#ri-${Ps[e]||e}-line`,mutator:e=>{e.setAttribute("fill","currentColor"),e.setAttribute("viewBox","0 0 24 24")},spriteSheet:!0};function Hs(e,t,i,s){document.querySelectorAll(t).forEach(t=>{t.addEventListener(e,e=>{const n=Array.from(t.querySelectorAll(i));let o=e.target;for(;o!==t;){if(n.includes(o))return void s.call(o,e);o=o.parentElement}})})}o("default",zs),o("system",zs);class Rs{#Ce=!1;#Ae=null;#Te=null;#Oe=null;constructor(e,t){this.image=e,this.defaultBox=t.default_box,this.aspectRatio=t.ratio,this.#Te=document.getElementById(t.crop_from_form_field_id),this.#Oe=document.getElementById(t.crop_size_form_field_id),this.elementId=t.element_id,this.elementEditor=document.querySelector(`[data-element-id='${this.elementId}']`),this.dialog=Alchemy.currentDialog(),this.dialog&&(this.dialog.options.closed=()=>this.destroy(),this.bind()),this.init()}get cropperOptions(){return{aspectRatio:this.aspectRatio,viewMode:1,zoomable:!1,checkCrossOrigin:!1,checkOrientation:!1,data:this.box}}get cropFrom(){if(this.#Te?.value)return this.#Te.value.split("x").map(e=>parseInt(e))}get cropSize(){if(this.#Oe?.value)return this.#Oe.value.split("x").map(e=>parseInt(e))}get box(){return this.cropFrom&&this.cropSize?{x:this.cropFrom[0],y:this.cropFrom[1],width:this.cropSize[0],height:this.cropSize[1]}:this.defaultBoxSize}get defaultBoxSize(){return{x:this.defaultBox[0],y:this.defaultBox[1],width:this.defaultBox[2],height:this.defaultBox[3]}}init(){this.#Ce||(this.#Ae=new r(this.image,this.cropperOptions),this.#Ce=!0)}update(e){this.#Te.value=`${e.x}x${e.y}`,this.#Te.dispatchEvent(new Event("change")),this.#Oe.value=`${e.width}x${e.height}`,this.#Oe.dispatchEvent(new Event("change"))}reset(){const e=this.#Ae;e.setData(this.defaultBoxSize);const t=e.getCanvasData(),i=t.width/t.naturalWidth;e.setCropBoxData({left:t.left+this.defaultBoxSize.x*i,top:t.top+this.defaultBoxSize.y*i}),this.update(this.defaultBoxSize)}destroy(){return this.#Ae&&this.#Ae.destroy(),this.#Ce=!1,!0}bind(){this.dialog.dialog_body.find('button[type="submit"]').on("click",()=>{const e=this.#Ae.getData(!0);return this.update(e),this.elementEditor.setDirty(),this.dialog.close(),!1}),this.dialog.dialog_body.find('button[type="reset"]').on("click",()=>(this.reset(),!1))}}class Ns extends b{constructor(e,t={}){super(e,t)}init(){$(".zoomed-picture-background").on("click",e=>{if(e.stopPropagation(),"IMG"!==e.target.nodeName)return this.close(),!1}),$(".picture-overlay-handle").on("click",e=>(this.dialog.toggleClass("hide-form"),!1)),this.$previous=$(".previous-picture"),this.$next=$(".next-picture"),this.#Ie(),super.init()}previous(){null!=this.$previous[0]&&this.$previous[0].click()}next(){null!=this.$next[0]&&this.$next[0].click()}build(){this.dialog_container=$('<div class="alchemy-image-overlay-container" />'),this.dialog=$('<div class="alchemy-image-overlay-dialog" />'),this.dialog_body=$('<div class="alchemy-image-overlay-body" />'),this.close_button=$('<a class="alchemy-image-overlay-close">\n <alchemy-icon name="close" size="xl"></alchemy-icon>\n </a>'),this.dialog.append(this.close_button),this.dialog.append(this.dialog_body),this.dialog_container.append(this.dialog),this.overlay=$('<div class="alchemy-image-overlay" />'),this.$body.append(this.overlay),this.$body.append(this.dialog_container)}#Ie(){this.$document.keydown(e=>{if("INPUT"===e.target.nodeName||"TEXTAREA"===e.target.nodeName)return!0;switch(e.which){case 37:return this.previous(),!1;case 39:return this.next(),!1;default:return!0}})}}function js(){return document.querySelectorAll("#picture_archive input:checked")}function Vs(){const e=document.querySelector("#select_all_pictures"),t=document.querySelector(".selected_item_tools");Hs("click",".toolbar_buttons","a#select_all_pictures",i=>{i.preventDefault(),e.classList.toggle("active");const s=e.classList.contains("active");!function(e){document.querySelectorAll(".picture_tool.select input[type='checkbox']").forEach(t=>{t.checked=e,t.closest(".picture_thumbnail").classList.toggle("active",e)})}(s),t.classList.toggle("hidden",!s)}),Hs("change",".picture_tool.select","input",e=>{t.classList.toggle("hidden",0===js().length);const i=e.target.parentElement.classList,s=e.target.checked;i.toggle("visible",s)}),Hs("click",".selected_item_tools","a#edit_multiple_pictures",e=>{e.preventDefault();k(function(e){const t=new URL(e);return js().forEach(e=>t.searchParams.append(e.name,e.value)),t.toString()}(e.target.href),{title:e.target.title,size:"400x295"})})}function Ws(){document.querySelectorAll("li.menu-item").forEach(e=>{const t=e.querySelector(".nodes_tree-left_images"),i=e.querySelector(".children"),s={folded:"true"===e.dataset.folded,id:e.dataset.id,type:e.dataset.type};i.children.length>0||s.folded?t.innerHTML=Handlebars.templates["node_folder.hbs"]({node:s}):t.innerHTML=" "})}function Us(e){Z(Alchemy.routes[e.item.dataset.type].move_api_path(e.item.dataset.id),{target_parent_id:e.to.dataset.recordId,new_position:e.newIndex}).then(()=>{O(Alchemy.t("Successfully moved menu item")),Ws()}).catch(e=>{O(e.message||e,"error")})}function Ks(){Hs("click",".nodes_tree",".node_folder",function(){const e=this.dataset.recordId,t=this.closest("li.menu-item"),i=Alchemy.routes[this.dataset.recordType].toggle_folded_api_path(e),s=t.querySelector(".children");Z(i).then(()=>{s.classList.toggle("folded"),t.dataset.folded="true"==t.dataset.folded?"false":"true",Ws()}).catch(e=>{O(e.message||e)})}),Ws(),document.querySelectorAll(".nodes_tree ul.children").forEach(e=>{new s(e,{group:"nodes",animation:150,fallbackOnBody:!0,swapThreshold:.65,handle:".node_name",invertSwap:!0,onEnd:Us})})}void 0===window.Alchemy&&(window.Alchemy={}),Object.assign(Alchemy,{closeCurrentDialog:E,currentDialog:w,...C,t:d,FixedElements:T,growl:O,LinkDialog:class extends b{#Fe;constructor(e){const t=new URL(Alchemy.routes.link_admin_pages_path,window.location),i={url:e.url,selected_tab:e.type,link_title:e.title,link_target:e.target};Object.keys(i).forEach(e=>{i[e]&&t.searchParams.set(e,i[e])}),super(t.href,{size:"600x320",title:d("Link")})}replace(e){super.replace(e),this.#a()}open(){return super.open(),new Promise(e=>this.#Fe=e)}#a(){const e=document.querySelector('[data-link-form-type="internal"]'),t=document.querySelector('[data-link-form-type="file"] alchemy-attachment-select');e.addEventListener("Alchemy.RemoteSelect.Change",e=>{this.#$e(e.detail.added)}),t.addEventListener("Alchemy.RemoteSelect.Change",e=>{const t=e.detail.added;document.getElementById("file_link").value=t?t.url:""}),document.querySelectorAll("[data-link-form-type]").forEach(e=>{e.addEventListener("submit",e=>{e.preventDefault(),this.#qe(e.target.dataset.linkFormType)})})}#$e(e=null){const t=document.getElementById("internal_link"),i=document.querySelector('[data-link-form-type="internal"] alchemy-dom-id-api-select');t.value=e?e.url_path:"",i.page=e?e.id:void 0}#qe(e){const t=document.getElementById("element_anchor");let i=document.getElementById(`${e}_link`).value;if("internal"===e&&""!==t.value)i=i.replace(I,"")+t.value;else if("external"===e&&!i.match(Alchemy.link_url_regexp))return void this.#De();this.#Fe({url:i.trim(),title:document.getElementById(`${e}_link_title`).value,target:document.getElementById(`${e}_link_target`)?.value,type:e}),this.close()}#De(){const e=document.getElementById("errors");e.querySelector("ul").innerHTML=`<li>${Alchemy.t("url_validation_failed")}</li>`,e.style.display="block"}},pleaseWaitOverlay:S,Spinner:f,reloadPreview:q}),t.start(),e.config.forms.confirm=L,document.addEventListener("turbo:load",function(){document.documentElement.classList.remove("no-js"),m(),document.querySelectorAll(".please_wait").forEach(e=>{e.addEventListener("click",S)}),document.querySelectorAll("a.button").forEach(e=>{e.setAttribute("tabindex",0)}),key.filter=function(e){let t=(e.target||e.srcElement).tagName;return key.isPressed("esc")||!("INPUT"===t||"SELECT"===t||"TEXTAREA"===t)}});export{Rs as ImageCropper,Ns as ImageOverlay,Ks as NodeTree,P as RemoteSelect,Hs as on,Vs as pictureSelector};
|
|
9
|
+
>>>>>>> 81677ebac (Update build artifacts)
|
|
6
10
|
//# sourceMappingURL=alchemy_admin.min.js.map
|