domma-cms 1.6.9 → 1.6.11
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.
- package/CLAUDE.md +1 -1
- package/admin/js/lib/hotkeys.js +1 -1
- package/admin/js/lib/layouts-arrange.js +1 -1
- package/admin/js/lib/menu-editor-arrange.js +2 -2
- package/admin/js/lib/menu-rows.js +1 -1
- package/admin/js/lib/menu-tree.js +1 -1
- package/admin/js/lib/shortcode-registry.js +1 -1
- package/admin/js/lib/sidebar-grouping.js +1 -1
- package/admin/js/lib/sidebar-renderer.js +1 -1
- package/admin/js/templates/docs/usage-navigation.html +1 -1
- package/admin/js/templates/docs/usage-shortcodes.html +4 -0
- package/admin/js/templates/layouts.html +2 -1
- package/admin/js/templates/menu-editor.html +1 -0
- package/admin/js/views/layouts.js +8 -4
- package/admin/js/views/menu-editor.js +20 -15
- package/package.json +1 -1
- package/public/css/site.css +1 -1
- package/public/css/theme-switcher.css +1 -1
- package/public/js/site.js +1 -1
- package/public/js/theme-switcher.js +1 -1
- package/server/routes/api/layouts.js +1 -0
- package/server/services/markdown.js +49 -1
- package/server/services/menuRender.js +4 -0
- package/server/services/menus.js +19 -1
- package/server/services/renderer.js +28 -8
- package/server/templates/page.html +3 -3
|
@@ -1,25 +1,30 @@
|
|
|
1
|
-
import{api as j}from"../api.js";import{colourToCss as kt,HIGHLIGHT_HOVER as st,HIGHLIGHT_ACTIVE as
|
|
2
|
-
<div class="menu-tree-row menu-tree-row--separator" data-id="${
|
|
1
|
+
import{api as j}from"../api.js";import{colourToCss as kt,HIGHLIGHT_HOVER as st,HIGHLIGHT_ACTIVE as it,HIGHLIGHT_HOVER_LABELS as lt,HIGHLIGHT_ACTIVE_LABELS as rt,cssClassProblems as ct,normaliseCssClasses as St}from"/public/js/menu-decor.mjs?v=20261009-hover-darken";import{openIconPicker as $t}from"../lib/card-builder.js";import{sortableMenuRows as xt}from"../lib/menu-drag.js";import{placeTools as Et,ensureLockedTools as At,isLockedUrl as Ct,groupKeyFor as Lt,slugify as _t,GROUP_ICON as It,TOOLS_FOLDER_KEY as Ht}from"../lib/sidebar-grouping.js";import{flatten as dt,nest as Tt,uid as _e}from"../lib/menu-rows.js";import{addBannerAction as qe}from"../lib/plugin-chrome.js";import{helpPopovers as Rt}from"../lib/help-popover.js";import{onceClosed as jt,openMenuAt as Ue,sidebarCount as Dt}from"../lib/tool-kit.js";import{addChild as Nt,bindingFrom as Ot,duplicateRow as Pt,indentRow as Ft,insertBelow as Bt,isStructural as oe,menuFromForm as zt,menuProblems as Mt,moveRow as ut,outdentRow as Kt,siblingsOf as Wt,snapshot as Ie}from"../lib/menu-editor-arrange.js";import{fmtDateTime as qt}from"../lib/dates.js";const Ut=760,Gt="admin-sidebar",Vt=/^\/menus\/(new|edit\/[^?#]+)(\?.*)?$/;function b(t){return String(t||"").replace(/&/g,"&").replace(/"/g,""").replace(/</g,"<")}const He=t=>String(t??"").replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""");function Yt(t,c){let i=0,l=c.find(s=>s.id===t);for(;l&&l.parentId;)i++,l=c.find(s=>s.id===l.parentId);return i}function mt(t){const c=new Set,i=new Set,l=s=>{for(const g of t.filter(w=>w.parentId===s))!g.type&&Ct(g.url)&&!i.has(g.url)&&(i.add(g.url),c.add(g.id)),l(g.id)};return l(null),c}const Te='<button type="button" class="btn btn-sm btn-ghost mex-kebab" aria-label="Actions" title="Actions (right-click, or Shift+F10)">\u22EE</button>';function Xt(t,c,i=!1){const l=i?mt(c):new Set,s=[];function g(w){for(const m of c.filter(F=>F.parentId===w)){const A=`style="margin-left:${Yt(m.id,c)*28}px"`;if(m.type==="separator"){s.push(`
|
|
2
|
+
<div class="menu-tree-row menu-tree-row--separator" data-id="${m.id}" tabindex="0" ${A}>
|
|
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
|
-
${
|
|
6
|
-
</div>`);continue}if(
|
|
7
|
-
<div class="menu-tree-row menu-tree-row--spacer" data-id="${
|
|
5
|
+
${Te}
|
|
6
|
+
</div>`);continue}if(m.type==="spacer"){const te=["xs","sm","md","lg","xl","flex"].map(B=>`<option value="${B}"${(m.size||"md")===B?" selected":""}>${B==="flex"?"flexible":B}</option>`).join("");s.push(`
|
|
7
|
+
<div class="menu-tree-row menu-tree-row--spacer" data-id="${m.id}" tabindex="0" ${A}>
|
|
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
11
|
<select class="form-input me-spacer-size" title="Spacer size - flexible fills the leftover room" aria-label="Spacer size">${te}</select>
|
|
12
12
|
</span>
|
|
13
|
-
${
|
|
14
|
-
</div>`);continue}
|
|
15
|
-
|
|
13
|
+
${Te}
|
|
14
|
+
</div>`);continue}if(m.type==="theme-switcher"){s.push(`
|
|
15
|
+
<div class="menu-tree-row menu-tree-row--switcher" data-id="${m.id}" tabindex="0" ${A}>
|
|
16
|
+
<span class="menu-tree-grip" data-icon="grip-vertical" data-icon-size="18" title="Drag to move"></span>
|
|
17
|
+
<span class="me-sep-line"><span class="me-sep-label"><span data-icon="palette"></span> Theme switcher - the themes chosen under Theme > Theme switcher</span></span>
|
|
18
|
+
${Te}
|
|
19
|
+
</div>`);continue}const X=m.badge&&(m.badge.text||m.badge.countFrom)?`<span class="dm-menu-badge">${b(String(m.badge.text||"#"))}</span>`:"",C=m.tool,h=C&&(C.persisted||m.touched),W=C?C.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="${h?"A Tool, placed here by this menu":"A Tool in its default place - move or edit it to place it here"}">${b(C.source||"Tool")}${h?"":" \xB7 default"}</span>`:"",ae=l.has(m.id),ee=kt(m.colour),q=ee?` style="color:${b(ee)}"`:"",se=ae?'<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 ${m.hidden?"active":""}" title="${m.hidden?"Hidden - click to show":"Hide"}" aria-label="${m.hidden?"Show":"Hide"}" aria-pressed="${m.hidden?"true":"false"}"><span data-icon="${m.hidden?"eye-off":"eye"}"></span></button>`;s.push(`
|
|
20
|
+
<div class="menu-tree-row menu-tree-row--slim${m.hidden?" menu-tree-row--hidden":""}${C?" menu-tree-row--tool":""}${C&&!h?" menu-tree-row--default":""}" data-id="${m.id}" tabindex="0" ${A}>
|
|
16
21
|
<span class="menu-tree-grip" data-icon="grip-vertical" data-icon-size="18" title="Drag to move"></span>
|
|
17
|
-
<span class="me-row-label${!
|
|
18
|
-
<span class="me-row-url">${b(
|
|
19
|
-
${
|
|
22
|
+
<span class="me-row-label${!m.text&&!C?" mex-untitled":""}"${q}>${b(m.text||C?.label||"(no label - click to add one)")}${X}${W}</span>
|
|
23
|
+
<span class="me-row-url">${b(m.url||"")}</span>
|
|
24
|
+
${se}
|
|
20
25
|
<button type="button" class="btn btn-sm btn-ghost me-edit" title="Edit" aria-label="Edit"><span data-icon="edit"></span></button>
|
|
21
|
-
${
|
|
22
|
-
</div>`),g(f.id)}}g(null),t.innerHTML=s.join("")||'<p class="mex-note">No items yet - Add item, or right-click an item for more.</p>',I.scan(t)}function y(t,c={},...l){const i=document.createElement(t);Object.assign(i,c);for(const s of l)s!=null&&i.append(s);return i}function T(t,c,l){const i=y("label",{className:"form-field"},y("span",{className:"form-label",textContent:t}),c);return l&&i.append(y("small",{className:"form-hint",textContent:l,style:"display:block;font-size:.78em;opacity:.7;margin-top:.25rem;line-height:1.35"})),i}function Jt(t,c){const l=[["","- Everyone -"],["public","Public - anyone, incl. logged-out"],...(c||[]).map(s=>[s.name,`${s.label||s.name} and above`]),...(c||[]).filter(s=>s.level!==0).map(s=>[`=${s.name}`,`${s.label||s.name} only`]),["private","Private - super-admin only"]];t&&!l.some(([s])=>s===t)&&l.push([t,`${t} (custom)`]);const i=Z(l,t||"");return i.name="visibility",i}function Z(t,c){const l=y("select",{className:"form-select"});return t.forEach(([i,s])=>l.add(new Option(s,i))),l.value=c??"",l}function Re(t,c){const l=typeof c=="string"&&c.startsWith("#"),i=Z([["","- none -"],["primary","primary"],["success","success"],["danger","danger"],["warning","warning"],["info","info"],["neutral","neutral"],["__custom__","Custom\u2026"]],l?"__custom__":c||""),s=y("input",{type:"color",className:"form-input me-colour-hex",value:l?c:"#000000"});s.style.display=l?"":"none",i.addEventListener("change",()=>{s.style.display=i.value==="__custom__"?"":"none"});const g=T(t,i);return g.append(s),g._read=()=>i.value==="__custom__"?s.value:i.value,g}function Qt(t,c){const l=y("input",{className:"form-input me-icon",name:"icon",value:c||""}),i=y("span",{className:"me-icon-preview"});c&&i.setAttribute("data-icon",c);const s=y("button",{type:"button",className:"btn btn-sm btn-ghost",textContent:"Browse\u2026"}),g=w=>{w?i.setAttribute("data-icon",w):i.removeAttribute("data-icon"),Domma.icons.scan(i.parentNode||i)};return s.addEventListener("click",()=>$t(w=>{l.value=w,g(w)})),l.addEventListener("input",()=>g(l.value.trim())),T(t,y("div",{className:"me-icon-field"},l,s,i))}function Te(...t){return y("div",{className:"me-field-grid"},...t)}async function Zt(t,c,l,i,s){const g=t.text||t.tool?.label||"",w=u=>y("h4",{className:"me-form-section",textContent:u}),f=T("Label",y("input",{className:"form-input",name:"text",value:t.text||""}),"The text shown for this item."),P=y("input",{className:"form-input",name:"url",value:t.url||""}),_=T("URL",P,t.tool||t.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.");(t.tool||t.locked)&&(P.readOnly=!0);const Y=Qt("Icon",t.icon||""),A=Jt(t.visibility||"",i),h=T("Visibility",A,t.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.');t.locked&&(A.disabled=!0);const K=Z([["","- no permission gate -"],...(c||[]).map(u=>[u.key,u.label||u.key])],t.permission||"");K.name="permission";const oe=T("Permission",K,t.tool||t.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.");(t.tool||t.locked)&&(K.disabled=!0);const ee=T("Badge text",y("input",{className:"form-input",name:"badgeText",value:t.badge?.text||""})),W=Z([["","- none -"],...(l||[]).map(u=>[u.slug,u.title||u.slug])],t.badge?.countFrom||"");W.name="badgeCount";const ae=T("Badge count from",W,"Show a live count of this collection\u2019s entries as the badge."),te=Re("Badge colour",t.badge?.variant||""),F=Z([["link","Link"],["pill","Pill"]],t.pill?"pill":"link");F.name="renderAs";const je=T("Render as",F,"Pill draws the item as a rounded chip. Pill styling applies to top-level navbar items."),q=T("Pill style",Z([["filled","Filled"],["outline","Outline"]],t.pill?.style||"filled"));q.querySelector("select").name="pillStyle";const me=Re("Pill colour",t.pill?.variant||""),se=y("div",{className:"me-pill-wrap"},Te(q,me));se.style.display=t.pill?"":"none",F.addEventListener("change",()=>{se.style.display=F.value==="pill"?"":"none"});const m=Re("Text colour",t.colour||""),D=Z([["","- use the menu default -"],...st.map(u=>[u,it[u]||u])],t.highlight?.hover||"");D.name="hlHover";const le=T("Hover effect",D,"Overrides the menu-wide hover effect for this item only."),pe=Z([["","- use the menu default -"],...lt.map(u=>[u,rt[u]||u])],t.highlight?.active||"");pe.name="hlActive";const Se=T("When selected",pe,"How this item is marked when it points at the page being viewed."),B=Re("Highlight colour",t.highlight?.accent||""),C=y("input",{className:"form-input",name:"class",value:t.class||"",placeholder:"nav-cta push-right",autocomplete:"off",spellcheck:!1}),ie=T("CSS classes",C,"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."),L=y("small",{className:"text-danger",style:"display:none;margin-top:.25rem"});ie.append(L);const U=y("button",{className:"btn btn-primary",textContent:"Apply",title:"Apply to the item (Ctrl+Enter) - Save the menu to keep it"}),N=y("div",{className:"me-item-form"},w("Link"),f,_,Y,w("Access"),Te(h,oe),w("Badge"),Te(ee,te),ae,w("Appearance"),je,se,m,w("Highlighting"),Te(le,Se),B,w("Styling"),ie,U),x=E.slideover({title:g?`Edit ${He(g)}`:"Edit menu item",size:"lg",position:"right"});x.element.appendChild(N);const fe=()=>JSON.stringify([...N.querySelectorAll("input, select, textarea")].map(u=>u.type==="checkbox"?u.checked:u.value)),$e=fe();let re=!1,ce=!1;jt(x);const G=x.close.bind(x);x.close=async u=>{if(!re&&u!==!0&&fe()!==$e){if(ce)return;ce=!0;const X=await E.confirm("Discard the changes to this item?");if(ce=!1,!X)return}return re=!0,G()},N.addEventListener("keydown",u=>{(u.ctrlKey||u.metaKey)&&u.key==="Enter"&&(u.preventDefault(),U.click())}),x.open();const de=x.element.closest(".dm-slideover")||x.element.querySelector(".dm-slideover")||x.element;de.style.setProperty("width",Ut+"px","important"),de.style.setProperty("max-width","95vw","important"),Domma.icons.scan(N);const k=u=>N.querySelector(`[name="${u}"]`)?.value||"";U.addEventListener("click",()=>{const u=ct(k("class"));if(u.length){L.textContent=u.join("; "),L.style.display="block",C.focus();return}t.class=St(k("class")),t.text=k("text"),t.icon=k("icon"),t.locked||(t.visibility=k("visibility")),!t.tool&&!t.locked?(t.url=k("url"),t.permission=k("permission")):t.touched=!0;const X=k("badgeText"),ue=k("badgeCount"),he=te._read();if(t.badge=X||ue?{...X&&{text:X},...ue&&{countFrom:ue},...he&&{variant:he}}:null,k("renderAs")==="pill"){const ye=me._read();t.pill={style:k("pillStyle")||"filled",...ye&&{variant:ye}}}else t.pill=null;t.colour=m._read();const ve=k("hlHover"),ge=k("hlActive"),be=B._read();t.highlight=ve||ge||be?{...ve&&{hover:ve},...ge&&{active:ge},...be&&{accent:be}}:null,re=!0,x.close(!0),s()})}let z=null,pt=!1;function en(){pt||!window.R?.use||(pt=!0,R.use((t,c,l)=>{const i=c?.path||"";return!(Vt.test(i)&&(t?.path||"")!==i)||!z?.dirty()?l():E.confirm(`You have unsaved changes to the menu "${He(z.name())}". Leave anyway? They are kept as a draft for your next visit.`).then(g=>{g?l():history.replaceState(null,"",`#${i}`)})}),M.subscribe("router:afterChange",({to:t}={})=>{if(z&&(t?.path||"")!==z.path){const c=z;z=null,c.dispose()}}))}function ft(t,c){const l=t.querySelector(".dm-plugin-banner-name"),i=l?.querySelector(".dm-plugin-banner-sep");if(!(!l||!i)){for(;i.nextSibling;)i.nextSibling.remove();l.appendChild(document.createTextNode(c))}}export const menuEditorView={templateUrl:"/admin/js/templates/menu-editor.html",async onMount(t){if(en(),z){const e=z;z=null,e.dispose()}const c=[],l=e=>(c.push(e),e);let i=!1;const s=t.get(0).querySelector(".mex")||t.get(0),g=()=>!i&&s.isConnected,w=location.hash.replace(/^#/,""),f=location.hash.match(/^#\/menus\/edit\/([^?#]+)/),P=f?decodeURIComponent(f[1]):null,_=!P,Y=`menu-editor.draft.${P||"new"}`,A=E.loader(t.get(0),{type:"dots"});let h,K,oe,ee,W,ae,te;try{if(_)h={slug:"",name:"",description:"",items:[]};else try{h=await j.menus.get(P)}catch(e){E.toast(`Failed to load menu: ${e.message||e}`,{type:"error"}),location.hash="#/menus";return}[K,oe,ee,W,ae,te]=await Promise.all([j.projects.list().catch(()=>[]),H.get("/api/auth/permissions-registry").catch(()=>({resources:[]})),j.collections.list().catch(()=>[]),j.get("/collections/roles/entries?limit=100").catch(()=>null),j.menuLocations.registry().catch(()=>[]),j.pages.list().catch(()=>[])])}finally{A.destroy()}if(!s.isConnected)return;const je=(Array.isArray(W)?W:W?.entries||[]).map(e=>({name:e.data?.name,label:e.data?.label,level:e.data?.level??99})).filter(e=>e.name).sort((e,n)=>n.level-e.level),q=!_&&P===Gt;let me=[];if(q&&(me=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 se=e=>dt(q?At(Et(e||[],me,{forEditor:!0}),{leaveInHiddenFolders:!0}):e);let m=se(h.items);const D=M.observable(!1),le=M.observable(!1),pe=M.observable(""),Se=M.observable(0);let B="";const C=s.querySelector("#me-items-list");function ie(){Xt(C,m,q),Se.value=m.filter(e=>!ne(e)).length}const L=()=>{ie(),V()},U=()=>q?mt(m):new Set,N=e=>m.find(n=>n.id===e);function x(e){requestAnimationFrame(()=>C.querySelector(`.menu-tree-row[data-id="${CSS.escape(e)}"]`)?.focus())}function fe(e){const n=v=>m.find(r=>!r.type&&!r.url&&!r.tool&&(r.key||"").toLowerCase()===v)||m.find(r=>!r.type&&!r.url&&!r.tool&&!r.key&&(r.text||"").toLowerCase()===v);let a=n(String(e.tool.folder||"").toLowerCase())||n(Ht);const p=String(e.tool.group||"").trim();if(a&&p){const v=Lt(a.key||_t(a.text),p),r=d=>d!==e&&!d.type&&!d.url&&!d.tool;let $=m.find(d=>r(d)&&(d.key||"").toLowerCase()===v)||m.find(d=>r(d)&&d.parentId===a.id&&(!d.key||d.key.toLowerCase()===v)&&(d.text||"").toLowerCase()===p.toLowerCase());$||([$]=dt([{text:p,key:v,icon:It,synthesised:!0}],a.id),m.push($)),a=$}e.parentId=a?a.id:null,m.splice(m.indexOf(e),1),m.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 $e=e=>!U().has(e.id)&&!(e.tool&&!e.tool.orphan);async function re(e){const n=N(e);if(!n||!$e(n))return;const a=d=>{let Q=d;for(;Q;){if(Q.id===e)return!0;Q=m.find(O=>O.id===Q.parentId)}return!1},p=m.filter(d=>d.id!==e&&a(d));if(p.length&&!await E.confirm(`Remove "${He(n.text||n.type||"this item")}" and the ${p.length} item${p.length===1?"":"s"} beneath it?`))return;const v=U(),r=p.filter(d=>d.tool),$=p.filter(d=>!d.tool&&v.has(d.id));m=m.filter(d=>!a(d)||r.includes(d)||$.includes(d));for(const d of $)d.parentId=n.parentId??null;for(const d of r)d.tool.orphan?d.parentId=n.parentId??null:fe(d);L()}function ce(e){const n=N(e);!n||ne(n)||U().has(e)||(n.hidden=!n.hidden,n.touched=!0,L())}function G(e){const n=N(e);!n||ne(n)||(n.locked=q&&U().has(n.id),Zt(n,oe.resources||[],ee,je,()=>{L(),x(e)}))}function de(e){const n={id:_e(),parentId:null,...e==="separator"?{type:e}:e==="spacer"?{type:e,size:"md"}:{text:"",url:"/",icon:"",visibility:"",permission:"",hidden:!1,bundled:!1}};m.push(n),L(),ne(n)?x(n.id):G(n.id)}const k=e=>n=>{e(n)&&(L(),x(n))},u=k(e=>ut(m,e,-1)),X=k(e=>ut(m,e,1)),ue=k(e=>Ft(m,e)),he=k(e=>Kt(m,e));function ve(e){const n=N(e);if(!n)return[];const a=ne(n),p=U().has(e),v=Wt(m,e),r=v.findIndex(O=>O.id===e),$=n.tool,d=$&&($.persisted||n.touched),Q=O=>()=>{const ke=Bt(m,e,O,_e());L(),ke&&!ne(ke)?G(ke.id):ke&&x(ke.id)};return[{header:a?n.type==="separator"?"Separator":"Spacer":n.text||$?.label||"(untitled)"},...a?[]:[{label:"Edit\u2026",icon:"edit",action:()=>G(e)}],{type:"divider"},{label:"Add item below",icon:"plus",action:Q("item")},{label:"Add sub-item",icon:"corner-down-right",disabled:a,action:()=>{const O=Nt(m,e,_e());L(),O&&G(O.id)}},{label:"Add separator below",icon:"minus",action:Q("separator")},{label:"Add spacer below",icon:"move",action:Q("spacer")},{type:"divider"},{label:"Move up",icon:"arrow-up",shortcut:"Alt+\u2191",disabled:r<=0,action:()=>u(e)},{label:"Move down",icon:"arrow-down",shortcut:"Alt+\u2193",disabled:r<0||r>=v.length-1,action:()=>X(e)},{label:"Indent",icon:"chevron-right",shortcut:"Alt+\u2192",disabled:r<=0||ne(v[r-1]),action:()=>ue(e)},{label:"Outdent",icon:"chevron-left",shortcut:"Alt+\u2190",disabled:n.parentId==null,action:()=>he(e)},{type:"divider"},...a?[]:[{label:n.hidden?"Show":"Hide",icon:n.hidden?"eye":"eye-off",disabled:p,action:()=>ce(e)}],{label:"Duplicate",icon:"copy",disabled:!!$,action:()=>{const O=Pt(m,e,_e);L(),O&&x(O.id)}},...$&&!$.orphan&&d?[{label:"Back to its default place",icon:"rotate-ccw",action:()=>{fe(n),L()}}]:[],{label:p?"Remove - always in the sidebar":$&&!$.orphan?"Remove - a Tool is hidden, not removed":"Remove\u2026",icon:"trash",danger:!0,disabled:!$e(n),action:()=>re(e)}]}const ge=E.contextMenu(C,{cursor:"glyph",match:".menu-tree-row",inherit:!1,density:"compact",items:e=>ve(e.dataset.id)});l(()=>ge?.destroy?.());const be=xt(C,()=>m,L,{items:".menu-tree-row",handle:".menu-tree-grip"});l(()=>be?.destroy());const ye=e=>{const n=e.target.closest(".menu-tree-row");if(!n)return;const a=n.dataset.id;if(e.target.closest(".mex-kebab")){qe(e.target.closest(".mex-kebab"));return}if(e.target.closest(".me-hidden")){ce(a);return}if(e.target.closest(".me-edit")){G(a);return}e.target.closest("select, .menu-tree-grip, button")||G(a)},Ge=e=>{const n=e.target.closest(".menu-tree-row");if(!n||e.target!==n){n&&e.key==="F10"&&e.shiftKey&&(e.preventDefault(),qe(n));return}const a=n.dataset.id;if(e.key==="F10"&&e.shiftKey)e.preventDefault(),qe(n);else if(e.key==="Enter")e.preventDefault(),G(a);else if(e.key==="Delete")e.preventDefault(),re(a);else if(e.altKey&&e.key==="ArrowUp")e.preventDefault(),u(a);else if(e.altKey&&e.key==="ArrowDown")e.preventDefault(),X(a);else if(e.altKey&&e.key==="ArrowRight")e.preventDefault(),ue(a);else if(e.altKey&&e.key==="ArrowLeft")e.preventDefault(),he(a);else if(e.key==="ArrowDown"||e.key==="ArrowUp"){const p=[...C.querySelectorAll(".menu-tree-row")],v=p.indexOf(n)+(e.key==="ArrowDown"?1:-1);p[v]&&(e.preventDefault(),p[v].focus())}},Ve=e=>{if(!e.target.matches(".me-spacer-size"))return;const n=N(e.target.closest(".menu-tree-row")?.dataset.id);n&&(n.size=e.target.value,V())};C.addEventListener("click",ye),C.addEventListener("keydown",Ge),C.addEventListener("change",Ve),l(()=>{C.removeEventListener("click",ye),C.removeEventListener("keydown",Ge),C.removeEventListener("change",Ve)});const o=e=>t.find(e),xe=o("#me-float-accent"),De=o("#me-float-accent-hex"),Ne=()=>{De.get(0).style.display=xe.val()==="__custom__"?"":"none"},ht=()=>xe.val()==="__custom__"?De.val():xe.val(),Ee=o("#me-highlight-accent"),Oe=o("#me-highlight-accent-hex"),Ye=()=>{Oe.get(0).style.display=Ee.val()==="__custom__"?"":"none"},vt=()=>Ee.val()==="__custom__"?Oe.val():Ee.val(),Xe=()=>{const e=o("#me-position").val()==="floating";o(".dm-float-field").each(function(){this.style.display=e?"":"none"}),e&&Ne();const n=o("#me-orientation").val()==="vertical";o(".dm-vertical-field").each(function(){this.style.display=n?"":"none"});const a=!!(o("#me-float-collapsible").get(0)||{}).checked;o(".dm-float-collapsed-field").each(function(){this.style.display=e&&a?"":"none"})},Je=(e,n,a,p)=>{const v=o(e).get(0);v&&(v.innerHTML="",v.add(new Option(p,"")),n.forEach(r=>v.add(new Option(a[r]||r,r))))};Je("#me-highlight-hover",st,it,"- theme default -"),Je("#me-highlight-active",lt,rt,"- theme default -");const Pe=o("#me-bind-slot"),Fe=o("#me-bind-projects"),Ae=o("#me-bind-pages");Pe.html('<option value="">- not bound -</option>'+(ae||[]).map(e=>`<option value="${b(e.slot)}">${b(e.label||e.slot)} (${b(e.slot)})</option>`).join("")),Fe.html(K.map(e=>`<option value="${b(e.slug)}">${b(e.name||e.slug)}</option>`).join("")),o("#me-bind-page-pick").html('<option value="">- pick a page -</option>'+te.map(e=>{const n=e.urlPath||e.url||"";return n?`<option value="${b(n)}">${b(e.title||n)} - ${b(n)}</option>`:""}).join(""));const Qe=()=>Ot({slot:Pe.val(),projects:Array.from(Fe.get(0).selectedOptions).map(e=>e.value),pagesText:Ae.val()});function Be(){const e=Qe(),n=o("#me-bind-summary");if(!e){n.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(r=>`<code>${b(r)}</code>`).join(", ")}`),e.pages.length&&a.push(`pages matching ${e.pages.map(r=>`<code>${b(r)}</code>`).join(", ")}`);const p=e.pages.filter(r=>!/^\/[^\s?#*]*(\/\*)?$|^\/\*$/.test(r)),v=p.length?`<div class="text-danger" style="margin-top:.4rem">Not valid page patterns: ${p.map(r=>`<code>${b(r)}</code>`).join(", ")}</div>`:"";n.html(a.length?`Takes over the <code>${b(e.slot)}</code> slot on ${a.join(" and ")}.${v}`:`<span class="text-warning">Slot <code>${b(e.slot)}</code> selected but no project or page chosen - the binding will never match.</span>`)}const{getProjectFromHash:gt}=await import("../lib/project-context.js");if(!g())return;const bt=_?gt():null;o("#me-project").html('<option value="">- none -</option>'+K.map(e=>`<option value="${b(e.slug)}">${b(e.name||e.slug)}</option>`).join(""));function ze(e){m=se(e.items),o("#me-variant").val(e.variant||""),o("#me-position").val(e.position||"");const n=o("#me-appearOnHover").get(0);n&&(n.checked=e.appearOnHover===!0),o("#me-float-anchor").val(e.float?.anchor||"TL"),o("#me-float-offsetX").val(e.float?.offsetX??""),o("#me-float-offsetY").val(e.float?.offsetY??""),o("#me-float-width").val(e.float?.width??""),o("#me-float-radius").val(e.float?.radius??""),o("#me-float-shadow").val(e.float?.shadow||""),o("#me-float-opacity").val(e.float?.opacity??""),o("#me-float-title").val(e.float?.title||"");for(const[r,$]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 d=o(r).get(0);d&&(d.checked=$===!0)}const a=e.float?.accent||"";xe.val(a.startsWith("#")?"__custom__":a),a.startsWith("#")&&De.val(a),Ne(),o("#me-orientation").val(e.orientation||""),o("#me-align").val(e.align||""),o("#me-side").val(e.side||"left"),o("#me-class").val(e.class||""),o("#me-highlight-hover").val(e.highlight?.hover||""),o("#me-highlight-active").val(e.highlight?.active||"");const p=e.highlight?.accent||"";Ee.val(p.startsWith("#")?"__custom__":p),p.startsWith("#")&&Oe.val(p),Ye(),o("#me-fontFamily").val(e.style?.fontFamily||""),o("#me-fontSize").val(e.style?.fontSize||""),o("#me-fontWeight").val(e.style?.fontWeight||""),o("#me-letterSpacing").val(e.style?.letterSpacing||""),o("#me-iconSize").val(e.style?.iconSize||""),Pe.val(e.binding?.slot||"");const v=new Set(e.binding?.projects||[]);Array.from(Fe.get(0).options).forEach(r=>{r.selected=v.has(r.value)}),Ae.val((e.binding?.pages||[]).join(`
|
|
23
|
-
`)),o("#me-slug").val(e.slug||""),o("#me-name").val(e.name||""),o("#me-description").val(e.description||""),o("#me-project").val(e.meta?.project||bt||""),Xe(),
|
|
26
|
+
${Te}
|
|
27
|
+
</div>`),g(m.id)}}g(null),t.innerHTML=s.join("")||'<p class="mex-note">No items yet - Add item, or right-click an item for more.</p>',I.scan(t)}function y(t,c={},...i){const l=document.createElement(t);Object.assign(l,c);for(const s of i)s!=null&&l.append(s);return l}function T(t,c,i){const l=y("label",{className:"form-field"},y("span",{className:"form-label",textContent:t}),c);return i&&l.append(y("small",{className:"form-hint",textContent:i,style:"display:block;font-size:.78em;opacity:.7;margin-top:.25rem;line-height:1.35"})),l}function Jt(t,c){const i=[["","- Everyone -"],["public","Public - anyone, incl. logged-out"],...(c||[]).map(s=>[s.name,`${s.label||s.name} and above`]),...(c||[]).filter(s=>s.level!==0).map(s=>[`=${s.name}`,`${s.label||s.name} only`]),["private","Private - super-admin only"]];t&&!i.some(([s])=>s===t)&&i.push([t,`${t} (custom)`]);const l=Z(i,t||"");return l.name="visibility",l}function Z(t,c){const i=y("select",{className:"form-select"});return t.forEach(([l,s])=>i.add(new Option(s,l))),i.value=c??"",i}function Re(t,c){const i=typeof c=="string"&&c.startsWith("#"),l=Z([["","- none -"],["primary","primary"],["success","success"],["danger","danger"],["warning","warning"],["info","info"],["neutral","neutral"],["__custom__","Custom\u2026"]],i?"__custom__":c||""),s=y("input",{type:"color",className:"form-input me-colour-hex",value:i?c:"#000000"});s.style.display=i?"":"none",l.addEventListener("change",()=>{s.style.display=l.value==="__custom__"?"":"none"});const g=T(t,l);return g.append(s),g._read=()=>l.value==="__custom__"?s.value:l.value,g}function Qt(t,c){const i=y("input",{className:"form-input me-icon",name:"icon",value:c||""}),l=y("span",{className:"me-icon-preview"});c&&l.setAttribute("data-icon",c);const s=y("button",{type:"button",className:"btn btn-sm btn-ghost",textContent:"Browse\u2026"}),g=w=>{w?l.setAttribute("data-icon",w):l.removeAttribute("data-icon"),Domma.icons.scan(l.parentNode||l)};return s.addEventListener("click",()=>$t(w=>{i.value=w,g(w)})),i.addEventListener("input",()=>g(i.value.trim())),T(t,y("div",{className:"me-icon-field"},i,s,l))}function je(...t){return y("div",{className:"me-field-grid"},...t)}async function Zt(t,c,i,l,s){const g=t.text||t.tool?.label||"",w=u=>y("h4",{className:"me-form-section",textContent:u}),m=T("Label",y("input",{className:"form-input",name:"text",value:t.text||""}),"The text shown for this item."),F=y("input",{className:"form-input",name:"url",value:t.url||""}),A=T("URL",F,t.tool||t.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.");(t.tool||t.locked)&&(F.readOnly=!0);const X=Qt("Icon",t.icon||""),C=Jt(t.visibility||"",l),h=T("Visibility",C,t.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.');t.locked&&(C.disabled=!0);const W=Z([["","- no permission gate -"],...(c||[]).map(u=>[u.key,u.label||u.key])],t.permission||"");W.name="permission";const ae=T("Permission",W,t.tool||t.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.");(t.tool||t.locked)&&(W.disabled=!0);const ee=T("Badge text",y("input",{className:"form-input",name:"badgeText",value:t.badge?.text||""})),q=Z([["","- none -"],...(i||[]).map(u=>[u.slug,u.title||u.slug])],t.badge?.countFrom||"");q.name="badgeCount";const se=T("Badge count from",q,"Show a live count of this collection\u2019s entries as the badge."),te=Re("Badge colour",t.badge?.variant||""),B=Z([["link","Link"],["pill","Pill"]],t.pill?"pill":"link");B.name="renderAs";const De=T("Render as",B,"Pill draws the item as a rounded chip. Pill styling applies to top-level navbar items."),D=T("Pill style",Z([["filled","Filled"],["outline","Outline"]],t.pill?.style||"filled"));D.querySelector("select").name="pillStyle";const me=Re("Pill colour",t.pill?.variant||""),ie=y("div",{className:"me-pill-wrap"},je(D,me));ie.style.display=t.pill?"":"none",B.addEventListener("change",()=>{ie.style.display=B.value==="pill"?"":"none"});const p=Re("Text colour",t.colour||""),N=Z([["","- use the menu default -"],...st.map(u=>[u,lt[u]||u])],t.highlight?.hover||"");N.name="hlHover";const le=T("Hover effect",N,"Overrides the menu-wide hover effect for this item only."),pe=Z([["","- use the menu default -"],...it.map(u=>[u,rt[u]||u])],t.highlight?.active||"");pe.name="hlActive";const Se=T("When selected",pe,"How this item is marked when it points at the page being viewed."),z=Re("Highlight colour",t.highlight?.accent||""),L=y("input",{className:"form-input",name:"class",value:t.class||"",placeholder:"nav-cta push-right",autocomplete:"off",spellcheck:!1}),re=T("CSS classes",L,"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."),_=y("small",{className:"text-danger",style:"display:none;margin-top:.25rem"});re.append(_);const U=y("button",{className:"btn btn-primary",textContent:"Apply",title:"Apply to the item (Ctrl+Enter) - Save the menu to keep it"}),O=y("div",{className:"me-item-form"},w("Link"),m,A,X,w("Access"),je(h,ae),w("Badge"),je(ee,te),se,w("Appearance"),De,ie,p,w("Highlighting"),je(le,Se),z,w("Styling"),re,U),x=E.slideover({title:g?`Edit ${He(g)}`:"Edit menu item",size:"lg",position:"right"});x.element.appendChild(O);const fe=()=>JSON.stringify([...O.querySelectorAll("input, select, textarea")].map(u=>u.type==="checkbox"?u.checked:u.value)),$e=fe();let ce=!1,de=!1;jt(x);const G=x.close.bind(x);x.close=async u=>{if(!ce&&u!==!0&&fe()!==$e){if(de)return;de=!0;const J=await E.confirm("Discard the changes to this item?");if(de=!1,!J)return}return ce=!0,G()},O.addEventListener("keydown",u=>{(u.ctrlKey||u.metaKey)&&u.key==="Enter"&&(u.preventDefault(),U.click())}),x.open();const ne=x.element.closest(".dm-slideover")||x.element.querySelector(".dm-slideover")||x.element;ne.style.setProperty("width",Ut+"px","important"),ne.style.setProperty("max-width","95vw","important"),Domma.icons.scan(O);const k=u=>O.querySelector(`[name="${u}"]`)?.value||"";U.addEventListener("click",()=>{const u=ct(k("class"));if(u.length){_.textContent=u.join("; "),_.style.display="block",L.focus();return}t.class=St(k("class")),t.text=k("text"),t.icon=k("icon"),t.locked||(t.visibility=k("visibility")),!t.tool&&!t.locked?(t.url=k("url"),t.permission=k("permission")):t.touched=!0;const J=k("badgeText"),ue=k("badgeCount"),he=te._read();if(t.badge=J||ue?{...J&&{text:J},...ue&&{countFrom:ue},...he&&{variant:he}}:null,k("renderAs")==="pill"){const ye=me._read();t.pill={style:k("pillStyle")||"filled",...ye&&{variant:ye}}}else t.pill=null;t.colour=p._read();const ve=k("hlHover"),ge=k("hlActive"),be=z._read();t.highlight=ve||ge||be?{...ve&&{hover:ve},...ge&&{active:ge},...be&&{accent:be}}:null,ce=!0,x.close(!0),s()})}let K=null,pt=!1;function en(){pt||!window.R?.use||(pt=!0,R.use((t,c,i)=>{const l=c?.path||"";return!(Vt.test(l)&&(t?.path||"")!==l)||!K?.dirty()?i():E.confirm(`You have unsaved changes to the menu "${He(K.name())}". Leave anyway? They are kept as a draft for your next visit.`).then(g=>{g?i():history.replaceState(null,"",`#${l}`)})}),M.subscribe("router:afterChange",({to:t}={})=>{if(K&&(t?.path||"")!==K.path){const c=K;K=null,c.dispose()}}))}function ft(t,c){const i=t.querySelector(".dm-plugin-banner-name"),l=i?.querySelector(".dm-plugin-banner-sep");if(!(!i||!l)){for(;l.nextSibling;)l.nextSibling.remove();i.appendChild(document.createTextNode(c))}}export const menuEditorView={templateUrl:"/admin/js/templates/menu-editor.html",async onMount(t){if(en(),K){const e=K;K=null,e.dispose()}const c=[],i=e=>(c.push(e),e);let l=!1;const s=t.get(0).querySelector(".mex")||t.get(0),g=()=>!l&&s.isConnected,w=location.hash.replace(/^#/,""),m=location.hash.match(/^#\/menus\/edit\/([^?#]+)/),F=m?decodeURIComponent(m[1]):null,A=!F,X=`menu-editor.draft.${F||"new"}`,C=E.loader(t.get(0),{type:"dots"});let h,W,ae,ee,q,se,te;try{if(A)h={slug:"",name:"",description:"",items:[]};else try{h=await j.menus.get(F)}catch(e){E.toast(`Failed to load menu: ${e.message||e}`,{type:"error"}),location.hash="#/menus";return}[W,ae,ee,q,se,te]=await Promise.all([j.projects.list().catch(()=>[]),H.get("/api/auth/permissions-registry").catch(()=>({resources:[]})),j.collections.list().catch(()=>[]),j.get("/collections/roles/entries?limit=100").catch(()=>null),j.menuLocations.registry().catch(()=>[]),j.pages.list().catch(()=>[])])}finally{C.destroy()}if(!s.isConnected)return;const De=(Array.isArray(q)?q:q?.entries||[]).map(e=>({name:e.data?.name,label:e.data?.label,level:e.data?.level??99})).filter(e=>e.name).sort((e,n)=>n.level-e.level),D=!A&&F===Gt;let me=[];if(D&&(me=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 ie=e=>dt(D?At(Et(e||[],me,{forEditor:!0}),{leaveInHiddenFolders:!0}):e);let p=ie(h.items);const N=M.observable(!1),le=M.observable(!1),pe=M.observable(""),Se=M.observable(0);let z="";const L=s.querySelector("#me-items-list");function re(){Xt(L,p,D),Se.value=p.filter(e=>!oe(e)).length}const _=()=>{re(),V()},U=()=>D?mt(p):new Set,O=e=>p.find(n=>n.id===e);function x(e){requestAnimationFrame(()=>L.querySelector(`.menu-tree-row[data-id="${CSS.escape(e)}"]`)?.focus())}function fe(e){const n=v=>p.find(r=>!r.type&&!r.url&&!r.tool&&(r.key||"").toLowerCase()===v)||p.find(r=>!r.type&&!r.url&&!r.tool&&!r.key&&(r.text||"").toLowerCase()===v);let a=n(String(e.tool.folder||"").toLowerCase())||n(Ht);const f=String(e.tool.group||"").trim();if(a&&f){const v=Lt(a.key||_t(a.text),f),r=d=>d!==e&&!d.type&&!d.url&&!d.tool;let $=p.find(d=>r(d)&&(d.key||"").toLowerCase()===v)||p.find(d=>r(d)&&d.parentId===a.id&&(!d.key||d.key.toLowerCase()===v)&&(d.text||"").toLowerCase()===f.toLowerCase());$||([$]=dt([{text:f,key:v,icon:It,synthesised:!0}],a.id),p.push($)),a=$}e.parentId=a?a.id:null,p.splice(p.indexOf(e),1),p.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 $e=e=>!U().has(e.id)&&!(e.tool&&!e.tool.orphan);async function ce(e){const n=O(e);if(!n||!$e(n))return;const a=d=>{let Y=d;for(;Y;){if(Y.id===e)return!0;Y=p.find(P=>P.id===Y.parentId)}return!1},f=p.filter(d=>d.id!==e&&a(d));if(f.length&&!await E.confirm(`Remove "${He(n.text||n.type||"this item")}" and the ${f.length} item${f.length===1?"":"s"} beneath it?`))return;const v=U(),r=f.filter(d=>d.tool),$=f.filter(d=>!d.tool&&v.has(d.id));p=p.filter(d=>!a(d)||r.includes(d)||$.includes(d));for(const d of $)d.parentId=n.parentId??null;for(const d of r)d.tool.orphan?d.parentId=n.parentId??null:fe(d);_()}function de(e){const n=O(e);!n||oe(n)||U().has(e)||(n.hidden=!n.hidden,n.touched=!0,_())}function G(e){const n=O(e);!n||oe(n)||(n.locked=D&&U().has(n.id),Zt(n,ae.resources||[],ee,De,()=>{_(),x(e)}))}function ne(e){const n={id:_e(),parentId:null,...e==="separator"||e==="theme-switcher"?{type:e}:e==="spacer"?{type:e,size:"md"}:{text:"",url:"/",icon:"",visibility:"",permission:"",hidden:!1,bundled:!1}};p.push(n),_(),oe(n)?x(n.id):G(n.id)}const k=e=>n=>{e(n)&&(_(),x(n))},u=k(e=>ut(p,e,-1)),J=k(e=>ut(p,e,1)),ue=k(e=>Ft(p,e)),he=k(e=>Kt(p,e));function ve(e){const n=O(e);if(!n)return[];const a=oe(n),f=U().has(e),v=Wt(p,e),r=v.findIndex(P=>P.id===e),$=n.tool,d=$&&($.persisted||n.touched),Y=P=>()=>{const ke=Bt(p,e,P,_e());_(),ke&&!oe(ke)?G(ke.id):ke&&x(ke.id)};return[{header:a?{separator:"Separator",spacer:"Spacer","theme-switcher":"Theme switcher"}[n.type]:n.text||$?.label||"(untitled)"},...a?[]:[{label:"Edit\u2026",icon:"edit",action:()=>G(e)}],{type:"divider"},{label:"Add item below",icon:"plus",action:Y("item")},{label:"Add sub-item",icon:"corner-down-right",disabled:a,action:()=>{const P=Nt(p,e,_e());_(),P&&G(P.id)}},{label:"Add separator below",icon:"minus",action:Y("separator")},{label:"Add spacer below",icon:"move",action:Y("spacer")},...D?[]:[{label:"Add theme switcher below",icon:"palette",action:Y("theme-switcher")}],{type:"divider"},{label:"Move up",icon:"arrow-up",shortcut:"Alt+\u2191",disabled:r<=0,action:()=>u(e)},{label:"Move down",icon:"arrow-down",shortcut:"Alt+\u2193",disabled:r<0||r>=v.length-1,action:()=>J(e)},{label:"Indent",icon:"chevron-right",shortcut:"Alt+\u2192",disabled:r<=0||oe(v[r-1]),action:()=>ue(e)},{label:"Outdent",icon:"chevron-left",shortcut:"Alt+\u2190",disabled:n.parentId==null,action:()=>he(e)},{type:"divider"},...a?[]:[{label:n.hidden?"Show":"Hide",icon:n.hidden?"eye":"eye-off",disabled:f,action:()=>de(e)}],{label:"Duplicate",icon:"copy",disabled:!!$,action:()=>{const P=Pt(p,e,_e);_(),P&&x(P.id)}},...$&&!$.orphan&&d?[{label:"Back to its default place",icon:"rotate-ccw",action:()=>{fe(n),_()}}]:[],{label:f?"Remove - always in the sidebar":$&&!$.orphan?"Remove - a Tool is hidden, not removed":"Remove\u2026",icon:"trash",danger:!0,disabled:!$e(n),action:()=>ce(e)}]}const ge=E.contextMenu(L,{cursor:"glyph",match:".menu-tree-row",inherit:!1,density:"compact",items:e=>ve(e.dataset.id)});i(()=>ge?.destroy?.());const be=xt(L,()=>p,_,{items:".menu-tree-row",handle:".menu-tree-grip"});i(()=>be?.destroy());const ye=e=>{const n=e.target.closest(".menu-tree-row");if(!n)return;const a=n.dataset.id;if(e.target.closest(".mex-kebab")){Ue(e.target.closest(".mex-kebab"));return}if(e.target.closest(".me-hidden")){de(a);return}if(e.target.closest(".me-edit")){G(a);return}e.target.closest("select, .menu-tree-grip, button")||G(a)},Ge=e=>{const n=e.target.closest(".menu-tree-row");if(!n||e.target!==n){n&&e.key==="F10"&&e.shiftKey&&(e.preventDefault(),Ue(n));return}const a=n.dataset.id;if(e.key==="F10"&&e.shiftKey)e.preventDefault(),Ue(n);else if(e.key==="Enter")e.preventDefault(),G(a);else if(e.key==="Delete")e.preventDefault(),ce(a);else if(e.altKey&&e.key==="ArrowUp")e.preventDefault(),u(a);else if(e.altKey&&e.key==="ArrowDown")e.preventDefault(),J(a);else if(e.altKey&&e.key==="ArrowRight")e.preventDefault(),ue(a);else if(e.altKey&&e.key==="ArrowLeft")e.preventDefault(),he(a);else if(e.key==="ArrowDown"||e.key==="ArrowUp"){const f=[...L.querySelectorAll(".menu-tree-row")],v=f.indexOf(n)+(e.key==="ArrowDown"?1:-1);f[v]&&(e.preventDefault(),f[v].focus())}},Ve=e=>{if(!e.target.matches(".me-spacer-size"))return;const n=O(e.target.closest(".menu-tree-row")?.dataset.id);n&&(n.size=e.target.value,V())};L.addEventListener("click",ye),L.addEventListener("keydown",Ge),L.addEventListener("change",Ve),i(()=>{L.removeEventListener("click",ye),L.removeEventListener("keydown",Ge),L.removeEventListener("change",Ve)});const o=e=>t.find(e),xe=o("#me-float-accent"),Ne=o("#me-float-accent-hex"),Oe=()=>{Ne.get(0).style.display=xe.val()==="__custom__"?"":"none"},ht=()=>xe.val()==="__custom__"?Ne.val():xe.val(),Ee=o("#me-highlight-accent"),Pe=o("#me-highlight-accent-hex"),Ye=()=>{Pe.get(0).style.display=Ee.val()==="__custom__"?"":"none"},vt=()=>Ee.val()==="__custom__"?Pe.val():Ee.val(),Xe=()=>{const e=o("#me-position").val()==="floating";o(".dm-float-field").each(function(){this.style.display=e?"":"none"}),e&&Oe();const n=o("#me-orientation").val()==="vertical";o(".dm-vertical-field").each(function(){this.style.display=n?"":"none"});const a=!!(o("#me-float-collapsible").get(0)||{}).checked;o(".dm-float-collapsed-field").each(function(){this.style.display=e&&a?"":"none"})},Je=(e,n,a,f)=>{const v=o(e).get(0);v&&(v.innerHTML="",v.add(new Option(f,"")),n.forEach(r=>v.add(new Option(a[r]||r,r))))};Je("#me-highlight-hover",st,lt,"- theme default -"),Je("#me-highlight-active",it,rt,"- theme default -");const Fe=o("#me-bind-slot"),Be=o("#me-bind-projects"),Ae=o("#me-bind-pages");Fe.html('<option value="">- not bound -</option>'+(se||[]).map(e=>`<option value="${b(e.slot)}">${b(e.label||e.slot)} (${b(e.slot)})</option>`).join("")),Be.html(W.map(e=>`<option value="${b(e.slug)}">${b(e.name||e.slug)}</option>`).join("")),o("#me-bind-page-pick").html('<option value="">- pick a page -</option>'+te.map(e=>{const n=e.urlPath||e.url||"";return n?`<option value="${b(n)}">${b(e.title||n)} - ${b(n)}</option>`:""}).join(""));const Qe=()=>Ot({slot:Fe.val(),projects:Array.from(Be.get(0).selectedOptions).map(e=>e.value),pagesText:Ae.val()});function ze(){const e=Qe(),n=o("#me-bind-summary");if(!e){n.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(r=>`<code>${b(r)}</code>`).join(", ")}`),e.pages.length&&a.push(`pages matching ${e.pages.map(r=>`<code>${b(r)}</code>`).join(", ")}`);const f=e.pages.filter(r=>!/^\/[^\s?#*]*(\/\*)?$|^\/\*$/.test(r)),v=f.length?`<div class="text-danger" style="margin-top:.4rem">Not valid page patterns: ${f.map(r=>`<code>${b(r)}</code>`).join(", ")}</div>`:"";n.html(a.length?`Takes over the <code>${b(e.slot)}</code> slot on ${a.join(" and ")}.${v}`:`<span class="text-warning">Slot <code>${b(e.slot)}</code> selected but no project or page chosen - the binding will never match.</span>`)}const{getProjectFromHash:gt}=await import("../lib/project-context.js");if(!g())return;const bt=A?gt():null;o("#me-project").html('<option value="">- none -</option>'+W.map(e=>`<option value="${b(e.slug)}">${b(e.name||e.slug)}</option>`).join(""));function Me(e){p=ie(e.items),o("#me-variant").val(e.variant||""),o("#me-position").val(e.position||"");const n=o("#me-appearOnHover").get(0);n&&(n.checked=e.appearOnHover===!0),o("#me-float-anchor").val(e.float?.anchor||"TL"),o("#me-float-offsetX").val(e.float?.offsetX??""),o("#me-float-offsetY").val(e.float?.offsetY??""),o("#me-float-width").val(e.float?.width??""),o("#me-float-radius").val(e.float?.radius??""),o("#me-float-shadow").val(e.float?.shadow||""),o("#me-float-opacity").val(e.float?.opacity??""),o("#me-float-title").val(e.float?.title||"");for(const[r,$]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 d=o(r).get(0);d&&(d.checked=$===!0)}const a=e.float?.accent||"";xe.val(a.startsWith("#")?"__custom__":a),a.startsWith("#")&&Ne.val(a),Oe(),o("#me-orientation").val(e.orientation||""),o("#me-align").val(e.align||""),o("#me-side").val(e.side||"left"),o("#me-class").val(e.class||""),o("#me-highlight-hover").val(e.highlight?.hover||""),o("#me-highlight-active").val(e.highlight?.active||"");const f=e.highlight?.accent||"";Ee.val(f.startsWith("#")?"__custom__":f),f.startsWith("#")&&Pe.val(f),Ye(),o("#me-fontFamily").val(e.style?.fontFamily||""),o("#me-fontSize").val(e.style?.fontSize||""),o("#me-fontWeight").val(e.style?.fontWeight||""),o("#me-letterSpacing").val(e.style?.letterSpacing||""),o("#me-iconSize").val(e.style?.iconSize||""),Fe.val(e.binding?.slot||"");const v=new Set(e.binding?.projects||[]);Array.from(Be.get(0).options).forEach(r=>{r.selected=v.has(r.value)}),Ae.val((e.binding?.pages||[]).join(`
|
|
28
|
+
`)),o("#me-slug").val(e.slug||""),o("#me-name").val(e.name||""),o("#me-description").val(e.description||""),o("#me-project").val(e.meta?.project||bt||""),Xe(),ze(),re()}const we=e=>!!(o(e).get(0)||{}).checked;function Ce(){const e={variant:o("#me-variant").val(),position:o("#me-position").val(),appearOnHover:we("#me-appearOnHover"),floatAnchor:o("#me-float-anchor").val(),floatOffsetX:o("#me-float-offsetX").val(),floatOffsetY:o("#me-float-offsetY").val(),floatWidth:o("#me-float-width").val(),floatRadius:o("#me-float-radius").val(),floatShadow:o("#me-float-shadow").val(),floatAccent:ht(),floatOpacity:o("#me-float-opacity").val(),floatTitle:o("#me-float-title").val(),floatCollapsible:we("#me-float-collapsible"),floatCollapsed:we("#me-float-collapsed"),floatMovable:we("#me-float-movable"),floatResizable:we("#me-float-resizable"),highlightHover:o("#me-highlight-hover").val(),highlightActive:o("#me-highlight-active").val(),highlightAccent:vt(),class:o("#me-class").val(),orientation:o("#me-orientation").val(),align:o("#me-align").val(),side:o("#me-side").val(),fontFamily:o("#me-fontFamily").val(),fontSize:o("#me-fontSize").val(),fontWeight:o("#me-fontWeight").val(),letterSpacing:o("#me-letterSpacing").val(),iconSize:o("#me-iconSize").val()},n={slug:o("#me-slug").val(),name:o("#me-name").val(),description:o("#me-description").val(),project:o("#me-project").val()};return zt(e,n,Qe(),Tt(p),h.meta||{})}const Ze=e=>[...Mt(e),...ct(e.class).map(n=>`CSS classes: ${n} (Behaviour tab).`)];let et=!1,Ke=null;function V(){if(!z)return;const e=Ce();Ke=e,N.value=Ie(e)!==z,pe.value=N.peek()||et?Ze(e).join(" "):""}const Le=e=>{e.target.closest("#me-items-list")||(e.target.matches("#me-position, #me-orientation, #me-float-collapsible")&&Xe(),e.target.matches("#me-float-accent")&&Oe(),e.target.matches("#me-highlight-accent")&&Ye(),e.target.closest("#me-binding")&&ze(),V())};s.addEventListener("input",Le),s.addEventListener("change",Le),i(()=>{s.removeEventListener("input",Le),s.removeEventListener("change",Le)}),o("#me-bind-page-add").on("click",()=>{const e=o("#me-bind-page-pick").val();if(!e)return;const n=Ae.val().split(`
|
|
24
29
|
`).map(a=>a.trim()).filter(Boolean);n.includes(e)||n.push(e),Ae.val(n.join(`
|
|
25
|
-
`)),
|
|
30
|
+
`)),ze(),V()}),Me(h),z=Ie(Ce()),V();const tt=()=>{try{S.remove?S.remove(X):S.set(X,null)}catch{}};async function We(){if(le.peek())return;const e=Ce(),n=Ze(e);if(n.length){et=!0,V(),E.toast(n.join(" "),{type:"warning",duration:7e3});return}le.value=!0;try{if(A)await j.menus.create(e);else if(e.slug!==h.slug){await j.menus.create(e);const a=await j.menuLocations.get();let f=!1;for(const[v,r]of Object.entries(a))r===h.slug&&(a[v]=e.slug,f=!0);f&&await j.menuLocations.save(a),await j.menus.remove(h.slug)}else await j.menus.update(h.slug,e);if(z=Ie(e),N.value=!1,tt(),Dt("#/menus"),E.toast("Saved.",{type:"success"}),A||e.slug!==h.slug)location.hash="#/menus/edit/"+encodeURIComponent(e.slug);else{h={...h,...e};for(const a of p)a.tool&&a.touched&&(a.tool={...a.tool,persisted:!0});re(),z=Ie(Ce()),V(),ft(t.get(0),e.name||e.slug)}if(D)try{document.dispatchEvent(new CustomEvent("dm:sidebar-rebuild"))}catch{}}catch(a){E.toast(`Save failed: ${a.message||a}`,{type:"error"})}finally{le.value=!1}}async function yt(){!N.peek()||!await E.confirm("Throw away the changes you have not saved?")||(Me(h),V())}E.tabs(o("#me-tabs").get(0));const wt=M.applyBindings({dirty:N,saving:le,problems:pe,itemCount:Se},s,{methods:{save:()=>We(),discard:()=>yt(),addItem:()=>ne("item"),addSeparator:()=>ne("separator"),addSpacer:()=>ne("spacer"),addSwitcher:()=>ne("theme-switcher")}});i(()=>wt.dispose()),i(Rt(s,{position:"bottom"})),D&&o("#me-add-switcher").hide(),ft(t.get(0),A?"New menu":h.name||h.slug),qe(t,{id:"menu-editor-back",icon:"arrow-left",title:"All menus",onClick:()=>{location.hash="#/menus"}}),qe(t,{id:"menu-editor-locations",icon:"map-pin",title:"Menu locations",onClick:()=>{location.hash="#/menu-locations"}}),qe(t,{id:"menu-editor-save",icon:"save",title:"Save (Ctrl+S)",onClick:()=>We()});const nt=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}We()}};document.addEventListener("keydown",nt,!0),i(()=>document.removeEventListener("keydown",nt,!0));const ot=()=>{if(!(!N.peek()||!Ke))try{S.set(X,{menu:Ke,base:z,at:new Date().toISOString()})}catch{}},at=e=>{N.peek()&&(ot(),e.preventDefault(),e.returnValue="")};window.addEventListener("beforeunload",at),i(()=>window.removeEventListener("beforeunload",at)),K={path:w,dirty:()=>N.peek(),name:()=>o("#me-name").val()||h.name||h.slug||"new menu",dispose(){l=!0,ot(),c.splice(0).reverse().forEach(e=>{try{e()}catch{}})}},I.scan(s);let Q=null;try{Q=S.get(X)}catch{}if(Q?.menu){tt();const e=Q.base&&Q.base!==z,n=Q.at?` (${qt(Q.at)})`:"",a=A?"the new menu you started":`the menu "${He(h.name||h.slug)}"`,f=e?`You left unsaved changes to ${a}${n}, but the saved menu has changed since. Restore your version anyway?`:`You left unsaved changes to ${a}${n}. Restore them?`;await E.confirm(f)&&g()&&(Me({...Q.menu,meta:{...h.meta||{},...Q.menu.meta||{}}}),V())}}};
|