domma-cms 0.96.0 → 0.98.0

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