domma-cms 1.21.0 → 1.22.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,33 +1,33 @@
1
- import{api as P}from"../api.js";import{colourToCss as At,HIGHLIGHT_HOVER as ut,HIGHLIGHT_ACTIVE as pt,HIGHLIGHT_HOVER_LABELS as mt,HIGHLIGHT_ACTIVE_LABELS as ht,cssClassProblems as ft,normaliseCssClasses as Et,ENTRANCE_ANIMATIONS as ot,ENTRANCE_ANIMATION_LABELS as Ct}from"/public/js/menu-decor.mjs?v=20261014-menu-entrance";import{openIconPicker as Lt}from"../lib/card-builder.js";import{normalisePanel as $t,DESCRIPTION_MAX as Tt}from"/public/js/menu-look.mjs?v=20261029-footer-bars";import{sortableMenuRows as _t}from"../lib/menu-drag.js";import{placeTools as Ht,ensureLockedTools as It,isLockedUrl as Nt,groupKeyFor as Ot,slugify as Rt,GROUP_ICON as Bt,TOOLS_FOLDER_KEY as Pt}from"../lib/sidebar-grouping.js";import{flatten as gt,nest as Dt,uid as Xe}from"../lib/menu-rows.js";import{addBannerAction as at}from"../lib/plugin-chrome.js";import{helpPopovers as st}from"../lib/help-popover.js";import{MENU_ITEM_HELP as jt}from"../lib/menu-item-help.js";import{onceClosed as Mt,openMenuAt as lt,sidebarCount as Ft}from"../lib/tool-kit.js";import{addChild as zt,bindingFrom as Ut,duplicateRow as Wt,indentRow as Kt,insertBelow as qt,isStructural as ve,menuFromForm as Gt,menuProblems as Vt,moveRow as vt,outdentRow as Yt,siblingsOf as Xt,snapshot as Je}from"../lib/menu-editor-arrange.js";import{fmtDateTime as Jt}from"../lib/dates.js";const Qt=760,Zt="admin-sidebar",en=/^\/menus\/(new|edit\/[^?#]+)(\?.*)?$/;function x(n){return String(n||"").replace(/&/g,"&amp;").replace(/"/g,"&quot;").replace(/</g,"&lt;")}const De=n=>String(n??"").replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;");function tn(n,p){let l=0,r=p.find(s=>s.id===n);for(;r&&r.parentId;)l++,r=p.find(s=>s.id===r.parentId);return l}function bt(n){const p=new Set,l=new Set,r=s=>{for(const y of n.filter(T=>T.parentId===s))!y.type&&Nt(y.url)&&!l.has(y.url)&&(l.add(y.url),p.add(y.id)),r(y.id)};return r(null),p}const Qe='<button type="button" class="btn btn-sm btn-ghost mex-kebab" aria-label="Actions" title="Actions (right-click, or Shift+F10)">\u22EE</button>';function nn(n,p,l=!1){const r=l?bt(p):new Set,s=[];function y(T){for(const d of p.filter(Y=>Y.parentId===T)){const L=`style="margin-left:${tn(d.id,p)*28}px"`;if(d.type==="separator"){s.push(`
2
- <div class="menu-tree-row menu-tree-row--separator" data-id="${d.id}" tabindex="0" ${L}>
1
+ import{api as D}from"../api.js";import{colourToCss as Ct,HIGHLIGHT_HOVER as pt,HIGHLIGHT_ACTIVE as ht,HIGHLIGHT_HOVER_LABELS as ft,HIGHLIGHT_ACTIVE_LABELS as gt,cssClassProblems as vt,normaliseCssClasses as $t,ENTRANCE_ANIMATIONS as at,ENTRANCE_ANIMATION_LABELS as Lt}from"/public/js/menu-decor.mjs?v=20261014-menu-entrance";import{openIconPicker as Tt}from"../lib/card-builder.js";import{normalisePanel as _t,DESCRIPTION_MAX as Ht}from"/public/js/menu-look.mjs?v=20261029-footer-bars";import{sortableMenuRows as It}from"../lib/menu-drag.js";import{placeTools as Nt,ensureLockedTools as Ot,isLockedUrl as Rt,groupKeyFor as Bt,slugify as Pt,GROUP_ICON as Dt,TOOLS_FOLDER_KEY as jt}from"../lib/sidebar-grouping.js";import{flatten as bt,nest as Ft,uid as Je}from"../lib/menu-rows.js";import{addBannerAction as st}from"../lib/plugin-chrome.js";import{helpPopovers as lt}from"../lib/help-popover.js";import{enhanceFontSelect as Mt}from"../lib/font-picker.js";import{MENU_ITEM_HELP as zt}from"../lib/menu-item-help.js";import{onceClosed as Ut,openMenuAt as it,sidebarCount as Wt}from"../lib/tool-kit.js";import{addChild as Kt,bindingFrom as qt,duplicateRow as Gt,indentRow as Vt,insertBelow as Yt,isStructural as be,menuFromForm as Xt,menuProblems as Jt,moveRow as yt,outdentRow as Qt,siblingsOf as Zt,snapshot as Qe}from"../lib/menu-editor-arrange.js";import{fmtDateTime as en}from"../lib/dates.js";const tn=760,nn="admin-sidebar",on=/^\/menus\/(new|edit\/[^?#]+)(\?.*)?$/;function x(n){return String(n||"").replace(/&/g,"&amp;").replace(/"/g,"&quot;").replace(/</g,"&lt;")}const De=n=>String(n??"").replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;");function an(n,m){let i=0,r=m.find(l=>l.id===n);for(;r&&r.parentId;)i++,r=m.find(l=>l.id===r.parentId);return i}function kt(n){const m=new Set,i=new Set,r=l=>{for(const k of n.filter(_=>_.parentId===l))!k.type&&Rt(k.url)&&!i.has(k.url)&&(i.add(k.url),m.add(k.id)),r(k.id)};return r(null),m}const Ze='<button type="button" class="btn btn-sm btn-ghost mex-kebab" aria-label="Actions" title="Actions (right-click, or Shift+F10)">\u22EE</button>';function sn(n,m,i=!1){const r=i?kt(m):new Set,l=[];function k(_){for(const d of m.filter(V=>V.parentId===_)){const $=`style="margin-left:${an(d.id,m)*28}px"`;if(d.type==="separator"){l.push(`
2
+ <div class="menu-tree-row menu-tree-row--separator" data-id="${d.id}" tabindex="0" ${$}>
3
3
  <span class="menu-tree-grip" data-icon="grip-vertical" data-icon-size="18" title="Drag to move"></span>
4
4
  <span class="me-sep-line"><span class="me-sep-label">Separator</span></span>
5
- ${Qe}
6
- </div>`);continue}if(d.type==="spacer"){const be=["xs","sm","md","lg","xl","flex"].map(ae=>`<option value="${ae}"${(d.size||"md")===ae?" selected":""}>${ae==="flex"?"flexible":ae}</option>`).join("");s.push(`
7
- <div class="menu-tree-row menu-tree-row--spacer" data-id="${d.id}" tabindex="0" ${L}>
5
+ ${Ze}
6
+ </div>`);continue}if(d.type==="spacer"){const ye=["xs","sm","md","lg","xl","flex"].map(ne=>`<option value="${ne}"${(d.size||"md")===ne?" selected":""}>${ne==="flex"?"flexible":ne}</option>`).join("");l.push(`
7
+ <div class="menu-tree-row menu-tree-row--spacer" data-id="${d.id}" tabindex="0" ${$}>
8
8
  <span class="menu-tree-grip" data-icon="grip-vertical" data-icon-size="18" title="Drag to move"></span>
9
9
  <span class="me-spacer-line">
10
10
  <span class="me-spacer-label">Spacer</span>
11
- <select class="form-input me-spacer-size" title="Spacer size - flexible fills the leftover room" aria-label="Spacer size">${be}</select>
11
+ <select class="form-input me-spacer-size" title="Spacer size - flexible fills the leftover room" aria-label="Spacer size">${ye}</select>
12
12
  <span data-help-title="Spacer size" data-help="Choose a fixed gap from xs (smallest) to xl (largest), or flexible to fill leftover room along the menu. A fixed size separates neighbouring links; a flexible spacer can push groups apart in a horizontal row. This row supplies space only, with no label or destination. Save the menu to keep a size change."></span>
13
13
  </span>
14
- ${Qe}
15
- </div>`);continue}if(d.type==="theme-switcher"){s.push(`
16
- <div class="menu-tree-row menu-tree-row--switcher" data-id="${d.id}" tabindex="0" ${L}>
14
+ ${Ze}
15
+ </div>`);continue}if(d.type==="theme-switcher"){l.push(`
16
+ <div class="menu-tree-row menu-tree-row--switcher" data-id="${d.id}" tabindex="0" ${$}>
17
17
  <span class="menu-tree-grip" data-icon="grip-vertical" data-icon-size="18" title="Drag to move"></span>
18
18
  <span class="me-sep-line"><span class="me-sep-label"><span data-icon="palette"></span> Theme switcher - the themes chosen under Theme &gt; Theme switcher</span></span>
19
- ${Qe}
20
- </div>`);continue}const X=d.badge&&(d.badge.text||d.badge.countFrom)?`<span class="dm-menu-badge">${x(String(d.badge.text||"#"))}</span>`:"",_=d.tool,g=_&&(_.persisted||d.touched),re=_?_.orphan?' <span class="badge badge-secondary me-tool-badge" title="A placeholder for a Tool that is not enabled - it returns here when it is">Not enabled</span>':` <span class="badge badge-secondary me-tool-badge" title="${g?"A Tool, placed here by this menu":"A Tool in its default place - move or edit it to place it here"}">${x(_.source||"Tool")}${g?"":" \xB7 default"}</span>`:"",ne=r.has(d.id),ce=At(d.colour),oe=ce?` style="color:${x(ce)}"`:"",de=ne?'<button type="button" class="btn btn-sm btn-ghost" disabled title="Always shown - it can be moved, not hidden" aria-label="Always shown"><span data-icon="lock"></span></button>':`<button type="button" class="btn btn-sm btn-ghost me-hidden ${d.hidden?"active":""}" title="${d.hidden?"Hidden - click to show":"Hide"}" aria-label="${d.hidden?"Show":"Hide"}" aria-pressed="${d.hidden?"true":"false"}"><span data-icon="${d.hidden?"eye-off":"eye"}"></span></button>`;s.push(`
21
- <div class="menu-tree-row menu-tree-row--slim${d.hidden?" menu-tree-row--hidden":""}${_?" menu-tree-row--tool":""}${_&&!g?" menu-tree-row--default":""}" data-id="${d.id}" tabindex="0" ${L}>
19
+ ${Ze}
20
+ </div>`);continue}const Y=d.badge&&(d.badge.text||d.badge.countFrom)?`<span class="dm-menu-badge">${x(String(d.badge.text||"#"))}</span>`:"",N=d.tool,g=N&&(N.persisted||d.touched),re=N?N.orphan?' <span class="badge badge-secondary me-tool-badge" title="A placeholder for a Tool that is not enabled - it returns here when it is">Not enabled</span>':` <span class="badge badge-secondary me-tool-badge" title="${g?"A Tool, placed here by this menu":"A Tool in its default place - move or edit it to place it here"}">${x(N.source||"Tool")}${g?"":" \xB7 default"}</span>`:"",ee=r.has(d.id),ce=Ct(d.colour),te=ce?` style="color:${x(ce)}"`:"",de=ee?'<button type="button" class="btn btn-sm btn-ghost" disabled title="Always shown - it can be moved, not hidden" aria-label="Always shown"><span data-icon="lock"></span></button>':`<button type="button" class="btn btn-sm btn-ghost me-hidden ${d.hidden?"active":""}" title="${d.hidden?"Hidden - click to show":"Hide"}" aria-label="${d.hidden?"Show":"Hide"}" aria-pressed="${d.hidden?"true":"false"}"><span data-icon="${d.hidden?"eye-off":"eye"}"></span></button>`;l.push(`
21
+ <div class="menu-tree-row menu-tree-row--slim${d.hidden?" menu-tree-row--hidden":""}${N?" menu-tree-row--tool":""}${N&&!g?" menu-tree-row--default":""}" data-id="${d.id}" tabindex="0" ${$}>
22
22
  <span class="menu-tree-grip" data-icon="grip-vertical" data-icon-size="18" title="Drag to move"></span>
23
- <span class="me-row-label${!d.text&&!_?" mex-untitled":""}"${oe}>${x(d.text||_?.label||"(no label - click to add one)")}${X}${re}</span>
23
+ <span class="me-row-label${!d.text&&!N?" mex-untitled":""}"${te}>${x(d.text||N?.label||"(no label - click to add one)")}${Y}${re}</span>
24
24
  <span class="me-row-url">${x(d.url||"")}</span>
25
25
  ${de}
26
26
  <button type="button" class="btn btn-sm btn-ghost me-edit" title="Edit" aria-label="Edit"><span data-icon="edit"></span></button>
27
- ${Qe}
28
- </div>`),y(d.id)}}y(null),n._disposeMenuHelp?.(),n.innerHTML=s.join("")||'<p class="mex-note">No items yet - Add item, or right-click an item for more.</p>',n._disposeMenuHelp=st(n),I.scan(n)}function f(n,p={},...l){const r=document.createElement(n);Object.assign(r,p);for(const s of l)s!=null&&r.append(s);return r}function w(n,p,l){const r=f("label",{className:"form-field"},f("span",{className:"form-label",textContent:n}),p),s=jt[n];if(s){const y=f("span");y.dataset.help=s+(l?" "+l:""),y.dataset.helpTitle=n,r.querySelector(".form-label").append(" ",y)}return l&&r.append(f("small",{className:"form-hint",textContent:l,style:"display:block;font-size:.78em;opacity:.7;margin-top:.25rem;line-height:1.35"})),r}function on(n,p){const l=[["","- Everyone -"],["public","Public - anyone, incl. logged-out"],...(p||[]).map(s=>[s.name,`${s.label||s.name} and above`]),...(p||[]).filter(s=>s.level!==0).map(s=>[`=${s.name}`,`${s.label||s.name} only`]),["private","Private - super-admin only"]];n&&!l.some(([s])=>s===n)&&l.push([n,`${n} (custom)`]);const r=G(l,n||"");return r.name="visibility",r}function G(n,p){const l=f("select",{className:"form-select"});return n.forEach(([r,s])=>l.add(new Option(s,r))),l.value=p??"",l}function je(n,p){const l=typeof p=="string"&&p.startsWith("#"),r=G([["","- none -"],["primary","primary"],["success","success"],["danger","danger"],["warning","warning"],["info","info"],["neutral","neutral"],["__custom__","Custom\u2026"]],l?"__custom__":p||""),s=f("input",{type:"color",className:"form-input me-colour-hex",value:l?p:"#000000"});s.style.display=l?"":"none",r.addEventListener("change",()=>{s.style.display=r.value==="__custom__"?"":"none"});const y=w(n,r);return y.append(s),y._read=()=>r.value==="__custom__"?s.value:r.value,y}function an(n,p){const l=f("input",{className:"form-input me-icon",name:"icon",value:p||""}),r=f("span",{className:"me-icon-preview"});p&&r.setAttribute("data-icon",p);const s=f("button",{type:"button",className:"btn btn-sm btn-ghost",textContent:"Browse\u2026"}),y=T=>{T?r.setAttribute("data-icon",T):r.removeAttribute("data-icon"),Domma.icons.scan(r.parentNode||r)};return s.addEventListener("click",()=>Lt(T=>{l.value=T,y(T)})),l.addEventListener("input",()=>y(l.value.trim())),w(n,f("div",{className:"me-icon-field"},l,s,r))}function te(...n){return f("div",{className:"me-field-grid"},...n)}async function sn(n,p,l,r,s,{cards:y=!0}={}){const T=n.text||n.tool?.label||"",d=(m,...U)=>{const z=f("section",{className:"me-item-section"},f("h4",{className:"me-item-section-title",textContent:m}),f("div",{className:"me-item-section-body"},...U));return z.setAttribute("aria-label",m),z},Y=w("Label",f("input",{className:"form-input",name:"text",value:n.text||""}),"The text shown for this item."),L=f("input",{className:"form-input",name:"url",value:n.url||""}),X=w("URL",L,n.tool||n.locked?"A Tool's address is its identity, so it cannot be changed here.":"Where it links. Must start with /, #, https://, or mailto: . Leave blank for a parent that only groups sub-items.");(n.tool||n.locked)&&(L.readOnly=!0);const _=an("Icon",n.icon||""),g=on(n.visibility||"",r),re=w("Visibility",g,n.locked?"Always in the sidebar for everyone who may use it, so it cannot be restricted here.":'Who can see this item. "Role and above" shows it to that role and anyone more senior; "Role only" shows it to holders of that role alone (and the super-admin). Blank = everyone.');n.locked&&(g.disabled=!0);const ne=G([["","- no permission gate -"],...(p||[]).map(m=>[m.key,m.label||m.key])],n.permission||"");ne.name="permission";const ce=w("Permission",ne,n.tool||n.locked?"A Tool is guarded by its own permission, which always applies.":"Hide unless the viewer holds this specific permission. Independent of Visibility - both must pass.");(n.tool||n.locked)&&(ne.disabled=!0);const oe=w("Badge text",f("input",{className:"form-input",name:"badgeText",value:n.badge?.text||""})),de=G([["","- none -"],...(l||[]).map(m=>[m.slug,m.title||m.slug])],n.badge?.countFrom||"");de.name="badgeCount";const be=w("Badge count from",de,"Show a live count of this collection\u2019s entries as the badge."),ae=je("Badge colour",n.badge?.variant||""),ye=G([["link","Link"],["pill","Pill"]],n.pill?"pill":"link");ye.name="renderAs";const D=w("Render as",ye,"Pill draws the item as a rounded chip. Pill styling applies to top-level navbar items."),Le=w("Pill style",G([["filled","Filled"],["outline","Outline"]],n.pill?.style||"filled"));Le.querySelector("select").name="pillStyle";const $e=je("Pill colour",n.pill?.variant||""),h=f("div",{className:"me-pill-wrap"},te(Le,$e));h.style.display=n.pill?"":"none",ye.addEventListener("change",()=>{h.style.display=ye.value==="pill"?"":"none"});const j=je("Text colour",n.colour||""),ue=G([["","- use the menu default -"],...ut.map(m=>[m,mt[m]||m])],n.highlight?.hover||"");ue.name="hlHover";const Me=w("Hover effect",ue,"Overrides the menu-wide hover effect for this item only."),Te=G([["","- use the menu default -"],...pt.map(m=>[m,ht[m]||m])],n.highlight?.active||"");Te.name="hlActive";const K=w("When selected",Te,"How this item is marked when it points at the page being viewed."),$=je("Highlight colour",n.highlight?.accent||""),ke=f("input",{className:"form-input",name:"class",value:n.class||"",placeholder:"nav-cta push-right",autocomplete:"off",spellcheck:!1}),N=w("CSS classes",ke,"Your own class names, separated by spaces, added to this item's <li> - target the link with .your-class > a. Style them in Custom CSS."),J=f("small",{className:"text-danger",style:"display:none;margin-top:.25rem"});N.append(J);const pe=f("textarea",{className:"form-input",name:"description",rows:2,maxLength:Tt,value:n.description||"",placeholder:"Answers every new lead in under a minute."}),me=w("Description",pe,"One short line under the label, shown when the menu's dropdowns are Cards."),_e=je("Tile colour",n.tile||""),He=f("input",{type:"checkbox",name:"chip",checked:!!n.chip,style:"width:auto;margin:0"}),Ie=f("label",{className:"form-field",style:"display:flex;gap:.5rem;align-items:center;font-weight:400"},He,f("span",{textContent:"Show as a small chip in the card's footer strip"})),we=f("span");we.dataset.helpTitle="Show as a small chip",we.dataset.help="Place this sub-item in the compact chip strip at the bottom of its parent Cards dropdown instead of the main entries. Its label and destination remain the same. The parent card can provide a Chip strip label. This applies to sub-items in Cards dropdowns, rather than top-level navbar links.",Ie.append(we);const F=n.parentId==null,C=n.panel||{},O=(m,U,z,A=80)=>f("input",{className:"form-input",name:m,value:U||"",placeholder:z,maxLength:A}),Fe=w("Card heading",O("panelHeading",C.heading,"The crew - six agents, one job each"),"Small capitals over the entries."),ze=w("Link text",O("panelLinkText",C.link?.text,"Meet the crew",60)),Ue=w("Link URL",O("panelLinkUrl",C.link?.url,"/crew",500)),Ne=G([["","Automatic"],["1","1"],["2","2"],["3","3"],["4","4"]],C.columns?String(C.columns):"");Ne.name="panelColumns";const Ze=w("Columns",Ne),et=w("Chip strip label",O("panelChipsLabel",C.chipsLabel,"Add to your crew",60),'Words before the chips - tick "Show as a small chip" on the sub-items that belong there.'),he=G([["","- no side box -"],["dark","Dark"],["light","Light"],["accent","Theme colour"]],C.feature?C.feature.tone||"dark":"");he.name="featureTone";const We=w("Side box",he,"A box down the right of the card - a call to action or a short list."),Ke=w("Box small heading",O("featureEyebrow",C.feature?.eyebrow,"Free - 20 minutes",60)),qe=w("Box title",O("featureTitle",C.feature?.title,"See it live")),t=w("Box points",f("textarea",{className:"form-input",name:"featurePoints",rows:3,value:(C.feature?.points||[]).join(`
29
- `),placeholder:"One per line, up to six"})),Se=w("Button text",O("featureBtnText",C.feature?.button?.text,"Book a demo",60)),Oe=w("Button URL",O("featureBtnUrl",C.feature?.button?.url,"/book",500)),fe=f("div",{className:"me-feature-fields"},te(Ke,qe),t,te(Se,Oe));fe.style.display=he.value?"":"none",he.addEventListener("change",()=>{fe.style.display=he.value?"":"none"});const tt=y?[d("Card link",f("small",{className:"form-hint",textContent:"Used with card dropdowns. Choose Cards on the Behaviour tab."}),me,te(_e,F?null:Ie)),...F?[d("Dropdown panel",Fe,te(ze,Ue),te(Ze,et)),d("Side box",We,fe)]:[]]:[],se=f("button",{className:"btn btn-primary",textContent:"Apply",title:"Apply to the item (Ctrl+Enter) - Save the menu to keep it"}),q=f("div",{className:"me-item-form"},d("Link",Y,X,_),d("Appearance",D,h,j),d("Hover & selection",te(Me,K),$),...tt,d("Badge",te(oe,ae),be),d("Access",te(re,ce)),d("Custom styling",N),f("div",{className:"me-item-actions"},f("small",{className:"form-hint",textContent:"Apply updates this item. Save the menu to keep it."}),se)),B=E.slideover({title:T?`Edit ${De(T)}`:"Edit menu item",size:"lg",position:"right"});B.element.appendChild(q);const Ge=()=>JSON.stringify([...q.querySelectorAll("input, select, textarea")].map(m=>m.type==="checkbox"?m.checked:m.value)),Ve=Ge();let xe=!1,ge=!1;const Re=st(q,{position:"bottom"});Mt(B,Re);const Ae=B.close.bind(B);B.close=async m=>{if(!xe&&m!==!0&&Ge()!==Ve){if(ge)return;ge=!0;const U=await E.confirm("Discard the changes to this item?");if(ge=!1,!U)return}return xe=!0,Ae()},q.addEventListener("keydown",m=>{(m.ctrlKey||m.metaKey)&&m.key==="Enter"&&(m.preventDefault(),se.click())}),B.open();const Be=B.element.closest(".dm-slideover")||B.element.querySelector(".dm-slideover")||B.element;Be.style.setProperty("width",Qt+"px","important"),Be.style.setProperty("max-width","95vw","important"),Domma.icons.scan(q);const v=m=>q.querySelector(`[name="${m}"]`)?.value||"";se.addEventListener("click",()=>{const m=ft(v("class"));if(m.length){J.textContent=m.join("; "),J.style.display="block",ke.focus();return}n.class=Et(v("class")),n.text=v("text"),n.icon=v("icon"),n.locked||(n.visibility=v("visibility")),!n.tool&&!n.locked?(n.url=v("url"),n.permission=v("permission")):n.touched=!0;const U=v("badgeText"),z=v("badgeCount"),A=ae._read();if(n.badge=U||z?{...U&&{text:U},...z&&{countFrom:z},...A&&{variant:A}}:null,v("renderAs")==="pill"){const Q=$e._read();n.pill={style:v("pillStyle")||"filled",...Q&&{variant:Q}}}else n.pill=null;n.colour=j._read();const le=v("hlHover"),Ee=v("hlActive"),Ce=$._read();if(n.highlight=le||Ee||Ce?{...le&&{hover:le},...Ee&&{active:Ee},...Ce&&{accent:Ce}}:null,y&&(n.description=v("description").trim(),n.tile=_e._read(),n.chip=!F&&He.checked,F)){const Q=v("featureTone");n.panel=$t({heading:v("panelHeading"),link:{text:v("panelLinkText"),url:v("panelLinkUrl")},columns:v("panelColumns"),chipsLabel:v("panelChipsLabel"),feature:Q?{tone:Q,eyebrow:v("featureEyebrow"),title:v("featureTitle"),points:v("featurePoints").split(`
30
- `),button:{text:v("featureBtnText"),url:v("featureBtnUrl")}}:null})}xe=!0,B.close(!0),s()})}let V=null,yt=!1;function ln(){yt||!window.R?.use||(yt=!0,R.use((n,p,l)=>{const r=p?.path||"";return!(en.test(r)&&(n?.path||"")!==r)||!V?.dirty()?l():E.confirm(`You have unsaved changes to the menu "${De(V.name())}". Leave anyway? They are kept as a draft for your next visit.`).then(y=>{y?l():history.replaceState(null,"",`#${r}`)})}),M.subscribe("router:afterChange",({to:n}={})=>{if(V&&(n?.path||"")!==V.path){const p=V;V=null,p.dispose()}}))}function kt(n,p){const l=n.querySelector(".dm-plugin-banner-name"),r=l?.querySelector(".dm-plugin-banner-sep");if(!(!l||!r)){for(;r.nextSibling;)r.nextSibling.remove();l.appendChild(document.createTextNode(p))}}export const menuEditorView={templateUrl:"/admin/js/templates/menu-editor.html",async onMount(n){if(ln(),V){const e=V;V=null,e.dispose()}const p=[],l=e=>(p.push(e),e);let r=!1;const s=n.get(0).querySelector(".mex")||n.get(0),y=()=>!r&&s.isConnected,T=location.hash.replace(/^#/,""),d=location.hash.match(/^#\/menus\/edit\/([^?#]+)/),Y=d?decodeURIComponent(d[1]):null,L=!Y,X=`menu-editor.draft.${Y||"new"}`,_=E.loader(n.get(0),{type:"dots"});let g,re,ne,ce,oe,de,be;try{if(L)g={slug:"",name:"",description:"",items:[]};else try{g=await P.menus.get(Y)}catch(e){E.toast(`Failed to load menu: ${e.message||e}`,{type:"error"}),location.hash="#/menus";return}[re,ne,ce,oe,de,be]=await Promise.all([P.projects.list().catch(()=>[]),H.get("/api/auth/permissions-registry").catch(()=>({resources:[]})),P.collections.list().catch(()=>[]),P.get("/collections/roles/entries?limit=100").catch(()=>null),P.menuLocations.registry().catch(()=>[]),P.pages.list().catch(()=>[])])}finally{_.destroy()}if(!s.isConnected)return;const ye=(Array.isArray(oe)?oe:oe?.entries||[]).map(e=>({name:e.data?.name,label:e.data?.label,level:e.data?.level??99})).filter(e=>e.name).sort((e,o)=>o.level-e.level),D=!L&&Y===Zt;let Le=[];if(D&&(Le=await H.get("/api/sidebar/registered-items").catch(()=>(E.toast("Could not load the Tools - they are not shown, and saving keeps their places as they are.",{type:"warning",duration:8e3}),[])),!s.isConnected))return;const $e=e=>gt(D?It(Ht(e||[],Le,{forEditor:!0}),{leaveInHiddenFolders:!0}):e);let h=$e(g.items);const j=M.observable(!1),ue=M.observable(!1),Me=M.observable(""),Te=M.observable(0);let K="";const $=s.querySelector("#me-items-list");l(()=>$._disposeMenuHelp?.());function ke(){nn($,h,D),Te.value=h.filter(e=>!ve(e)).length}const N=()=>{ke(),Z()},J=()=>D?bt(h):new Set,pe=e=>h.find(o=>o.id===e);function me(e){requestAnimationFrame(()=>$.querySelector(`.menu-tree-row[data-id="${CSS.escape(e)}"]`)?.focus())}function _e(e){const o=b=>h.find(i=>!i.type&&!i.url&&!i.tool&&(i.key||"").toLowerCase()===b)||h.find(i=>!i.type&&!i.url&&!i.tool&&!i.key&&(i.text||"").toLowerCase()===b);let a=o(String(e.tool.folder||"").toLowerCase())||o(Pt);const c=String(e.tool.group||"").trim();if(a&&c){const b=Ot(a.key||Rt(a.text),c),i=u=>u!==e&&!u.type&&!u.url&&!u.tool;let k=h.find(u=>i(u)&&(u.key||"").toLowerCase()===b)||h.find(u=>i(u)&&u.parentId===a.id&&(!u.key||u.key.toLowerCase()===b)&&(u.text||"").toLowerCase()===c.toLowerCase());k||([k]=gt([{text:c,key:b,icon:Bt,synthesised:!0}],a.id),h.push(k)),a=k}e.parentId=a?a.id:null,h.splice(h.indexOf(e),1),h.push(e),Object.assign(e,{text:e.tool.defaults.text,icon:e.tool.defaults.icon,visibility:"",hidden:!1,badge:null,pill:null,colour:"",highlight:null,touched:!1}),e.tool={...e.tool,persisted:!1}}const He=e=>!J().has(e.id)&&!(e.tool&&!e.tool.orphan);async function Ie(e){const o=pe(e);if(!o||!He(o))return;const a=u=>{let ee=u;for(;ee;){if(ee.id===e)return!0;ee=h.find(W=>W.id===ee.parentId)}return!1},c=h.filter(u=>u.id!==e&&a(u));if(c.length&&!await E.confirm(`Remove "${De(o.text||o.type||"this item")}" and the ${c.length} item${c.length===1?"":"s"} beneath it?`))return;const b=J(),i=c.filter(u=>u.tool),k=c.filter(u=>!u.tool&&b.has(u.id));h=h.filter(u=>!a(u)||i.includes(u)||k.includes(u));for(const u of k)u.parentId=o.parentId??null;for(const u of i)u.tool.orphan?u.parentId=o.parentId??null:_e(u);N()}function we(e){const o=pe(e);!o||ve(o)||J().has(e)||(o.hidden=!o.hidden,o.touched=!0,N())}function F(e){const o=pe(e);!o||ve(o)||(o.locked=D&&J().has(o.id),sn(o,ne.resources||[],ce,ye,()=>{N(),me(e)},{cards:!D}))}function C(e){const o={id:Xe(),parentId:null,...e==="separator"||e==="theme-switcher"?{type:e}:e==="spacer"?{type:e,size:"md"}:{text:"",url:"/",icon:"",visibility:"",permission:"",hidden:!1,bundled:!1}};h.push(o),N(),ve(o)?me(o.id):F(o.id)}const O=e=>o=>{e(o)&&(N(),me(o))},Fe=O(e=>vt(h,e,-1)),ze=O(e=>vt(h,e,1)),Ue=O(e=>Kt(h,e)),Ne=O(e=>Yt(h,e));function Ze(e){const o=pe(e);if(!o)return[];const a=ve(o),c=J().has(e),b=Xt(h,e),i=b.findIndex(W=>W.id===e),k=o.tool,u=k&&(k.persisted||o.touched),ee=W=>()=>{const Pe=qt(h,e,W,Xe());N(),Pe&&!ve(Pe)?F(Pe.id):Pe&&me(Pe.id)};return[{header:a?{separator:"Separator",spacer:"Spacer","theme-switcher":"Theme switcher"}[o.type]:o.text||k?.label||"(untitled)"},...a?[]:[{label:"Edit\u2026",icon:"edit",action:()=>F(e)}],{type:"divider"},{label:"Add item below",icon:"plus",action:ee("item")},{label:"Add sub-item",icon:"corner-down-right",disabled:a,action:()=>{const W=zt(h,e,Xe());N(),W&&F(W.id)}},{label:"Add separator below",icon:"minus",action:ee("separator")},{label:"Add spacer below",icon:"move",action:ee("spacer")},...D?[]:[{label:"Add theme switcher below",icon:"palette",action:ee("theme-switcher")}],{type:"divider"},{label:"Move up",icon:"arrow-up",shortcut:"Alt+\u2191",disabled:i<=0,action:()=>Fe(e)},{label:"Move down",icon:"arrow-down",shortcut:"Alt+\u2193",disabled:i<0||i>=b.length-1,action:()=>ze(e)},{label:"Indent",icon:"chevron-right",shortcut:"Alt+\u2192",disabled:i<=0||ve(b[i-1]),action:()=>Ue(e)},{label:"Outdent",icon:"chevron-left",shortcut:"Alt+\u2190",disabled:o.parentId==null,action:()=>Ne(e)},{type:"divider"},...a?[]:[{label:o.hidden?"Show":"Hide",icon:o.hidden?"eye":"eye-off",disabled:c,action:()=>we(e)}],{label:"Duplicate",icon:"copy",disabled:!!k,action:()=>{const W=Wt(h,e,Xe);N(),W&&me(W.id)}},...k&&!k.orphan&&u?[{label:"Back to its default place",icon:"rotate-ccw",action:()=>{_e(o),N()}}]:[],{label:c?"Remove - always in the sidebar":k&&!k.orphan?"Remove - a Tool is hidden, not removed":"Remove\u2026",icon:"trash",danger:!0,disabled:!He(o),action:()=>Ie(e)}]}const et=E.contextMenu($,{cursor:"glyph",match:".menu-tree-row",inherit:!1,density:"compact",items:e=>Ze(e.dataset.id)});l(()=>et?.destroy?.());const he=_t($,()=>h,N,{items:".menu-tree-row",handle:".menu-tree-grip"});l(()=>he?.destroy());const We=e=>{const o=e.target.closest(".menu-tree-row");if(!o)return;const a=o.dataset.id;if(e.target.closest(".mex-kebab")){lt(e.target.closest(".mex-kebab"));return}if(e.target.closest(".me-hidden")){we(a);return}if(e.target.closest(".me-edit")){F(a);return}e.target.closest("select, .menu-tree-grip, button")||F(a)},Ke=e=>{const o=e.target.closest(".menu-tree-row");if(!o||e.target!==o){o&&e.key==="F10"&&e.shiftKey&&(e.preventDefault(),lt(o));return}const a=o.dataset.id;if(e.key==="F10"&&e.shiftKey)e.preventDefault(),lt(o);else if(e.key==="Enter")e.preventDefault(),F(a);else if(e.key==="Delete")e.preventDefault(),Ie(a);else if(e.altKey&&e.key==="ArrowUp")e.preventDefault(),Fe(a);else if(e.altKey&&e.key==="ArrowDown")e.preventDefault(),ze(a);else if(e.altKey&&e.key==="ArrowRight")e.preventDefault(),Ue(a);else if(e.altKey&&e.key==="ArrowLeft")e.preventDefault(),Ne(a);else if(e.key==="ArrowDown"||e.key==="ArrowUp"){const c=[...$.querySelectorAll(".menu-tree-row")],b=c.indexOf(o)+(e.key==="ArrowDown"?1:-1);c[b]&&(e.preventDefault(),c[b].focus())}},qe=e=>{if(!e.target.matches(".me-spacer-size"))return;const o=pe(e.target.closest(".menu-tree-row")?.dataset.id);o&&(o.size=e.target.value,Z())};$.addEventListener("click",We),$.addEventListener("keydown",Ke),$.addEventListener("change",qe),l(()=>{$.removeEventListener("click",We),$.removeEventListener("keydown",Ke),$.removeEventListener("change",qe)});const t=e=>n.find(e),Se=t("#me-float-accent"),Oe=t("#me-float-accent-hex"),fe=()=>{Oe.get(0).style.display=Se.val()==="__custom__"?"":"none"},tt=()=>Se.val()==="__custom__"?Oe.val():Se.val(),se=t("#me-highlight-accent"),q=t("#me-highlight-accent-hex"),B=()=>{q.get(0).style.display=se.val()==="__custom__"?"":"none"},Ge=()=>se.val()==="__custom__"?q.val():se.val(),Ve=()=>{const e=!!(t("#me-entrance-enabled").get(0)||{}).checked;t(".dm-entrance-field").each(function(){this.style.display=e?"":"none"});const o=t("#me-position").val()==="floating";t(".dm-float-field").each(function(){this.style.display=o?"":"none"}),o&&fe();const a=t("#me-orientation").val()==="vertical";t(".dm-vertical-field").each(function(){this.style.display=a?"":"none"}),t(".dm-dock-rail-field").each(function(){this.style.display=a&&!o?"":"none"}),t(".dm-dock-bar-field").each(function(){this.style.display=!a&&!o?"":"none"});const c=!!(t("#me-dock-collapsible").get(0)||{}).checked,b=!!(t("#me-dock-autohide").get(0)||{}).checked;t(".dm-dock-collapsed-field").each(function(){this.style.display=c&&!b?"":"none"});const i=!!(t("#me-float-collapsible").get(0)||{}).checked;t(".dm-float-collapsed-field").each(function(){this.style.display=o&&i?"":"none"});const k=!a&&!D;t(".dm-look-field").each(function(){this.style.display=k?"":"none"});const u=k&&t("#me-look-dropdown").val()==="cards";t(".dm-look-cards-field").each(function(){this.style.display=u?"":"none"})},xe=(e,o,a,c)=>{const b=t(e).get(0);b&&(b.innerHTML="",b.add(new Option(c,"")),o.forEach(i=>b.add(new Option(a[i]||i,i))))};xe("#me-highlight-hover",ut,mt,"- theme default -"),xe("#me-highlight-active",pt,ht,"- theme default -");{const e=t("#me-entrance-animation").get(0);e&&(e.innerHTML="",ot.forEach(o=>e.add(new Option(Ct[o]||o,o))))}const ge=t("#me-bind-slot"),Re=t("#me-bind-projects"),Ae=t("#me-bind-pages");ge.get(0).innerHTML='<option value="">- not bound -</option>'+(de||[]).map(e=>`<option value="${x(e.slot)}">${x(e.label||e.slot)} (${x(e.slot)})</option>`).join(""),Re.get(0).innerHTML=re.map(e=>`<option value="${x(e.slug)}">${x(e.name||e.slug)}</option>`).join(""),t("#me-bind-page-pick").get(0).innerHTML='<option value="">- pick a page -</option>'+be.map(e=>{const o=e.urlPath||e.url||"";return o?`<option value="${x(o)}">${x(e.title||o)} - ${x(o)}</option>`:""}).join("");const Be=()=>Ut({slot:ge.val(),projects:Array.from(Re.get(0).selectedOptions).map(e=>e.value),pagesText:Ae.val()});function v(){const e=Be(),o=t("#me-bind-summary");if(!e){o.html('<span class="text-muted">Not bound - this menu renders only where it is mapped or placed by a shortcode.</span>');return}const a=[];e.projects.length&&a.push(`pages in ${e.projects.map(i=>`<code>${x(i)}</code>`).join(", ")}`),e.pages.length&&a.push(`pages matching ${e.pages.map(i=>`<code>${x(i)}</code>`).join(", ")}`);const c=e.pages.filter(i=>!/^\/[^\s?#*]*(\/\*)?$|^\/\*$/.test(i)),b=c.length?`<div class="text-danger" style="margin-top:.4rem">Not valid page patterns: ${c.map(i=>`<code>${x(i)}</code>`).join(", ")}</div>`:"";o.html(a.length?`Takes over the <code>${x(e.slot)}</code> slot on ${a.join(" and ")}.${b}`:`<span class="text-warning">Slot <code>${x(e.slot)}</code> selected but no project or page chosen - the binding will never match.</span>`)}const{getProjectFromHash:m}=await import("../lib/project-context.js");if(!y())return;const U=L?m():null;t("#me-project").get(0).innerHTML='<option value="">- none -</option>'+re.map(e=>`<option value="${x(e.slug)}">${x(e.name||e.slug)}</option>`).join("");function z(e){h=$e(e.items),t("#me-variant").val(e.variant||""),t("#me-position").val(e.position||"");const o=t("#me-appearOnHover").get(0);o&&(o.checked=e.appearOnHover===!0),t("#me-float-anchor").val(e.float?.anchor||"TL"),t("#me-float-offsetX").val(e.float?.offsetX??""),t("#me-float-offsetY").val(e.float?.offsetY??""),t("#me-float-width").val(e.float?.width??""),t("#me-float-radius").val(e.float?.radius??""),t("#me-float-shadow").val(e.float?.shadow||""),t("#me-float-opacity").val(e.float?.opacity??""),t("#me-float-title").val(e.float?.title||"");for(const[i,k]of[["#me-float-collapsible",e.float?.collapsible],["#me-float-collapsed",e.float?.collapsed],["#me-float-movable",e.float?.movable],["#me-float-resizable",e.float?.resizable]]){const u=t(i).get(0);u&&(u.checked=k===!0)}const a=e.float?.accent||"";Se.val(a.startsWith("#")?"__custom__":a),a.startsWith("#")&&Oe.val(a),fe(),t("#me-orientation").val(e.orientation||""),t("#me-align").val(e.align||""),t("#me-mobile-hamburger").get(0).checked=e.mobile?.hamburgerOnly===!0,t("#me-mobile-brand").get(0).checked=e.mobile?.hideBrand===!0,t("#me-look-bar").val(e.look?.bar||""),t("#me-look-brand").val(e.look?.brand||""),t("#me-look-strip").val(e.look?.strip||""),t("#me-look-icons").val(e.look?.icons||""),t("#me-look-dropdown").val(e.look?.dropdown||""),t("#me-look-tiles").val(e.look?.tiles||""),t("#me-look-morph").get(0).checked=e.look?.morph===!0,t("#me-look-shrink").get(0).checked=e.look?.shrink===!0,t("#me-side").val(e.side||"left"),t("#me-dock-width").val(e.dock?.width??"");for(const i of["collapsible","collapsed","autohide","hideOnScroll"]){const k=t(`#me-dock-${i}`).get(0);k&&(k.checked=e.dock?.[i]===!0)}t("#me-class").val(e.class||""),t("#me-highlight-hover").val(e.highlight?.hover||""),t("#me-highlight-active").val(e.highlight?.active||"");const c=e.highlight?.accent||"";se.val(c.startsWith("#")?"__custom__":c),c.startsWith("#")&&q.val(c),B();{const i=t("#me-entrance-enabled").get(0);i&&(i.checked=e.entrance?.enabled===!0)}t("#me-entrance-animation").val(ot.includes(e.entrance?.animation)?e.entrance.animation:ot[0]),t("#me-entrance-stagger").val(e.entrance?.stagger??""),t("#me-entrance-duration").val(e.entrance?.duration??""),t("#me-fontFamily").val(e.style?.fontFamily||""),t("#me-fontSize").val(e.style?.fontSize||""),t("#me-fontWeight").val(e.style?.fontWeight||""),t("#me-letterSpacing").val(e.style?.letterSpacing||""),t("#me-iconSize").val(e.style?.iconSize||""),ge.val(e.binding?.slot||"");const b=new Set(e.binding?.projects||[]);Array.from(Re.get(0).options).forEach(i=>{i.selected=b.has(i.value)}),Ae.val((e.binding?.pages||[]).join(`
31
- `)),t("#me-slug").val(e.slug||""),t("#me-name").val(e.name||""),t("#me-description").val(e.description||""),t("#me-project").val(e.meta?.project||U||""),Ve(),v(),ke()}const A=e=>!!(t(e).get(0)||{}).checked;function le(){const e={variant:t("#me-variant").val(),position:t("#me-position").val(),appearOnHover:A("#me-appearOnHover"),floatAnchor:t("#me-float-anchor").val(),floatOffsetX:t("#me-float-offsetX").val(),floatOffsetY:t("#me-float-offsetY").val(),floatWidth:t("#me-float-width").val(),floatRadius:t("#me-float-radius").val(),floatShadow:t("#me-float-shadow").val(),floatAccent:tt(),floatOpacity:t("#me-float-opacity").val(),floatTitle:t("#me-float-title").val(),floatCollapsible:A("#me-float-collapsible"),floatCollapsed:A("#me-float-collapsed"),floatMovable:A("#me-float-movable"),floatResizable:A("#me-float-resizable"),highlightHover:t("#me-highlight-hover").val(),highlightActive:t("#me-highlight-active").val(),highlightAccent:Ge(),class:t("#me-class").val(),entranceEnabled:A("#me-entrance-enabled"),entranceAnimation:t("#me-entrance-animation").val(),entranceStagger:t("#me-entrance-stagger").val(),entranceDuration:t("#me-entrance-duration").val(),orientation:t("#me-orientation").val(),align:t("#me-align").val(),side:t("#me-side").val(),fontFamily:t("#me-fontFamily").val(),fontSize:t("#me-fontSize").val(),fontWeight:t("#me-fontWeight").val(),letterSpacing:t("#me-letterSpacing").val(),iconSize:t("#me-iconSize").val(),dockWidth:t("#me-dock-width").val(),dockCollapsible:A("#me-dock-collapsible"),dockCollapsed:A("#me-dock-collapsed"),dockAutohide:A("#me-dock-autohide"),mobileHamburgerOnly:A("#me-mobile-hamburger"),mobileHideBrand:A("#me-mobile-brand"),lookBar:t("#me-look-bar").val(),lookDropdown:t("#me-look-dropdown").val(),lookBrand:t("#me-look-brand").val(),lookStrip:t("#me-look-strip").val(),lookIcons:t("#me-look-icons").val(),lookTiles:t("#me-look-tiles").val(),lookMorph:A("#me-look-morph"),lookShrink:A("#me-look-shrink"),dockHideOnScroll:A("#me-dock-hideOnScroll")},o={slug:t("#me-slug").val(),name:t("#me-name").val(),description:t("#me-description").val(),project:t("#me-project").val()};return Gt(e,o,Be(),Dt(h),g.meta||{})}const Ee=e=>[...Vt(e),...ft(e.class).map(o=>`CSS classes: ${o} (Behaviour tab).`)];let Ce=!1,Q=null;function Z(){if(!K)return;const e=le();Q=e,j.value=Je(e)!==K,Me.value=j.peek()||Ce?Ee(e).join(" "):""}const Ye=e=>{e.target.closest("#me-items-list")||(e.target.matches("#me-position, #me-orientation, #me-look-dropdown, #me-float-collapsible, #me-dock-collapsible, #me-dock-autohide, #me-entrance-enabled")&&Ve(),e.target.matches("#me-float-accent")&&fe(),e.target.matches("#me-highlight-accent")&&B(),e.target.closest("#me-binding")&&v(),Z())};s.addEventListener("input",Ye),s.addEventListener("change",Ye),l(()=>{s.removeEventListener("input",Ye),s.removeEventListener("change",Ye)}),t("#me-bind-page-add").on("click",()=>{const e=t("#me-bind-page-pick").val();if(!e)return;const o=Ae.val().split(`
32
- `).map(a=>a.trim()).filter(Boolean);o.includes(e)||o.push(e),Ae.val(o.join(`
33
- `)),v(),Z()}),z(g),K=Je(le()),Z();const it=()=>{try{S.remove?S.remove(X):S.set(X,null)}catch{}};async function nt(){if(ue.peek())return;const e=le(),o=Ee(e);if(o.length){Ce=!0,Z(),E.toast(o.join(" "),{type:"warning",duration:7e3});return}ue.value=!0;let a=null;try{if(L)await P.menus.create(e);else if(e.slug!==g.slug){await P.menus.create(e);const c=await P.menuLocations.get();let b=!1;for(const[i,k]of Object.entries(c))k===g.slug&&(c[i]=e.slug,b=!0);b&&await P.menuLocations.save(c),await P.menus.remove(g.slug)}else{const c=await wt(e);if(!c)return;a=c.revision}if(K=Je(e),j.value=!1,it(),Ft("#/menus"),E.toast("Saved.",{type:"success"}),L||e.slug!==g.slug)location.hash="#/menus/edit/"+encodeURIComponent(e.slug);else{g={...g,...e,revision:a};for(const c of h)c.tool&&c.touched&&(c.tool={...c.tool,persisted:!0});ke(),K=Je(le()),Z(),kt(n.get(0),e.name||e.slug)}if(D)try{document.dispatchEvent(new CustomEvent("dm:sidebar-rebuild"))}catch{}}catch(c){E.toast(`Save failed: ${c.message||c}`,{type:"error"})}finally{ue.value=!1}}async function wt(e){try{return await P.menus.update(g.slug,{...e,revision:g.revision})}catch(a){if(a.status!==409)throw a}if(await E.confirm(`The menu "${De(g.name||g.slug)}" was changed somewhere else after you opened it - in another tab, by someone else, or on the server. Saving now would undo those changes.<br><br><strong>OK</strong> saves yours over them. <strong>Cancel</strong> loads the latest version, and offers your changes back as a draft.`))return P.menus.update(g.slug,e);try{S.set(X,{menu:e,base:K,at:new Date().toISOString()})}catch{}return j.value=!1,location.reload(),null}async function St(){!j.peek()||!await E.confirm("Throw away the changes you have not saved?")||(z(g),Z())}E.tabs(t("#me-tabs").get(0));const xt=M.applyBindings({dirty:j,saving:ue,problems:Me,itemCount:Te},s,{methods:{save:()=>nt(),discard:()=>St(),addItem:()=>C("item"),addSeparator:()=>C("separator"),addSpacer:()=>C("spacer"),addSwitcher:()=>C("theme-switcher")}});l(()=>xt.dispose()),l(st(s,{position:"bottom"})),D&&t("#me-add-switcher").hide(),kt(n.get(0),L?"New menu":g.name||g.slug),at(n,{id:"menu-editor-back",icon:"arrow-left",title:"All menus",onClick:()=>{location.hash="#/menus"}}),at(n,{id:"menu-editor-locations",icon:"map-pin",title:"Menu locations",onClick:()=>{location.hash="#/menu-locations"}}),at(n,{id:"menu-editor-save",icon:"save",title:"Save (Ctrl+S)",onClick:()=>nt()});const rt=e=>{if(!(!(e.ctrlKey||e.metaKey)||e.key!=="s")){if(e.preventDefault(),e.stopImmediatePropagation(),document.querySelector(".me-item-form")?.offsetParent){E.toast("Apply the item first (Ctrl+Enter), then Save.",{type:"info"});return}nt()}};document.addEventListener("keydown",rt,!0),l(()=>document.removeEventListener("keydown",rt,!0));const ct=()=>{if(!(!j.peek()||!Q))try{S.set(X,{menu:Q,base:K,at:new Date().toISOString()})}catch{}},dt=e=>{j.peek()&&(ct(),e.preventDefault(),e.returnValue="")};window.addEventListener("beforeunload",dt),l(()=>window.removeEventListener("beforeunload",dt)),V={path:T,dirty:()=>j.peek(),name:()=>t("#me-name").val()||g.name||g.slug||"new menu",dispose(){r=!0,ct(),p.splice(0).reverse().forEach(e=>{try{e()}catch{}})}},I.scan(s);let ie=null;try{ie=S.get(X)}catch{}if(ie?.menu){it();const e=ie.base&&ie.base!==K,o=ie.at?` (${Jt(ie.at)})`:"",a=L?"the new menu you started":`the menu "${De(g.name||g.slug)}"`,c=e?`You left unsaved changes to ${a}${o}, but the saved menu has changed since. Restore your version anyway?`:`You left unsaved changes to ${a}${o}. Restore them?`;await E.confirm(c)&&y()&&(z({...ie.menu,meta:{...g.meta||{},...ie.menu.meta||{}}}),Z())}}};
27
+ ${Ze}
28
+ </div>`),k(d.id)}}k(null),n._disposeMenuHelp?.(),n.innerHTML=l.join("")||'<p class="mex-note">No items yet - Add item, or right-click an item for more.</p>',n._disposeMenuHelp=lt(n),I.scan(n)}function f(n,m={},...i){const r=document.createElement(n);Object.assign(r,m);for(const l of i)l!=null&&r.append(l);return r}function w(n,m,i){const r=f("label",{className:"form-field"},f("span",{className:"form-label",textContent:n}),m),l=zt[n];if(l){const k=f("span");k.dataset.help=l+(i?" "+i:""),k.dataset.helpTitle=n,r.querySelector(".form-label").append(" ",k)}return i&&r.append(f("small",{className:"form-hint",textContent:i,style:"display:block;font-size:.78em;opacity:.7;margin-top:.25rem;line-height:1.35"})),r}function ln(n,m){const i=[["","- Everyone -"],["public","Public - anyone, incl. logged-out"],...(m||[]).map(l=>[l.name,`${l.label||l.name} and above`]),...(m||[]).filter(l=>l.level!==0).map(l=>[`=${l.name}`,`${l.label||l.name} only`]),["private","Private - super-admin only"]];n&&!i.some(([l])=>l===n)&&i.push([n,`${n} (custom)`]);const r=q(i,n||"");return r.name="visibility",r}function q(n,m){const i=f("select",{className:"form-select"});return n.forEach(([r,l])=>i.add(new Option(l,r))),i.value=m??"",i}function je(n,m){const i=typeof m=="string"&&m.startsWith("#"),r=q([["","- none -"],["primary","primary"],["success","success"],["danger","danger"],["warning","warning"],["info","info"],["neutral","neutral"],["__custom__","Custom\u2026"]],i?"__custom__":m||""),l=f("input",{type:"color",className:"form-input me-colour-hex",value:i?m:"#000000"});l.style.display=i?"":"none",r.addEventListener("change",()=>{l.style.display=r.value==="__custom__"?"":"none"});const k=w(n,r);return k.append(l),k._read=()=>r.value==="__custom__"?l.value:r.value,k}function rn(n,m){const i=f("input",{className:"form-input me-icon",name:"icon",value:m||""}),r=f("span",{className:"me-icon-preview"});m&&r.setAttribute("data-icon",m);const l=f("button",{type:"button",className:"btn btn-sm btn-ghost",textContent:"Browse\u2026"}),k=_=>{_?r.setAttribute("data-icon",_):r.removeAttribute("data-icon"),Domma.icons.scan(r.parentNode||r)};return l.addEventListener("click",()=>Tt(_=>{i.value=_,k(_)})),i.addEventListener("input",()=>k(i.value.trim())),w(n,f("div",{className:"me-icon-field"},i,l,r))}function Z(...n){return f("div",{className:"me-field-grid"},...n)}async function cn(n,m,i,r,l,{cards:k=!0}={}){const _=n.text||n.tool?.label||"",d=(p,...P)=>{const K=f("section",{className:"me-item-section"},f("h4",{className:"me-item-section-title",textContent:p}),f("div",{className:"me-item-section-body"},...P));return K.setAttribute("aria-label",p),K},V=w("Label",f("input",{className:"form-input",name:"text",value:n.text||""}),"The text shown for this item."),$=f("input",{className:"form-input",name:"url",value:n.url||""}),Y=w("URL",$,n.tool||n.locked?"A Tool's address is its identity, so it cannot be changed here.":"Where it links. Must start with /, #, https://, or mailto: . Leave blank for a parent that only groups sub-items.");(n.tool||n.locked)&&($.readOnly=!0);const N=rn("Icon",n.icon||""),g=ln(n.visibility||"",r),re=w("Visibility",g,n.locked?"Always in the sidebar for everyone who may use it, so it cannot be restricted here.":'Who can see this item. "Role and above" shows it to that role and anyone more senior; "Role only" shows it to holders of that role alone (and the super-admin). Blank = everyone.');n.locked&&(g.disabled=!0);const ee=q([["","- no permission gate -"],...(m||[]).map(p=>[p.key,p.label||p.key])],n.permission||"");ee.name="permission";const ce=w("Permission",ee,n.tool||n.locked?"A Tool is guarded by its own permission, which always applies.":"Hide unless the viewer holds this specific permission. Independent of Visibility - both must pass.");(n.tool||n.locked)&&(ee.disabled=!0);const te=w("Badge text",f("input",{className:"form-input",name:"badgeText",value:n.badge?.text||""})),de=q([["","- none -"],...(i||[]).map(p=>[p.slug,p.title||p.slug])],n.badge?.countFrom||"");de.name="badgeCount";const ye=w("Badge count from",de,"Show a live count of this collection\u2019s entries as the badge."),ne=je("Badge colour",n.badge?.variant||""),ke=q([["link","Link"],["pill","Pill"]],n.pill?"pill":"link");ke.name="renderAs";const j=w("Render as",ke,"Pill draws the item as a rounded chip. Pill styling applies to top-level navbar items."),$e=w("Pill style",q([["filled","Filled"],["outline","Outline"]],n.pill?.style||"filled"));$e.querySelector("select").name="pillStyle";const Le=je("Pill colour",n.pill?.variant||""),h=f("div",{className:"me-pill-wrap"},Z($e,Le));h.style.display=n.pill?"":"none",ke.addEventListener("change",()=>{h.style.display=ke.value==="pill"?"":"none"});const F=je("Text colour",n.colour||""),ue=q([["","- use the menu default -"],...pt.map(p=>[p,ft[p]||p])],n.highlight?.hover||"");ue.name="hlHover";const Fe=w("Hover effect",ue,"Overrides the menu-wide hover effect for this item only."),Te=q([["","- use the menu default -"],...ht.map(p=>[p,gt[p]||p])],n.highlight?.active||"");Te.name="hlActive";const W=w("When selected",Te,"How this item is marked when it points at the page being viewed."),L=je("Highlight colour",n.highlight?.accent||""),we=f("input",{className:"form-input",name:"class",value:n.class||"",placeholder:"nav-cta push-right",autocomplete:"off",spellcheck:!1}),O=w("CSS classes",we,"Your own class names, separated by spaces, added to this item's <li> - target the link with .your-class > a. Style them in Custom CSS."),X=f("small",{className:"text-danger",style:"display:none;margin-top:.25rem"});O.append(X);const me=f("textarea",{className:"form-input",name:"description",rows:2,maxLength:Ht,value:n.description||"",placeholder:"Answers every new lead in under a minute."}),pe=w("Description",me,"One short line under the label, shown when the menu's dropdowns are Cards."),_e=je("Tile colour",n.tile||""),He=f("input",{type:"checkbox",name:"chip",checked:!!n.chip,style:"width:auto;margin:0"}),Ie=f("label",{className:"form-field",style:"display:flex;gap:.5rem;align-items:center;font-weight:400"},He,f("span",{textContent:"Show as a small chip in the card's footer strip"})),Se=f("span");Se.dataset.helpTitle="Show as a small chip",Se.dataset.help="Place this sub-item in the compact chip strip at the bottom of its parent Cards dropdown instead of the main entries. Its label and destination remain the same. The parent card can provide a Chip strip label. This applies to sub-items in Cards dropdowns, rather than top-level navbar links.",Ie.append(Se);const z=n.parentId==null,A=n.panel||{},B=(p,P,K,Ce=80)=>f("input",{className:"form-input",name:p,value:P||"",placeholder:K,maxLength:Ce}),Me=w("Card heading",B("panelHeading",A.heading,"The crew - six agents, one job each"),"Small capitals over the entries."),ze=w("Link text",B("panelLinkText",A.link?.text,"Meet the crew",60)),Ue=w("Link URL",B("panelLinkUrl",A.link?.url,"/crew",500)),Ne=q([["","Automatic"],["1","1"],["2","2"],["3","3"],["4","4"]],A.columns?String(A.columns):"");Ne.name="panelColumns";const et=w("Columns",Ne),tt=w("Chip strip label",B("panelChipsLabel",A.chipsLabel,"Add to your crew",60),'Words before the chips - tick "Show as a small chip" on the sub-items that belong there.'),he=q([["","- no side box -"],["dark","Dark"],["light","Light"],["accent","Theme colour"]],A.feature?A.feature.tone||"dark":"");he.name="featureTone";const We=w("Side box",he,"A box down the right of the card - a call to action or a short list."),Ke=w("Box small heading",B("featureEyebrow",A.feature?.eyebrow,"Free - 20 minutes",60)),qe=w("Box title",B("featureTitle",A.feature?.title,"See it live")),t=w("Box points",f("textarea",{className:"form-input",name:"featurePoints",rows:3,value:(A.feature?.points||[]).join(`
29
+ `),placeholder:"One per line, up to six"})),fe=w("Button text",B("featureBtnText",A.feature?.button?.text,"Book a demo",60)),Ge=w("Button URL",B("featureBtnUrl",A.feature?.button?.url,"/book",500)),oe=f("div",{className:"me-feature-fields"},Z(Ke,qe),t,Z(fe,Ge));oe.style.display=he.value?"":"none",he.addEventListener("change",()=>{oe.style.display=he.value?"":"none"});const Oe=k?[d("Card link",f("small",{className:"form-hint",textContent:"Used with card dropdowns. Choose Cards on the Behaviour tab."}),pe,Z(_e,z?null:Ie)),...z?[d("Dropdown panel",Me,Z(ze,Ue),Z(et,tt)),d("Side box",We,oe)]:[]]:[],ge=f("button",{className:"btn btn-primary",textContent:"Apply",title:"Apply to the item (Ctrl+Enter) - Save the menu to keep it"}),ae=f("div",{className:"me-item-form"},d("Link",V,Y,N),d("Appearance",j,h,F),d("Hover & selection",Z(Fe,W),L),...Oe,d("Badge",Z(te,ne),ye),d("Access",Z(re,ce)),d("Custom styling",O),f("div",{className:"me-item-actions"},f("small",{className:"form-hint",textContent:"Apply updates this item. Save the menu to keep it."}),ge)),T=E.slideover({title:_?`Edit ${De(_)}`:"Edit menu item",size:"lg",position:"right"});T.element.appendChild(ae);const xe=()=>JSON.stringify([...ae.querySelectorAll("input, select, textarea")].map(p=>p.type==="checkbox"?p.checked:p.value)),Ve=xe();let Re=!1,Ae=!1;const Ye=lt(ae,{position:"bottom"});Ut(T,Ye);const Be=T.close.bind(T);T.close=async p=>{if(!Re&&p!==!0&&xe()!==Ve){if(Ae)return;Ae=!0;const P=await E.confirm("Discard the changes to this item?");if(Ae=!1,!P)return}return Re=!0,Be()},ae.addEventListener("keydown",p=>{(p.ctrlKey||p.metaKey)&&p.key==="Enter"&&(p.preventDefault(),ge.click())}),T.open();const Ee=T.element.closest(".dm-slideover")||T.element.querySelector(".dm-slideover")||T.element;Ee.style.setProperty("width",tn+"px","important"),Ee.style.setProperty("max-width","95vw","important"),Domma.icons.scan(ae);const b=p=>ae.querySelector(`[name="${p}"]`)?.value||"";ge.addEventListener("click",()=>{const p=vt(b("class"));if(p.length){X.textContent=p.join("; "),X.style.display="block",we.focus();return}n.class=$t(b("class")),n.text=b("text"),n.icon=b("icon"),n.locked||(n.visibility=b("visibility")),!n.tool&&!n.locked?(n.url=b("url"),n.permission=b("permission")):n.touched=!0;const P=b("badgeText"),K=b("badgeCount"),Ce=ne._read();if(n.badge=P||K?{...P&&{text:P},...K&&{countFrom:K},...Ce&&{variant:Ce}}:null,b("renderAs")==="pill"){const le=Le._read();n.pill={style:b("pillStyle")||"filled",...le&&{variant:le}}}else n.pill=null;n.colour=F._read();const ve=b("hlHover"),C=b("hlActive"),se=L._read();if(n.highlight=ve||C||se?{...ve&&{hover:ve},...C&&{active:C},...se&&{accent:se}}:null,k&&(n.description=b("description").trim(),n.tile=_e._read(),n.chip=!z&&He.checked,z)){const le=b("featureTone");n.panel=_t({heading:b("panelHeading"),link:{text:b("panelLinkText"),url:b("panelLinkUrl")},columns:b("panelColumns"),chipsLabel:b("panelChipsLabel"),feature:le?{tone:le,eyebrow:b("featureEyebrow"),title:b("featureTitle"),points:b("featurePoints").split(`
30
+ `),button:{text:b("featureBtnText"),url:b("featureBtnUrl")}}:null})}Re=!0,T.close(!0),l()})}let G=null,wt=!1;function dn(){wt||!window.R?.use||(wt=!0,R.use((n,m,i)=>{const r=m?.path||"";return!(on.test(r)&&(n?.path||"")!==r)||!G?.dirty()?i():E.confirm(`You have unsaved changes to the menu "${De(G.name())}". Leave anyway? They are kept as a draft for your next visit.`).then(k=>{k?i():history.replaceState(null,"",`#${r}`)})}),M.subscribe("router:afterChange",({to:n}={})=>{if(G&&(n?.path||"")!==G.path){const m=G;G=null,m.dispose()}}))}function St(n,m){const i=n.querySelector(".dm-plugin-banner-name"),r=i?.querySelector(".dm-plugin-banner-sep");if(!(!i||!r)){for(;r.nextSibling;)r.nextSibling.remove();i.appendChild(document.createTextNode(m))}}export const menuEditorView={templateUrl:"/admin/js/templates/menu-editor.html",async onMount(n){if(dn(),G){const e=G;G=null,e.dispose()}const m=[],i=e=>(m.push(e),e);let r=!1;const l=n.get(0).querySelector(".mex")||n.get(0),k=()=>!r&&l.isConnected,_=location.hash.replace(/^#/,""),d=location.hash.match(/^#\/menus\/edit\/([^?#]+)/),V=d?decodeURIComponent(d[1]):null,$=!V,Y=`menu-editor.draft.${V||"new"}`,N=E.loader(n.get(0),{type:"dots"});let g,re,ee,ce,te,de,ye;try{if($)g={slug:"",name:"",description:"",items:[]};else try{g=await D.menus.get(V)}catch(e){E.toast(`Failed to load menu: ${e.message||e}`,{type:"error"}),location.hash="#/menus";return}[re,ee,ce,te,de,ye]=await Promise.all([D.projects.list().catch(()=>[]),H.get("/api/auth/permissions-registry").catch(()=>({resources:[]})),D.collections.list().catch(()=>[]),D.get("/collections/roles/entries?limit=100").catch(()=>null),D.menuLocations.registry().catch(()=>[]),D.pages.list().catch(()=>[])])}finally{N.destroy()}if(!l.isConnected)return;const ke=(Array.isArray(te)?te:te?.entries||[]).map(e=>({name:e.data?.name,label:e.data?.label,level:e.data?.level??99})).filter(e=>e.name).sort((e,o)=>o.level-e.level),j=!$&&V===nn;let $e=[];if(j&&($e=await H.get("/api/sidebar/registered-items").catch(()=>(E.toast("Could not load the Tools - they are not shown, and saving keeps their places as they are.",{type:"warning",duration:8e3}),[])),!l.isConnected))return;const Le=e=>bt(j?Ot(Nt(e||[],$e,{forEditor:!0}),{leaveInHiddenFolders:!0}):e);let h=Le(g.items);const F=M.observable(!1),ue=M.observable(!1),Fe=M.observable(""),Te=M.observable(0);let W="";const L=l.querySelector("#me-items-list");i(()=>L._disposeMenuHelp?.());function we(){sn(L,h,j),Te.value=h.filter(e=>!be(e)).length}const O=()=>{we(),J()},X=()=>j?kt(h):new Set,me=e=>h.find(o=>o.id===e);function pe(e){requestAnimationFrame(()=>L.querySelector(`.menu-tree-row[data-id="${CSS.escape(e)}"]`)?.focus())}function _e(e){const o=y=>h.find(s=>!s.type&&!s.url&&!s.tool&&(s.key||"").toLowerCase()===y)||h.find(s=>!s.type&&!s.url&&!s.tool&&!s.key&&(s.text||"").toLowerCase()===y);let a=o(String(e.tool.folder||"").toLowerCase())||o(jt);const c=String(e.tool.group||"").trim();if(a&&c){const y=Bt(a.key||Pt(a.text),c),s=u=>u!==e&&!u.type&&!u.url&&!u.tool;let v=h.find(u=>s(u)&&(u.key||"").toLowerCase()===y)||h.find(u=>s(u)&&u.parentId===a.id&&(!u.key||u.key.toLowerCase()===y)&&(u.text||"").toLowerCase()===c.toLowerCase());v||([v]=bt([{text:c,key:y,icon:Dt,synthesised:!0}],a.id),h.push(v)),a=v}e.parentId=a?a.id:null,h.splice(h.indexOf(e),1),h.push(e),Object.assign(e,{text:e.tool.defaults.text,icon:e.tool.defaults.icon,visibility:"",hidden:!1,badge:null,pill:null,colour:"",highlight:null,touched:!1}),e.tool={...e.tool,persisted:!1}}const He=e=>!X().has(e.id)&&!(e.tool&&!e.tool.orphan);async function Ie(e){const o=me(e);if(!o||!He(o))return;const a=u=>{let Q=u;for(;Q;){if(Q.id===e)return!0;Q=h.find(U=>U.id===Q.parentId)}return!1},c=h.filter(u=>u.id!==e&&a(u));if(c.length&&!await E.confirm(`Remove "${De(o.text||o.type||"this item")}" and the ${c.length} item${c.length===1?"":"s"} beneath it?`))return;const y=X(),s=c.filter(u=>u.tool),v=c.filter(u=>!u.tool&&y.has(u.id));h=h.filter(u=>!a(u)||s.includes(u)||v.includes(u));for(const u of v)u.parentId=o.parentId??null;for(const u of s)u.tool.orphan?u.parentId=o.parentId??null:_e(u);O()}function Se(e){const o=me(e);!o||be(o)||X().has(e)||(o.hidden=!o.hidden,o.touched=!0,O())}function z(e){const o=me(e);!o||be(o)||(o.locked=j&&X().has(o.id),cn(o,ee.resources||[],ce,ke,()=>{O(),pe(e)},{cards:!j}))}function A(e){const o={id:Je(),parentId:null,...e==="separator"||e==="theme-switcher"?{type:e}:e==="spacer"?{type:e,size:"md"}:{text:"",url:"/",icon:"",visibility:"",permission:"",hidden:!1,bundled:!1}};h.push(o),O(),be(o)?pe(o.id):z(o.id)}const B=e=>o=>{e(o)&&(O(),pe(o))},Me=B(e=>yt(h,e,-1)),ze=B(e=>yt(h,e,1)),Ue=B(e=>Vt(h,e)),Ne=B(e=>Qt(h,e));function et(e){const o=me(e);if(!o)return[];const a=be(o),c=X().has(e),y=Zt(h,e),s=y.findIndex(U=>U.id===e),v=o.tool,u=v&&(v.persisted||o.touched),Q=U=>()=>{const Pe=Yt(h,e,U,Je());O(),Pe&&!be(Pe)?z(Pe.id):Pe&&pe(Pe.id)};return[{header:a?{separator:"Separator",spacer:"Spacer","theme-switcher":"Theme switcher"}[o.type]:o.text||v?.label||"(untitled)"},...a?[]:[{label:"Edit\u2026",icon:"edit",action:()=>z(e)}],{type:"divider"},{label:"Add item below",icon:"plus",action:Q("item")},{label:"Add sub-item",icon:"corner-down-right",disabled:a,action:()=>{const U=Kt(h,e,Je());O(),U&&z(U.id)}},{label:"Add separator below",icon:"minus",action:Q("separator")},{label:"Add spacer below",icon:"move",action:Q("spacer")},...j?[]:[{label:"Add theme switcher below",icon:"palette",action:Q("theme-switcher")}],{type:"divider"},{label:"Move up",icon:"arrow-up",shortcut:"Alt+\u2191",disabled:s<=0,action:()=>Me(e)},{label:"Move down",icon:"arrow-down",shortcut:"Alt+\u2193",disabled:s<0||s>=y.length-1,action:()=>ze(e)},{label:"Indent",icon:"chevron-right",shortcut:"Alt+\u2192",disabled:s<=0||be(y[s-1]),action:()=>Ue(e)},{label:"Outdent",icon:"chevron-left",shortcut:"Alt+\u2190",disabled:o.parentId==null,action:()=>Ne(e)},{type:"divider"},...a?[]:[{label:o.hidden?"Show":"Hide",icon:o.hidden?"eye":"eye-off",disabled:c,action:()=>Se(e)}],{label:"Duplicate",icon:"copy",disabled:!!v,action:()=>{const U=Gt(h,e,Je);O(),U&&pe(U.id)}},...v&&!v.orphan&&u?[{label:"Back to its default place",icon:"rotate-ccw",action:()=>{_e(o),O()}}]:[],{label:c?"Remove - always in the sidebar":v&&!v.orphan?"Remove - a Tool is hidden, not removed":"Remove\u2026",icon:"trash",danger:!0,disabled:!He(o),action:()=>Ie(e)}]}const tt=E.contextMenu(L,{cursor:"glyph",match:".menu-tree-row",inherit:!1,density:"compact",items:e=>et(e.dataset.id)});i(()=>tt?.destroy?.());const he=It(L,()=>h,O,{items:".menu-tree-row",handle:".menu-tree-grip"});i(()=>he?.destroy());const We=e=>{const o=e.target.closest(".menu-tree-row");if(!o)return;const a=o.dataset.id;if(e.target.closest(".mex-kebab")){it(e.target.closest(".mex-kebab"));return}if(e.target.closest(".me-hidden")){Se(a);return}if(e.target.closest(".me-edit")){z(a);return}e.target.closest("select, .menu-tree-grip, button")||z(a)},Ke=e=>{const o=e.target.closest(".menu-tree-row");if(!o||e.target!==o){o&&e.key==="F10"&&e.shiftKey&&(e.preventDefault(),it(o));return}const a=o.dataset.id;if(e.key==="F10"&&e.shiftKey)e.preventDefault(),it(o);else if(e.key==="Enter")e.preventDefault(),z(a);else if(e.key==="Delete")e.preventDefault(),Ie(a);else if(e.altKey&&e.key==="ArrowUp")e.preventDefault(),Me(a);else if(e.altKey&&e.key==="ArrowDown")e.preventDefault(),ze(a);else if(e.altKey&&e.key==="ArrowRight")e.preventDefault(),Ue(a);else if(e.altKey&&e.key==="ArrowLeft")e.preventDefault(),Ne(a);else if(e.key==="ArrowDown"||e.key==="ArrowUp"){const c=[...L.querySelectorAll(".menu-tree-row")],y=c.indexOf(o)+(e.key==="ArrowDown"?1:-1);c[y]&&(e.preventDefault(),c[y].focus())}},qe=e=>{if(!e.target.matches(".me-spacer-size"))return;const o=me(e.target.closest(".menu-tree-row")?.dataset.id);o&&(o.size=e.target.value,J())};L.addEventListener("click",We),L.addEventListener("keydown",Ke),L.addEventListener("change",qe),i(()=>{L.removeEventListener("click",We),L.removeEventListener("keydown",Ke),L.removeEventListener("change",qe)});const t=e=>n.find(e),fe=t("#me-fontFamily").get(0),Ge=Mt(fe,{label:"Font family"});i(()=>Ge.destroy());const oe=t("#me-float-accent"),Oe=t("#me-float-accent-hex"),ge=()=>{Oe.get(0).style.display=oe.val()==="__custom__"?"":"none"},ae=()=>oe.val()==="__custom__"?Oe.val():oe.val(),T=t("#me-highlight-accent"),xe=t("#me-highlight-accent-hex"),Ve=()=>{xe.get(0).style.display=T.val()==="__custom__"?"":"none"},Re=()=>T.val()==="__custom__"?xe.val():T.val(),Ae=()=>{const e=!!(t("#me-entrance-enabled").get(0)||{}).checked;t(".dm-entrance-field").each(function(){this.style.display=e?"":"none"});const o=t("#me-position").val()==="floating";t(".dm-float-field").each(function(){this.style.display=o?"":"none"}),o&&ge();const a=t("#me-orientation").val()==="vertical";t(".dm-vertical-field").each(function(){this.style.display=a?"":"none"}),t(".dm-dock-rail-field").each(function(){this.style.display=a&&!o?"":"none"}),t(".dm-dock-bar-field").each(function(){this.style.display=!a&&!o?"":"none"});const c=!!(t("#me-dock-collapsible").get(0)||{}).checked,y=!!(t("#me-dock-autohide").get(0)||{}).checked;t(".dm-dock-collapsed-field").each(function(){this.style.display=c&&!y?"":"none"});const s=!!(t("#me-float-collapsible").get(0)||{}).checked;t(".dm-float-collapsed-field").each(function(){this.style.display=o&&s?"":"none"});const v=!a&&!j;t(".dm-look-field").each(function(){this.style.display=v?"":"none"});const u=v&&t("#me-look-dropdown").val()==="cards";t(".dm-look-cards-field").each(function(){this.style.display=u?"":"none"})},Ye=(e,o,a,c)=>{const y=t(e).get(0);y&&(y.innerHTML="",y.add(new Option(c,"")),o.forEach(s=>y.add(new Option(a[s]||s,s))))};Ye("#me-highlight-hover",pt,ft,"- theme default -"),Ye("#me-highlight-active",ht,gt,"- theme default -");{const e=t("#me-entrance-animation").get(0);e&&(e.innerHTML="",at.forEach(o=>e.add(new Option(Lt[o]||o,o))))}const Be=t("#me-bind-slot"),Ee=t("#me-bind-projects"),b=t("#me-bind-pages");Be.get(0).innerHTML='<option value="">- not bound -</option>'+(de||[]).map(e=>`<option value="${x(e.slot)}">${x(e.label||e.slot)} (${x(e.slot)})</option>`).join(""),Ee.get(0).innerHTML=re.map(e=>`<option value="${x(e.slug)}">${x(e.name||e.slug)}</option>`).join(""),t("#me-bind-page-pick").get(0).innerHTML='<option value="">- pick a page -</option>'+ye.map(e=>{const o=e.urlPath||e.url||"";return o?`<option value="${x(o)}">${x(e.title||o)} - ${x(o)}</option>`:""}).join("");const p=()=>qt({slot:Be.val(),projects:Array.from(Ee.get(0).selectedOptions).map(e=>e.value),pagesText:b.val()});function P(){const e=p(),o=t("#me-bind-summary");if(!e){o.html('<span class="text-muted">Not bound - this menu renders only where it is mapped or placed by a shortcode.</span>');return}const a=[];e.projects.length&&a.push(`pages in ${e.projects.map(s=>`<code>${x(s)}</code>`).join(", ")}`),e.pages.length&&a.push(`pages matching ${e.pages.map(s=>`<code>${x(s)}</code>`).join(", ")}`);const c=e.pages.filter(s=>!/^\/[^\s?#*]*(\/\*)?$|^\/\*$/.test(s)),y=c.length?`<div class="text-danger" style="margin-top:.4rem">Not valid page patterns: ${c.map(s=>`<code>${x(s)}</code>`).join(", ")}</div>`:"";o.html(a.length?`Takes over the <code>${x(e.slot)}</code> slot on ${a.join(" and ")}.${y}`:`<span class="text-warning">Slot <code>${x(e.slot)}</code> selected but no project or page chosen - the binding will never match.</span>`)}const{getProjectFromHash:K}=await import("../lib/project-context.js");if(!k())return;const Ce=$?K():null;t("#me-project").get(0).innerHTML='<option value="">- none -</option>'+re.map(e=>`<option value="${x(e.slug)}">${x(e.name||e.slug)}</option>`).join("");function ve(e){h=Le(e.items),t("#me-variant").val(e.variant||""),t("#me-position").val(e.position||"");const o=t("#me-appearOnHover").get(0);o&&(o.checked=e.appearOnHover===!0),t("#me-float-anchor").val(e.float?.anchor||"TL"),t("#me-float-offsetX").val(e.float?.offsetX??""),t("#me-float-offsetY").val(e.float?.offsetY??""),t("#me-float-width").val(e.float?.width??""),t("#me-float-radius").val(e.float?.radius??""),t("#me-float-shadow").val(e.float?.shadow||""),t("#me-float-opacity").val(e.float?.opacity??""),t("#me-float-title").val(e.float?.title||"");for(const[s,v]of[["#me-float-collapsible",e.float?.collapsible],["#me-float-collapsed",e.float?.collapsed],["#me-float-movable",e.float?.movable],["#me-float-resizable",e.float?.resizable]]){const u=t(s).get(0);u&&(u.checked=v===!0)}const a=e.float?.accent||"";oe.val(a.startsWith("#")?"__custom__":a),a.startsWith("#")&&Oe.val(a),ge(),t("#me-orientation").val(e.orientation||""),t("#me-align").val(e.align||""),t("#me-mobile-hamburger").get(0).checked=e.mobile?.hamburgerOnly===!0,t("#me-mobile-brand").get(0).checked=e.mobile?.hideBrand===!0,t("#me-look-bar").val(e.look?.bar||""),t("#me-look-brand").val(e.look?.brand||""),t("#me-look-strip").val(e.look?.strip||""),t("#me-look-icons").val(e.look?.icons||""),t("#me-look-dropdown").val(e.look?.dropdown||""),t("#me-look-tiles").val(e.look?.tiles||""),t("#me-look-morph").get(0).checked=e.look?.morph===!0,t("#me-look-shrink").get(0).checked=e.look?.shrink===!0,t("#me-side").val(e.side||"left"),t("#me-dock-width").val(e.dock?.width??"");for(const s of["collapsible","collapsed","autohide","hideOnScroll"]){const v=t(`#me-dock-${s}`).get(0);v&&(v.checked=e.dock?.[s]===!0)}t("#me-class").val(e.class||""),t("#me-highlight-hover").val(e.highlight?.hover||""),t("#me-highlight-active").val(e.highlight?.active||"");const c=e.highlight?.accent||"";T.val(c.startsWith("#")?"__custom__":c),c.startsWith("#")&&xe.val(c),Ve();{const s=t("#me-entrance-enabled").get(0);s&&(s.checked=e.entrance?.enabled===!0)}t("#me-entrance-animation").val(at.includes(e.entrance?.animation)?e.entrance.animation:at[0]),t("#me-entrance-stagger").val(e.entrance?.stagger??""),t("#me-entrance-duration").val(e.entrance?.duration??"");{const s=e.style?.fontFamily||"";if(fe.querySelector("option[data-custom]")?.remove(),s&&![...fe.options].some(v=>v.value===s)){const v=new Option(`${s} (custom)`,s);v.dataset.custom="1",fe.add(v,1)}fe.value=s,Ge.refresh()}t("#me-fontSize").val(e.style?.fontSize||""),t("#me-fontWeight").val(e.style?.fontWeight||""),t("#me-letterSpacing").val(e.style?.letterSpacing||""),t("#me-iconSize").val(e.style?.iconSize||""),Be.val(e.binding?.slot||"");const y=new Set(e.binding?.projects||[]);Array.from(Ee.get(0).options).forEach(s=>{s.selected=y.has(s.value)}),b.val((e.binding?.pages||[]).join(`
31
+ `)),t("#me-slug").val(e.slug||""),t("#me-name").val(e.name||""),t("#me-description").val(e.description||""),t("#me-project").val(e.meta?.project||Ce||""),Ae(),P(),we()}const C=e=>!!(t(e).get(0)||{}).checked;function se(){const e={variant:t("#me-variant").val(),position:t("#me-position").val(),appearOnHover:C("#me-appearOnHover"),floatAnchor:t("#me-float-anchor").val(),floatOffsetX:t("#me-float-offsetX").val(),floatOffsetY:t("#me-float-offsetY").val(),floatWidth:t("#me-float-width").val(),floatRadius:t("#me-float-radius").val(),floatShadow:t("#me-float-shadow").val(),floatAccent:ae(),floatOpacity:t("#me-float-opacity").val(),floatTitle:t("#me-float-title").val(),floatCollapsible:C("#me-float-collapsible"),floatCollapsed:C("#me-float-collapsed"),floatMovable:C("#me-float-movable"),floatResizable:C("#me-float-resizable"),highlightHover:t("#me-highlight-hover").val(),highlightActive:t("#me-highlight-active").val(),highlightAccent:Re(),class:t("#me-class").val(),entranceEnabled:C("#me-entrance-enabled"),entranceAnimation:t("#me-entrance-animation").val(),entranceStagger:t("#me-entrance-stagger").val(),entranceDuration:t("#me-entrance-duration").val(),orientation:t("#me-orientation").val(),align:t("#me-align").val(),side:t("#me-side").val(),fontFamily:t("#me-fontFamily").val(),fontSize:t("#me-fontSize").val(),fontWeight:t("#me-fontWeight").val(),letterSpacing:t("#me-letterSpacing").val(),iconSize:t("#me-iconSize").val(),dockWidth:t("#me-dock-width").val(),dockCollapsible:C("#me-dock-collapsible"),dockCollapsed:C("#me-dock-collapsed"),dockAutohide:C("#me-dock-autohide"),mobileHamburgerOnly:C("#me-mobile-hamburger"),mobileHideBrand:C("#me-mobile-brand"),lookBar:t("#me-look-bar").val(),lookDropdown:t("#me-look-dropdown").val(),lookBrand:t("#me-look-brand").val(),lookStrip:t("#me-look-strip").val(),lookIcons:t("#me-look-icons").val(),lookTiles:t("#me-look-tiles").val(),lookMorph:C("#me-look-morph"),lookShrink:C("#me-look-shrink"),dockHideOnScroll:C("#me-dock-hideOnScroll")},o={slug:t("#me-slug").val(),name:t("#me-name").val(),description:t("#me-description").val(),project:t("#me-project").val()};return Xt(e,o,p(),Ft(h),g.meta||{})}const le=e=>[...Jt(e),...vt(e.class).map(o=>`CSS classes: ${o} (Behaviour tab).`)];let rt=!1,nt=null;function J(){if(!W)return;const e=se();nt=e,F.value=Qe(e)!==W,Fe.value=F.peek()||rt?le(e).join(" "):""}const Xe=e=>{e.target.closest("#me-items-list")||(e.target.matches("#me-position, #me-orientation, #me-look-dropdown, #me-float-collapsible, #me-dock-collapsible, #me-dock-autohide, #me-entrance-enabled")&&Ae(),e.target.matches("#me-float-accent")&&ge(),e.target.matches("#me-highlight-accent")&&Ve(),e.target.closest("#me-binding")&&P(),J())};l.addEventListener("input",Xe),l.addEventListener("change",Xe),i(()=>{l.removeEventListener("input",Xe),l.removeEventListener("change",Xe)}),t("#me-bind-page-add").on("click",()=>{const e=t("#me-bind-page-pick").val();if(!e)return;const o=b.val().split(`
32
+ `).map(a=>a.trim()).filter(Boolean);o.includes(e)||o.push(e),b.val(o.join(`
33
+ `)),P(),J()}),ve(g),W=Qe(se()),J();const ct=()=>{try{S.remove?S.remove(Y):S.set(Y,null)}catch{}};async function ot(){if(ue.peek())return;const e=se(),o=le(e);if(o.length){rt=!0,J(),E.toast(o.join(" "),{type:"warning",duration:7e3});return}ue.value=!0;let a=null;try{if($)await D.menus.create(e);else if(e.slug!==g.slug){await D.menus.create(e);const c=await D.menuLocations.get();let y=!1;for(const[s,v]of Object.entries(c))v===g.slug&&(c[s]=e.slug,y=!0);y&&await D.menuLocations.save(c),await D.menus.remove(g.slug)}else{const c=await xt(e);if(!c)return;a=c.revision}if(W=Qe(e),F.value=!1,ct(),Wt("#/menus"),E.toast("Saved.",{type:"success"}),$||e.slug!==g.slug)location.hash="#/menus/edit/"+encodeURIComponent(e.slug);else{g={...g,...e,revision:a};for(const c of h)c.tool&&c.touched&&(c.tool={...c.tool,persisted:!0});we(),W=Qe(se()),J(),St(n.get(0),e.name||e.slug)}if(j)try{document.dispatchEvent(new CustomEvent("dm:sidebar-rebuild"))}catch{}}catch(c){E.toast(`Save failed: ${c.message||c}`,{type:"error"})}finally{ue.value=!1}}async function xt(e){try{return await D.menus.update(g.slug,{...e,revision:g.revision})}catch(a){if(a.status!==409)throw a}if(await E.confirm(`The menu "${De(g.name||g.slug)}" was changed somewhere else after you opened it - in another tab, by someone else, or on the server. Saving now would undo those changes.<br><br><strong>OK</strong> saves yours over them. <strong>Cancel</strong> loads the latest version, and offers your changes back as a draft.`))return D.menus.update(g.slug,e);try{S.set(Y,{menu:e,base:W,at:new Date().toISOString()})}catch{}return F.value=!1,location.reload(),null}async function At(){!F.peek()||!await E.confirm("Throw away the changes you have not saved?")||(ve(g),J())}E.tabs(t("#me-tabs").get(0));const Et=M.applyBindings({dirty:F,saving:ue,problems:Fe,itemCount:Te},l,{methods:{save:()=>ot(),discard:()=>At(),addItem:()=>A("item"),addSeparator:()=>A("separator"),addSpacer:()=>A("spacer"),addSwitcher:()=>A("theme-switcher")}});i(()=>Et.dispose()),i(lt(l,{position:"bottom"})),j&&t("#me-add-switcher").hide(),St(n.get(0),$?"New menu":g.name||g.slug),st(n,{id:"menu-editor-back",icon:"arrow-left",title:"All menus",onClick:()=>{location.hash="#/menus"}}),st(n,{id:"menu-editor-locations",icon:"map-pin",title:"Menu locations",onClick:()=>{location.hash="#/menu-locations"}}),st(n,{id:"menu-editor-save",icon:"save",title:"Save (Ctrl+S)",onClick:()=>ot()});const dt=e=>{if(!(!(e.ctrlKey||e.metaKey)||e.key!=="s")){if(e.preventDefault(),e.stopImmediatePropagation(),document.querySelector(".me-item-form")?.offsetParent){E.toast("Apply the item first (Ctrl+Enter), then Save.",{type:"info"});return}ot()}};document.addEventListener("keydown",dt,!0),i(()=>document.removeEventListener("keydown",dt,!0));const ut=()=>{if(!(!F.peek()||!nt))try{S.set(Y,{menu:nt,base:W,at:new Date().toISOString()})}catch{}},mt=e=>{F.peek()&&(ut(),e.preventDefault(),e.returnValue="")};window.addEventListener("beforeunload",mt),i(()=>window.removeEventListener("beforeunload",mt)),G={path:_,dirty:()=>F.peek(),name:()=>t("#me-name").val()||g.name||g.slug||"new menu",dispose(){r=!0,ut(),m.splice(0).reverse().forEach(e=>{try{e()}catch{}})}},I.scan(l);let ie=null;try{ie=S.get(Y)}catch{}if(ie?.menu){ct();const e=ie.base&&ie.base!==W,o=ie.at?` (${en(ie.at)})`:"",a=$?"the new menu you started":`the menu "${De(g.name||g.slug)}"`,c=e?`You left unsaved changes to ${a}${o}, but the saved menu has changed since. Restore your version anyway?`:`You left unsaved changes to ${a}${o}. Restore them?`;await E.confirm(c)&&k()&&(ve({...ie.menu,meta:{...g.meta||{},...ie.menu.meta||{}}}),J())}}};