diff --git a/app/assets/builds/alchemy/alchemy_admin.min.js b/app/assets/builds/alchemy/alchemy_admin.min.js index 3ea6e9f864..d165306f61 100644 --- a/app/assets/builds/alchemy/alchemy_admin.min.js +++ b/app/assets/builds/alchemy/alchemy_admin.min.js @@ -1,2 +1,2 @@ -import"handlebars";import"@ungap/custom-elements";import{Turbo as e}from"@hotwired/turbo-rails";import t from"@rails/ujs";import"keymaster";import"clipboard";import i from"flatpickr";import s from"cropperjs";import n from"sortablejs";import"tinymce";import{setDefaultAnimation as o,registerIconLibrary as r}from"shoelace";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}const h=[];function u(e=document){e===document&&h.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}),h.push("alt+f"),key("esc","search",function(){i.forEach(e=>e.click()),t.forEach(e=>e.blur())}),h.push("esc"),e.querySelectorAll("[data-alchemy-hotkey]").forEach(function(e){const t=e.dataset.alchemyHotkey;key(t,()=>e.click()),h.push(t)})}function p(e){const t=document.createElement("template");return t.innerHTML=e,t.content.children[0]}let m=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=p(``),e.append(this.spinner),this}stop(){this.spinner&&(this.spinner.remove(),this.spinner=void 0)}};function g(e,t,i={}){e.dispatchEvent(new CustomEvent(t,{bubbles:!0,detail:i}))}function f(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}})})}const v=[],y={header_height:36,size:"400x300",padding:!0,title:"",modal:!0,overflow:"visible",ready:()=>{},closed:()=>{}};class b{#e=null;#t=!1;constructor(e,t={}){this.url=e,this.options={...y,...t};const i=this.options.size.split("x");this.width=parseInt(i[0],10),this.height=parseInt(i[1],10),this.build(),this.resize()}open(){g(this.dialog,"Alchemy.DialogOpen"),this.bind_close_events(),this.options.modal?(this.dialog_container.showModal(),this.#i()):this.dialog_container.show(),window.requestAnimationFrame(()=>{this.dialog_container.classList.add("open")}),document.body.classList.add("prevent-scrolling"),v.push(this),this.load()}close(){return this.#t||(this.#t=!0,g(this.dialog,"DialogClose.Alchemy"),this.dialog_container.classList.remove("open"),this.dialog_container.addEventListener("transitionend",()=>{this.#s(),this.dialog_container.close(),this.dialog_container.remove(),v.pop(),0===v.length&&document.body.classList.remove("prevent-scrolling"),null!=this.options.closed&&this.options.closed()},{once:!0})),!0}#i(){const e=document.getElementById("flash_notices");e&&(this.#e=e.parentElement,this.dialog_container.append(e),this.#n(e))}#s(){const e=document.getElementById("flash_notices");e&&this.#e&&(this.#e.append(e),this.#n(e))}#n(e){e.querySelectorAll('alchemy-message[dismissable]:not([type="error"])').forEach(e=>e.remove())}load(){this.show_spinner(),fetch(this.url,{headers:{"X-Requested-With":"XMLHttpRequest"}}).then(async e=>{const t=await e.text();e.ok?this.replace(t):this.show_error({status:e.status,statusText:e.statusText,responseText:t})}).catch(()=>{this.show_error({status:0})})}reload(){this.dialog_body.innerHTML="",this.load()}replace(e){this.remove_spinner(),this.dialog_body.style.display="none",this.dialog_body.innerHTML=e,this.init(),g(this.dialog,"DialogReady.Alchemy",{body:this.dialog_body}),null!=this.options.ready&&this.options.ready(this.dialog_body),this.dialog_body.style.display=""}show_spinner(){this.spinner=new m("medium"),this.spinner.spin(this.dialog_body)}remove_spinner(){this.spinner.stop()}init(){u(this.dialog_body),this.watch_remote_forms(),window.requestAnimationFrame(()=>this.#o())}#o(e=0){const t=this.dialog_body.querySelector("[autofocus]")??this.dialog_body.querySelector("form [type='submit']");t?.focus(),document.activeElement===this.close_button&&e<20&&window.requestAnimationFrame(()=>this.#o(e+1))}watch_remote_forms(){this.dialog_body.querySelectorAll('[data-remote="true"]').forEach(e=>{e.addEventListener("ajax:success",e=>{const t=e.detail[2];t.getResponseHeader("Content-Type").match(/javascript/)||(this.dialog_body.innerHTML=t.responseText,this.init())}),e.addEventListener("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.innerHTML=e.responseText,void this.init();const{error_body:i,error_header:s,error_type:n}=this.error_messages(e,t);this.dialog_body.innerHTML=`\n

${s}

\n

${i}

\n
`}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.addEventListener("click",e=>{e.preventDefault(),this.close()}),this.dialog_container.classList.add("closable"),this.dialog_container.addEventListener("pointerdown",e=>{e.target===this.dialog_container&&this.close()}),this.dialog_container.addEventListener("cancel",e=>{e.preventDefault(),this.close()})}build(){this.dialog_container=p(''),this.dialog=p('
'),this.dialog_body=p('
'),this.dialog_header=p('
'),this.dialog_title=p('
'),this.close_button=p(''),this.dialog_title.textContent=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.classList.add("modal"),this.options.padding&&this.dialog_body.classList.add("padded"),document.body.append(this.dialog_container)}resize(){const{width:e,height:t}=this.getSize();this.dialog.style.width=`${e}px`,this.dialog.style.minHeight=`${t}px`,this.dialog.style.overflow=this.options.overflow,"hidden"===this.options.overflow?(this.dialog_body.style.height=`${t}px`,this.dialog_body.style.overflow="auto"):(this.dialog_body.style.minHeight=`${t}px`,this.dialog_body.style.overflow="visible")}getSize(){const e=this.options.padding?16:0,t=window.innerWidth,i=window.innerHeight;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 L{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.#r(),this.#l()}open(){requestAnimationFrame(()=>{this.dialog.show()})}#r(){const e=this.options.size.split("x")[0];this.dialog=p(`\n \n ${this.message}\n \n \n \n `);(w()?.dialog_container??document.body).append(this.dialog)}#l(){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(i=>{new L(e,{...t,on_ok(){i(!0)},on_cancel(){i(!1)}}).open()})}function x(e=!0){document.querySelector("alchemy-overlay").show=!!e}function S(e){let t=()=>{};e.matches("form")?t=function(){const t=document.createElement("form");t.action=e.action,t.method="POST",t.style.display="none",e.querySelectorAll("input").forEach(e=>t.append(e)),document.body.append(t),x(),t.requestSubmit()}:e.matches("a")&&(t=()=>Turbo.visit(e.pathname));return!(document.querySelectorAll("alchemy-element-editor.dirty").length>0)||(_(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:S,PageLeaveObserver:function(){document.querySelectorAll("#main_navi a").forEach(e=>{e.addEventListener("click",e=>{S(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 O=Object.freeze({__proto__:null,createTab:function(e,t){const i=document.getElementById("fixed-elements"),s=`fixed-element-${e}`,n=`${t}`,o=``;i.innerHTML+=n+o,window.requestAnimationFrame(function(){i.show(s)})},removeTab:A});function T(e,t="notice"){!function(e,t){const i=document.getElementById("flash_notices"),s=p(`\n \n ${e}\n \n `);i.append(s)}(e,t)}function I(e){return!(!e.target.matches("input, textarea")&&"?"===String.fromCharCode(e.which))||(k("/admin/help",{title:Alchemy.t("help"),size:"400x492"}),!1)}const F=/#[\w.~-]+$/;class q extends HTMLIFrameElement{#a;#c;#d;handleEvent(e){"load"===e.type&&(this.#h(),this.#u(),this.#a?.call(this,e))}#p=e=>{"Alchemy.previewReady"===e.data.message&&(this.#h(),this.#u(),this.#a?.call(this,e))};connectedCallback(){let e=this.url;this.addEventListener("load",this),this.#m(),window.addEventListener("message",this.#p),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.#p)}postMessage(e){this.contentWindow.postMessage(e,"*")}resize(e){this.style.width=`${e}px`}refresh(e){return this.#g(),this.src=e||this.url,this.#h(),this.#d=setTimeout(()=>{this.#u(),T(d("Preview failed to load"),"warning")},5e3),new Promise(e=>{this.#a=e})}set isDragged(e){this.style.transitionProperty=e?"none":null,this.style.pointerEvents=e?"none":null}#m(){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)})}#g(){this.reloadButton.innerHTML.includes("alchemy-spinner")||(this.#c=this.reloadButton.innerHTML),this.reloadButton.innerHTML=''}#u(){this.reloadButton.innerHTML=this.#c}#h(){this.#d&&(clearTimeout(this.#d),this.#d=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 $(){document.getElementById("alchemy_preview_window").refresh()}customElements.define("alchemy-preview-window",q,{extends:"iframe"}),e.StreamActions.assign_picture=function(){const[e]=this.targetElements;e&&(e.value=this.getAttribute("picture-id"),e.setAttribute("data-image-file-width",this.getAttribute("image-file-width")),e.setAttribute("data-image-file-height",this.getAttribute("image-file-height")),E(()=>{e.closest("alchemy-element-editor")?.setDirty()}))},e.StreamActions.assign_attachment=function(){const[e]=this.targetElements;if(!e)return;const t=e.parentElement;e.value=this.getAttribute("attachment-id"),t.querySelector(":scope > .file_name").textContent=this.getAttribute("attachment-name"),t.querySelector(":scope > .file_icon").replaceChildren(this.templateContent),t.querySelector(":scope > .remove_file_link").classList.remove("hidden"),E(()=>{e.closest("alchemy-element-editor")?.setDirty(e)})};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:$,removeFixedElement:A,updateAnchorIcon:D.updateIcon,hidePleaseWaitOverlay(){x(!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 H(e,t){e.split(/\s+/).forEach(e=>{t(e)})}customElements.define("alchemy-action",M);class P{constructor(){this._events={}}on(e,t){H(e,e=>{const i=this._events[e]||[];i.push(t),this._events[e]=i})}off(e,t){var i=arguments.length;0!==i?H(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;H(e,e=>{const s=i._events[e];void 0!==s&&s.forEach(e=>{e.apply(i,t)})})}}const B=e=>(e=e.filter(Boolean)).length<2?e[0]||"":1==W(e)?"["+e.join("")+"]":"(?:"+e.join("|")+")",z=e=>{if(!N(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},R=e=>{let t=Array.from(e);return B(t)},N=e=>new Set(e).size!==e.length,j=e=>(e+"").replace(/([\$\(\)\*\+\.\?\[\]\^\{\|\}\\])/gu,"\\$1"),W=e=>e.reduce((e,t)=>Math.max(e,U(t)),0),U=e=>Array.from(e).length,V=e=>{if(1===e.length)return[[e]];let t=[];const i=e.substring(1);return V(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},K=[[0,65535]];let J,G;const X={},Q={"/":"⁄∕",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 Q){let t=Q[e]||"";for(let i=0;ie.normalize(t),ee=e=>Array.from(e).reduce((e,t)=>e+te(t),""),te=e=>(e=Z(e).toLowerCase().replace(Y,e=>X[e]||""),Z(e,"NFC"));const ie=e=>{const t={},i=(e,i)=>{const s=t[e]||new Set,n=new RegExp("^"+R(s)+"$","iu");i.match(n)||(s.add(j(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=ee(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},se=e=>{const t=ie(e),i={};let s=[];for(let e in t){let n=t[e];n&&(i[e]=R(n)),e.length>1&&s.push(j(e))}s.sort((e,t)=>t.length-e.length);const n=B(s);return G=new RegExp("^"+n,"u"),i},ne=(e,t=1)=>(t=Math.max(t,e.length-1),B(V(e).map(e=>((e,t=1)=>{let i=0;return e=e.map(e=>(J[e]&&(i+=e.length),J[e]||e)),i>=t?z(e):""})(e,t)))),oe=(e,t=!0)=>{let i=e.length>1?1:0;return B(e.map(e=>{let s=[];const n=t?e.length():e.length()-1;for(let t=0;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.starti.start)return!0;if(i.starte.start)return!0}}return!1};if(!(i.parts.filter(s).length>0))return!0}return!1};class le{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 le,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 ae=e=>{void 0===J&&(J=se(K)),e=ee(e);let t="",i=[new le];for(let s=0;s0){l=l.sort((e,t)=>e.length()-t.length());for(let e of l)re(e,i)||i.push(e)}else if(s>0&&1==a.size&&!a.has("3")){t+=oe(i,!1);let e=new le;const s=i[0];s&&e.add(s.last()),i=[e]}}return t+=oe(i,!0),t},ce=(e,t)=>{if(e)return e[t]},de=(e,t)=>{if(e){for(var i,s=t.split(".");(i=s.shift())&&(e=e[i]););return e}},he=(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},ue=(e,t)=>{var i=e[t];if("function"==typeof i)return i;i&&!Array.isArray(i)&&(e[t]=[i])},pe=(e,t)=>{if(Array.isArray(e))e.forEach(t);else for(var i in e)e.hasOwnProperty(i)&&t(e[i],i)},me=(e,t)=>"number"==typeof e&&"number"==typeof t?e>t?1:e(t=ee(t+"").toLowerCase())?1:t>e?-1:0;class ge{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(j).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?ae(e)||null:j(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 he(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+=he(s,e,1)}else pe(n,(s,n)=>{i+=he(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 pe(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)*me(r(n,e),r(n,t)))return s}return 0}:null}prepareSearch(e,t){const i={};var s=Object.assign({},t);if(ue(s,"sort"),ue(s,"sort_empty"),s.fields){ue(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?de:ce}}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?pe(n.items,(e,n)=>{i=o(e),(!1===t.filter||i>0)&&s.items.push({score:i,id:n})}):pe(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 fe=e=>null==e?null:ve(e),ve=e=>"boolean"==typeof e?e?"1":"0":e+"",ye=e=>(e+"").replace(/&/g,"&").replace(//g,">").replace(/"/g,"""),be=(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)}},we=(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])},Ee=(e,t=!1)=>{e&&(e.preventDefault(),t&&e.stopPropagation())},ke=(e,t,i,s)=>{e.addEventListener(t,i,s)},Le=(e,t)=>!!t&&(!!t[e]&&1===(t.altKey?1:0)+(t.ctrlKey?1:0)+(t.shiftKey?1:0)+(t.metaKey?1:0)),_e=(e,t)=>{const i=e.getAttribute("id");return i||(e.setAttribute("id",t),t)},xe=e=>e.replace(/[\\"']/g,"\\$&"),Se=(e,t)=>{t&&e.append(t)},Ce=(e,t)=>{if(Array.isArray(e))e.forEach(t);else for(var i in e)e.hasOwnProperty(i)&&t(e[i],i)},Ae=e=>{if(e.jquery)return e[0];if(e instanceof HTMLElement)return e;if(Oe(e)){var t=document.createElement("template");return t.innerHTML=e.trim(),t.content.firstChild}return document.querySelector(e)},Oe=e=>"string"==typeof e&&e.indexOf("<")>-1,Te=(e,t)=>{var i=document.createEvent("HTMLEvents");i.initEvent(t,!0,!1),e.dispatchEvent(i)},Ie=(e,t)=>{Object.assign(e.style,t)},Fe=(e,...t)=>{var i=$e(t);(e=De(e)).map(e=>{i.map(t=>{e.classList.add(t)})})},qe=(e,...t)=>{var i=$e(t);(e=De(e)).map(e=>{i.map(t=>{e.classList.remove(t)})})},$e=e=>{var t=[];return Ce(e,e=>{"string"==typeof e&&(e=e.trim().split(/[\t\n\f\r\s]/)),Array.isArray(e)&&(t=t.concat(e))}),t.filter(Boolean)},De=e=>(Array.isArray(e)||(e=[e]),e),Me=(e,t,i)=>{if(!i||i.contains(e))for(;e&&e.matches;){if(e.matches(t))return e;e=e.parentNode}},He=(e,t=0)=>t>0?e[e.length-1]:e[0],Pe=(e,t)=>{if(!e)return-1;t=t||e.nodeName;for(var i=0;e=e.previousElementSibling;)e.matches(t)&&i++;return i},Be=(e,t)=>{Ce(t,(t,i)=>{null==t?e.removeAttribute(i):e.setAttribute(i,""+t)})},ze=(e,t)=>{e.parentNode&&e.parentNode.replaceChild(t,e)},Re=(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),ze(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)},Ne="undefined"!=typeof navigator&&/Mac/.test(navigator.userAgent)?"metaKey":"ctrlKey";var je={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:'',copyClassesToDropdown:!1,placeholder:null,hidePlaceholder:null,shouldLoad:function(e){return e.length>0},render:{}};function We(e,t){var i=Object.assign({},je,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=fe(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,Ce(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],Ce(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),Ce(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);Ce(s,e=>{const t={};t[n]=e,t[o]=e,u.options.push(t)}),u.items=s}})(),Object.assign({},je,u,t)}var Ue=0;class Ve 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]}}}(P)){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,Ue++;var s=Ae(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=We(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=_e(s,"tomselect-"+Ue),this.isRequired=s.required,this.sifter=new ge(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=Ae("
"),l=Ae("
"),a=this._render("dropdown"),c=Ae('
'),d=this.input.getAttribute("class")||"",h=n.mode;var u;if(Fe(r,n.wrapperClass,d,h),Fe(l,n.controlClass),Se(r,l),Fe(a,n.dropdownClass,h),n.copyClassesToDropdown&&Fe(a,d),Fe(c,n.dropdownContentClass),Se(a,c),Ae(n.dropdownParent||r).appendChild(a),Oe(n.controlInput)){u=Ae(n.controlInput);Ce(["autocorrect","autocapitalize","autocomplete","spellcheck","aria-label"],e=>{s.getAttribute(e)&&Be(u,{[e]:s.getAttribute(e)})}),u.tabIndex=-1,l.appendChild(u),this.focus_node=u}else n.controlInput?(u=Ae(n.controlInput),this.focus_node=u):(u=Ae(""),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";Be(n,{id:d}),Be(a,{role:"combobox","aria-haspopup":"listbox","aria-expanded":"false","aria-controls":d});const h=_e(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){ke(p,"click",m),Be(p,{for:h});const t=_e(p,e.inputId+"-ts-label");Be(a,{"aria-labelledby":t}),Be(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-");Fe([o,s],t)}(null===t.maxItems||t.maxItems>1)&&e.is_select_tag&&Be(l,{multiple:"multiple"}),t.placeholder&&Be(i,{placeholder:t.placeholder}),!t.splitOn&&t.delimiter&&(t.splitOn=new RegExp("\\s*"+j(t.delimiter)+"+\\s*")),t.load&&t.loadThrottle&&(t.load=be(t.load,t.loadThrottle)),ke(s,"mousemove",()=>{e.ignoreHover=!1}),ke(s,"mouseenter",t=>{var i=Me(t.target,"[data-selectable]",s);i&&e.onOptionHover(t,i)},{capture:!0}),ke(s,"click",t=>{const i=Me(t.target,"[data-selectable]");i&&(e.onOptionSelect(t,i),Ee(t,!0))}),ke(r,"click",t=>{var s=Me(t.target,"[data-ts-item]",r);s&&e.onItemSelect(t,s)?Ee(t,!0):""==i.value&&(e.onClick(),Ee(t,!0))}),ke(a,"keydown",t=>e.onKeyDown(t)),ke(i,"keypress",t=>e.onKeyPress(t)),ke(i,"input",t=>e.onInput(t)),ke(a,"blur",t=>e.onBlur(t)),ke(a,"focus",t=>e.onFocus(t)),ke(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():Ee(t,!0)},f=()=>{e.isOpen&&e.positionDropdown()},v=()=>{e.isValid&&(e.isValid=!1,e.isInvalid=!0,e.refreshState())};ke(l,"invalid",v),ke(document,"mousedown",g),ke(window,"scroll",f,c),ke(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),Fe(l,"tomselected","ts-hidden-accessible"),e.trigger("initialize"),!0===t.preload&&e.preload()}setupOptions(e=[],t=[]){this.addOptions(e),Ce(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)=>'
'+t(e[i])+"
",option:(e,i)=>"
"+i(e[t])+"
",item:(e,i)=>"
"+i(e[t])+"
",option_create:(e,t)=>'
Add '+t(e.input)+"
",no_results:()=>'
No results found
',loading:()=>'
',not_loading:()=>{},dropdown:()=>"
"};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?We(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(){Te(this.input,"input"),Te(this.input,"change")}onPaste(e){var t=this;t.isInputHidden||t.isLocked?Ee(e):t.settings.splitOn&&setTimeout(()=>{var e=t.inputValue();if(e.match(t.settings.splitOn)){var i=e.trim().split(t.settings.splitOn);Ce(i,e=>{fe(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 Ee(e)):void 0}Ee(e)}onKeyDown(e){var t=this;if(t.ignoreHover=!0,t.isLocked)9!==e.keyCode&&Ee(e);else{switch(e.keyCode){case 65:if(Le(Ne,e)&&""==t.control_input.value)return Ee(e),void t.selectAll();break;case 27:return t.isOpen&&(Ee(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 Ee(e);case 38:if(t.activeOption){let e=t.getAdjacent(t.activeOption,-1);e&&t.setActiveOption(e)}return void Ee(e);case 13:return void(t.canSelect(t.activeOption)?(t.onOptionSelect(e,t.activeOption),Ee(e)):(t.settings.create&&t.createItem()||document.activeElement==t.control_input&&t.isOpen)&&Ee(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),Ee(e)):t.settings.create&&t.createItem()&&Ee(e)));case 8:case 46:return void t.deleteSelection(e)}t.isInputHidden&&!Le(Ne,e)&&Ee(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 Ee(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&&(Ee(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;Fe(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||qe(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,Te(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){we(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())&&Le("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);Ee(t)}else"click"===i&&Le(Ne,t)||"keydown"===i&&Le("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&&qe(i,"last-active"),Fe(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),qe(e,"active")}clearActiveItems(){qe(this.activeItems,"active"),this.activeItems=[]}setActiveOption(e,t=!0){e!==this.activeOption&&(this.clearActiveOption(),e&&(this.activeOption=e,Be(this.focus_node,{"aria-activedescendant":e.getAttribute("id")}),Be(e,{"aria-selected":"true"}),Fe(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{e.setActiveItemClass(t)}))}inputState(){var e=this;e.control.contains(e.control_input)&&(Be(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&&Be(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=fe(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;t0&&(d=d.cloneNode(!0),Be(d,{id:l.$id+"-clone-"+i,"aria-selected":null}),d.classList.add("ts-cloned"),qe(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(),Ce(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);Se(e,i),Se(e,t);let n=p.render("optgroup",{group:s,options:e});Se(l,n)}else Se(l,t)}),b.innerHTML="",Se(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&&Ce(f.tokens,e=>{Re(b,e.regex)}));var L=e=>{let t=p.render(e,{input:m});return t&&(y=!0,b.insertBefore(t,b.firstChild)),t};if(p.loading?L("loading"):p.settings.shouldLoad.call(p,m)?0===f.items.length&&L("no_results"):L("not_loading"),(a=p.canCreate(m))&&(d=L("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=fe(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){Ce(e,e=>{this.addOption(e,t)})}registerOption(e){return this.addOption(e)}registerOptionGroup(e){var t=fe(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=fe(e),r=fe(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);ze(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")&&Fe(s,"active"),ze(c,s)),i.isDropdownContentStale=!0}removeOption(e,t){const i=this;e=ve(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={};Ce(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=fe(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;i0?s[i+1]:s[i-1];return null}getItem(e){if("object"==typeof e)return e;var t=fe(e);return null!==t?this.control.querySelector(`[data-value="${xe(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){we(this,t?[]:["change","dropdown_close"],()=>{var i,s;const n=this,o=n.settings.mode,r=fe(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=Pe(e),e.remove(),e.classList.contains("active")&&(n=i.activeItems.indexOf(e),i.activeItems.splice(n,1),qe(e,"active")),i.items.splice(s,1),i.isDropdownContentStale=!0,!i.settings.persist&&i.userOptions.hasOwnProperty(o)&&i.removeOption(o,t),s{}){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 fe(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=fe(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=Ae('")),e!=n&&t.input.append(e),o.push(e),(e!=n||r>0||"multi"==t.settings.mode)&&(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="${xe(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,Be(e.focus_node,{"aria-expanded":"true"}),e.refreshState(),Ie(e.dropdown,{visibility:"hidden",display:"block"}),e.positionDropdown(),Ie(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,Be(t.focus_node,{"aria-expanded":"false"}),Ie(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;Ie(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();Ce(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=He(r.activeItems,t),s=Pe(n),t>0&&s++,Ce(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(Ee(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||(Le(Ne,t)||Le("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?He(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,qe(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,ye)))return null;if(s=Ae(s),"option"===e||"option_create"===e?t[n.settings.disabledField]?Be(s,{"aria-disabled":"true"}):Be(s,{"data-selectable":""}):"optgroup"===e&&(i=t.group[n.settings.optgroupValueField],Be(s,{"data-group":i}),t.group[n.settings.disabledField]&&Be(s,{"data-disabled":""})),"option"===e||"item"===e){const i=ve(t[n.settings.valueField]);Be(s,{"data-value":i}),"item"===e?(Fe(s,n.settings.itemClass),Be(s,{"data-ts-item":""})):(Fe(s,n.settings.optionClass),Be(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(){Ce(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 Ke=e=>"boolean"==typeof e?e?"1":"0":e+"",Je=(e,t=!1)=>{e&&(e.preventDefault(),t&&e.stopPropagation())},Ge=e=>"string"==typeof e&&e.indexOf("<")>-1;const Xe=e=>"string"==typeof e&&e.indexOf("<")>-1;const Qe=(e,t,i,s)=>{e.addEventListener(t,i,s)},Ye=e=>"string"==typeof e&&e.indexOf("<")>-1,Ze=(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 et=e=>"string"==typeof e&&e.indexOf("<")>-1;const tt=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)},it=e=>(Array.isArray(e)||(e=[e]),e);const st=e=>{if(e.jquery)return e[0];if(e instanceof HTMLElement)return e;if(nt(e)){var t=document.createElement("template");return t.innerHTML=e.trim(),t.content.firstChild}return document.querySelector(e)},nt=e=>"string"==typeof e&&e.indexOf("<")>-1,ot=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)},rt=e=>(Array.isArray(e)||(e=[e]),e);const lt=(e,t,i,s)=>{e.addEventListener(t,i,s)};const at=(e,t=!1)=>{e&&(e.preventDefault(),t&&e.stopPropagation())},ct=(e,t,i,s)=>{e.addEventListener(t,i,s)},dt=e=>{if(e.jquery)return e[0];if(e instanceof HTMLElement)return e;if(ht(e)){var t=document.createElement("template");return t.innerHTML=e.trim(),t.content.firstChild}return document.querySelector(e)},ht=e=>"string"==typeof e&&e.indexOf("<")>-1;const ut=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)},pt=e=>(Array.isArray(e)||(e=[e]),e);Ve.define("change_listener",function(){((e,t,i,s)=>{e.addEventListener(t,i,s)})(this.input,"change",()=>{this.sync()})}),Ve.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(Ge(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){Je(e)}),l.type="checkbox";const a=null==(c=i[t.settings.valueField])?null:Ke(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 Je(e,!0);i.call(t,e,s),o(s)})}),Ve.define("clear_button",function(e){const t=this,i=Object.assign({className:"clear-button",title:"Clear All",role:"button",tabindex:0,html:e=>`
×
`},e);t.on("initialize",()=>{var e=(e=>{if(e.jquery)return e[0];if(e instanceof HTMLElement)return e;if(Xe(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)})}),Ve.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(Ye(e)){var t=document.createElement("template");return t.innerHTML=e.trim(),t.content.firstChild}return document.querySelector(e)})(t.call(e,i,o));Ze(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 Qe(r,"mousedown",e=>{n||((e,t=!1)=>{e&&(e.preventDefault(),t&&e.stopPropagation())})(e),e.stopPropagation()}),Qe(r,"dragstart",e=>{s=r,setTimeout(()=>{r.classList.add("ts-dragging")},0)}),Qe(r,"dragenter",l),Qe(r,"dragover",l),Qe(r,"dragleave",()=>{r.classList.remove("ts-drag-over")}),Qe(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)))}),Ve.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=>'
'+e.title+'×
'},e);t.on("initialize",()=>{var e=(e=>{if(e.jquery)return e[0];if(e instanceof HTMLElement)return e;if(et(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)})}),Ve.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{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=tt(t);(e=it(e)).map(e=>{i.map(t=>{e.classList.remove(t)})})})(i,"last-active")}else e.setCaret(e.caretPos+t)})}),Ve.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=ot(t);(e=rt(e)).map(e=>{i.map(t=>{e.classList.add(t)})})})(e.control_input,"dropdown-input");const i=st('\n `}#_(e){return`\n
\n ${this.#x(e)}\n ${this.#S("remote-select--selection-name",e.primary,{raw:!0})}\n ${this.#S("remote-select--selection-aside",e.secondary)}\n
\n `}#x(e){return e.icon?``:e.media?``:""}#S(e,t,{raw:i=!1}={}){if(null==t||""===t)return"";if("object"==typeof t){if(null!=t.badge&&""!==t.badge)return`${Di(t.badge)}`;if(null==t.text||""===t.text)return"";const s=i?t.text:Di(t.text);return"head"===t.truncate?`${s}`:`${s}`}return`${i?t:Di(t)}`}_hightlightTerm(e,t){return function(e,t){return t?e.replace(new RegExp(t,"gi"),e=>`${e}`):e}(e,t)}}class Pi extends Hi{_entry(e,t){return{icon:e.icon_css_class,primary:this._hightlightTerm(e.name,t)}}_selectedEntry(e){return{icon:e.icon_css_class,primary:e.name}}}customElements.define("alchemy-attachment-select",Pi);class Bi extends HTMLElement{connectedCallback(){this.addEventListener("change",this.#w)}disconnectedCallback(){this.removeEventListener("change",this.#w)}#w=e=>{const t=new Event("submit",{bubbles:!0,cancelable:!0});return e.target.form.dispatchEvent(t),!1}}customElements.define("alchemy-auto-submit",Bi);class zi 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 m("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",zi,{extends:"button"});class Ri 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",Ri);class Ni extends HTMLElement{connectedCallback(){this.innerHTML='',this.clipboard=new ClipboardJS(this,{text:()=>this.getAttribute("content")}),this.clipboard.on("success",()=>{T(this.getAttribute("success-text"))})}disconnectedCallback(){this.clipboard.destroy()}}customElements.define("alchemy-clipboard-button",Ni);class ji extends HTMLSelectElement{#f=null;connectedCallback(){this.classList.add("alchemy_selectbox"),this.#C()}disconnectedCallback(){this.#A()}enable(){this.removeAttribute("disabled"),this.#f?.enable()}disable(){this.setAttribute("disabled","disabled"),this.#f?.disable()}focus(){Ii(this.#f,()=>super.focus())}setOptions(e,t=void 0){const i=this.value;this.#A(),this.innerHTML="",t&&this.add(new Option(t,"")),e.forEach(e=>{this.add(new Option(e.text,e.id,!1,e.id===i))}),this.#C()}get allowClear(){return this.dataset.hasOwnProperty("allowClear")||this.multiple}get placeholder(){return this.getAttribute("placeholder")}get renderers(){return{}}#C(){const e={},t=!!this.placeholder,i=!!this.querySelector("option[selected]"),{onDropdownOpen:s,onDropdownClose:n}=Fi();this.multiple&&(e.remove_button=qi()),this.allowClear&&(e.clear_button={html:()=>``});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:s,onDropdownClose(){this.control_input.classList.remove("has-value"),n.call(this)},allowEmptyOption:!0,openOnFocus:!1,sortField:"$order",maxOptions:null,render:{...$i,...this.renderers}};this.#f=new Ve(this,o),this.#f.control.addEventListener("click",this.#f.open.bind(this.#f))}#A(){this.#f?.destroy(),this.#f=null}}customElements.define("alchemy-select",ji,{extends:"select"});const Wi=(e,t)=>{const i=e.swatch||e.value;return`\n
\n ${"custom_color"===e.value?'':``}\n ${t(e.text)}\n
`};customElements.define("alchemy-color-select",class extends ji{connectedCallback(){super.connectedCallback(),this.addEventListener("change",this.#w)}disconnectedCallback(){super.disconnectedCallback(),this.removeEventListener("change",this.#w)}get renderers(){return{item:Wi,option:Wi}}#w=()=>{const e=this.parentElement?.querySelector("input[type='color']");e&&(e.disabled="custom_color"!==this.value)}},{extends:"select"});class Ui extends HTMLElement{connectedCallback(){this.colorInput?.addEventListener("input",this),this.textInput?.addEventListener("input",this),this.colorInput&&(this.colorInput.disabled=!1)}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)}get colorInput(){return this.querySelector("input[type='color']")}get textInput(){return this.querySelector("input[type='text']")}}customElements.define("alchemy-color-input",Ui);const Vi=c();class Ki extends HTMLElement{async connectedCallback(){"en"!==Vi&&await import(`flatpickr/${Vi}.js`),this.isConnected&&(this.flatpickr=i(this.inputField,this.flatpickrOptions))}disconnectedCallback(){this.flatpickr?.destroy()}get flatpickrOptions(){const e=/time/.test(this.inputType),t={locale:Vi.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",Ki);class Ji 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",Ji,{extends:"a"});const Gi="application/json";function Xi(e){return"get"===e.toLowerCase()}function Qi(e,t,i){const s=function(e){return{"Content-Type":"application/json; charset=utf-8",Accept:e,"X-Requested-With":"XMLHttpRequest","X-CSRF-Token":Yi()}}(i),n={method:e,headers:s};return t&&!Xi(e)&&(n.body=JSON.stringify(t)),n}function Yi(){return document.querySelector('meta[name="csrf-token"]').attributes.content.textContent}function Zi(e,t){return is("GET",e,t)}function es(e,t,i){return is("PATCH",e,t,i)}function ts(e,t,i=Gi){return is("POST",e,t,i)}async function is(e,t,i,s=Gi){const n=await fetch(function(e,t,i){const s=new URL(window.location.origin+e);return t&&Xi(i)&&(s.search=new URLSearchParams(t).toString()),s.toString()}(t,i,e),Qi(e,i,s)),o=n.headers.get("content-type"),r=o?.includes(Gi),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 ss extends HTMLElement{dataItem(e){return{id:`#${e}`,text:`#${e}`}}get selectElement(){return this.querySelector('select[is="alchemy-select"]')}}function ns(e){document.dispatchEvent(new CustomEvent("alchemy:page-dirty",{detail:{tooltip:e.publishButtonTooltip}}))}customElements.define("alchemy-dom-id-api-select",class extends ss{#O=void 0;connectedCallback(){this.page=this.getAttribute("page")}async#T(){const e=(await Zi(Alchemy.routes.api_ingredients_path,{page_id:this.#O})).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()}#E(){requestAnimationFrame(()=>{this.selectElement.disable(),this.selectElement.setOptions([],d("Select a page first"))})}set page(e){this.#O=e,e?this.#T():this.#E()}}),customElements.define("alchemy-dom-id-preview-select",class extends ss{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 os extends HTMLElement{#I;connectedCallback(){this.#I=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.#I)}}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",os);class rs extends HTMLElement{connectedCallback(){this.button?.addEventListener("click",this)}disconnectedCallback(){this.button?.removeEventListener("click",this)}async handleEvent(){if(await _(this.message)){const e=await is("DELETE",this.url);this.#F(e.data)}}#F(e){const t=this.closest("alchemy-element-editor");t.addEventListener("transitionend",()=>{t.fixed&&A(t.elementId),t.remove()}),t.classList.add("dismiss"),T(e.message),e.pageHasUnpublishedChanges&&ns(e),$()}get url(){return this.getAttribute("href")}get message(){return this.getAttribute("message")}get button(){return this.querySelector("button")}}customElements.define("alchemy-delete-element-button",rs);class ls extends HTMLElement{#q=null;#$=null;#D=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.#q=this.form,this.#q&&this.#q.addEventListener("change",this.onChange),this.#$=this.header,this.#$?.addEventListener("dblclick",this.#M),this.#D=this.toggleButton,this.#D?.addEventListener("click",this.#H),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.#q&&(this.#q.removeEventListener("change",this.onChange),this.#q=null),this.#$?.removeEventListener("dblclick",this.#M),this.#$=null,this.#D?.removeEventListener("click",this.#H),this.#D=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=p(`${e.errorMessage}`);t?.appendChild(i),t?.classList.add("validation_failed")}),T(e,"warn"),this.elementErrors.classList.remove("hidden")}else T(t.notice),this.previewWindow?.refresh().then(()=>{this.focusElementPreview()}),this.updateTitle(t.previewText),t.ingredientAnchors.forEach(e=>{D.updateIcon(e.ingredientId,e.active)}),t.pageHasUnpublishedChanges&&ns(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"),ts(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=>{T(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)=>{ts(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=>{T(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")}#M=()=>{this.toggle()};#H=e=>{e.target.closest("alchemy-element-editor")===this&&this.toggle()}}customElements.define("alchemy-element-editor",ls);const as=(e,t)=>`\n
\n ${e}${t}\n
\n`;class cs extends ji{get renderers(){return{item:(e,t)=>as(e.icon,t(e.text)),option:(e,t)=>{const i=e.hint?`
${t(e.hint)}
`:"";return`\n
\n ${as(e.icon,t(e.text))}\n ${i}\n
\n `}}}}customElements.define("alchemy-element-select",cs,{extends:"select"});class ds extends HTMLElement{#P=!0;#B=null;connectedCallback(){this.toggleButton?.addEventListener("click",this.#H),this.collapseButton?.addEventListener("click",this.#z),window.addEventListener("message",this.#R),document.body.addEventListener("click",this.#N),window.location.hash&&this.focusElementEditor(window.location.hash),this.resize()}disconnectedCallback(){this.toggleButton?.removeEventListener("click",this.#H),this.collapseButton?.removeEventListener("click",this.#z),window.removeEventListener("message",this.#R),document.body.removeEventListener("click",this.#N)}#H=e=>{e.preventDefault(),this.toggle()};#z=()=>{this.collapseAllElements()};#R=e=>{const t=e.data;if("Alchemy.focusElementEditor"==t?.message){const e=document.getElementById(`element_${t.element_id}`);this.show(),e?.focusElement()}};#N=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.#P?this.hide():this.show()}show(){document.body.classList.add("elements-window-visible"),this.#P=!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.#P=!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 ls&&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}}customElements.define("alchemy-elements-window",ds);class hs extends HTMLElement{#j=!1;#W=null;#U=null;#V=400;#K=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.#j&&this.onDrag(e.pageX)}}onMouseDown(){this.#j=!0;const e=getComputedStyle(this.elementsWindow);this.#V=parseFloat(e.minWidth)||400,this.#K="none"===e.maxWidth?1e3:parseFloat(e.maxWidth),this.elementsWindow.isDragged=!0,this.previewWindow.isDragged=!0,this.classList.add("is-dragged")}onMouseUp(){this.#j=!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.#V),this.#K);this.elementsWindow.resize(i)}get elementsWindow(){return this.#W||(this.#W=document.querySelector("alchemy-elements-window")),this.#W}get previewWindow(){return this.#U||(this.#U=document.getElementById("alchemy_preview_window")),this.#U}}customElements.define("alchemy-elements-window-handle",hs);class us 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",us);class ps extends HTMLElement{#J;#G=null;#X=null;connectedCallback(){this.hotkey&&key(this.hotkey,this.#Q),this.#G=this.filterField,this.#G.addEventListener("keyup",this.#Y),this.#G.addEventListener("focus",this.#Z),this.#X=this.clearButton,this.#X.addEventListener("click",this.#ee),key("esc","list_filter",this.#te)}disconnectedCallback(){clearTimeout(this.#J),this.#G?.removeEventListener("keyup",this.#Y),this.#G?.removeEventListener("focus",this.#Z),this.#G=null,this.#X?.removeEventListener("click",this.#ee),this.#X=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")}#Q=()=>(this.filterField.focus(),!1);#Y=()=>{clearTimeout(this.#J),this.#J=setTimeout(()=>{const e=this.filterField.value;this.clearButton.style.visibility=e?"visible":"hidden",this.filter(e)},this.debounceTime)};#Z=()=>key.setScope("list_filter");#ee=e=>{e.preventDefault(),this.clear()};#te=()=>{this.clear(),this.filterField.blur()}}customElements.define("alchemy-list-filter",ps);class ms extends HTMLElement{#ie=null;handleEvent(e){"click"===e.type&&this.dismiss()}connectedCallback(){if(!this.querySelector(":scope > alchemy-icon")){const e=this.dismissable&&"error"===this.type?'':"";this.insertAdjacentHTML("afterbegin",`${e}`)}(this.dismissable||"error"===this.type)&&this.addEventListener("click",this),this.dismissable&&"error"!==this.type&&(this.#ie=setTimeout(()=>{this.dismiss()},this.dismissDelay))}disconnectedCallback(){null!==this.#ie&&(clearTimeout(this.#ie),this.#ie=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",ms);class gs extends HTMLElement{connectedCallback(){T(this.message,this.getAttribute("type")||"notice"),this.remove()}get message(){return this.getAttribute("message")||this.innerHTML}}customElements.define("alchemy-growl",gs);class fs 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=``}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",fs);class vs extends HTMLElement{#se=null;#ne=null;#oe=null;connectedCallback(){this.image=this.querySelector("img"),this.form=this.querySelector("form"),this.#ne=document.getElementById(this.getAttribute("crop-from-field-id")),this.#oe=document.getElementById(this.getAttribute("crop-size-field-id")),this.elementEditor=document.querySelector(`[data-element-id='${this.getAttribute("element-id")}']`),this.form.addEventListener("submit",this.#re),this.form.addEventListener("reset",this.#le),this.#se=new s(this.image,this.cropperOptions)}disconnectedCallback(){this.#se?.destroy()}get cropperOptions(){return{aspectRatio:this.aspectRatio,viewMode:1,zoomable:!1,checkCrossOrigin:!1,checkOrientation:!1,data:this.box}}get aspectRatio(){const e=this.getAttribute("ratio");return e?parseFloat(e):NaN}get cropFrom(){if(this.#ne?.value)return this.#ne.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.defaultBox}get defaultBox(){const e=JSON.parse(this.getAttribute("default-box"));return{x:e[0],y:e[1],width:e[2],height:e[3]}}update(e){this.#ne.value=`${e.x}x${e.y}`,this.#ne.dispatchEvent(new Event("change")),this.#oe.value=`${e.width}x${e.height}`,this.#oe.dispatchEvent(new Event("change"))}reset(){const e=this.#se;e.setData(this.defaultBox);const t=e.getCanvasData(),i=t.width/t.naturalWidth;e.setCropBoxData({left:t.left+this.defaultBox.x*i,top:t.top+this.defaultBox.y*i}),this.update(this.defaultBox)}#re=e=>{e.preventDefault(),this.update(this.#se.getData(!0)),this.elementEditor?.setDirty(),w()?.close()};#le=e=>{e.preventDefault(),this.reset()}}customElements.define("alchemy-image-cropper",vs);class ys extends HTMLDetailsElement{#ae="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.#ae,JSON.stringify(e))}get isInLocalStorage(){return this.localStorageItem.includes(this.id)}get localStorageItem(){const e=localStorage.getItem(this.#ae);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",ys,{extends:"details"});class bs extends HTMLButtonElement{connectedCallback(){this.addEventListener("click",this),this.classList.add("icon_button"),this.setAttribute("type","button"),this.innerHTML=''}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",bs,{extends:"button"});class ws extends HTMLButtonElement{connectedCallback(){this.addEventListener("click",this),this.classList.add("icon_button"),this.setAttribute("type","button"),this.linked=this.linked,this.innerHTML=''}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",ws,{extends:"button"});class Es 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",Es);class ks extends HTMLElement{connectedCallback(){this.track=this.querySelector(".news-reader--track"),this.slides=Array.from(this.querySelectorAll(".news-reader--item")),!this.track||this.slides.length<2||(this.currentIndex=0,this.createDots(),this.setActive(0),this.startRotation(),this.addEventListener("mouseenter",this),this.addEventListener("mouseleave",this),this.track.addEventListener("scroll",this,{passive:!0}))}disconnectedCallback(){this.stopRotation()}handleEvent(e){switch(e.type){case"mouseenter":this.stopRotation();break;case"mouseleave":this.startRotation();break;case"scroll":this.syncActiveToScroll()}}createDots(){this.dotList=document.createElement("div"),this.dotList.className="news-reader--dots",this.dots=this.slides.map((e,t)=>{const i=document.createElement("button");return i.type="button",i.className="news-reader--dot",i.setAttribute("aria-label",`${t+1}`),i.addEventListener("click",()=>{this.goTo(t),this.startRotation()}),this.dotList.append(i),i}),this.append(this.dotList)}goTo(e){this.currentIndex=e,this.slides[e].scrollIntoView({behavior:"smooth",inline:"start",block:"nearest"}),this.setActive(e)}next(){this.goTo((this.currentIndex+1)%this.slides.length)}syncActiveToScroll(){const e=this.track.clientWidth;if(!e)return;const t=Math.round(this.track.scrollLeft/e);t!==this.currentIndex&&this.slides[t]&&(this.currentIndex=t,this.setActive(t))}setActive(e){this.dots.forEach((t,i)=>{t.classList.toggle("is-active",i===e)})}startRotation(){this.stopRotation(),this.timer=window.setInterval(()=>this.next(),this.interval)}stopRotation(){this.timer&&window.clearInterval(this.timer),this.timer=null}get interval(){return parseInt(this.getAttribute("interval"),10)||8e3}}customElements.define("alchemy-news-reader",ks);class Ls extends HTMLElement{connectedCallback(){this.addEventListener("Alchemy.RemoteSelect.Change",this.#ce)}disconnectedCallback(){this.removeEventListener("Alchemy.RemoteSelect.Change",this.#ce)}#ce=e=>{const t=e.detail.added;t?(this.nameField.setAttribute("placeholder",t.name),this.urlField.value=t.url_path,this.urlField.setAttribute("disabled","disabled")):(this.nameField.removeAttribute("placeholder"),this.urlField.value="",this.urlField.removeAttribute("disabled"))};get nameField(){return this.querySelector("#node_name")}get urlField(){return this.querySelector("#node_url")}}customElements.define("alchemy-node-form",Ls);function _s(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 Hi{_searchQuery(e,t){return{filter:{name_or_page_name_cont:e,...JSON.parse(this.queryParams)},page:t}}_entry(e,t){return{icon:"menu-2",primary:this.#de(e)+this._hightlightTerm(e.name,t),secondary:{text:e.url,truncate:"head"}}}_selectedEntry(e){return{icon:"menu-2",primary:this.#de(e)+Di(e.name)}}#de(e){const t=e.ancestors.map(e=>e.name);if(0===t.length)return"";const i='';return`${t.map(Di).join(i)}${i}`}});class xs extends HTMLElement{file=null;request=null;progressEventLoaded=0;progressEventTotal=0;#he=!0;#ue=0;#pe=void 0;#me="";connectedCallback(){if(this.innerHTML=`\n \n
\n ${this.file?.name}\n ${this.loadedSize}\n ${this.errorMessage}\n
\n \n \n \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.#ge(),this.#fe()}cancel(){this.finished||(this.status="canceled",this.request?.abort(),this.dispatchCustomEvent("FileUpload.Change"))}dispatchCustomEvent(e){this.dispatchEvent(new CustomEvent(`Alchemy.${e}`,{bubbles:!0}))}#ge(){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)}#fe(){this.request&&(this.request.upload.onprogress=e=>{this.progressEvent=e},this.request.onload=()=>{this.request.status<400?(this.status="successful",T(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.#me||""}set errorMessage(e){this.#me=e;const t=this.querySelector(".error-message");t&&(t.textContent=e),T(e,"error")}get finished(){return["canceled","successful","failed"].includes(this.status)}get loadedSize(){return`${_s(this.progressEventLoaded)} / ${_s(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.#pe}set status(e){this.#pe=e,this.className=e,this.progressElement?.toggleAttribute("indeterminate","upload-finished"===e)}get valid(){return this.#he}set valid(e){this.#he=e,this.classList.toggle("invalid",!e)}get value(){return this.#ue}set value(e){this.#ue=e,this.progressElement&&(this.progressElement.value=e),100===e&&(this.status="upload-finished"),this.dispatchCustomEvent("FileUpload.Change")}}customElements.define("alchemy-file-upload",xs);class Ss extends HTMLElement{fileCount=0;#ve=[];#ye=d("Cancel all uploads");#be=null;#P=!1;#we=()=>this.#Ee();connectedCallback(){var e,t;this.innerHTML=(e=this.#ye,t=this.fileCount,`\n \n
\n \n\n \n \n \n
\n
\n
\n`),this.visible=!0,this.#be=this.querySelector("button"),this.#be.addEventListener("click",()=>{this.finished?this.onComplete(this.status):this.cancel()}),this.#ve.forEach(e=>{this.querySelector(".single-uploads").append(e)}),this.#Ee(),this.addEventListener("Alchemy.FileUpload.Change",this.#we)}disconnectedCallback(){this.removeEventListener("Alchemy.FileUpload.Change",this.#we)}initialize(e=[]){this.#ve=e,this.fileCount=e.length}cancel(){this.#ke().forEach(e=>{e.cancel()}),this.#Le()}onComplete(e){}#ke(){return this.#ve.filter(e=>e.active)}#Le(){this.#ye=d("Close"),this.#be.ariaLabel=this.#ye,this.#be.parentElement.content=this.#ye}#_e(e){return this.#ke().reduce((t,i)=>i[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.#Le(),this.onComplete(e)):this.visible=!0}get finished(){return this.#ke().every(e=>e.finished)}get overallUploadSize(){this.#ke().filter(e=>e.value>=100).length;return this.totalProgress,this.#ke().length,`${_s(this.#_e("progressEventLoaded"))} / ${_s(this.#_e("progressEventTotal"))}`}get overallProgressValue(){const e=this.#ke().filter(e=>e.value>=100).length;return`${this.totalProgress}% (${e} / ${this.#ke().length})`}get progressElement(){return this.querySelector("sl-progress-bar")}get status(){const e=this.#ke().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.#ke().reduce((e,t)=>e+t.file.size,0);let t=Math.ceil(this.#ke().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.#P}set visible(e){this.classList.toggle("visible",e),this.#P=e}}customElements.define("alchemy-upload-progress",Ss);class Cs extends HTMLElement{#xe=null;#Se=!1;connectedCallback(){this.fileInput.addEventListener("change",this.#Ce),this.dropzone&&this.#Ae(),this.addEventListener("Alchemy.upload.successful",this)}disconnectedCallback(){this.fileInput?.removeEventListener("change",this.#Ce),this.#xe&&(this.#xe.removeEventListener("dragleave",this.#Oe),this.#xe.removeEventListener("drop",this.#Te),this.#xe.removeEventListener("dragover",this.#Ie),this.#xe=null)}handleEvent(e){if("Alchemy.upload.successful"===e.type)this.#Fe()}#Ce=e=>{this.uploadFiles(Array.from(e.target.files))};#qe=e=>{this.#Se!==e&&(this.#Se=e,this.#xe.classList.toggle("dragover"))};#Oe=()=>this.#qe(!1);#Te=async e=>{e.preventDefault(),this.#qe(!1);const t=[...e.dataTransfer.items].map(e=>e.getAsFile());this.uploadFiles(t)};#Ie=e=>{e.preventDefault(),this.#qe(!0)};#Fe(){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)}#Ae(){this.#xe=document.querySelector(this.dropzone),this.#xe&&(this.#xe.addEventListener("dragleave",this.#Oe),this.#xe.addEventListener("drop",this.#Te),this.#xe.addEventListener("dragover",this.#Ie))}uploadFiles(e){let t=0;const i=e.map(e=>{const i=new XMLHttpRequest,s=new xs;return s.initialize(e,i),Alchemy.uploader_defaults.upload_limit-1{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",Cs);class As extends HTMLElement{connectedCallback(){this.innerHTML=`\n \n
\n ${this.getAttribute("text")??""}\n
\n `}set show(e){this.classList.toggle("visible",e)}}customElements.define("alchemy-overlay",As);const Os="BUTTON";class Ts 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 m("small");i.spin(t);try{await es(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){T(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=``}}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=``,this.folderButton?.addEventListener("click",this)}else t||e.tagName!==Os?t&&e.tagName===Os&&this.updateFolderIcon():e.outerHTML=''}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",Ts);class Is extends HTMLElement{connectedCallback(){this.publicField?.addEventListener("click",this.#Me)}disconnectedCallback(){this.publicField?.removeEventListener("click",this.#Me)}#Me=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",Is);class Fs extends Hi{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_pagee.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,Zi(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),T(e.message||e,"error")}))}removeImage=()=>{this.pictureThumbnail.innerHTML='',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",$s);class Ds extends HTMLElement{constructor(){super(),this.spinner=new m("small")}handleEvent(e){switch(e.type){case"load":this.#He();break;case"error":this.#Pe(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()}#He(){this.spinner.stop(),this.removeAttribute("loading")}#Pe(e){const t=`Could not load ${this.image.src}`,i=this.closest(".ingredient-editor");this.spinner.stop(),this.innerHTML=`\n \n \n \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",Ds);class Ms 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",Ms);class Hs 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 n(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};x(!0);try{const o=await es(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),T(d("Successfully moved page"))}catch(e){T(e.message||e,"error"),window.location.reload()}finally{x(!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",Hs);const Ps={draggable:".element-editor",handle:".element-handle.draggable",ghostClass:"dragged",animation:150,swapThreshold:.65,easing:"cubic-bezier(1, 0, 0, 1)"};function Bs(e){const t=e.item.dataset.elementName;document.querySelectorAll(`[data-droppable-elements~="${t}"]`).forEach(e=>e.classList.add("droppable-elements"))}function zs(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&&ts(Alchemy.routes.order_admin_elements_path,s).then(e=>{const i=e.data;T(i.message),i.pageHasUnpublishedChanges&&ns(i),$(),t.updateTitle(i.preview_text)})}function Rs(){document.querySelectorAll("[data-droppable-elements]").forEach(e=>e.classList.remove("droppable-elements"))}class Ns extends HTMLElement{connectedCallback(){const e={name:this.dataset.elementName,put:(e,t,i)=>e.el.dataset.droppableElements.split(" ").includes(i.dataset.elementName)};new n(this,{...Ps,onStart:Bs,onSort:zs,onEnd:Rs,group:e})}}customElements.define("alchemy-sortable-elements",Ns);class js extends HTMLElement{connectedCallback(){this.className=`spinner spinner--${this.size}`,this.innerHTML=`\n \n \n \n \n \n `}get size(){return this.getAttribute("size")||"medium"}get color(){return this.getAttribute("color")||"currentColor"}}customElements.define("alchemy-spinner",js);class Ws extends HTMLElement{#f=null;connectedCallback(){this.classList.add("autocomplete_tag_list"),this.input.classList.add("alchemy_selectbox"),this.#f=new Ve(this.input,this.settings)}disconnectedCallback(){this.#f?.destroy(),this.#f=null}focus(){Ii(this.#f,()=>super.focus())}get input(){return this.getElementsByTagName("input")[0]}get settings(){return{plugins:{remove_button:qi()},valueField:"id",delimiter:",",create:!0,createFilter(e){return!this.loading&&(this.settings.duplicates||!this.options[e])},persist:!1,clearAfterSelect:!0,maxOptions:null,openOnFocus:!1,placeholder:this.getAttribute("placeholder"),load:(e,t)=>{Zi(this.getAttribute("url"),{term:e}).then(e=>t(e.data)).catch(()=>t())},...Fi(),render:{...$i}}}}customElements.define("alchemy-tags-autocomplete",Ws);const Us="alchemy-dark",Vs="alchemy";class Ks extends HTMLElement{#ze=null;connectedCallback(){this.className="tinymce_container",this.querySelector(":scope > alchemy-spinner")||this.insertAdjacentHTML("beforeend",''),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?Us:Vs,s=e.matches?Us:Vs;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?Us:Vs}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.#ze||this.configuration.min_height}set minHeight(e){this.#ze=e}}customElements.define("alchemy-tinymce",Ks);class Js extends HTMLElement{async connectedCallback(){const e=new m("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 Gs;customElements.define("alchemy-update-check",Js),Gs=Handlebars.template,(Handlebars.templates=Handlebars.templates||{})["node_folder.hbs"]=Gs({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'\n \n\n'},useData:!0}),o("tooltip.show",{keyframes:[{transform:"translateY(10px)",opacity:"0"},{transform:"translateY(0)",opacity:"1"}],options:{duration:100}}),o("tooltip.hide",{keyframes:[{transform:"translateY(0)",opacity:"1"},{transform:"translateY(10px)",opacity:"0"}],options:{duration:100}}),o("dialog.show",{keyframes:[{transform:"scale(0.98)",opacity:"0"},{transform:"scale(1)",opacity:"1"}],options:{duration:150}}),o("dialog.hide",{keyframes:[{transform:"scale(1)",opacity:"1"},{transform:"scale(0.98)",opacity:"0"}],options:{duration:150}});const Xs=document.querySelector('link[rel="preload"][as="image"]').getAttribute("href"),Qs={"x-lg":"close",caret:"arrow-down-s"},Ys={resolver:e=>`${Xs}#ri-${Qs[e]||e}-line`,mutator:e=>{e.setAttribute("fill","currentColor"),e.setAttribute("viewBox","0 0 24 24")},spriteSheet:!0};r("default",Ys),r("system",Ys);class Zs extends b{#Re=e=>{if(e.target.closest(".picture-overlay-handle"))return e.preventDefault(),void this.dialog.classList.toggle("hide-form");if(e.target.closest(".zoomed-picture-background")){if(e.stopPropagation(),"IMG"===e.target.nodeName)return;this.close()}};#Ne=e=>{if("INPUT"!==e.target.nodeName&&"TEXTAREA"!==e.target.nodeName)switch(e.key){case"ArrowLeft":this.previous(),e.preventDefault();break;case"ArrowRight":this.next(),e.preventDefault()}};init(){this.dialog_body.removeEventListener("click",this.#Re),this.dialog_body.addEventListener("click",this.#Re),this.#je(),super.init()}previous(){this.dialog_body.querySelector(".previous-picture")?.click()}next(){this.dialog_body.querySelector(".next-picture")?.click()}close(){return document.removeEventListener("keydown",this.#Ne),super.close()}build(){this.dialog_container=p(''),this.dialog=p('
'),this.dialog_body=p('
'),this.close_button=p('\n \n '),this.dialog.append(this.close_button),this.dialog.append(this.dialog_body),this.dialog_container.append(this.dialog),document.body.append(this.dialog_container)}#je(){document.removeEventListener("keydown",this.#Ne),document.addEventListener("keydown",this.#Ne)}}function en(){return document.querySelectorAll("#picture_archive input:checked")}function tn(){const e=document.querySelector("#select_all_pictures"),t=document.querySelector(".selected_item_tools");f("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)}),f("change",".picture_tool.select","input",e=>{t.classList.toggle("hidden",0===en().length);const i=e.target.parentElement.classList,s=e.target.checked;i.toggle("visible",s)}),f("click",".selected_item_tools","a#edit_multiple_pictures",e=>{e.preventDefault();k(function(e){const t=new URL(e);return en().forEach(e=>t.searchParams.append(e.name,e.value)),t.toString()}(e.target.href),{title:e.target.title,size:"400x295"})})}function sn(){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 nn(e){es(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(()=>{T(Alchemy.t("Successfully moved menu item")),sn()}).catch(e=>{T(e.message||e,"error")})}function on(){f("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");es(i).then(()=>{s.classList.toggle("folded"),t.dataset.folded="true"==t.dataset.folded?"false":"true",sn()}).catch(e=>{T(e.message||e)})}),sn(),document.querySelectorAll(".nodes_tree ul.children").forEach(e=>{new n(e,{group:"nodes",animation:150,fallbackOnBody:!0,swapThreshold:.65,handle:".node_name",invertSwap:!0,onEnd:nn})})}void 0===window.Alchemy&&(window.Alchemy={}),Object.assign(Alchemy,{closeCurrentDialog:E,currentDialog:w,...C,t:d,FixedElements:O,growl:T,LinkDialog:class extends b{#We;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.#m()}open(){return super.open(),new Promise(e=>this.#We=e)}#m(){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.#Ue(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.#Ve(e.target.dataset.linkFormType)})})}#Ue(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}#Ve(e){const t=document.getElementById("element_anchor");let i=document.getElementById(`${e}_link`).value;if("internal"===e&&""!==t.value)i=i.replace(F,"")+t.value;else if("external"===e&&!i.match(Alchemy.link_url_regexp))return void this.#Ke();this.#We({url:i.trim(),title:document.getElementById(`${e}_link_title`).value,target:document.getElementById(`${e}_link_target`)?.value,type:e}),this.close()}#Ke(){const e=document.getElementById("errors");e.querySelector("ul").innerHTML=`
  • ${Alchemy.t("url_validation_failed")}
  • `,e.style.display="block"}},pleaseWaitOverlay:x,Spinner:m,reloadPreview:$}),t.start(),e.config.forms.confirm=_,document.addEventListener("turbo:load",function(){document.documentElement.classList.remove("no-js"),u(),document.removeEventListener("keypress",I),document.addEventListener("keypress",I),document.querySelectorAll(".please_wait").forEach(e=>{e.addEventListener("click",x)}),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{Pi as AttachmentSelect,cs as ElementSelect,Zs as ImageOverlay,on as NodeTree,Fs as PageSelect,Hi as RemoteSelect,Ws as TagsAutocomplete,Ks as Tinymce,f as on,tn as pictureSelector}; +import"handlebars";import"@ungap/custom-elements";import{Turbo as e}from"@hotwired/turbo-rails";import t from"@rails/ujs";import"keymaster";import"clipboard";import i from"flatpickr";import s from"cropperjs";import n from"sortablejs";import"tinymce";import{setDefaultAnimation as o,registerIconLibrary as r}from"shoelace";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}const h=[];function u(e=document){e===document&&h.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}),h.push("alt+f"),key("esc","search",function(){i.forEach(e=>e.click()),t.forEach(e=>e.blur())}),h.push("esc"),e.querySelectorAll("[data-alchemy-hotkey]").forEach(function(e){const t=e.dataset.alchemyHotkey;key(t,()=>e.click()),h.push(t)})}function p(e){const t=document.createElement("template");return t.innerHTML=e,t.content.children[0]}let m=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=p(``),e.append(this.spinner),this}stop(){this.spinner&&(this.spinner.remove(),this.spinner=void 0)}};function g(e,t,i={}){e.dispatchEvent(new CustomEvent(t,{bubbles:!0,detail:i}))}function f(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}})})}const v=[],y={header_height:36,size:"400x300",padding:!0,title:"",modal:!0,overflow:"visible",ready:()=>{},closed:()=>{}};class b{#e=null;#t=!1;constructor(e,t={}){this.url=e,this.options={...y,...t};const i=this.options.size.split("x");this.width=parseInt(i[0],10),this.height=parseInt(i[1],10),this.build(),this.resize()}open(){g(this.dialog,"Alchemy.DialogOpen"),this.bind_close_events(),this.options.modal?(this.dialog_container.showModal(),this.#i()):this.dialog_container.show(),window.requestAnimationFrame(()=>{this.dialog_container.classList.add("open")}),document.body.classList.add("prevent-scrolling"),v.push(this),this.load()}close(){return this.#t||(this.#t=!0,g(this.dialog,"DialogClose.Alchemy"),this.dialog_container.classList.remove("open"),this.dialog_container.addEventListener("transitionend",()=>{this.#s(),this.dialog_container.close(),this.dialog_container.remove(),v.pop(),0===v.length&&document.body.classList.remove("prevent-scrolling"),null!=this.options.closed&&this.options.closed()},{once:!0})),!0}#i(){const e=document.getElementById("flash_notices");e&&(this.#e=e.parentElement,this.dialog_container.append(e),this.#n(e))}#s(){const e=document.getElementById("flash_notices");e&&this.#e&&(this.#e.append(e),this.#n(e))}#n(e){e.querySelectorAll('alchemy-message[dismissable]:not([type="error"])').forEach(e=>e.remove())}load(){this.show_spinner(),fetch(this.url,{headers:{"X-Requested-With":"XMLHttpRequest"}}).then(async e=>{const t=await e.text();e.ok?this.replace(t):this.show_error({status:e.status,statusText:e.statusText,responseText:t})}).catch(()=>{this.show_error({status:0})})}reload(){this.dialog_body.innerHTML="",this.load()}replace(e){this.remove_spinner(),this.dialog_body.style.display="none",this.dialog_body.innerHTML=e,this.init(),g(this.dialog,"DialogReady.Alchemy",{body:this.dialog_body}),null!=this.options.ready&&this.options.ready(this.dialog_body),this.dialog_body.style.display=""}show_spinner(){this.spinner=new m("medium"),this.spinner.spin(this.dialog_body)}remove_spinner(){this.spinner.stop()}init(){u(this.dialog_body),this.watch_remote_forms(),window.requestAnimationFrame(()=>this.#o())}#o(e=0){const t=this.dialog_body.querySelector("[autofocus]")??this.dialog_body.querySelector("form [type='submit']");t?.focus(),document.activeElement===this.close_button&&e<20&&window.requestAnimationFrame(()=>this.#o(e+1))}watch_remote_forms(){this.dialog_body.querySelectorAll('[data-remote="true"]').forEach(e=>{e.addEventListener("ajax:success",e=>{const t=e.detail[2];t.getResponseHeader("Content-Type").match(/javascript/)||(this.dialog_body.innerHTML=t.responseText,this.init())}),e.addEventListener("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.innerHTML=e.responseText,void this.init();const{error_body:i,error_header:s,error_type:n}=this.error_messages(e,t);this.dialog_body.innerHTML=`\n

    ${s}

    \n

    ${i}

    \n
    `}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.addEventListener("click",e=>{e.preventDefault(),this.close()}),this.dialog_container.classList.add("closable"),this.dialog_container.addEventListener("pointerdown",e=>{e.target===this.dialog_container&&this.close()}),this.dialog_container.addEventListener("cancel",e=>{e.preventDefault(),this.close()})}build(){this.dialog_container=p(''),this.dialog=p('
    '),this.dialog_body=p('
    '),this.dialog_header=p('
    '),this.dialog_title=p('
    '),this.close_button=p(''),this.dialog_title.textContent=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.classList.add("modal"),this.options.padding&&this.dialog_body.classList.add("padded"),document.body.append(this.dialog_container)}resize(){const{width:e,height:t}=this.getSize();this.dialog.style.width=`${e}px`,this.dialog.style.minHeight=`${t}px`,this.dialog.style.overflow=this.options.overflow,"hidden"===this.options.overflow?(this.dialog_body.style.height=`${t}px`,this.dialog_body.style.overflow="auto"):(this.dialog_body.style.minHeight=`${t}px`,this.dialog_body.style.overflow="visible")}getSize(){const e=this.options.padding?16:0,t=window.innerWidth,i=window.innerHeight;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 L{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.#r(),this.#l()}open(){requestAnimationFrame(()=>{this.dialog.show()})}#r(){const e=this.options.size.split("x")[0];this.dialog=p(`\n \n ${this.message}\n \n \n \n `);(w()?.dialog_container??document.body).append(this.dialog)}#l(){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(i=>{new L(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.matches("form")?t=function(){const t=document.createElement("form");t.action=e.action,t.method="POST",t.style.display="none",e.querySelectorAll("input").forEach(e=>t.append(e)),document.body.append(t),S(),t.requestSubmit()}:e.matches("a")&&(t=()=>Turbo.visit(e.pathname));return!(document.querySelectorAll("alchemy-element-editor.dirty").length>0)||(_(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 O=Object.freeze({__proto__:null,createTab:function(e,t){const i=document.getElementById("fixed-elements"),s=`fixed-element-${e}`,n=`${t}`,o=``;i.innerHTML+=n+o,window.requestAnimationFrame(function(){i.show(s)})},removeTab:A});function T(e,t="notice"){!function(e,t){const i=document.getElementById("flash_notices"),s=p(`\n \n ${e}\n \n `);i.append(s)}(e,t)}function I(e){return!(!e.target.matches("input, textarea")&&"?"===String.fromCharCode(e.which))||(k("/admin/help",{title:Alchemy.t("help"),size:"400x492"}),!1)}const F=/#[\w.~-]+$/;class q extends HTMLIFrameElement{#a;#c;#d;handleEvent(e){"load"===e.type&&(this.#h(),this.#u(),this.#a?.call(this,e))}#p=e=>{"Alchemy.previewReady"===e.data.message&&(this.#h(),this.#u())};connectedCallback(){let e=this.url;this.addEventListener("load",this),this.#m(),window.addEventListener("message",this.#p),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.#p)}postMessage(e){this.contentWindow.postMessage(e,"*")}resize(e){this.style.width=`${e}px`}refresh(e){return this.#g(),this.src=e||this.url,this.#h(),this.#d=setTimeout(()=>{this.#u(),T(d("Preview failed to load"),"warning")},5e3),new Promise(e=>{this.#a=e})}set isDragged(e){this.style.transitionProperty=e?"none":null,this.style.pointerEvents=e?"none":null}#m(){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)})}#g(){this.reloadButton.innerHTML.includes("alchemy-spinner")||(this.#c=this.reloadButton.innerHTML),this.reloadButton.innerHTML=''}#u(){this.reloadButton.innerHTML=this.#c}#h(){this.#d&&(clearTimeout(this.#d),this.#d=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 $(){document.getElementById("alchemy_preview_window").refresh()}customElements.define("alchemy-preview-window",q,{extends:"iframe"}),e.StreamActions.assign_picture=function(){const[e]=this.targetElements;e&&(e.value=this.getAttribute("picture-id"),e.setAttribute("data-image-file-width",this.getAttribute("image-file-width")),e.setAttribute("data-image-file-height",this.getAttribute("image-file-height")),E(()=>{e.closest("alchemy-element-editor")?.setDirty()}))},e.StreamActions.assign_attachment=function(){const[e]=this.targetElements;if(!e)return;const t=e.parentElement;e.value=this.getAttribute("attachment-id"),t.querySelector(":scope > .file_name").textContent=this.getAttribute("attachment-name"),t.querySelector(":scope > .file_icon").replaceChildren(this.templateContent),t.querySelector(":scope > .remove_file_link").classList.remove("hidden"),E(()=>{e.closest("alchemy-element-editor")?.setDirty(e)})};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:$,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 H(e,t){e.split(/\s+/).forEach(e=>{t(e)})}customElements.define("alchemy-action",M);class P{constructor(){this._events={}}on(e,t){H(e,e=>{const i=this._events[e]||[];i.push(t),this._events[e]=i})}off(e,t){var i=arguments.length;0!==i?H(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;H(e,e=>{const s=i._events[e];void 0!==s&&s.forEach(e=>{e.apply(i,t)})})}}const B=e=>(e=e.filter(Boolean)).length<2?e[0]||"":1==W(e)?"["+e.join("")+"]":"(?:"+e.join("|")+")",z=e=>{if(!N(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},R=e=>{let t=Array.from(e);return B(t)},N=e=>new Set(e).size!==e.length,j=e=>(e+"").replace(/([\$\(\)\*\+\.\?\[\]\^\{\|\}\\])/gu,"\\$1"),W=e=>e.reduce((e,t)=>Math.max(e,V(t)),0),V=e=>Array.from(e).length,U=e=>{if(1===e.length)return[[e]];let t=[];const i=e.substring(1);return U(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},K=[[0,65535]];let J,G;const X={},Q={"/":"⁄∕",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 Q){let t=Q[e]||"";for(let i=0;ie.normalize(t),ee=e=>Array.from(e).reduce((e,t)=>e+te(t),""),te=e=>(e=Z(e).toLowerCase().replace(Y,e=>X[e]||""),Z(e,"NFC"));const ie=e=>{const t={},i=(e,i)=>{const s=t[e]||new Set,n=new RegExp("^"+R(s)+"$","iu");i.match(n)||(s.add(j(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=ee(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},se=e=>{const t=ie(e),i={};let s=[];for(let e in t){let n=t[e];n&&(i[e]=R(n)),e.length>1&&s.push(j(e))}s.sort((e,t)=>t.length-e.length);const n=B(s);return G=new RegExp("^"+n,"u"),i},ne=(e,t=1)=>(t=Math.max(t,e.length-1),B(U(e).map(e=>((e,t=1)=>{let i=0;return e=e.map(e=>(J[e]&&(i+=e.length),J[e]||e)),i>=t?z(e):""})(e,t)))),oe=(e,t=!0)=>{let i=e.length>1?1:0;return B(e.map(e=>{let s=[];const n=t?e.length():e.length()-1;for(let t=0;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.starti.start)return!0;if(i.starte.start)return!0}}return!1};if(!(i.parts.filter(s).length>0))return!0}return!1};class le{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 le,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 ae=e=>{void 0===J&&(J=se(K)),e=ee(e);let t="",i=[new le];for(let s=0;s0){l=l.sort((e,t)=>e.length()-t.length());for(let e of l)re(e,i)||i.push(e)}else if(s>0&&1==a.size&&!a.has("3")){t+=oe(i,!1);let e=new le;const s=i[0];s&&e.add(s.last()),i=[e]}}return t+=oe(i,!0),t},ce=(e,t)=>{if(e)return e[t]},de=(e,t)=>{if(e){for(var i,s=t.split(".");(i=s.shift())&&(e=e[i]););return e}},he=(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},ue=(e,t)=>{var i=e[t];if("function"==typeof i)return i;i&&!Array.isArray(i)&&(e[t]=[i])},pe=(e,t)=>{if(Array.isArray(e))e.forEach(t);else for(var i in e)e.hasOwnProperty(i)&&t(e[i],i)},me=(e,t)=>"number"==typeof e&&"number"==typeof t?e>t?1:e(t=ee(t+"").toLowerCase())?1:t>e?-1:0;class ge{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(j).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?ae(e)||null:j(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 he(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+=he(s,e,1)}else pe(n,(s,n)=>{i+=he(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 pe(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)*me(r(n,e),r(n,t)))return s}return 0}:null}prepareSearch(e,t){const i={};var s=Object.assign({},t);if(ue(s,"sort"),ue(s,"sort_empty"),s.fields){ue(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?de:ce}}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?pe(n.items,(e,n)=>{i=o(e),(!1===t.filter||i>0)&&s.items.push({score:i,id:n})}):pe(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 fe=e=>null==e?null:ve(e),ve=e=>"boolean"==typeof e?e?"1":"0":e+"",ye=e=>(e+"").replace(/&/g,"&").replace(//g,">").replace(/"/g,"""),be=(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)}},we=(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])},Ee=(e,t=!1)=>{e&&(e.preventDefault(),t&&e.stopPropagation())},ke=(e,t,i,s)=>{e.addEventListener(t,i,s)},Le=(e,t)=>!!t&&(!!t[e]&&1===(t.altKey?1:0)+(t.ctrlKey?1:0)+(t.shiftKey?1:0)+(t.metaKey?1:0)),_e=(e,t)=>{const i=e.getAttribute("id");return i||(e.setAttribute("id",t),t)},Se=e=>e.replace(/[\\"']/g,"\\$&"),xe=(e,t)=>{t&&e.append(t)},Ce=(e,t)=>{if(Array.isArray(e))e.forEach(t);else for(var i in e)e.hasOwnProperty(i)&&t(e[i],i)},Ae=e=>{if(e.jquery)return e[0];if(e instanceof HTMLElement)return e;if(Oe(e)){var t=document.createElement("template");return t.innerHTML=e.trim(),t.content.firstChild}return document.querySelector(e)},Oe=e=>"string"==typeof e&&e.indexOf("<")>-1,Te=(e,t)=>{var i=document.createEvent("HTMLEvents");i.initEvent(t,!0,!1),e.dispatchEvent(i)},Ie=(e,t)=>{Object.assign(e.style,t)},Fe=(e,...t)=>{var i=$e(t);(e=De(e)).map(e=>{i.map(t=>{e.classList.add(t)})})},qe=(e,...t)=>{var i=$e(t);(e=De(e)).map(e=>{i.map(t=>{e.classList.remove(t)})})},$e=e=>{var t=[];return Ce(e,e=>{"string"==typeof e&&(e=e.trim().split(/[\t\n\f\r\s]/)),Array.isArray(e)&&(t=t.concat(e))}),t.filter(Boolean)},De=e=>(Array.isArray(e)||(e=[e]),e),Me=(e,t,i)=>{if(!i||i.contains(e))for(;e&&e.matches;){if(e.matches(t))return e;e=e.parentNode}},He=(e,t=0)=>t>0?e[e.length-1]:e[0],Pe=(e,t)=>{if(!e)return-1;t=t||e.nodeName;for(var i=0;e=e.previousElementSibling;)e.matches(t)&&i++;return i},Be=(e,t)=>{Ce(t,(t,i)=>{null==t?e.removeAttribute(i):e.setAttribute(i,""+t)})},ze=(e,t)=>{e.parentNode&&e.parentNode.replaceChild(t,e)},Re=(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),ze(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)},Ne="undefined"!=typeof navigator&&/Mac/.test(navigator.userAgent)?"metaKey":"ctrlKey";var je={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:'',copyClassesToDropdown:!1,placeholder:null,hidePlaceholder:null,shouldLoad:function(e){return e.length>0},render:{}};function We(e,t){var i=Object.assign({},je,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=fe(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,Ce(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],Ce(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),Ce(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);Ce(s,e=>{const t={};t[n]=e,t[o]=e,u.options.push(t)}),u.items=s}})(),Object.assign({},je,u,t)}var Ve=0;class Ue 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]}}}(P)){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,Ve++;var s=Ae(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=We(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=_e(s,"tomselect-"+Ve),this.isRequired=s.required,this.sifter=new ge(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=Ae("
    "),l=Ae("
    "),a=this._render("dropdown"),c=Ae('
    '),d=this.input.getAttribute("class")||"",h=n.mode;var u;if(Fe(r,n.wrapperClass,d,h),Fe(l,n.controlClass),xe(r,l),Fe(a,n.dropdownClass,h),n.copyClassesToDropdown&&Fe(a,d),Fe(c,n.dropdownContentClass),xe(a,c),Ae(n.dropdownParent||r).appendChild(a),Oe(n.controlInput)){u=Ae(n.controlInput);Ce(["autocorrect","autocapitalize","autocomplete","spellcheck","aria-label"],e=>{s.getAttribute(e)&&Be(u,{[e]:s.getAttribute(e)})}),u.tabIndex=-1,l.appendChild(u),this.focus_node=u}else n.controlInput?(u=Ae(n.controlInput),this.focus_node=u):(u=Ae(""),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";Be(n,{id:d}),Be(a,{role:"combobox","aria-haspopup":"listbox","aria-expanded":"false","aria-controls":d});const h=_e(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){ke(p,"click",m),Be(p,{for:h});const t=_e(p,e.inputId+"-ts-label");Be(a,{"aria-labelledby":t}),Be(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-");Fe([o,s],t)}(null===t.maxItems||t.maxItems>1)&&e.is_select_tag&&Be(l,{multiple:"multiple"}),t.placeholder&&Be(i,{placeholder:t.placeholder}),!t.splitOn&&t.delimiter&&(t.splitOn=new RegExp("\\s*"+j(t.delimiter)+"+\\s*")),t.load&&t.loadThrottle&&(t.load=be(t.load,t.loadThrottle)),ke(s,"mousemove",()=>{e.ignoreHover=!1}),ke(s,"mouseenter",t=>{var i=Me(t.target,"[data-selectable]",s);i&&e.onOptionHover(t,i)},{capture:!0}),ke(s,"click",t=>{const i=Me(t.target,"[data-selectable]");i&&(e.onOptionSelect(t,i),Ee(t,!0))}),ke(r,"click",t=>{var s=Me(t.target,"[data-ts-item]",r);s&&e.onItemSelect(t,s)?Ee(t,!0):""==i.value&&(e.onClick(),Ee(t,!0))}),ke(a,"keydown",t=>e.onKeyDown(t)),ke(i,"keypress",t=>e.onKeyPress(t)),ke(i,"input",t=>e.onInput(t)),ke(a,"blur",t=>e.onBlur(t)),ke(a,"focus",t=>e.onFocus(t)),ke(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():Ee(t,!0)},f=()=>{e.isOpen&&e.positionDropdown()},v=()=>{e.isValid&&(e.isValid=!1,e.isInvalid=!0,e.refreshState())};ke(l,"invalid",v),ke(document,"mousedown",g),ke(window,"scroll",f,c),ke(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),Fe(l,"tomselected","ts-hidden-accessible"),e.trigger("initialize"),!0===t.preload&&e.preload()}setupOptions(e=[],t=[]){this.addOptions(e),Ce(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)=>'
    '+t(e[i])+"
    ",option:(e,i)=>"
    "+i(e[t])+"
    ",item:(e,i)=>"
    "+i(e[t])+"
    ",option_create:(e,t)=>'
    Add '+t(e.input)+"
    ",no_results:()=>'
    No results found
    ',loading:()=>'
    ',not_loading:()=>{},dropdown:()=>"
    "};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?We(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(){Te(this.input,"input"),Te(this.input,"change")}onPaste(e){var t=this;t.isInputHidden||t.isLocked?Ee(e):t.settings.splitOn&&setTimeout(()=>{var e=t.inputValue();if(e.match(t.settings.splitOn)){var i=e.trim().split(t.settings.splitOn);Ce(i,e=>{fe(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 Ee(e)):void 0}Ee(e)}onKeyDown(e){var t=this;if(t.ignoreHover=!0,t.isLocked)9!==e.keyCode&&Ee(e);else{switch(e.keyCode){case 65:if(Le(Ne,e)&&""==t.control_input.value)return Ee(e),void t.selectAll();break;case 27:return t.isOpen&&(Ee(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 Ee(e);case 38:if(t.activeOption){let e=t.getAdjacent(t.activeOption,-1);e&&t.setActiveOption(e)}return void Ee(e);case 13:return void(t.canSelect(t.activeOption)?(t.onOptionSelect(e,t.activeOption),Ee(e)):(t.settings.create&&t.createItem()||document.activeElement==t.control_input&&t.isOpen)&&Ee(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),Ee(e)):t.settings.create&&t.createItem()&&Ee(e)));case 8:case 46:return void t.deleteSelection(e)}t.isInputHidden&&!Le(Ne,e)&&Ee(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 Ee(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&&(Ee(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;Fe(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||qe(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,Te(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){we(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())&&Le("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);Ee(t)}else"click"===i&&Le(Ne,t)||"keydown"===i&&Le("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&&qe(i,"last-active"),Fe(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),qe(e,"active")}clearActiveItems(){qe(this.activeItems,"active"),this.activeItems=[]}setActiveOption(e,t=!0){e!==this.activeOption&&(this.clearActiveOption(),e&&(this.activeOption=e,Be(this.focus_node,{"aria-activedescendant":e.getAttribute("id")}),Be(e,{"aria-selected":"true"}),Fe(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{e.setActiveItemClass(t)}))}inputState(){var e=this;e.control.contains(e.control_input)&&(Be(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&&Be(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=fe(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;t0&&(d=d.cloneNode(!0),Be(d,{id:l.$id+"-clone-"+i,"aria-selected":null}),d.classList.add("ts-cloned"),qe(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(),Ce(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);xe(e,i),xe(e,t);let n=p.render("optgroup",{group:s,options:e});xe(l,n)}else xe(l,t)}),b.innerHTML="",xe(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&&Ce(f.tokens,e=>{Re(b,e.regex)}));var L=e=>{let t=p.render(e,{input:m});return t&&(y=!0,b.insertBefore(t,b.firstChild)),t};if(p.loading?L("loading"):p.settings.shouldLoad.call(p,m)?0===f.items.length&&L("no_results"):L("not_loading"),(a=p.canCreate(m))&&(d=L("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=fe(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){Ce(e,e=>{this.addOption(e,t)})}registerOption(e){return this.addOption(e)}registerOptionGroup(e){var t=fe(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=fe(e),r=fe(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);ze(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")&&Fe(s,"active"),ze(c,s)),i.isDropdownContentStale=!0}removeOption(e,t){const i=this;e=ve(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={};Ce(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=fe(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;i0?s[i+1]:s[i-1];return null}getItem(e){if("object"==typeof e)return e;var t=fe(e);return null!==t?this.control.querySelector(`[data-value="${Se(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){we(this,t?[]:["change","dropdown_close"],()=>{var i,s;const n=this,o=n.settings.mode,r=fe(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=Pe(e),e.remove(),e.classList.contains("active")&&(n=i.activeItems.indexOf(e),i.activeItems.splice(n,1),qe(e,"active")),i.items.splice(s,1),i.isDropdownContentStale=!0,!i.settings.persist&&i.userOptions.hasOwnProperty(o)&&i.removeOption(o,t),s{}){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 fe(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=fe(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=Ae('")),e!=n&&t.input.append(e),o.push(e),(e!=n||r>0||"multi"==t.settings.mode)&&(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="${Se(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,Be(e.focus_node,{"aria-expanded":"true"}),e.refreshState(),Ie(e.dropdown,{visibility:"hidden",display:"block"}),e.positionDropdown(),Ie(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,Be(t.focus_node,{"aria-expanded":"false"}),Ie(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;Ie(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();Ce(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=He(r.activeItems,t),s=Pe(n),t>0&&s++,Ce(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(Ee(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||(Le(Ne,t)||Le("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?He(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,qe(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,ye)))return null;if(s=Ae(s),"option"===e||"option_create"===e?t[n.settings.disabledField]?Be(s,{"aria-disabled":"true"}):Be(s,{"data-selectable":""}):"optgroup"===e&&(i=t.group[n.settings.optgroupValueField],Be(s,{"data-group":i}),t.group[n.settings.disabledField]&&Be(s,{"data-disabled":""})),"option"===e||"item"===e){const i=ve(t[n.settings.valueField]);Be(s,{"data-value":i}),"item"===e?(Fe(s,n.settings.itemClass),Be(s,{"data-ts-item":""})):(Fe(s,n.settings.optionClass),Be(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(){Ce(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 Ke=e=>"boolean"==typeof e?e?"1":"0":e+"",Je=(e,t=!1)=>{e&&(e.preventDefault(),t&&e.stopPropagation())},Ge=e=>"string"==typeof e&&e.indexOf("<")>-1;const Xe=e=>"string"==typeof e&&e.indexOf("<")>-1;const Qe=(e,t,i,s)=>{e.addEventListener(t,i,s)},Ye=e=>"string"==typeof e&&e.indexOf("<")>-1,Ze=(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 et=e=>"string"==typeof e&&e.indexOf("<")>-1;const tt=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)},it=e=>(Array.isArray(e)||(e=[e]),e);const st=e=>{if(e.jquery)return e[0];if(e instanceof HTMLElement)return e;if(nt(e)){var t=document.createElement("template");return t.innerHTML=e.trim(),t.content.firstChild}return document.querySelector(e)},nt=e=>"string"==typeof e&&e.indexOf("<")>-1,ot=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)},rt=e=>(Array.isArray(e)||(e=[e]),e);const lt=(e,t,i,s)=>{e.addEventListener(t,i,s)};const at=(e,t=!1)=>{e&&(e.preventDefault(),t&&e.stopPropagation())},ct=(e,t,i,s)=>{e.addEventListener(t,i,s)},dt=e=>{if(e.jquery)return e[0];if(e instanceof HTMLElement)return e;if(ht(e)){var t=document.createElement("template");return t.innerHTML=e.trim(),t.content.firstChild}return document.querySelector(e)},ht=e=>"string"==typeof e&&e.indexOf("<")>-1;const ut=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)},pt=e=>(Array.isArray(e)||(e=[e]),e);Ue.define("change_listener",function(){((e,t,i,s)=>{e.addEventListener(t,i,s)})(this.input,"change",()=>{this.sync()})}),Ue.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(Ge(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){Je(e)}),l.type="checkbox";const a=null==(c=i[t.settings.valueField])?null:Ke(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 Je(e,!0);i.call(t,e,s),o(s)})}),Ue.define("clear_button",function(e){const t=this,i=Object.assign({className:"clear-button",title:"Clear All",role:"button",tabindex:0,html:e=>`
    ×
    `},e);t.on("initialize",()=>{var e=(e=>{if(e.jquery)return e[0];if(e instanceof HTMLElement)return e;if(Xe(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)})}),Ue.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(Ye(e)){var t=document.createElement("template");return t.innerHTML=e.trim(),t.content.firstChild}return document.querySelector(e)})(t.call(e,i,o));Ze(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 Qe(r,"mousedown",e=>{n||((e,t=!1)=>{e&&(e.preventDefault(),t&&e.stopPropagation())})(e),e.stopPropagation()}),Qe(r,"dragstart",e=>{s=r,setTimeout(()=>{r.classList.add("ts-dragging")},0)}),Qe(r,"dragenter",l),Qe(r,"dragover",l),Qe(r,"dragleave",()=>{r.classList.remove("ts-drag-over")}),Qe(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)))}),Ue.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=>'
    '+e.title+'×
    '},e);t.on("initialize",()=>{var e=(e=>{if(e.jquery)return e[0];if(e instanceof HTMLElement)return e;if(et(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)})}),Ue.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{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=tt(t);(e=it(e)).map(e=>{i.map(t=>{e.classList.remove(t)})})})(i,"last-active")}else e.setCaret(e.caretPos+t)})}),Ue.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=ot(t);(e=rt(e)).map(e=>{i.map(t=>{e.classList.add(t)})})})(e.control_input,"dropdown-input");const i=st('\n `}#_(e){return`\n
    \n ${this.#S(e)}\n ${this.#x("remote-select--selection-name",e.primary,{raw:!0})}\n ${this.#x("remote-select--selection-aside",e.secondary)}\n
    \n `}#S(e){return e.icon?``:e.media?``:""}#x(e,t,{raw:i=!1}={}){if(null==t||""===t)return"";if("object"==typeof t){if(null!=t.badge&&""!==t.badge)return`${Di(t.badge)}`;if(null==t.text||""===t.text)return"";const s=i?t.text:Di(t.text);return"head"===t.truncate?`${s}`:`${s}`}return`${i?t:Di(t)}`}_hightlightTerm(e,t){return function(e,t){return t?e.replace(new RegExp(t,"gi"),e=>`${e}`):e}(e,t)}}class Pi extends Hi{_entry(e,t){return{icon:e.icon_css_class,primary:this._hightlightTerm(e.name,t)}}_selectedEntry(e){return{icon:e.icon_css_class,primary:e.name}}}customElements.define("alchemy-attachment-select",Pi);class Bi extends HTMLElement{connectedCallback(){this.addEventListener("change",this.#w)}disconnectedCallback(){this.removeEventListener("change",this.#w)}#w=e=>{const t=new Event("submit",{bubbles:!0,cancelable:!0});return e.target.form.dispatchEvent(t),!1}}customElements.define("alchemy-auto-submit",Bi);class zi extends HTMLButtonElement{connectedCallback(){this.form?(this.form.addEventListener("submit",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"turbo:submit-end":this.enable()}}disable(){const e=new m("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",zi,{extends:"button"});class Ri 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",Ri);class Ni extends HTMLElement{connectedCallback(){this.innerHTML='',this.clipboard=new ClipboardJS(this,{text:()=>this.getAttribute("content")}),this.clipboard.on("success",()=>{T(this.getAttribute("success-text"))})}disconnectedCallback(){this.clipboard.destroy()}}customElements.define("alchemy-clipboard-button",Ni);class ji extends HTMLSelectElement{#f=null;connectedCallback(){this.classList.add("alchemy_selectbox"),this.#C()}disconnectedCallback(){this.#A()}enable(){this.removeAttribute("disabled"),this.#f?.enable()}disable(){this.setAttribute("disabled","disabled"),this.#f?.disable()}focus(){Ii(this.#f,()=>super.focus())}setOptions(e,t=void 0){const i=this.value;this.#A(),this.innerHTML="",t&&this.add(new Option(t,"")),e.forEach(e=>{this.add(new Option(e.text,e.id,!1,e.id===i))}),this.#C()}get allowClear(){return this.dataset.hasOwnProperty("allowClear")||this.multiple}get placeholder(){return this.getAttribute("placeholder")}get renderers(){return{}}#C(){const e={},t=!!this.placeholder,i=!!this.querySelector("option[selected]"),{onDropdownOpen:s,onDropdownClose:n}=Fi();this.multiple&&(e.remove_button=qi()),this.allowClear&&(e.clear_button={html:()=>``});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:s,onDropdownClose(){this.control_input.classList.remove("has-value"),n.call(this)},allowEmptyOption:!0,openOnFocus:!1,sortField:"$order",maxOptions:null,render:{...$i,...this.renderers}};this.#f=new Ue(this,o),this.#f.control.addEventListener("click",this.#f.open.bind(this.#f))}#A(){this.#f?.destroy(),this.#f=null}}customElements.define("alchemy-select",ji,{extends:"select"});const Wi=(e,t)=>{const i=e.swatch||e.value;return`\n
    \n ${"custom_color"===e.value?'':``}\n ${t(e.text)}\n
    `};customElements.define("alchemy-color-select",class extends ji{connectedCallback(){super.connectedCallback(),this.addEventListener("change",this.#w)}disconnectedCallback(){super.disconnectedCallback(),this.removeEventListener("change",this.#w)}get renderers(){return{item:Wi,option:Wi}}#w=()=>{const e=this.parentElement?.querySelector("input[type='color']");e&&(e.disabled="custom_color"!==this.value)}},{extends:"select"});class Vi extends HTMLElement{connectedCallback(){this.colorInput?.addEventListener("input",this),this.textInput?.addEventListener("input",this),this.colorInput&&(this.colorInput.disabled=!1)}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)}get colorInput(){return this.querySelector("input[type='color']")}get textInput(){return this.querySelector("input[type='text']")}}customElements.define("alchemy-color-input",Vi);const Ui=c();class Ki extends HTMLElement{async connectedCallback(){"en"!==Ui&&await import(`flatpickr/${Ui}.js`),this.isConnected&&(this.flatpickr=i(this.inputField,this.flatpickrOptions))}disconnectedCallback(){this.flatpickr?.destroy()}get flatpickrOptions(){const e=/time/.test(this.inputType),t={locale:Ui.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",Ki);class Ji 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",Ji,{extends:"a"});const Gi="application/json";function Xi(e){return"get"===e.toLowerCase()}function Qi(e,t,i){const s=function(e){return{"Content-Type":"application/json; charset=utf-8",Accept:e,"X-Requested-With":"XMLHttpRequest","X-CSRF-Token":Yi()}}(i),n={method:e,headers:s};return t&&!Xi(e)&&(n.body=JSON.stringify(t)),n}function Yi(){return document.querySelector('meta[name="csrf-token"]').attributes.content.textContent}function Zi(e,t){return is("GET",e,t)}function es(e,t,i){return is("PATCH",e,t,i)}function ts(e,t,i=Gi){return is("POST",e,t,i)}async function is(e,t,i,s=Gi){const n=await fetch(function(e,t,i){const s=new URL(window.location.origin+e);return t&&Xi(i)&&(s.search=new URLSearchParams(t).toString()),s.toString()}(t,i,e),Qi(e,i,s)),o=n.headers.get("content-type"),r=o?.includes(Gi),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 ss 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 ss{#O=void 0;connectedCallback(){this.page=this.getAttribute("page")}async#T(){const e=(await Zi(Alchemy.routes.api_ingredients_path,{page_id:this.#O})).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()}#E(){requestAnimationFrame(()=>{this.selectElement.disable(),this.selectElement.setOptions([],d("Select a page first"))})}set page(e){this.#O=e,e?this.#T():this.#E()}}),customElements.define("alchemy-dom-id-preview-select",class extends ss{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 ns extends HTMLElement{#I;connectedCallback(){this.#I=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.#I)}}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']")}}function os(e){document.dispatchEvent(new CustomEvent("alchemy:page-dirty",{detail:{tooltip:e.publishButtonTooltip}}))}customElements.define("alchemy-publish-element-button",ns);class rs extends HTMLElement{connectedCallback(){this.button?.addEventListener("click",this)}disconnectedCallback(){this.button?.removeEventListener("click",this)}async handleEvent(){if(await _(this.message)){const e=await is("DELETE",this.url);this.#F(e.data)}}#F(e){const t=this.closest("alchemy-element-editor");t.addEventListener("transitionend",()=>{t.fixed&&A(t.elementId),t.remove()}),t.classList.add("dismiss"),T(e.message),e.pageHasUnpublishedChanges&&os(e),$()}get url(){return this.getAttribute("href")}get message(){return this.getAttribute("message")}get button(){return this.querySelector("button")}}customElements.define("alchemy-delete-element-button",rs);class ls extends HTMLElement{#q=null;#$=null;#D=null;connectedCallback(){this.classList.contains("ui-sortable-placeholder")||(this.addEventListener("click",this),this.addEventListener("alchemy:element-update-title",this),this.#q=this.form,this.#q&&(this.#q.addEventListener("change",this.onChange),this.#q.addEventListener("turbo:submit-start",this),this.#q.addEventListener("turbo:submit-end",this)),this.#$=this.header,this.#$?.addEventListener("dblclick",this.#M),this.#D=this.toggleButton,this.#D?.addEventListener("click",this.#H),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.#q&&(this.#q.removeEventListener("change",this.onChange),this.#q.removeEventListener("turbo:submit-start",this),this.#q.removeEventListener("turbo:submit-end",this),this.#q=null),this.#$?.removeEventListener("dblclick",this.#M),this.#$=null,this.#D?.removeEventListener("click",this.#H),this.#D=null}handleEvent(e){switch(e.type){case"click":e.target.closest("alchemy-element-editor")===this&&this.onClickElement();break;case"turbo:submit-start":this.setClean();break;case"turbo:submit-end":this.onSaveElement(e.detail.success);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){e?this.previewWindow?.refresh().then(()=>{this.focusElementPreview()}):this.elementErrors.classList.remove("hidden")}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"),ts(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=>{T(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)=>{ts(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=>{T(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(`#${this.id} > form.element-body`)}get parentElementEditor(){return this.parentElement?.closest("alchemy-element-editor")}get previewWindow(){return document.getElementById("alchemy_preview_window")}#M=()=>{this.toggle()};#H=e=>{e.target.closest("alchemy-element-editor")===this&&this.toggle()}}customElements.define("alchemy-element-editor",ls);const as=(e,t)=>`\n
    \n ${e}${t}\n
    \n`;class cs extends ji{get renderers(){return{item:(e,t)=>as(e.icon,t(e.text)),option:(e,t)=>{const i=e.hint?`
    ${t(e.hint)}
    `:"";return`\n
    \n ${as(e.icon,t(e.text))}\n ${i}\n
    \n `}}}}customElements.define("alchemy-element-select",cs,{extends:"select"});class ds extends HTMLElement{#P=!0;#B=null;connectedCallback(){this.toggleButton?.addEventListener("click",this.#H),this.collapseButton?.addEventListener("click",this.#z),window.addEventListener("message",this.#R),document.body.addEventListener("click",this.#N),window.location.hash&&this.focusElementEditor(window.location.hash),this.resize()}disconnectedCallback(){this.toggleButton?.removeEventListener("click",this.#H),this.collapseButton?.removeEventListener("click",this.#z),window.removeEventListener("message",this.#R),document.body.removeEventListener("click",this.#N)}#H=e=>{e.preventDefault(),this.toggle()};#z=()=>{this.collapseAllElements()};#R=e=>{const t=e.data;if("Alchemy.focusElementEditor"==t?.message){const e=document.getElementById(`element_${t.element_id}`);this.show(),e?.focusElement()}};#N=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.#P?this.hide():this.show()}show(){document.body.classList.add("elements-window-visible"),this.#P=!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.#P=!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 ls&&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}}customElements.define("alchemy-elements-window",ds);class hs extends HTMLElement{#j=!1;#W=null;#V=null;#U=400;#K=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.#j&&this.onDrag(e.pageX)}}onMouseDown(){this.#j=!0;const e=getComputedStyle(this.elementsWindow);this.#U=parseFloat(e.minWidth)||400,this.#K="none"===e.maxWidth?1e3:parseFloat(e.maxWidth),this.elementsWindow.isDragged=!0,this.previewWindow.isDragged=!0,this.classList.add("is-dragged")}onMouseUp(){this.#j=!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.#U),this.#K);this.elementsWindow.resize(i)}get elementsWindow(){return this.#W||(this.#W=document.querySelector("alchemy-elements-window")),this.#W}get previewWindow(){return this.#V||(this.#V=document.getElementById("alchemy_preview_window")),this.#V}}customElements.define("alchemy-elements-window-handle",hs);class us 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",us);class ps extends HTMLElement{#J;#G=null;#X=null;connectedCallback(){this.hotkey&&key(this.hotkey,this.#Q),this.#G=this.filterField,this.#G.addEventListener("keyup",this.#Y),this.#G.addEventListener("focus",this.#Z),this.#X=this.clearButton,this.#X.addEventListener("click",this.#ee),key("esc","list_filter",this.#te)}disconnectedCallback(){clearTimeout(this.#J),this.#G?.removeEventListener("keyup",this.#Y),this.#G?.removeEventListener("focus",this.#Z),this.#G=null,this.#X?.removeEventListener("click",this.#ee),this.#X=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")}#Q=()=>(this.filterField.focus(),!1);#Y=()=>{clearTimeout(this.#J),this.#J=setTimeout(()=>{const e=this.filterField.value;this.clearButton.style.visibility=e?"visible":"hidden",this.filter(e)},this.debounceTime)};#Z=()=>key.setScope("list_filter");#ee=e=>{e.preventDefault(),this.clear()};#te=()=>{this.clear(),this.filterField.blur()}}customElements.define("alchemy-list-filter",ps);class ms extends HTMLElement{#ie=null;handleEvent(e){"click"===e.type&&this.dismiss()}connectedCallback(){if(!this.querySelector(":scope > alchemy-icon")){const e=this.dismissable&&"error"===this.type?'':"";this.insertAdjacentHTML("afterbegin",`${e}`)}(this.dismissable||"error"===this.type)&&this.addEventListener("click",this),this.dismissable&&"error"!==this.type&&(this.#ie=setTimeout(()=>{this.dismiss()},this.dismissDelay))}disconnectedCallback(){null!==this.#ie&&(clearTimeout(this.#ie),this.#ie=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",ms);class gs extends HTMLElement{connectedCallback(){T(this.message,this.getAttribute("type")||"notice"),this.remove()}get message(){return this.getAttribute("message")||this.innerHTML}}customElements.define("alchemy-growl",gs);class fs 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=``}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",fs);class vs extends HTMLElement{#se=null;#ne=null;#oe=null;connectedCallback(){this.image=this.querySelector("img"),this.form=this.querySelector("form"),this.#ne=document.getElementById(this.getAttribute("crop-from-field-id")),this.#oe=document.getElementById(this.getAttribute("crop-size-field-id")),this.elementEditor=document.querySelector(`[data-element-id='${this.getAttribute("element-id")}']`),this.form.addEventListener("submit",this.#re),this.form.addEventListener("reset",this.#le),this.#se=new s(this.image,this.cropperOptions)}disconnectedCallback(){this.#se?.destroy()}get cropperOptions(){return{aspectRatio:this.aspectRatio,viewMode:1,zoomable:!1,checkCrossOrigin:!1,checkOrientation:!1,data:this.box}}get aspectRatio(){const e=this.getAttribute("ratio");return e?parseFloat(e):NaN}get cropFrom(){if(this.#ne?.value)return this.#ne.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.defaultBox}get defaultBox(){const e=JSON.parse(this.getAttribute("default-box"));return{x:e[0],y:e[1],width:e[2],height:e[3]}}update(e){this.#ne.value=`${e.x}x${e.y}`,this.#ne.dispatchEvent(new Event("change")),this.#oe.value=`${e.width}x${e.height}`,this.#oe.dispatchEvent(new Event("change"))}reset(){const e=this.#se;e.setData(this.defaultBox);const t=e.getCanvasData(),i=t.width/t.naturalWidth;e.setCropBoxData({left:t.left+this.defaultBox.x*i,top:t.top+this.defaultBox.y*i}),this.update(this.defaultBox)}#re=e=>{e.preventDefault(),this.update(this.#se.getData(!0)),this.elementEditor?.setDirty(),w()?.close()};#le=e=>{e.preventDefault(),this.reset()}}customElements.define("alchemy-image-cropper",vs);class ys extends HTMLDetailsElement{#ae="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.#ae,JSON.stringify(e))}get isInLocalStorage(){return this.localStorageItem.includes(this.id)}get localStorageItem(){const e=localStorage.getItem(this.#ae);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",ys,{extends:"details"});class bs extends HTMLButtonElement{connectedCallback(){this.addEventListener("click",this),this.classList.add("icon_button"),this.setAttribute("type","button"),this.innerHTML=''}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",bs,{extends:"button"});class ws extends HTMLButtonElement{connectedCallback(){this.addEventListener("click",this),this.classList.add("icon_button"),this.setAttribute("type","button"),this.linked=this.linked,this.innerHTML=''}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",ws,{extends:"button"});class Es 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",Es);class ks extends HTMLElement{connectedCallback(){this.track=this.querySelector(".news-reader--track"),this.slides=Array.from(this.querySelectorAll(".news-reader--item")),!this.track||this.slides.length<2||(this.currentIndex=0,this.createDots(),this.setActive(0),this.startRotation(),this.addEventListener("mouseenter",this),this.addEventListener("mouseleave",this),this.track.addEventListener("scroll",this,{passive:!0}))}disconnectedCallback(){this.stopRotation()}handleEvent(e){switch(e.type){case"mouseenter":this.stopRotation();break;case"mouseleave":this.startRotation();break;case"scroll":this.syncActiveToScroll()}}createDots(){this.dotList=document.createElement("div"),this.dotList.className="news-reader--dots",this.dots=this.slides.map((e,t)=>{const i=document.createElement("button");return i.type="button",i.className="news-reader--dot",i.setAttribute("aria-label",`${t+1}`),i.addEventListener("click",()=>{this.goTo(t),this.startRotation()}),this.dotList.append(i),i}),this.append(this.dotList)}goTo(e){this.currentIndex=e,this.slides[e].scrollIntoView({behavior:"smooth",inline:"start",block:"nearest"}),this.setActive(e)}next(){this.goTo((this.currentIndex+1)%this.slides.length)}syncActiveToScroll(){const e=this.track.clientWidth;if(!e)return;const t=Math.round(this.track.scrollLeft/e);t!==this.currentIndex&&this.slides[t]&&(this.currentIndex=t,this.setActive(t))}setActive(e){this.dots.forEach((t,i)=>{t.classList.toggle("is-active",i===e)})}startRotation(){this.stopRotation(),this.timer=window.setInterval(()=>this.next(),this.interval)}stopRotation(){this.timer&&window.clearInterval(this.timer),this.timer=null}get interval(){return parseInt(this.getAttribute("interval"),10)||8e3}}customElements.define("alchemy-news-reader",ks);class Ls extends HTMLElement{connectedCallback(){this.addEventListener("Alchemy.RemoteSelect.Change",this.#ce)}disconnectedCallback(){this.removeEventListener("Alchemy.RemoteSelect.Change",this.#ce)}#ce=e=>{const t=e.detail.added;t?(this.nameField.setAttribute("placeholder",t.name),this.urlField.value=t.url_path,this.urlField.setAttribute("disabled","disabled")):(this.nameField.removeAttribute("placeholder"),this.urlField.value="",this.urlField.removeAttribute("disabled"))};get nameField(){return this.querySelector("#node_name")}get urlField(){return this.querySelector("#node_url")}}customElements.define("alchemy-node-form",Ls);function _s(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 Hi{_searchQuery(e,t){return{filter:{name_or_page_name_cont:e,...JSON.parse(this.queryParams)},page:t}}_entry(e,t){return{icon:"menu-2",primary:this.#de(e)+this._hightlightTerm(e.name,t),secondary:{text:e.url,truncate:"head"}}}_selectedEntry(e){return{icon:"menu-2",primary:this.#de(e)+Di(e.name)}}#de(e){const t=e.ancestors.map(e=>e.name);if(0===t.length)return"";const i='';return`${t.map(Di).join(i)}${i}`}});class Ss extends HTMLElement{file=null;request=null;progressEventLoaded=0;progressEventTotal=0;#he=!0;#ue=0;#pe=void 0;#me="";connectedCallback(){if(this.innerHTML=`\n \n
    \n ${this.file?.name}\n ${this.loadedSize}\n ${this.errorMessage}\n
    \n \n \n \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.#ge(),this.#fe()}cancel(){this.finished||(this.status="canceled",this.request?.abort(),this.dispatchCustomEvent("FileUpload.Change"))}dispatchCustomEvent(e){this.dispatchEvent(new CustomEvent(`Alchemy.${e}`,{bubbles:!0}))}#ge(){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)}#fe(){this.request&&(this.request.upload.onprogress=e=>{this.progressEvent=e},this.request.onload=()=>{this.request.status<400?(this.status="successful",T(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.#me||""}set errorMessage(e){this.#me=e;const t=this.querySelector(".error-message");t&&(t.textContent=e),T(e,"error")}get finished(){return["canceled","successful","failed"].includes(this.status)}get loadedSize(){return`${_s(this.progressEventLoaded)} / ${_s(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.#pe}set status(e){this.#pe=e,this.className=e,this.progressElement?.toggleAttribute("indeterminate","upload-finished"===e)}get valid(){return this.#he}set valid(e){this.#he=e,this.classList.toggle("invalid",!e)}get value(){return this.#ue}set value(e){this.#ue=e,this.progressElement&&(this.progressElement.value=e),100===e&&(this.status="upload-finished"),this.dispatchCustomEvent("FileUpload.Change")}}customElements.define("alchemy-file-upload",Ss);class xs extends HTMLElement{fileCount=0;#ve=[];#ye=d("Cancel all uploads");#be=null;#P=!1;#we=()=>this.#Ee();connectedCallback(){var e,t;this.innerHTML=(e=this.#ye,t=this.fileCount,`\n \n
    \n \n\n \n \n \n
    \n
    \n
    \n`),this.visible=!0,this.#be=this.querySelector("button"),this.#be.addEventListener("click",()=>{this.finished?this.onComplete(this.status):this.cancel()}),this.#ve.forEach(e=>{this.querySelector(".single-uploads").append(e)}),this.#Ee(),this.addEventListener("Alchemy.FileUpload.Change",this.#we)}disconnectedCallback(){this.removeEventListener("Alchemy.FileUpload.Change",this.#we)}initialize(e=[]){this.#ve=e,this.fileCount=e.length}cancel(){this.#ke().forEach(e=>{e.cancel()}),this.#Le()}onComplete(e){}#ke(){return this.#ve.filter(e=>e.active)}#Le(){this.#ye=d("Close"),this.#be.ariaLabel=this.#ye,this.#be.parentElement.content=this.#ye}#_e(e){return this.#ke().reduce((t,i)=>i[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.#Le(),this.onComplete(e)):this.visible=!0}get finished(){return this.#ke().every(e=>e.finished)}get overallUploadSize(){this.#ke().filter(e=>e.value>=100).length;return this.totalProgress,this.#ke().length,`${_s(this.#_e("progressEventLoaded"))} / ${_s(this.#_e("progressEventTotal"))}`}get overallProgressValue(){const e=this.#ke().filter(e=>e.value>=100).length;return`${this.totalProgress}% (${e} / ${this.#ke().length})`}get progressElement(){return this.querySelector("sl-progress-bar")}get status(){const e=this.#ke().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.#ke().reduce((e,t)=>e+t.file.size,0);let t=Math.ceil(this.#ke().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.#P}set visible(e){this.classList.toggle("visible",e),this.#P=e}}customElements.define("alchemy-upload-progress",xs);class Cs extends HTMLElement{#Se=null;#xe=!1;connectedCallback(){this.fileInput.addEventListener("change",this.#Ce),this.dropzone&&this.#Ae(),this.addEventListener("Alchemy.upload.successful",this)}disconnectedCallback(){this.fileInput?.removeEventListener("change",this.#Ce),this.#Se&&(this.#Se.removeEventListener("dragleave",this.#Oe),this.#Se.removeEventListener("drop",this.#Te),this.#Se.removeEventListener("dragover",this.#Ie),this.#Se=null)}handleEvent(e){if("Alchemy.upload.successful"===e.type)this.#Fe()}#Ce=e=>{this.uploadFiles(Array.from(e.target.files))};#qe=e=>{this.#xe!==e&&(this.#xe=e,this.#Se.classList.toggle("dragover"))};#Oe=()=>this.#qe(!1);#Te=async e=>{e.preventDefault(),this.#qe(!1);const t=[...e.dataTransfer.items].map(e=>e.getAsFile());this.uploadFiles(t)};#Ie=e=>{e.preventDefault(),this.#qe(!0)};#Fe(){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)}#Ae(){this.#Se=document.querySelector(this.dropzone),this.#Se&&(this.#Se.addEventListener("dragleave",this.#Oe),this.#Se.addEventListener("drop",this.#Te),this.#Se.addEventListener("dragover",this.#Ie))}uploadFiles(e){let t=0;const i=e.map(e=>{const i=new XMLHttpRequest,s=new Ss;return s.initialize(e,i),Alchemy.uploader_defaults.upload_limit-1{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",Cs);class As extends HTMLElement{connectedCallback(){this.innerHTML=`\n \n
    \n ${this.getAttribute("text")??""}\n
    \n `}set show(e){this.classList.toggle("visible",e)}}customElements.define("alchemy-overlay",As);const Os="BUTTON";class Ts 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 m("small");i.spin(t);try{await es(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){T(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=``}}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=``,this.folderButton?.addEventListener("click",this)}else t||e.tagName!==Os?t&&e.tagName===Os&&this.updateFolderIcon():e.outerHTML=''}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",Ts);class Is extends HTMLElement{connectedCallback(){this.publicField?.addEventListener("click",this.#Me)}disconnectedCallback(){this.publicField?.removeEventListener("click",this.#Me)}#Me=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",Is);class Fs extends Hi{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_pagee.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,Zi(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),T(e.message||e,"error")}))}removeImage=()=>{this.pictureThumbnail.innerHTML='',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",$s);class Ds extends HTMLElement{constructor(){super(),this.spinner=new m("small")}handleEvent(e){switch(e.type){case"load":this.#He();break;case"error":this.#Pe(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()}#He(){this.spinner.stop(),this.removeAttribute("loading")}#Pe(e){const t=`Could not load ${this.image.src}`,i=this.closest(".ingredient-editor");this.spinner.stop(),this.innerHTML=`\n \n \n \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",Ds);class Ms 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",Ms);class Hs 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 n(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 es(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),T(d("Successfully moved page"))}catch(e){T(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",Hs);const Ps={draggable:".element-editor",handle:".element-handle.draggable",ghostClass:"dragged",animation:150,swapThreshold:.65,easing:"cubic-bezier(1, 0, 0, 1)"};function Bs(e){const t=e.item.dataset.elementName;document.querySelectorAll(`[data-droppable-elements~="${t}"]`).forEach(e=>e.classList.add("droppable-elements"))}function zs(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&&ts(Alchemy.routes.order_admin_elements_path,s).then(e=>{const i=e.data;T(i.message),i.pageHasUnpublishedChanges&&os(i),$(),t.updateTitle(i.preview_text)})}function Rs(){document.querySelectorAll("[data-droppable-elements]").forEach(e=>e.classList.remove("droppable-elements"))}class Ns extends HTMLElement{connectedCallback(){const e={name:this.dataset.elementName,put:(e,t,i)=>e.el.dataset.droppableElements.split(" ").includes(i.dataset.elementName)};new n(this,{...Ps,onStart:Bs,onSort:zs,onEnd:Rs,group:e})}}customElements.define("alchemy-sortable-elements",Ns);class js extends HTMLElement{connectedCallback(){this.className=`spinner spinner--${this.size}`,this.innerHTML=`\n \n \n \n \n \n `}get size(){return this.getAttribute("size")||"medium"}get color(){return this.getAttribute("color")||"currentColor"}}customElements.define("alchemy-spinner",js);class Ws extends HTMLElement{#f=null;connectedCallback(){this.classList.add("autocomplete_tag_list"),this.input.classList.add("alchemy_selectbox"),this.#f=new Ue(this.input,this.settings)}disconnectedCallback(){this.#f?.destroy(),this.#f=null}focus(){Ii(this.#f,()=>super.focus())}get input(){return this.getElementsByTagName("input")[0]}get settings(){return{plugins:{remove_button:qi()},valueField:"id",delimiter:",",create:!0,createFilter(e){return!this.loading&&(this.settings.duplicates||!this.options[e])},persist:!1,clearAfterSelect:!0,maxOptions:null,openOnFocus:!1,placeholder:this.getAttribute("placeholder"),load:(e,t)=>{Zi(this.getAttribute("url"),{term:e}).then(e=>t(e.data)).catch(()=>t())},...Fi(),render:{...$i}}}}customElements.define("alchemy-tags-autocomplete",Ws);const Vs="alchemy-dark",Us="alchemy";class Ks extends HTMLElement{#ze=null;connectedCallback(){this.className="tinymce_container",this.querySelector(":scope > alchemy-spinner")||this.insertAdjacentHTML("beforeend",''),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?Vs:Us,s=e.matches?Vs:Us;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?Vs:Us}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.#ze||this.configuration.min_height}set minHeight(e){this.#ze=e}}customElements.define("alchemy-tinymce",Ks);class Js extends HTMLElement{async connectedCallback(){const e=new m("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 Gs;customElements.define("alchemy-update-check",Js),Gs=Handlebars.template,(Handlebars.templates=Handlebars.templates||{})["node_folder.hbs"]=Gs({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'\n \n\n'},useData:!0}),o("tooltip.show",{keyframes:[{transform:"translateY(10px)",opacity:"0"},{transform:"translateY(0)",opacity:"1"}],options:{duration:100}}),o("tooltip.hide",{keyframes:[{transform:"translateY(0)",opacity:"1"},{transform:"translateY(10px)",opacity:"0"}],options:{duration:100}}),o("dialog.show",{keyframes:[{transform:"scale(0.98)",opacity:"0"},{transform:"scale(1)",opacity:"1"}],options:{duration:150}}),o("dialog.hide",{keyframes:[{transform:"scale(1)",opacity:"1"},{transform:"scale(0.98)",opacity:"0"}],options:{duration:150}});const Xs=document.querySelector('link[rel="preload"][as="image"]').getAttribute("href"),Qs={"x-lg":"close",caret:"arrow-down-s"},Ys={resolver:e=>`${Xs}#ri-${Qs[e]||e}-line`,mutator:e=>{e.setAttribute("fill","currentColor"),e.setAttribute("viewBox","0 0 24 24")},spriteSheet:!0};r("default",Ys),r("system",Ys);class Zs extends b{#Re=e=>{if(e.target.closest(".picture-overlay-handle"))return e.preventDefault(),void this.dialog.classList.toggle("hide-form");if(e.target.closest(".zoomed-picture-background")){if(e.stopPropagation(),"IMG"===e.target.nodeName)return;this.close()}};#Ne=e=>{if("INPUT"!==e.target.nodeName&&"TEXTAREA"!==e.target.nodeName)switch(e.key){case"ArrowLeft":this.previous(),e.preventDefault();break;case"ArrowRight":this.next(),e.preventDefault()}};init(){this.dialog_body.removeEventListener("click",this.#Re),this.dialog_body.addEventListener("click",this.#Re),this.#je(),super.init()}previous(){this.dialog_body.querySelector(".previous-picture")?.click()}next(){this.dialog_body.querySelector(".next-picture")?.click()}close(){return document.removeEventListener("keydown",this.#Ne),super.close()}build(){this.dialog_container=p(''),this.dialog=p('
    '),this.dialog_body=p('
    '),this.close_button=p('\n \n '),this.dialog.append(this.close_button),this.dialog.append(this.dialog_body),this.dialog_container.append(this.dialog),document.body.append(this.dialog_container)}#je(){document.removeEventListener("keydown",this.#Ne),document.addEventListener("keydown",this.#Ne)}}function en(){return document.querySelectorAll("#picture_archive input:checked")}function tn(){const e=document.querySelector("#select_all_pictures"),t=document.querySelector(".selected_item_tools");f("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)}),f("change",".picture_tool.select","input",e=>{t.classList.toggle("hidden",0===en().length);const i=e.target.parentElement.classList,s=e.target.checked;i.toggle("visible",s)}),f("click",".selected_item_tools","a#edit_multiple_pictures",e=>{e.preventDefault();k(function(e){const t=new URL(e);return en().forEach(e=>t.searchParams.append(e.name,e.value)),t.toString()}(e.target.href),{title:e.target.title,size:"400x295"})})}function sn(){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 nn(e){es(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(()=>{T(Alchemy.t("Successfully moved menu item")),sn()}).catch(e=>{T(e.message||e,"error")})}function on(){f("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");es(i).then(()=>{s.classList.toggle("folded"),t.dataset.folded="true"==t.dataset.folded?"false":"true",sn()}).catch(e=>{T(e.message||e)})}),sn(),document.querySelectorAll(".nodes_tree ul.children").forEach(e=>{new n(e,{group:"nodes",animation:150,fallbackOnBody:!0,swapThreshold:.65,handle:".node_name",invertSwap:!0,onEnd:nn})})}void 0===window.Alchemy&&(window.Alchemy={}),Object.assign(Alchemy,{closeCurrentDialog:E,currentDialog:w,...C,t:d,FixedElements:O,growl:T,LinkDialog:class extends b{#We;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.#m()}open(){return super.open(),new Promise(e=>this.#We=e)}#m(){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.#Ve(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.#Ue(e.target.dataset.linkFormType)})})}#Ve(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}#Ue(e){const t=document.getElementById("element_anchor");let i=document.getElementById(`${e}_link`).value;if("internal"===e&&""!==t.value)i=i.replace(F,"")+t.value;else if("external"===e&&!i.match(Alchemy.link_url_regexp))return void this.#Ke();this.#We({url:i.trim(),title:document.getElementById(`${e}_link_title`).value,target:document.getElementById(`${e}_link_target`)?.value,type:e}),this.close()}#Ke(){const e=document.getElementById("errors");e.querySelector("ul").innerHTML=`
  • ${Alchemy.t("url_validation_failed")}
  • `,e.style.display="block"}},pleaseWaitOverlay:S,Spinner:m,reloadPreview:$}),t.start(),e.config.forms.confirm=_,document.addEventListener("turbo:load",function(){document.documentElement.classList.remove("no-js"),u(),document.removeEventListener("keypress",I),document.addEventListener("keypress",I),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{Pi as AttachmentSelect,cs as ElementSelect,Zs as ImageOverlay,on as NodeTree,Fs as PageSelect,Hi as RemoteSelect,Ws as TagsAutocomplete,Ks as Tinymce,f as on,tn as pictureSelector}; //# sourceMappingURL=alchemy_admin.min.js.map diff --git a/app/assets/builds/alchemy/alchemy_admin.min.js.map b/app/assets/builds/alchemy/alchemy_admin.min.js.map index 72cb5cb9f7..c0e0fe2572 100644 --- a/app/assets/builds/alchemy/alchemy_admin.min.js.map +++ b/app/assets/builds/alchemy/alchemy_admin.min.js.map @@ -1 +1 @@ -{"version":3,"file":"alchemy_admin.min.js","sources":["../../../javascript/alchemy_admin/i18n.js","../../../javascript/alchemy_admin/hotkeys.js","../../../javascript/alchemy_admin/utils/dom_helpers.js","../../../javascript/alchemy_admin/spinner.js","../../../javascript/alchemy_admin/utils/events.js","../../../javascript/alchemy_admin/dialog.js","../../../javascript/alchemy_admin/confirm_dialog.js","../../../javascript/alchemy_admin/please_wait_overlay.js","../../../javascript/alchemy_admin/dirty.js","../../../javascript/alchemy_admin/fixed_elements.js","../../../javascript/alchemy_admin/growler.js","../../../javascript/alchemy_admin/initializer.js","../../../javascript/alchemy_admin/link_dialog.js","../../../javascript/alchemy_admin/components/preview_window.js","../../../javascript/alchemy_admin/turbo_stream_actions.js","../../../javascript/alchemy_admin/ingredient_anchor_link.js","../../../javascript/alchemy_admin/components/action.js","../../../../node_modules/.pnpm/tom-select@2.6.2/node_modules/tom-select/dist/esm/contrib/microevent.js","../../../../node_modules/.pnpm/@orchidjs+unicode-variants@1.1.2/node_modules/@orchidjs/unicode-variants/dist/esm/regex.js","../../../../node_modules/.pnpm/@orchidjs+unicode-variants@1.1.2/node_modules/@orchidjs/unicode-variants/dist/esm/strings.js","../../../../node_modules/.pnpm/@orchidjs+unicode-variants@1.1.2/node_modules/@orchidjs/unicode-variants/dist/esm/index.js","../../../../node_modules/.pnpm/@orchidjs+sifter@1.1.0/node_modules/@orchidjs/sifter/dist/esm/utils.js","../../../../node_modules/.pnpm/@orchidjs+sifter@1.1.0/node_modules/@orchidjs/sifter/dist/esm/sifter.js","../../../../node_modules/.pnpm/tom-select@2.6.2/node_modules/tom-select/dist/esm/utils.js","../../../../node_modules/.pnpm/tom-select@2.6.2/node_modules/tom-select/dist/esm/vanilla.js","../../../../node_modules/.pnpm/tom-select@2.6.2/node_modules/tom-select/dist/esm/contrib/highlight.js","../../../../node_modules/.pnpm/tom-select@2.6.2/node_modules/tom-select/dist/esm/constants.js","../../../../node_modules/.pnpm/tom-select@2.6.2/node_modules/tom-select/dist/esm/defaults.js","../../../../node_modules/.pnpm/tom-select@2.6.2/node_modules/tom-select/dist/esm/getSettings.js","../../../../node_modules/.pnpm/tom-select@2.6.2/node_modules/tom-select/dist/esm/tom-select.js","../../../../node_modules/.pnpm/tom-select@2.6.2/node_modules/tom-select/dist/esm/contrib/microplugin.js","../../../../node_modules/.pnpm/tom-select@2.6.2/node_modules/tom-select/dist/esm/plugins/checkbox_options/plugin.js","../../../../node_modules/.pnpm/tom-select@2.6.2/node_modules/tom-select/dist/esm/plugins/clear_button/plugin.js","../../../../node_modules/.pnpm/tom-select@2.6.2/node_modules/tom-select/dist/esm/plugins/drag_drop/plugin.js","../../../../node_modules/.pnpm/tom-select@2.6.2/node_modules/tom-select/dist/esm/plugins/dropdown_header/plugin.js","../../../../node_modules/.pnpm/tom-select@2.6.2/node_modules/tom-select/dist/esm/plugins/caret_position/plugin.js","../../../../node_modules/.pnpm/tom-select@2.6.2/node_modules/tom-select/dist/esm/plugins/dropdown_input/plugin.js","../../../../node_modules/.pnpm/tom-select@2.6.2/node_modules/tom-select/dist/esm/plugins/input_autogrow/plugin.js","../../../../node_modules/.pnpm/tom-select@2.6.2/node_modules/tom-select/dist/esm/plugins/remove_button/plugin.js","../../../../node_modules/.pnpm/tom-select@2.6.2/node_modules/tom-select/dist/esm/plugins/virtual_scroll/plugin.js","../../../../node_modules/.pnpm/tom-select@2.6.2/node_modules/tom-select/dist/esm/tom-select.complete.js","../../../../node_modules/.pnpm/tom-select@2.6.2/node_modules/tom-select/dist/esm/plugins/change_listener/plugin.js","../../../../node_modules/.pnpm/tom-select@2.6.2/node_modules/tom-select/dist/esm/plugins/no_backspace_delete/plugin.js","../../../../node_modules/.pnpm/tom-select@2.6.2/node_modules/tom-select/dist/esm/plugins/no_active_items/plugin.js","../../../../node_modules/.pnpm/tom-select@2.6.2/node_modules/tom-select/dist/esm/plugins/optgroup_columns/plugin.js","../../../../node_modules/.pnpm/tom-select@2.6.2/node_modules/tom-select/dist/esm/plugins/restore_on_backspace/plugin.js","../../../../node_modules/.pnpm/@floating-ui+utils@0.2.11/node_modules/@floating-ui/utils/dist/floating-ui.utils.mjs","../../../../node_modules/.pnpm/@floating-ui+core@1.7.5/node_modules/@floating-ui/core/dist/floating-ui.core.mjs","../../../../node_modules/.pnpm/@floating-ui+utils@0.2.11/node_modules/@floating-ui/utils/dist/floating-ui.utils.dom.mjs","../../../../node_modules/.pnpm/@floating-ui+dom@1.7.6/node_modules/@floating-ui/dom/dist/floating-ui.dom.mjs","../../../javascript/alchemy_admin/utils/tom_select.js","../../../javascript/alchemy_admin/components/remote_select.js","../../../javascript/alchemy_admin/components/attachment_select.js","../../../javascript/alchemy_admin/components/auto_submit.js","../../../javascript/alchemy_admin/components/button.js","../../../javascript/alchemy_admin/components/char_counter.js","../../../javascript/alchemy_admin/components/clipboard_button.js","../../../javascript/alchemy_admin/components/select.js","../../../javascript/alchemy_admin/components/color_select.js","../../../javascript/alchemy_admin/components/datepicker.js","../../../javascript/alchemy_admin/components/dialog_link.js","../../../javascript/alchemy_admin/utils/ajax.js","../../../javascript/alchemy_admin/components/dom_id_select.js","../../../javascript/alchemy_admin/utils/dispatch_page_dirty_event.js","../../../javascript/alchemy_admin/components/element_editor/publish_element_button.js","../../../javascript/alchemy_admin/components/element_editor/delete_element_button.js","../../../javascript/alchemy_admin/components/element_editor.js","../../../javascript/alchemy_admin/components/element_select.js","../../../javascript/alchemy_admin/components/elements_window.js","../../../javascript/alchemy_admin/components/elements_window_handle.js","../../../javascript/alchemy_admin/components/file_editor.js","../../../javascript/alchemy_admin/components/list_filter.js","../../../javascript/alchemy_admin/components/message.js","../../../javascript/alchemy_admin/components/growl.js","../../../javascript/alchemy_admin/components/icon.js","../../../javascript/alchemy_admin/components/image_cropper.js","../../../javascript/alchemy_admin/components/ingredient_group.js","../../../javascript/alchemy_admin/components/link_buttons/link_button.js","../../../javascript/alchemy_admin/components/link_buttons/unlink_button.js","../../../javascript/alchemy_admin/components/link_buttons.js","../../../javascript/alchemy_admin/components/news_reader.js","../../../javascript/alchemy_admin/components/node_form.js","../../../javascript/alchemy_admin/utils/format.js","../../../javascript/alchemy_admin/components/node_select.js","../../../javascript/alchemy_admin/components/uploader/file_upload.js","../../../javascript/alchemy_admin/components/uploader/progress.js","../../../javascript/alchemy_admin/components/uploader.js","../../../javascript/alchemy_admin/components/overlay.js","../../../javascript/alchemy_admin/components/page_node.js","../../../javascript/alchemy_admin/components/page_publication_fields.js","../../../javascript/alchemy_admin/components/page_select.js","../../../javascript/alchemy_admin/components/picture_description_select.js","../../../javascript/alchemy_admin/components/picture_editor.js","../../../javascript/alchemy_admin/utils/debounce.js","../../../javascript/alchemy_admin/utils/max.js","../../../javascript/alchemy_admin/components/picture_thumbnail.js","../../../javascript/alchemy_admin/components/publish_page_button.js","../../../javascript/alchemy_admin/components/sitemap.js","../../../javascript/alchemy_admin/components/sortable_elements.js","../../../javascript/alchemy_admin/components/spinner.js","../../../javascript/alchemy_admin/components/tags_autocomplete.js","../../../javascript/alchemy_admin/components/tinymce.js","../../../javascript/alchemy_admin/components/update_check.js","../../../javascript/alchemy_admin/templates/compiled.js","../../../javascript/alchemy_admin/shoelace_theme.js","../../../javascript/alchemy_admin/image_overlay.js","../../../javascript/alchemy_admin/picture_selector.js","../../../javascript/alchemy_admin/node_tree.js","../../../javascript/alchemy_admin.js"],"sourcesContent":["const KEY_SEPARATOR = /\\./\n\nfunction nestedTranslation(translations, key) {\n const keys = key.split(KEY_SEPARATOR)\n const group = translations[keys[0]]\n if (group) {\n return group[keys[1]] || key\n }\n return key\n}\n\nfunction getTranslation(key) {\n const locale = currentLocale()\n const translations = Alchemy.translations\n\n if (!translations) {\n console.warn(`Translations for locale ${locale} not found!`)\n return key\n }\n\n if (KEY_SEPARATOR.test(key)) {\n return nestedTranslation(translations, key)\n }\n return translations[key] || key\n}\n\nexport function currentLocale() {\n if (document.documentElement.lang) {\n return document.documentElement.lang\n }\n return \"en\"\n}\n\nexport function translate(key, replacement = undefined) {\n let translation = getTranslation(key)\n\n if (replacement) {\n return translation.replace(/%\\{.+\\}/, replacement)\n }\n return translation\n}\n","import \"keymaster\"\n\nconst bindedHotkeys = []\n\nexport default function (scope = document) {\n // Unbind all previously registered hotkeys if we are not inside a dialog.\n if (scope === document) {\n bindedHotkeys.forEach((hotkey) => key.unbind(hotkey))\n }\n\n // Binds keyboard shortcuts to search fields.\n const search_fields = scope.querySelectorAll(\".search_input_field\")\n const search_fields_clear = scope.querySelectorAll(\n \".search_field_clear, .js_filter_field_clear\"\n )\n key(\"alt+f\", function () {\n key.setScope(\"search\")\n search_fields.forEach((el) => el.focus({ focusVisible: true }))\n return false\n })\n bindedHotkeys.push(\"alt+f\")\n key(\"esc\", \"search\", function () {\n search_fields_clear.forEach((el) => el.click())\n search_fields.forEach((el) => el.blur())\n })\n bindedHotkeys.push(\"esc\")\n\n // Binds click events to buttons with hotkeys.\n //\n // Simply add a data-alchemy-hotkey attribute to your link.\n // If a hotkey is triggered by user, the click event of the element gets triggerd.\n //\n scope.querySelectorAll(\"[data-alchemy-hotkey]\").forEach(function (el) {\n const hotkey = el.dataset.alchemyHotkey\n key(hotkey, () => el.click())\n bindedHotkeys.push(hotkey)\n })\n}\n","/**\n * create a HTML element\n * @param {string} text\n * @returns {HTMLElement}\n */\nexport function createHtmlElement(text) {\n const element = document.createElement(\"template\")\n element.innerHTML = text\n return element.content.children[0]\n}\n\n/**\n * wrap element with wrappingElement\n * @param {HTMLElement} element\n * @param {HTMLElement} wrappingElement\n */\nexport function wrap(element, wrappingElement) {\n element.replaceWith(wrappingElement)\n wrappingElement.appendChild(element)\n}\n","import { createHtmlElement } from \"alchemy_admin/utils/dom_helpers\"\n\nexport default class Spinner {\n constructor(size, color = \"currentColor\") {\n this.size = size\n this.color = color\n this.spinner = undefined\n }\n\n /**\n * @returns {HTMLElement|undefined}\n */\n get el() {\n return this.spinner\n }\n /**\n * @param {HTMLElement|undefined} parent\n */\n spin(parent) {\n if (typeof parent === \"undefined\") {\n parent = document.body\n }\n this.spinner = createHtmlElement(\n ``\n )\n parent.append(this.spinner)\n return this\n }\n\n stop() {\n if (this.spinner) {\n this.spinner.remove()\n this.spinner = undefined\n }\n }\n}\n","// Dispatches a bubbling CustomEvent from the given element.\nexport function dispatchCustomEvent(element, name, detail = {}) {\n element.dispatchEvent(new CustomEvent(name, { bubbles: true, detail }))\n}\n\nexport function on(eventName, baseSelector, targetSelector, callback) {\n document.querySelectorAll(baseSelector).forEach((baseNode) => {\n baseNode.addEventListener(eventName, (evt) => {\n const targets = Array.from(baseNode.querySelectorAll(targetSelector))\n let currentNode = evt.target\n\n while (currentNode !== baseNode) {\n if (targets.includes(currentNode)) {\n callback.call(currentNode, evt)\n return\n }\n currentNode = currentNode.parentElement\n }\n })\n })\n}\n","import Hotkeys from \"alchemy_admin/hotkeys\"\nimport Spinner from \"alchemy_admin/spinner\"\nimport { createHtmlElement } from \"alchemy_admin/utils/dom_helpers\"\nimport { dispatchCustomEvent } from \"alchemy_admin/utils/events\"\n\n// Collection of all current dialog instances\nconst currentDialogs = []\n\nconst DEFAULTS = {\n header_height: 36,\n size: \"400x300\",\n padding: true,\n title: \"\",\n modal: true,\n overflow: \"visible\",\n ready: () => {},\n closed: () => {}\n}\n\nexport class Dialog {\n #previousFlashParent = null\n #closing = false\n\n // Arguments:\n // - url: The url to load the content from via ajax\n // - options: A object holding options\n // - size: The maximum size of the Dialog\n // - title: The title of the Dialog\n constructor(url, options = {}) {\n this.url = url\n this.options = { ...DEFAULTS, ...options }\n const size = this.options.size.split(\"x\")\n this.width = parseInt(size[0], 10)\n this.height = parseInt(size[1], 10)\n this.build()\n this.resize()\n }\n\n // Opens the Dialog and loads the content via ajax.\n open() {\n dispatchCustomEvent(this.dialog, \"Alchemy.DialogOpen\")\n this.bind_close_events()\n if (this.options.modal) {\n this.dialog_container.showModal()\n this.#adoptFlashNotices()\n } else {\n this.dialog_container.show()\n }\n window.requestAnimationFrame(() => {\n this.dialog_container.classList.add(\"open\")\n })\n document.body.classList.add(\"prevent-scrolling\")\n currentDialogs.push(this)\n this.load()\n }\n\n // Closes the Dialog and removes it from the DOM\n close() {\n // The container stays open during the closing transition, so close() can be\n // called again mid-fade (mashing Esc, a double click on the close button or\n // backdrop). Guard against re-entry, otherwise a second transitionend\n // listener is registered and the teardown runs twice.\n if (this.#closing) {\n return true\n }\n this.#closing = true\n dispatchCustomEvent(this.dialog, \"DialogClose.Alchemy\")\n this.dialog_container.classList.remove(\"open\")\n this.dialog_container.addEventListener(\n \"transitionend\",\n () => {\n // Move the flash notices back out before removing the container, so\n // they are not destroyed together with the dialog.\n this.#releaseFlashNotices()\n this.dialog_container.close()\n this.dialog_container.remove()\n currentDialogs.pop()\n if (currentDialogs.length === 0) {\n document.body.classList.remove(\"prevent-scrolling\")\n }\n if (this.options.closed != null) {\n this.options.closed()\n }\n },\n { once: true }\n )\n return true\n }\n\n // A modal makes everything outside its subtree inert, so flash\n // notices rendered on the body would be visible but not interactable while\n // the dialog is open. Move them into the dialog, which is in the top layer\n // and not inert, for the dialog's lifetime and restore them on close.\n #adoptFlashNotices() {\n const flashNotices = document.getElementById(\"flash_notices\")\n if (flashNotices) {\n this.#previousFlashParent = flashNotices.parentElement\n this.dialog_container.append(flashNotices)\n this.#clearTransientNotices(flashNotices)\n }\n }\n\n #releaseFlashNotices() {\n const flashNotices = document.getElementById(\"flash_notices\")\n if (flashNotices && this.#previousFlashParent) {\n this.#previousFlashParent.append(flashNotices)\n this.#clearTransientNotices(flashNotices)\n }\n }\n\n // Only the persistent error notices need to travel with the dialog to stay\n // interactable. Moving the auto-dismissing ones would restart their dismiss\n // timers (their connectedCallback re-arms the timer), making them linger, so\n // remove them instead. A fade-out is skipped on purpose: the just-moved\n // element has no transition baseline, so dismiss()'s transitionend would never\n // fire and the node would be stranded invisible-but-present.\n #clearTransientNotices(flashNotices) {\n flashNotices\n .querySelectorAll('alchemy-message[dismissable]:not([type=\"error\"])')\n .forEach((message) => message.remove())\n }\n\n // Loads the content via ajax and replaces the Dialog body with server response.\n load() {\n this.show_spinner()\n fetch(this.url, {\n headers: { \"X-Requested-With\": \"XMLHttpRequest\" }\n })\n .then(async (response) => {\n const responseText = await response.text()\n if (response.ok) {\n this.replace(responseText)\n } else {\n this.show_error({\n status: response.status,\n statusText: response.statusText,\n responseText\n })\n }\n })\n .catch(() => {\n this.show_error({ status: 0 })\n })\n }\n\n // Reloads the Dialog content\n reload() {\n this.dialog_body.innerHTML = \"\"\n this.load()\n }\n\n // Replaces the dialog body with given content and initializes it.\n replace(data) {\n this.remove_spinner()\n this.dialog_body.style.display = \"none\"\n this.dialog_body.innerHTML = data\n this.init()\n dispatchCustomEvent(this.dialog, \"DialogReady.Alchemy\", {\n body: this.dialog_body\n })\n if (this.options.ready != null) {\n this.options.ready(this.dialog_body)\n }\n this.dialog_body.style.display = \"\"\n }\n\n // Adds a spinner into Dialog body\n show_spinner() {\n this.spinner = new Spinner(\"medium\")\n this.spinner.spin(this.dialog_body)\n }\n\n // Removes the spinner from Dialog body\n remove_spinner() {\n this.spinner.stop()\n }\n\n // Initializes the Dialog body\n init() {\n Hotkeys(this.dialog_body)\n this.watch_remote_forms()\n window.requestAnimationFrame(() => this.#focusInitialElement())\n }\n\n // Shoelace tab panels (link, page configure) only render a few frames after\n // the content loaded, so their fields can not take focus yet. Hence the retry.\n #focusInitialElement(attempts = 0) {\n const target =\n this.dialog_body.querySelector(\"[autofocus]\") ??\n this.dialog_body.querySelector(\"form [type='submit']\")\n target?.focus()\n if (document.activeElement === this.close_button && attempts < 20) {\n window.requestAnimationFrame(() =>\n this.#focusInitialElement(attempts + 1)\n )\n }\n }\n\n // Watches ajax requests inside of dialog body and replaces the content accordingly\n watch_remote_forms() {\n this.dialog_body\n .querySelectorAll('[data-remote=\"true\"]')\n .forEach((form) => {\n form.addEventListener(\"ajax:success\", (event) => {\n const xhr = event.detail[2]\n const content_type = xhr.getResponseHeader(\"Content-Type\")\n if (content_type.match(/javascript/)) {\n return\n } else {\n this.dialog_body.innerHTML = xhr.responseText\n this.init()\n }\n })\n\n form.addEventListener(\"ajax:error\", (event) => {\n const statusText = event.detail[1]\n const xhr = event.detail[2]\n this.show_error(xhr, statusText)\n })\n })\n }\n\n // Displays an error message\n show_error(xhr, statusText) {\n if (xhr.status === 422) {\n this.dialog_body.innerHTML = xhr.responseText\n this.init()\n return\n }\n\n const { error_body, error_header, error_type } = this.error_messages(\n xhr,\n statusText\n )\n\n this.dialog_body.innerHTML = `\n

    ${error_header}

    \n

    ${error_body}

    \n
    `\n }\n\n // Returns error message based on xhr status\n error_messages(xhr, statusText) {\n let error_body,\n error_header,\n error_type = \"warning\"\n\n switch (xhr.status) {\n case 0:\n error_header = \"The server does not respond.\"\n error_body = \"Please check server and try again.\"\n break\n case 403:\n error_header = \"You are not authorized!\"\n error_body = \"Please close this window.\"\n break\n default:\n error_type = \"error\"\n if (statusText) {\n error_header = statusText\n console.error(xhr.responseText)\n } else {\n error_header = `${xhr.statusText} (${xhr.status})`\n }\n error_body = \"Please check log and try again.\"\n }\n\n return { error_header, error_body, error_type }\n }\n\n // Binds close events on:\n // - Close button\n // - Overlay (if the Dialog is a modal)\n // - ESC Key (the dialog element's cancel event)\n bind_close_events() {\n this.close_button.addEventListener(\"click\", (e) => {\n e.preventDefault()\n this.close()\n })\n this.dialog_container.classList.add(\"closable\")\n // Use pointerdown, not click: a click whose mousedown and mouseup land on\n // different nodes is dispatched to their common ancestor — this element for\n // anything inside the dialog — closing it although the backdrop was never\n // hit, e.g. when selecting text and releasing outside.\n this.dialog_container.addEventListener(\"pointerdown\", (e) => {\n if (e.target === this.dialog_container) {\n this.close()\n }\n })\n this.dialog_container.addEventListener(\"cancel\", (e) => {\n e.preventDefault()\n this.close()\n })\n }\n\n // Builds the html structure of the Dialog\n build() {\n this.dialog_container = createHtmlElement(\n ''\n )\n this.dialog = createHtmlElement('
    ')\n this.dialog_body = createHtmlElement(\n '
    '\n )\n this.dialog_header = createHtmlElement(\n '
    '\n )\n this.dialog_title = createHtmlElement(\n '
    '\n )\n this.close_button = createHtmlElement(\n ''\n )\n this.dialog_title.textContent = this.options.title\n this.dialog_header.append(this.dialog_title)\n this.dialog_header.append(this.close_button)\n this.dialog.append(this.dialog_header)\n this.dialog.append(this.dialog_body)\n this.dialog_container.append(this.dialog)\n if (this.options.modal) {\n this.dialog.classList.add(\"modal\")\n }\n if (this.options.padding) {\n this.dialog_body.classList.add(\"padded\")\n }\n document.body.append(this.dialog_container)\n }\n\n // Sets the correct size of the dialog\n // It normalizes the given size, so that it never acceeds the window size.\n resize() {\n const { width, height } = this.getSize()\n\n this.dialog.style.width = `${width}px`\n this.dialog.style.minHeight = `${height}px`\n this.dialog.style.overflow = this.options.overflow\n\n if (this.options.overflow === \"hidden\") {\n this.dialog_body.style.height = `${height}px`\n this.dialog_body.style.overflow = \"auto\"\n } else {\n this.dialog_body.style.minHeight = `${height}px`\n this.dialog_body.style.overflow = \"visible\"\n }\n }\n\n getSize() {\n const padding = this.options.padding ? 16 : 0\n const doc_width = window.innerWidth\n const doc_height = window.innerHeight\n\n let width = this.width\n let height = this.height\n\n if (width >= doc_width) {\n width = doc_width - padding\n }\n\n if (height >= doc_height) {\n height = doc_height - padding - DEFAULTS.header_height\n }\n\n return { width, height }\n }\n}\n\n// Gets the last dialog instantiated, which is the current one.\nexport function currentDialog() {\n const { length } = currentDialogs\n if (length === 0) {\n return\n }\n return currentDialogs[length - 1]\n}\n\n// Utility function to close the current Dialog\n//\n// You can pass a callback function, that gets triggered after the Dialog gets closed.\n//\nexport function closeCurrentDialog(callback) {\n const dialog = currentDialog()\n if (dialog != null) {\n dialog.options.closed = callback\n return dialog.close()\n }\n}\n\n// Utility function to open a new Dialog\nexport function openDialog(url, options) {\n if (!url) {\n throw \"No url given! Please provide an url.\"\n }\n const dialog = new Dialog(url, options)\n dialog.open()\n}\n","import { createHtmlElement } from \"alchemy_admin/utils/dom_helpers\"\nimport { currentDialog } from \"alchemy_admin/dialog\"\nimport { translate } from \"alchemy_admin/i18n\"\n\nconst getDefaults = () => ({\n // The default size of the dialog\n size: \"300x100\",\n title: translate(\"Please confirm\"),\n ok_label: translate(\"Yes\"),\n cancel_label: translate(\"No\"),\n on_ok() {}\n})\n\nclass ConfirmDialog {\n constructor(message, options = {}) {\n this.message = message\n this.options = { ...getDefaults(), ...options }\n this.#build()\n this.#bindEvents()\n }\n\n open() {\n requestAnimationFrame(() => {\n this.dialog.show()\n })\n }\n\n #build() {\n const width = this.options.size.split(\"x\")[0]\n this.dialog = createHtmlElement(`\n \n ${this.message}\n \n \n \n `)\n // A native opened with showModal() sits in the top layer and makes\n // everything outside its subtree inert. Append the confirm into the open\n // dialog (if any) so it stays visible and interactable above it, instead of\n // rendering below and unclickable on the body.\n const container = currentDialog()?.dialog_container ?? document.body\n container.append(this.dialog)\n }\n\n #bindEvents() {\n this.cancelButton.addEventListener(\"click\", (evt) => {\n evt.preventDefault()\n this.options.on_cancel()\n this.dialog.hide()\n })\n this.okButton.addEventListener(\"click\", (evt) => {\n evt.preventDefault()\n this.options.on_ok()\n this.dialog.hide()\n })\n // Prevent the dialog from closing when the user clicks on the overlay\n this.dialog.addEventListener(\"sl-request-close\", (event) => {\n if (event.detail.source === \"overlay\") {\n this.options.on_cancel()\n event.preventDefault()\n }\n })\n // Remove the dialog from the DOM after it has been hidden\n this.dialog.addEventListener(\"sl-after-hide\", () => {\n this.dialog.remove()\n })\n }\n\n get cancelButton() {\n return this.dialog.querySelector(\"button[type=reset]\")\n }\n\n get okButton() {\n return this.dialog.querySelector(\"button[type=submit]\")\n }\n}\n\n/* Opens a confirm dialog\n *\n * @param {string} message - The message that will be displayed to the user\n * @param {Object} [options={}] - Configuration options for the dialog\n * @param {string} [options.title=\"Please confirm\"] - The title of the overlay window\n * @param {string} [options.cancel_label=\"No\"] - The label of the cancel button\n * @param {string} [options.ok_label=\"Yes\"] - The label of the ok button\n *\n * @returns {Promise} A promise that resolves to true when the OK button is clicked and\n * resolves to false when the cancel button is clicked. Works as confirm dialog replacement\n * for Turbo.confirm.\n */\nexport function openConfirmDialog(message, options = {}) {\n return new Promise((resolve) => {\n const dialog = new ConfirmDialog(message, {\n ...options,\n on_ok() {\n resolve(true)\n },\n on_cancel() {\n resolve(false)\n }\n })\n dialog.open()\n })\n}\n","/**\n * To show the \"Please wait\" overlay.\n * Pass false to hide it.\n * @param {boolean} show\n */\nexport default function pleaseWaitOverlay(show = true) {\n document.querySelector(\"alchemy-overlay\").show = !!show\n}\n","import { openConfirmDialog } from \"alchemy_admin/confirm_dialog\"\nimport { translate } from \"alchemy_admin/i18n\"\nimport pleaseWaitOverlay from \"alchemy_admin/please_wait_overlay\"\n\nfunction checkPageDirtyness(element) {\n let callback = () => {}\n\n if (element.matches(\"form\")) {\n callback = function () {\n const form = document.createElement(\"form\")\n form.action = element.action\n form.method = \"POST\"\n form.style.display = \"none\"\n element.querySelectorAll(\"input\").forEach((input) => form.append(input))\n document.body.append(form)\n\n pleaseWaitOverlay()\n form.requestSubmit()\n }\n } else if (element.matches(\"a\")) {\n callback = () => Turbo.visit(element.pathname)\n }\n\n const isPageDirty =\n document.querySelectorAll(\"alchemy-element-editor.dirty\").length > 0\n\n if (isPageDirty) {\n openConfirmDialog(translate(\"page_dirty_notice\"), {\n title: translate(\"warning\"),\n ok_label: translate(\"ok\"),\n cancel_label: translate(\"cancel\")\n }).then((proceed) => {\n if (proceed) {\n window.onbeforeunload = void 0\n callback()\n }\n })\n return false\n }\n return true\n}\n\nfunction PageLeaveObserver() {\n document.querySelectorAll(\"#main_navi a\").forEach((element) => {\n element.addEventListener(\"click\", (event) => {\n if (!checkPageDirtyness(event.currentTarget)) {\n event.preventDefault()\n }\n })\n })\n}\n\nexport default {\n checkPageDirtyness,\n PageLeaveObserver\n}\n","// Creates a fixed element tab.\nexport function createTab(element_id, label) {\n const fixed_elements = document.getElementById(\"fixed-elements\")\n const panel_name = `fixed-element-${element_id}`\n\n const tab = `${label}`\n const panel = ``\n\n fixed_elements.innerHTML += tab + panel\n\n window.requestAnimationFrame(function () {\n fixed_elements.show(panel_name)\n })\n}\n\nexport function removeTab(element_id) {\n const fixed_elements = document.getElementById(\"fixed-elements\")\n const panel_name = `fixed-element-${element_id}`\n\n fixed_elements.querySelector(`sl-tab[panel=\"${panel_name}\"]`).remove()\n fixed_elements.querySelector(`sl-tab-panel[name=\"${panel_name}\"]`).remove()\n\n fixed_elements.show(\"main-content-elements\")\n}\n","import { createHtmlElement } from \"alchemy_admin/utils/dom_helpers\"\n\nfunction build(message, flashType) {\n const flashNotices = document.getElementById(\"flash_notices\")\n const flashMessage = createHtmlElement(`\n \n ${message}\n \n `)\n flashNotices.append(flashMessage)\n}\n\nexport function growl(message, style = \"notice\") {\n build(message, style)\n}\n","import Hotkeys from \"alchemy_admin/hotkeys\"\nimport pleaseWaitOverlay from \"alchemy_admin/please_wait_overlay\"\nimport { openDialog } from \"alchemy_admin/dialog\"\n\n// Opens the help dialog when the user presses the \"?\" key outside of a field.\nfunction showHelp(evt) {\n if (\n !evt.target.matches(\"input, textarea\") &&\n String.fromCharCode(evt.which) === \"?\"\n ) {\n openDialog(\"/admin/help\", {\n title: Alchemy.t(\"help\"),\n size: \"400x492\"\n })\n return false\n } else {\n return true\n }\n}\n\nexport default function Initializer() {\n // We obviously have javascript enabled.\n document.documentElement.classList.remove(\"no-js\")\n\n // Initialize hotkeys.\n Hotkeys()\n\n // (Re)bind the help dialog hotkey.\n document.removeEventListener(\"keypress\", showHelp)\n document.addEventListener(\"keypress\", showHelp)\n\n // Add observer for please wait overlay.\n document.querySelectorAll(\".please_wait\").forEach((element) => {\n element.addEventListener(\"click\", pleaseWaitOverlay)\n })\n\n // Hack for enabling tab focus for 's styled as button.\n document.querySelectorAll(\"a.button\").forEach((button) => {\n button.setAttribute(\"tabindex\", 0)\n })\n\n // Override the filter of keymaster.js so we can blur the fields on esc key.\n key.filter = function (event) {\n let tagName = (event.target || event.srcElement).tagName\n return (\n key.isPressed(\"esc\") ||\n !(tagName === \"INPUT\" || tagName === \"SELECT\" || tagName === \"TEXTAREA\")\n )\n }\n}\n","import { translate } from \"alchemy_admin/i18n\"\nimport { Dialog } from \"alchemy_admin/dialog\"\n\n// Matches a URL fragment (#anchor) at the end of a string.\n// Covers RFC 3986 unreserved characters (ALPHA, DIGIT, \"-\", \".\", \"_\", \"~\")\n// which are the characters valid in URL fragments and common in DOM element IDs.\nconst ANCHOR_REGEX = /#[\\w.~-]+$/\n\n// Represents the link Dialog that appears, if a user clicks the link buttons\n// in TinyMCE or on an Ingredient that has links enabled (e.g. Picture)\n//\nexport class LinkDialog extends Dialog {\n #onCreateLink\n\n constructor(link) {\n const url = new URL(Alchemy.routes.link_admin_pages_path, window.location)\n const parameterMapping = {\n url: link.url,\n selected_tab: link.type,\n link_title: link.title,\n link_target: link.target\n }\n\n // searchParams.set would also add undefined values\n Object.keys(parameterMapping).forEach((key) => {\n if (parameterMapping[key]) {\n url.searchParams.set(key, parameterMapping[key])\n }\n })\n\n super(url.href, {\n size: \"600x320\",\n title: translate(\"Link\")\n })\n }\n\n /**\n * Called from Dialog class after the url was loaded\n */\n replace(data) {\n // let Dialog class handle the content replacement\n super.replace(data)\n this.#attachEvents()\n }\n\n /**\n * make the open method a promise\n * maybe in a future version the whole Dialog will respond with a promise result if the dialog is closing\n * @returns {Promise}\n */\n open() {\n super.open()\n return new Promise((resolve) => (this.#onCreateLink = resolve))\n }\n\n /**\n * Attaches click events to forms in the link dialog.\n */\n #attachEvents() {\n // enable the dom selection in internal link tab\n const internalForm = document.querySelector(\n '[data-link-form-type=\"internal\"]'\n )\n const attachmentSelect = document.querySelector(\n '[data-link-form-type=\"file\"] alchemy-attachment-select'\n )\n\n internalForm.addEventListener(\"Alchemy.RemoteSelect.Change\", (e) => {\n this.#updatePage(e.detail.added)\n })\n\n attachmentSelect.addEventListener(\"Alchemy.RemoteSelect.Change\", (e) => {\n const attachment = e.detail.added\n document.getElementById(\"file_link\").value = attachment\n ? attachment.url\n : \"\"\n })\n\n document.querySelectorAll(\"[data-link-form-type]\").forEach((form) => {\n form.addEventListener(\"submit\", (e) => {\n e.preventDefault()\n this.#submitForm(e.target.dataset.linkFormType)\n })\n })\n }\n\n /**\n * update page select and set anchor select\n * @param page\n */\n #updatePage(page = null) {\n const internalLink = document.getElementById(\"internal_link\")\n const domIdSelect = document.querySelector(\n '[data-link-form-type=\"internal\"] alchemy-dom-id-api-select'\n )\n\n internalLink.value = page ? page.url_path : \"\"\n domIdSelect.page = page ? page.id : undefined\n }\n\n /**\n * submit the form itself\n * @param linkType\n */\n #submitForm(linkType) {\n const elementAnchor = document.getElementById(\"element_anchor\")\n let url = document.getElementById(`${linkType}_link`).value\n\n if (linkType === \"internal\" && elementAnchor.value !== \"\") {\n // remove possible fragments on the url and attach the fragment (which contains the #)\n url = url.replace(ANCHOR_REGEX, \"\") + elementAnchor.value\n } else if (linkType === \"external\" && !url.match(Alchemy.link_url_regexp)) {\n // show validation error and prevent link creation\n this.#showValidationError()\n return\n }\n\n // Create the link\n this.#onCreateLink({\n url: url.trim(),\n title: document.getElementById(`${linkType}_link_title`).value,\n target: document.getElementById(`${linkType}_link_target`)?.value,\n type: linkType\n })\n this.close()\n }\n\n /**\n * Shows validation errors\n */\n #showValidationError() {\n const errors = document.getElementById(\"errors\")\n errors.querySelector(\"ul\").innerHTML =\n `
  • ${Alchemy.t(\"url_validation_failed\")}
  • `\n errors.style.display = \"block\"\n }\n}\n","import { growl } from \"alchemy_admin/growler\"\nimport { translate } from \"alchemy_admin/i18n\"\n\nclass PreviewWindow extends HTMLIFrameElement {\n #afterLoad\n #reloadIcon\n #loadTimeout\n\n handleEvent(evt) {\n if (evt.type === \"load\") {\n this.#clearLoadTimeout()\n this.#stopSpinner()\n this.#afterLoad?.call(this, evt)\n }\n }\n\n #onPreviewReady = (event) => {\n if (event.data.message === \"Alchemy.previewReady\") {\n this.#clearLoadTimeout()\n this.#stopSpinner()\n this.#afterLoad?.call(this, event)\n }\n }\n\n connectedCallback() {\n let url = this.url\n\n this.addEventListener(\"load\", this)\n this.#attachEvents()\n window.addEventListener(\"message\", this.#onPreviewReady)\n\n if (window.localStorage.getItem(\"alchemy-preview-url\")) {\n url = window.localStorage.getItem(\"alchemy-preview-url\")\n this.previewUrlSelect.value = url\n }\n\n this.refresh(url)\n }\n\n disconnectedCallback() {\n this.removeEventListener(\"load\", this)\n key.unbind(\"alt+r\")\n window.removeEventListener(\"message\", this.#onPreviewReady)\n }\n\n postMessage(data) {\n this.contentWindow.postMessage(data, \"*\")\n }\n\n resize(width) {\n this.style.width = `${width}px`\n }\n\n refresh(url) {\n this.#startSpinner()\n\n if (url) {\n this.src = url\n } else {\n this.src = this.url\n }\n\n // Set 5s timeout as fallback - if iframe doesn't load, stop spinner anyway\n this.#clearLoadTimeout()\n this.#loadTimeout = setTimeout(() => {\n this.#stopSpinner()\n growl(translate(\"Preview failed to load\"), \"warning\")\n }, 5000)\n\n return new Promise((resolve) => {\n this.#afterLoad = resolve\n })\n }\n\n set isDragged(dragged) {\n this.style.transitionProperty = dragged ? \"none\" : null\n this.style.pointerEvents = dragged ? \"none\" : null\n }\n\n #attachEvents() {\n this.reloadButton?.addEventListener(\"click\", (evt) => {\n evt.preventDefault()\n this.refresh()\n })\n\n key(\"alt+r\", () => this.refresh())\n\n this.sizeSelect.addEventListener(\"change\", (evt) => {\n const select = evt.target\n const width = select.value\n\n if (width === \"\") {\n this.style.width = null\n } else {\n this.resize(width)\n }\n })\n\n this.previewUrlSelect?.addEventListener(\"change\", (evt) => {\n const url = evt.target.value\n window.localStorage.setItem(\"alchemy-preview-url\", url)\n this.refresh(url)\n })\n }\n\n #startSpinner() {\n // Only save the reload icon if we're not already showing a spinner\n if (!this.reloadButton.innerHTML.includes(\"alchemy-spinner\")) {\n this.#reloadIcon = this.reloadButton.innerHTML\n }\n this.reloadButton.innerHTML = ``\n }\n\n #stopSpinner() {\n this.reloadButton.innerHTML = this.#reloadIcon\n }\n\n #clearLoadTimeout() {\n if (this.#loadTimeout) {\n clearTimeout(this.#loadTimeout)\n this.#loadTimeout = null\n }\n }\n\n get url() {\n return this.getAttribute(\"url\")\n }\n\n get sizeSelect() {\n return document.querySelector(\"select#preview_size\")\n }\n\n get previewUrlSelect() {\n return document.querySelector(\"select#preview_url\")\n }\n\n get reloadButton() {\n return document.querySelector(\"#reload_preview_button\")\n }\n}\n\ncustomElements.define(\"alchemy-preview-window\", PreviewWindow, {\n extends: \"iframe\"\n})\n\nexport function reloadPreview() {\n const previewWindow = document.getElementById(\"alchemy_preview_window\")\n previewWindow.refresh()\n}\n","import { Turbo } from \"@hotwired/turbo-rails\"\nimport { closeCurrentDialog } from \"alchemy_admin/dialog\"\n\n// The editors observe their form field for mutations, so it must not be replaced.\n\nTurbo.StreamActions.assign_picture = function () {\n const [formField] = this.targetElements\n\n if (!formField) return\n\n formField.value = this.getAttribute(\"picture-id\")\n formField.setAttribute(\n \"data-image-file-width\",\n this.getAttribute(\"image-file-width\")\n )\n formField.setAttribute(\n \"data-image-file-height\",\n this.getAttribute(\"image-file-height\")\n )\n\n closeCurrentDialog(() => {\n formField.closest(\"alchemy-element-editor\")?.setDirty()\n })\n}\n\nTurbo.StreamActions.assign_attachment = function () {\n const [formField] = this.targetElements\n\n if (!formField) return\n\n const fileEditor = formField.parentElement\n\n formField.value = this.getAttribute(\"attachment-id\")\n fileEditor.querySelector(\":scope > .file_name\").textContent =\n this.getAttribute(\"attachment-name\")\n fileEditor\n .querySelector(\":scope > .file_icon\")\n .replaceChildren(this.templateContent)\n fileEditor\n .querySelector(\":scope > .remove_file_link\")\n .classList.remove(\"hidden\")\n\n closeCurrentDialog(() => {\n formField.closest(\"alchemy-element-editor\")?.setDirty(formField)\n })\n}\n","export default class IngredientAnchorLink {\n static updateIcon(ingredientId, active = false) {\n const ingredientEditor = document.querySelector(\n `[data-ingredient-id=\"${ingredientId}\"]`\n )\n if (ingredientEditor) {\n const icon = ingredientEditor.querySelector(\n \".edit-ingredient-anchor-link alchemy-icon\"\n )\n icon.setAttribute(\"icon-style\", active ? \"fill\" : \"line\")\n }\n }\n}\n","import { reloadPreview } from \"alchemy_admin/components/preview_window\"\nimport { removeTab } from \"alchemy_admin/fixed_elements\"\nimport { closeCurrentDialog } from \"alchemy_admin/dialog\"\nimport IngredientAnchorLink from \"alchemy_admin/ingredient_anchor_link\"\nimport pleaseWaitOverlay from \"alchemy_admin/please_wait_overlay\"\n\nclass Action extends HTMLElement {\n constructor() {\n super()\n\n // map action names with Javascript functions\n this.actions = {\n // add a intermediate closeCurrentDialog - action\n // this will be gone, if all dialogs are working with a promise and\n // we don't have to implicitly close the dialog\n closeCurrentDialog,\n reloadPreview,\n removeFixedElement: removeTab,\n updateAnchorIcon: IngredientAnchorLink.updateIcon,\n hidePleaseWaitOverlay() {\n pleaseWaitOverlay(false)\n }\n }\n }\n\n connectedCallback() {\n const func = this.actions[this.name]\n\n if (func) {\n func(...this.params)\n } else {\n console.error(`Unknown Alchemy action: ${this.name}`)\n }\n\n this.remove()\n }\n\n get name() {\n return this.getAttribute(\"name\")\n }\n\n get params() {\n if (this.hasAttribute(\"params\")) {\n return JSON.parse(this.getAttribute(\"params\"))\n }\n return []\n }\n}\n\ncustomElements.define(\"alchemy-action\", Action)\n","/**\n * MicroEvent - to make any js object an event emitter\n *\n * - pure javascript - server compatible, browser compatible\n * - dont rely on the browser doms\n * - super simple - you get it immediatly, no mistery, no magic involved\n *\n * @author Jerome Etienne (https://github.com/jeromeetienne)\n */\n/**\n * Execute callback for each event in space separated list of event names\n *\n */\nfunction forEvents(events, callback) {\n events.split(/\\s+/).forEach((event) => {\n callback(event);\n });\n}\nexport default class MicroEvent {\n constructor() {\n this._events = {};\n }\n on(events, fct) {\n forEvents(events, (event) => {\n const event_array = this._events[event] || [];\n event_array.push(fct);\n this._events[event] = event_array;\n });\n }\n off(events, fct) {\n var n = arguments.length;\n if (n === 0) {\n this._events = {};\n return;\n }\n forEvents(events, (event) => {\n if (n === 1) {\n delete this._events[event];\n return;\n }\n const event_array = this._events[event];\n if (event_array === undefined)\n return;\n event_array.splice(event_array.indexOf(fct), 1);\n this._events[event] = event_array;\n });\n }\n trigger(events, ...args) {\n var self = this;\n forEvents(events, (event) => {\n const event_array = self._events[event];\n if (event_array === undefined)\n return;\n event_array.forEach(fct => {\n fct.apply(self, args);\n });\n });\n }\n}\n;\n//# sourceMappingURL=microevent.js.map","/**\n * Convert array of strings to a regular expression\n *\tex ['ab','a'] => (?:ab|a)\n * \tex ['a','b'] => [ab]\n */\nexport const arrayToPattern = (chars) => {\n chars = chars.filter(Boolean);\n if (chars.length < 2) {\n return chars[0] || '';\n }\n return (maxValueLength(chars) == 1) ? '[' + chars.join('') + ']' : '(?:' + chars.join('|') + ')';\n};\nexport const sequencePattern = (array) => {\n if (!hasDuplicates(array)) {\n return array.join('');\n }\n let pattern = '';\n let prev_char_count = 0;\n const prev_pattern = () => {\n if (prev_char_count > 1) {\n pattern += '{' + prev_char_count + '}';\n }\n };\n array.forEach((char, i) => {\n if (char === array[i - 1]) {\n prev_char_count++;\n return;\n }\n prev_pattern();\n pattern += char;\n prev_char_count = 1;\n });\n prev_pattern();\n return pattern;\n};\n/**\n * Convert array of strings to a regular expression\n *\tex ['ab','a'] => (?:ab|a)\n * \tex ['a','b'] => [ab]\n */\nexport const setToPattern = (chars) => {\n let array = Array.from(chars);\n return arrayToPattern(array);\n};\n/**\n * https://stackoverflow.com/questions/7376598/in-javascript-how-do-i-check-if-an-array-has-duplicate-values\n */\nexport const hasDuplicates = (array) => {\n return (new Set(array)).size !== array.length;\n};\n/**\n * https://stackoverflow.com/questions/63006601/why-does-u-throw-an-invalid-escape-error\n */\nexport const escape_regex = (str) => {\n return (str + '').replace(/([\\$\\(\\)\\*\\+\\.\\?\\[\\]\\^\\{\\|\\}\\\\])/gu, '\\\\$1');\n};\n/**\n * Return the max length of array values\n */\nexport const maxValueLength = (array) => {\n return array.reduce((longest, value) => Math.max(longest, unicodeLength(value)), 0);\n};\nexport const unicodeLength = (str) => {\n return Array.from(str).length;\n};\n//# sourceMappingURL=regex.js.map","/**\n * Get all possible combinations of substrings that add up to the given string\n * https://stackoverflow.com/questions/30169587/find-all-the-combination-of-substrings-that-add-up-to-the-given-string\n */\nexport const allSubstrings = (input) => {\n if (input.length === 1)\n return [[input]];\n let result = [];\n const start = input.substring(1);\n const suba = allSubstrings(start);\n suba.forEach(function (subresult) {\n let tmp = subresult.slice(0);\n tmp[0] = input.charAt(0) + tmp[0];\n result.push(tmp);\n tmp = subresult.slice(0);\n tmp.unshift(input.charAt(0));\n result.push(tmp);\n });\n return result;\n};\n//# sourceMappingURL=strings.js.map","import { setToPattern, arrayToPattern, escape_regex, sequencePattern } from \"./regex.js\";\nimport { allSubstrings } from \"./strings.js\";\nexport const code_points = [[0, 65535]];\nconst accent_pat = '[\\u0300-\\u036F\\u{b7}\\u{2be}\\u{2bc}]';\nexport let unicode_map;\nlet multi_char_reg;\nconst max_char_length = 3;\nconst latin_convert = {};\nconst latin_condensed = {\n '/': '⁄∕',\n '0': '߀',\n \"a\": \"ⱥɐɑ\",\n \"aa\": \"ꜳ\",\n \"ae\": \"æǽǣ\",\n \"ao\": \"ꜵ\",\n \"au\": \"ꜷ\",\n \"av\": \"ꜹꜻ\",\n \"ay\": \"ꜽ\",\n \"b\": \"ƀɓƃ\",\n \"c\": \"ꜿƈȼↄ\",\n \"d\": \"đɗɖᴅƌꮷԁɦ\",\n \"e\": \"ɛǝᴇɇ\",\n \"f\": \"ꝼƒ\",\n \"g\": \"ǥɠꞡᵹꝿɢ\",\n \"h\": \"ħⱨⱶɥ\",\n \"i\": \"ɨı\",\n \"j\": \"ɉȷ\",\n \"k\": \"ƙⱪꝁꝃꝅꞣ\",\n \"l\": \"łƚɫⱡꝉꝇꞁɭ\",\n \"m\": \"ɱɯϻ\",\n \"n\": \"ꞥƞɲꞑᴎлԉ\",\n \"o\": \"øǿɔɵꝋꝍᴑ\",\n \"oe\": \"œ\",\n \"oi\": \"ƣ\",\n \"oo\": \"ꝏ\",\n \"ou\": \"ȣ\",\n \"p\": \"ƥᵽꝑꝓꝕρ\",\n \"q\": \"ꝗꝙɋ\",\n \"r\": \"ɍɽꝛꞧꞃ\",\n \"s\": \"ßȿꞩꞅʂ\",\n \"t\": \"ŧƭʈⱦꞇ\",\n \"th\": \"þ\",\n \"tz\": \"ꜩ\",\n \"u\": \"ʉ\",\n \"v\": \"ʋꝟʌ\",\n \"vy\": \"ꝡ\",\n \"w\": \"ⱳ\",\n \"y\": \"ƴɏỿ\",\n \"z\": \"ƶȥɀⱬꝣ\",\n \"hv\": \"ƕ\"\n};\nfor (let latin in latin_condensed) {\n let unicode = latin_condensed[latin] || '';\n for (let i = 0; i < unicode.length; i++) {\n let char = unicode.substring(i, i + 1);\n latin_convert[char] = latin;\n }\n}\nconst convert_pat = new RegExp(Object.keys(latin_convert).join('|') + '|' + accent_pat, 'gu');\n/**\n * Initialize the unicode_map from the give code point ranges\n */\nexport const initialize = (_code_points) => {\n if (unicode_map !== undefined)\n return;\n unicode_map = generateMap(_code_points || code_points);\n};\n/**\n * Helper method for normalize a string\n * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/normalize\n */\nexport const normalize = (str, form = 'NFKD') => str.normalize(form);\n/**\n * Remove accents without reordering string\n * calling str.normalize('NFKD') on \\u{594}\\u{595}\\u{596} becomes \\u{596}\\u{594}\\u{595}\n * via https://github.com/krisk/Fuse/issues/133#issuecomment-318692703\n */\nexport const asciifold = (str) => {\n return Array.from(str).reduce(\n /**\n * @param {string} result\n * @param {string} char\n */\n (result, char) => {\n return result + _asciifold(char);\n }, '');\n};\nexport const _asciifold = (str) => {\n str = normalize(str)\n .toLowerCase()\n .replace(convert_pat, (/** @type {string} */ char) => {\n return latin_convert[char] || '';\n });\n //return str;\n return normalize(str, 'NFC');\n};\n/**\n * Generate a list of unicode variants from the list of code points\n */\nexport function* generator(code_points) {\n for (const [code_point_min, code_point_max] of code_points) {\n for (let i = code_point_min; i <= code_point_max; i++) {\n let composed = String.fromCharCode(i);\n let folded = asciifold(composed);\n if (folded == composed.toLowerCase()) {\n continue;\n }\n // skip when folded is a string longer than 3 characters long\n // bc the resulting regex patterns will be long\n // eg:\n // folded صلى الله عليه وسلم length 18 code point 65018\n // folded جل جلاله length 8 code point 65019\n if (folded.length > max_char_length) {\n continue;\n }\n if (folded.length == 0) {\n continue;\n }\n yield { folded: folded, composed: composed, code_point: i };\n }\n }\n}\n/**\n * Generate a unicode map from the list of code points\n */\nexport const generateSets = (code_points) => {\n const unicode_sets = {};\n const addMatching = (folded, to_add) => {\n /** @type {Set} */\n const folded_set = unicode_sets[folded] || new Set();\n const patt = new RegExp('^' + setToPattern(folded_set) + '$', 'iu');\n if (to_add.match(patt)) {\n return;\n }\n folded_set.add(escape_regex(to_add));\n unicode_sets[folded] = folded_set;\n };\n for (let value of generator(code_points)) {\n addMatching(value.folded, value.folded);\n addMatching(value.folded, value.composed);\n }\n return unicode_sets;\n};\n/**\n * Generate a unicode map from the list of code points\n * ae => (?:(?:ae|Æ|Ǽ|Ǣ)|(?:A|Ⓐ|A...)(?:E|ɛ|Ⓔ...))\n */\nexport const generateMap = (code_points) => {\n const unicode_sets = generateSets(code_points);\n const unicode_map = {};\n let multi_char = [];\n for (let folded in unicode_sets) {\n let set = unicode_sets[folded];\n if (set) {\n unicode_map[folded] = setToPattern(set);\n }\n if (folded.length > 1) {\n multi_char.push(escape_regex(folded));\n }\n }\n multi_char.sort((a, b) => b.length - a.length);\n const multi_char_patt = arrayToPattern(multi_char);\n multi_char_reg = new RegExp('^' + multi_char_patt, 'u');\n return unicode_map;\n};\n/**\n * Map each element of an array from its folded value to all possible unicode matches\n */\nexport const mapSequence = (strings, min_replacement = 1) => {\n let chars_replaced = 0;\n strings = strings.map((str) => {\n if (unicode_map[str]) {\n chars_replaced += str.length;\n }\n return unicode_map[str] || str;\n });\n if (chars_replaced >= min_replacement) {\n return sequencePattern(strings);\n }\n return '';\n};\n/**\n * Convert a short string and split it into all possible patterns\n * Keep a pattern only if min_replacement is met\n *\n * 'abc'\n * \t\t=> [['abc'],['ab','c'],['a','bc'],['a','b','c']]\n *\t\t=> ['abc-pattern','ab-c-pattern'...]\n */\nexport const substringsToPattern = (str, min_replacement = 1) => {\n min_replacement = Math.max(min_replacement, str.length - 1);\n return arrayToPattern(allSubstrings(str).map((sub_pat) => {\n return mapSequence(sub_pat, min_replacement);\n }));\n};\n/**\n * Convert an array of sequences into a pattern\n * [{start:0,end:3,length:3,substr:'iii'}...] => (?:iii...)\n */\nconst sequencesToPattern = (sequences, all = true) => {\n let min_replacement = sequences.length > 1 ? 1 : 0;\n return arrayToPattern(sequences.map((sequence) => {\n let seq = [];\n const len = all ? sequence.length() : sequence.length() - 1;\n for (let j = 0; j < len; j++) {\n seq.push(substringsToPattern(sequence.substrs[j] || '', min_replacement));\n }\n return sequencePattern(seq);\n }));\n};\n/**\n * Return true if the sequence is already in the sequences\n */\nconst inSequences = (needle_seq, sequences) => {\n for (const seq of sequences) {\n if (seq.start != needle_seq.start || seq.end != needle_seq.end) {\n continue;\n }\n if (seq.substrs.join('') !== needle_seq.substrs.join('')) {\n continue;\n }\n let needle_parts = needle_seq.parts;\n const filter = (part) => {\n for (const needle_part of needle_parts) {\n if (needle_part.start === part.start && needle_part.substr === part.substr) {\n return false;\n }\n if (part.length == 1 || needle_part.length == 1) {\n continue;\n }\n // check for overlapping parts\n // a = ['::=','==']\n // b = ['::','===']\n // a = ['r','sm']\n // b = ['rs','m']\n if (part.start < needle_part.start && part.end > needle_part.start) {\n return true;\n }\n if (needle_part.start < part.start && needle_part.end > part.start) {\n return true;\n }\n }\n return false;\n };\n let filtered = seq.parts.filter(filter);\n if (filtered.length > 0) {\n continue;\n }\n return true;\n }\n return false;\n};\nclass Sequence {\n parts;\n substrs;\n start;\n end;\n constructor() {\n this.parts = [];\n this.substrs = [];\n this.start = 0;\n this.end = 0;\n }\n add(part) {\n if (part) {\n this.parts.push(part);\n this.substrs.push(part.substr);\n this.start = Math.min(part.start, this.start);\n this.end = Math.max(part.end, this.end);\n }\n }\n last() {\n return this.parts[this.parts.length - 1];\n }\n length() {\n return this.parts.length;\n }\n clone(position, last_piece) {\n let clone = new Sequence();\n let parts = JSON.parse(JSON.stringify(this.parts));\n let last_part = parts.pop();\n for (const part of parts) {\n clone.add(part);\n }\n let last_substr = last_piece.substr.substring(0, position - last_part.start);\n let clone_last_len = last_substr.length;\n clone.add({ start: last_part.start, end: last_part.start + clone_last_len, length: clone_last_len, substr: last_substr });\n return clone;\n }\n}\n/**\n * Expand a regular expression pattern to include unicode variants\n * \teg /a/ becomes /aⓐaẚàáâầấẫẩãāăằắẵẳȧǡäǟảåǻǎȁȃạậặḁąⱥɐɑAⒶAÀÁÂẦẤẪẨÃĀĂẰẮẴẲȦǠÄǞẢÅǺǍȀȂẠẬẶḀĄȺⱯ/\n *\n * Issue:\n * ﺊﺋ [ 'ﺊ = \\\\u{fe8a}', 'ﺋ = \\\\u{fe8b}' ]\n *\tbecomes:\tئئ [ 'ي = \\\\u{64a}', 'ٔ = \\\\u{654}', 'ي = \\\\u{64a}', 'ٔ = \\\\u{654}' ]\n *\n *\tİIJ = IIJ = ⅡJ\n *\n * \t1/2/4\n */\nexport const getPattern = (str) => {\n initialize();\n str = asciifold(str);\n let pattern = '';\n let sequences = [new Sequence()];\n for (let i = 0; i < str.length; i++) {\n let substr = str.substring(i);\n let match = substr.match(multi_char_reg);\n const char = str.substring(i, i + 1);\n const match_str = match ? match[0] : null;\n // loop through sequences\n // add either the char or multi_match\n let overlapping = [];\n let added_types = new Set();\n for (const sequence of sequences) {\n const last_piece = sequence.last();\n if (!last_piece || last_piece.length == 1 || last_piece.end <= i) {\n // if we have a multi match\n if (match_str) {\n const len = match_str.length;\n sequence.add({ start: i, end: i + len, length: len, substr: match_str });\n added_types.add('1');\n }\n else {\n sequence.add({ start: i, end: i + 1, length: 1, substr: char });\n added_types.add('2');\n }\n }\n else if (match_str) {\n let clone = sequence.clone(i, last_piece);\n const len = match_str.length;\n clone.add({ start: i, end: i + len, length: len, substr: match_str });\n overlapping.push(clone);\n }\n else {\n // don't add char\n // adding would create invalid patterns: 234 => [2,34,4]\n added_types.add('3');\n }\n }\n // if we have overlapping\n if (overlapping.length > 0) {\n // ['ii','iii'] before ['i','i','iii']\n overlapping = overlapping.sort((a, b) => {\n return a.length() - b.length();\n });\n for (let clone of overlapping) {\n // don't add if we already have an equivalent sequence\n if (inSequences(clone, sequences)) {\n continue;\n }\n sequences.push(clone);\n }\n continue;\n }\n // if we haven't done anything unique\n // clean up the patterns\n // helps keep patterns smaller\n // if str = 'r₨㎧aarss', pattern will be 446 instead of 655\n if (i > 0 && added_types.size == 1 && !added_types.has('3')) {\n pattern += sequencesToPattern(sequences, false);\n let new_seq = new Sequence();\n const old_seq = sequences[0];\n if (old_seq) {\n new_seq.add(old_seq.last());\n }\n sequences = [new_seq];\n }\n }\n pattern += sequencesToPattern(sequences, true);\n return pattern;\n};\nexport { escape_regex };\n//# sourceMappingURL=index.js.map","import { asciifold } from '@orchidjs/unicode-variants';\n/**\n * A property getter resolving dot-notation\n * @param {Object} obj The root object to fetch property on\n * @param {String} name The optionally dotted property name to fetch\n * @return {Object} The resolved property value\n */\nexport const getAttr = (obj, name) => {\n if (!obj)\n return;\n return obj[name];\n};\n/**\n * A property getter resolving dot-notation\n * @param {Object} obj The root object to fetch property on\n * @param {String} name The optionally dotted property name to fetch\n * @return {Object} The resolved property value\n */\nexport const getAttrNesting = (obj, name) => {\n if (!obj)\n return;\n var part, names = name.split(\".\");\n while ((part = names.shift()) && (obj = obj[part]))\n ;\n return obj;\n};\n/**\n * Calculates how close of a match the\n * given value is against a search token.\n *\n */\nexport const scoreValue = (value, token, weight) => {\n var score, pos;\n if (!value)\n return 0;\n value = value + '';\n if (token.regex == null)\n return 0;\n pos = value.search(token.regex);\n if (pos === -1)\n return 0;\n score = token.string.length / value.length;\n if (pos === 0)\n score += 0.5;\n return score * weight;\n};\n/**\n * Cast object property to an array if it exists and has a value\n *\n */\nexport const propToArray = (obj, key) => {\n var value = obj[key];\n if (typeof value == 'function')\n return value;\n if (value && !Array.isArray(value)) {\n obj[key] = [value];\n }\n};\n/**\n * Iterates over arrays and hashes.\n *\n * ```\n * iterate(this.items, function(item, id) {\n * // invoked for each item\n * });\n * ```\n *\n */\nexport const iterate = (object, callback) => {\n if (Array.isArray(object)) {\n object.forEach(callback);\n }\n else {\n for (var key in object) {\n if (object.hasOwnProperty(key)) {\n callback(object[key], key);\n }\n }\n }\n};\nexport const cmp = (a, b) => {\n if (typeof a === 'number' && typeof b === 'number') {\n return a > b ? 1 : (a < b ? -1 : 0);\n }\n a = asciifold(a + '').toLowerCase();\n b = asciifold(b + '').toLowerCase();\n if (a > b)\n return 1;\n if (b > a)\n return -1;\n return 0;\n};\n//# sourceMappingURL=utils.js.map","/**\n * sifter.js\n * Copyright (c) 2013–2020 Brian Reavis & contributors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\"); you may not use this\n * file except in compliance with the License. You may obtain a copy of the License at:\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software distributed under\n * the License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF\n * ANY KIND, either express or implied. See the License for the specific language\n * governing permissions and limitations under the License.\n *\n * @author Brian Reavis \n */\nimport { scoreValue, getAttr, getAttrNesting, propToArray, iterate, cmp } from \"./utils.js\";\nimport { getPattern, escape_regex } from '@orchidjs/unicode-variants';\nclass Sifter {\n items; // []|{};\n settings;\n /**\n * Textually searches arrays and hashes of objects\n * by property (or multiple properties). Designed\n * specifically for autocomplete.\n *\n */\n constructor(items, settings) {\n this.items = items;\n this.settings = settings || { diacritics: true };\n }\n ;\n /**\n * Splits a search string into an array of individual\n * regexps to be used to match results.\n *\n */\n tokenize(query, respect_word_boundaries, weights) {\n if (!query || !query.length)\n return [];\n const tokens = [];\n const words = query.split(/\\s+/);\n var field_regex;\n if (weights) {\n field_regex = new RegExp('^(' + Object.keys(weights).map(escape_regex).join('|') + ')\\:(.*)$');\n }\n words.forEach((word) => {\n let field_match;\n let field = null;\n let regex = null;\n // look for \"field:query\" tokens\n if (field_regex && (field_match = word.match(field_regex))) {\n field = field_match[1];\n word = field_match[2];\n }\n if (word.length > 0) {\n if (this.settings.diacritics) {\n regex = getPattern(word) || null;\n }\n else {\n regex = escape_regex(word);\n }\n if (regex && respect_word_boundaries)\n regex = \"\\\\b\" + regex;\n }\n tokens.push({\n string: word,\n regex: regex ? new RegExp(regex, 'iu') : null,\n field: field,\n });\n });\n return tokens;\n }\n ;\n /**\n * Returns a function to be used to score individual results.\n *\n * Good matches will have a higher score than poor matches.\n * If an item is not a match, 0 will be returned by the function.\n *\n * @returns {T.ScoreFn}\n */\n getScoreFunction(query, options) {\n var search = this.prepareSearch(query, options);\n return this._getScoreFunction(search);\n }\n /**\n * @returns {T.ScoreFn}\n *\n */\n _getScoreFunction(search) {\n const tokens = search.tokens, token_count = tokens.length;\n if (!token_count) {\n return function () { return 0; };\n }\n const fields = search.options.fields, weights = search.weights, field_count = fields.length, getAttrFn = search.getAttrFn;\n if (!field_count) {\n return function () { return 1; };\n }\n /**\n * Calculates the score of an object\n * against the search query.\n *\n */\n const scoreObject = (function () {\n if (field_count === 1) {\n return function (token, data) {\n const field = fields[0].field;\n return scoreValue(getAttrFn(data, field), token, weights[field] || 1);\n };\n }\n return function (token, data) {\n var sum = 0;\n // is the token specific to a field?\n if (token.field) {\n const value = getAttrFn(data, token.field);\n if (!token.regex && value) {\n sum += (1 / field_count);\n }\n else {\n sum += scoreValue(value, token, 1);\n }\n }\n else {\n iterate(weights, (weight, field) => {\n sum += scoreValue(getAttrFn(data, field), token, weight);\n });\n }\n return sum / field_count;\n };\n })();\n if (token_count === 1) {\n return function (data) {\n return scoreObject(tokens[0], data);\n };\n }\n if (search.options.conjunction === 'and') {\n return function (data) {\n var score, sum = 0;\n for (let token of tokens) {\n score = scoreObject(token, data);\n if (score <= 0)\n return 0;\n sum += score;\n }\n return sum / token_count;\n };\n }\n else {\n return function (data) {\n var sum = 0;\n iterate(tokens, (token) => {\n sum += scoreObject(token, data);\n });\n return sum / token_count;\n };\n }\n }\n ;\n /**\n * Returns a function that can be used to compare two\n * results, for sorting purposes. If no sorting should\n * be performed, `null` will be returned.\n *\n * @return function(a,b)\n */\n getSortFunction(query, options) {\n var search = this.prepareSearch(query, options);\n return this._getSortFunction(search);\n }\n _getSortFunction(search) {\n var implicit_score, sort_flds = [];\n const self = this, options = search.options, sort = (!search.query && options.sort_empty) ? options.sort_empty : options.sort;\n if (typeof sort == 'function') {\n return sort.bind(this);\n }\n /**\n * Fetches the specified sort field value\n * from a search result item.\n *\n */\n const get_field = function (name, result) {\n if (name === '$score')\n return result.score;\n return search.getAttrFn(self.items[result.id], name);\n };\n // parse options\n if (sort) {\n for (let s of sort) {\n if (search.query || s.field !== '$score') {\n sort_flds.push(s);\n }\n }\n }\n // the \"$score\" field is implied to be the primary\n // sort field, unless it's manually specified\n if (search.query) {\n implicit_score = true;\n for (let fld of sort_flds) {\n if (fld.field === '$score') {\n implicit_score = false;\n break;\n }\n }\n if (implicit_score) {\n sort_flds.unshift({ field: '$score', direction: 'desc' });\n }\n // without a search.query, all items will have the same score\n }\n else {\n sort_flds = sort_flds.filter((fld) => fld.field !== '$score');\n }\n // build function\n const sort_flds_count = sort_flds.length;\n if (!sort_flds_count) {\n return null;\n }\n return function (a, b) {\n var result, field;\n for (let sort_fld of sort_flds) {\n field = sort_fld.field;\n let multiplier = sort_fld.direction === 'desc' ? -1 : 1;\n result = multiplier * cmp(get_field(field, a), get_field(field, b));\n if (result)\n return result;\n }\n return 0;\n };\n }\n ;\n /**\n * Parses a search query and returns an object\n * with tokens and fields ready to be populated\n * with results.\n *\n */\n prepareSearch(query, optsUser) {\n const weights = {};\n var options = Object.assign({}, optsUser);\n propToArray(options, 'sort');\n propToArray(options, 'sort_empty');\n // convert fields to new format\n if (options.fields) {\n propToArray(options, 'fields');\n const fields = [];\n options.fields.forEach((field) => {\n if (typeof field == 'string') {\n field = { field: field, weight: 1 };\n }\n fields.push(field);\n weights[field.field] = ('weight' in field) ? field.weight : 1;\n });\n options.fields = fields;\n }\n return {\n options: options,\n query: query.toLowerCase().trim(),\n tokens: this.tokenize(query, options.respect_word_boundaries, weights),\n total: 0,\n items: [],\n weights: weights,\n getAttrFn: (options.nesting) ? getAttrNesting : getAttr,\n };\n }\n ;\n /**\n * Searches through all items and returns a sorted array of matches.\n *\n */\n search(query, options) {\n var self = this, score, search;\n search = this.prepareSearch(query, options);\n options = search.options;\n query = search.query;\n // generate result scoring function\n const fn_score = options.score || self._getScoreFunction(search);\n // perform search and sort\n if (query.length) {\n iterate(self.items, (item, id) => {\n score = fn_score(item);\n if (options.filter === false || score > 0) {\n search.items.push({ 'score': score, 'id': id });\n }\n });\n }\n else {\n iterate(self.items, (_, id) => {\n search.items.push({ 'score': 1, 'id': id });\n });\n }\n const fn_sort = self._getSortFunction(search);\n if (fn_sort)\n search.items.sort(fn_sort);\n // apply limits\n search.total = search.items.length;\n if (typeof options.limit === 'number') {\n search.items = search.items.slice(0, options.limit);\n }\n return search;\n }\n ;\n}\nexport { Sifter, scoreValue, getAttr, getAttrNesting, propToArray, iterate, cmp, getPattern };\nexport * from \"./types.js\";\n//# sourceMappingURL=sifter.js.map","/**\n * Converts a scalar to its best string representation\n * for hash keys and HTML attribute values.\n *\n * Transformations:\n * 'str' -> 'str'\n * null -> ''\n * undefined -> ''\n * true -> '1'\n * false -> '0'\n * 0 -> '0'\n * 1 -> '1'\n *\n */\nexport const hash_key = (value) => {\n if (typeof value === 'undefined' || value === null)\n return null;\n return get_hash(value);\n};\nexport const get_hash = (value) => {\n if (typeof value === 'boolean')\n return value ? '1' : '0';\n return value + '';\n};\n/**\n * Escapes a string for use within HTML.\n *\n */\nexport const escape_html = (str) => {\n return (str + '')\n .replace(/&/g, '&')\n .replace(//g, '>')\n .replace(/\"/g, '"');\n};\n/**\n * use setTimeout if timeout > 0\n */\nexport const timeout = (fn, timeout) => {\n if (timeout > 0) {\n return window.setTimeout(fn, timeout);\n }\n fn.call(null);\n return null;\n};\n/**\n * Debounce the user provided load function\n *\n */\nexport const loadDebounce = (fn, delay) => {\n var timeout;\n return function (value, callback) {\n var self = this;\n if (timeout) {\n self.loading = Math.max(self.loading - 1, 0);\n clearTimeout(timeout);\n }\n timeout = setTimeout(function () {\n timeout = null;\n self.loadedSearches[value] = true;\n fn.call(self, value, callback);\n }, delay);\n };\n};\n/**\n * Debounce all fired events types listed in `types`\n * while executing the provided `fn`.\n *\n */\nexport const debounce_events = (self, types, fn) => {\n var type;\n var trigger = self.trigger;\n var event_args = {};\n // override trigger method\n self.trigger = function () {\n var type = arguments[0];\n if (types.indexOf(type) !== -1) {\n event_args[type] = arguments;\n }\n else {\n return trigger.apply(self, arguments);\n }\n };\n // invoke provided function\n fn.apply(self, []);\n self.trigger = trigger;\n // trigger queued events\n for (type of types) {\n if (type in event_args) {\n trigger.apply(self, event_args[type]);\n }\n }\n};\n/**\n * Determines the current selection within a text input control.\n * Returns an object containing:\n * - start\n * - length\n *\n * Note: \"selectionStart, selectionEnd ... apply only to inputs of types text, search, URL, tel and password\"\n * \t- https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement/setSelectionRange\n */\nexport const getSelection = (input) => {\n return {\n start: input.selectionStart || 0,\n length: (input.selectionEnd || 0) - (input.selectionStart || 0),\n };\n};\n/**\n * Prevent default\n *\n */\nexport const preventDefault = (evt, stop = false) => {\n if (evt) {\n evt.preventDefault();\n if (stop) {\n evt.stopPropagation();\n }\n }\n};\n/**\n * Add event helper\n *\n */\nexport const addEvent = (target, type, callback, options) => {\n target.addEventListener(type, callback, options);\n};\n/**\n * Return true if the requested key is down\n * Will return false if more than one control character is pressed ( when [ctrl+shift+a] != [ctrl+a] )\n * The current evt may not always set ( eg calling advanceSelection() )\n *\n */\nexport const isKeyDown = (key_name, evt) => {\n if (!evt) {\n return false;\n }\n if (!evt[key_name]) {\n return false;\n }\n var count = (evt.altKey ? 1 : 0) + (evt.ctrlKey ? 1 : 0) + (evt.shiftKey ? 1 : 0) + (evt.metaKey ? 1 : 0);\n if (count === 1) {\n return true;\n }\n return false;\n};\n/**\n * Get the id of an element\n * If the id attribute is not set, set the attribute with the given id\n *\n */\nexport const getId = (el, id) => {\n const existing_id = el.getAttribute('id');\n if (existing_id) {\n return existing_id;\n }\n el.setAttribute('id', id);\n return id;\n};\n/**\n * Returns a string with backslashes added before characters that need to be escaped.\n */\nexport const addSlashes = (str) => {\n return str.replace(/[\\\\\"']/g, '\\\\$&');\n};\n/**\n *\n */\nexport const append = (parent, node) => {\n if (node)\n parent.append(node);\n};\n/**\n * Iterates over arrays and hashes.\n *\n * ```\n * iterate(this.items, function(item, id) {\n * // invoked for each item\n * });\n * ```\n *\n */\nexport const iterate = (object, callback) => {\n if (Array.isArray(object)) {\n object.forEach(callback);\n }\n else {\n for (var key in object) {\n if (object.hasOwnProperty(key)) {\n callback(object[key], key);\n }\n }\n }\n};\n//# sourceMappingURL=utils.js.map","import { iterate } from \"./utils.js\";\n/**\n * Return a dom element from either a dom query string, jQuery object, a dom element or html string\n * https://stackoverflow.com/questions/494143/creating-a-new-dom-element-from-an-html-string-using-built-in-dom-methods-or-pro/35385518#35385518\n *\n * param query should be {}\n */\nexport const getDom = (query) => {\n if (query.jquery) {\n return query[0];\n }\n if (query instanceof HTMLElement) {\n return query;\n }\n if (isHtmlString(query)) {\n var tpl = document.createElement('template');\n tpl.innerHTML = query.trim(); // Never return a text node of whitespace as the result\n return tpl.content.firstChild;\n }\n return document.querySelector(query);\n};\nexport const isHtmlString = (arg) => {\n if (typeof arg === 'string' && arg.indexOf('<') > -1) {\n return true;\n }\n return false;\n};\nexport const escapeQuery = (query) => {\n return query.replace(/['\"\\\\]/g, '\\\\$&');\n};\n/**\n * Dispatch an event\n *\n */\nexport const triggerEvent = (dom_el, event_name) => {\n var event = document.createEvent('HTMLEvents');\n event.initEvent(event_name, true, false);\n dom_el.dispatchEvent(event);\n};\n/**\n * Apply CSS rules to a dom element\n *\n */\nexport const applyCSS = (dom_el, css) => {\n Object.assign(dom_el.style, css);\n};\n/**\n * Add css classes\n *\n */\nexport const addClasses = (elmts, ...classes) => {\n var norm_classes = classesArray(classes);\n elmts = castAsArray(elmts);\n elmts.map(el => {\n norm_classes.map(cls => {\n el.classList.add(cls);\n });\n });\n};\n/**\n * Remove css classes\n *\n */\nexport const removeClasses = (elmts, ...classes) => {\n var norm_classes = classesArray(classes);\n elmts = castAsArray(elmts);\n elmts.map(el => {\n norm_classes.map(cls => {\n el.classList.remove(cls);\n });\n });\n};\n/**\n * Return arguments\n *\n */\nexport const classesArray = (args) => {\n var classes = [];\n iterate(args, (_classes) => {\n if (typeof _classes === 'string') {\n _classes = _classes.trim().split(/[\\t\\n\\f\\r\\s]/);\n }\n if (Array.isArray(_classes)) {\n classes = classes.concat(_classes);\n }\n });\n return classes.filter(Boolean);\n};\n/**\n * Create an array from arg if it's not already an array\n *\n */\nexport const castAsArray = (arg) => {\n if (!Array.isArray(arg)) {\n arg = [arg];\n }\n return arg;\n};\n/**\n * Get the closest node to the evt.target matching the selector\n * Stops at wrapper\n *\n */\nexport const parentMatch = (target, selector, wrapper) => {\n if (wrapper && !wrapper.contains(target)) {\n return;\n }\n while (target && target.matches) {\n if (target.matches(selector)) {\n return target;\n }\n target = target.parentNode;\n }\n};\n/**\n * Get the first or last item from an array\n *\n * > 0 - right (last)\n * <= 0 - left (first)\n *\n */\nexport const getTail = (list, direction = 0) => {\n if (direction > 0) {\n return list[list.length - 1];\n }\n return list[0];\n};\n/**\n * Return true if an object is empty\n *\n */\nexport const isEmptyObject = (obj) => {\n return (Object.keys(obj).length === 0);\n};\n/**\n * Get the index of an element amongst sibling nodes of the same type\n *\n */\nexport const nodeIndex = (el, amongst) => {\n if (!el)\n return -1;\n amongst = amongst || el.nodeName;\n var i = 0;\n while (el = el.previousElementSibling) {\n if (el.matches(amongst)) {\n i++;\n }\n }\n return i;\n};\n/**\n * Set attributes of an element\n *\n */\nexport const setAttr = (el, attrs) => {\n iterate(attrs, (val, attr) => {\n if (val == null) {\n el.removeAttribute(attr);\n }\n else {\n el.setAttribute(attr, '' + val);\n }\n });\n};\n/**\n * Replace a node\n */\nexport const replaceNode = (existing, replacement) => {\n if (existing.parentNode)\n existing.parentNode.replaceChild(replacement, existing);\n};\n//# sourceMappingURL=vanilla.js.map","/**\n * highlight v3 | MIT license | Johann Burkard \n * Highlights arbitrary terms in a node.\n *\n * - Modified by Marshal 2011-6-24 (added regex)\n * - Modified by Brian Reavis 2012-8-27 (cleanup)\n */\nimport { replaceNode } from \"../vanilla.js\";\nexport const highlight = (element, regex) => {\n if (regex === null)\n return;\n // convet string to regex\n if (typeof regex === 'string') {\n if (!regex.length)\n return;\n regex = new RegExp(regex, 'i');\n }\n // Wrap matching part of text node with highlighting , e.g.\n // Soccer -> Soccer for regex = /soc/i\n const highlightText = (node) => {\n var match = node.data.match(regex);\n if (match && node.data.length > 0) {\n var spannode = document.createElement('span');\n spannode.className = 'highlight';\n var middlebit = node.splitText(match.index);\n middlebit.splitText(match[0].length);\n var middleclone = middlebit.cloneNode(true);\n spannode.appendChild(middleclone);\n replaceNode(middlebit, spannode);\n return 1;\n }\n return 0;\n };\n // Recurse element node, looking for child text nodes to highlight, unless element\n // is childless,