domma-cms 1.48.1 → 1.48.3

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.
@@ -27,7 +27,7 @@ import{api as j,apiRequest as Lt}from"../api.js";import{launcherHref as Ct}from"
27
27
  ${Qe}
28
28
  </div>`),b(u.id)}}b(null),n._disposeMenuHelp?.(),n.innerHTML=l.join("")||'<p class="mex-note">No items yet - Add item, or right-click an item for more.</p>',n._disposeMenuHelp=it(n),I.scan(n)}function v(n,p={},...i){const c=document.createElement(n);Object.assign(c,p);for(const l of i)l!=null&&c.append(l);return c}function x(n,p,i){const c=v("label",{className:"form-field"},v("span",{className:"form-label",textContent:n}),p),l=Wt[n];if(l){const b=v("span");b.dataset.help=l+(i?" "+i:""),b.dataset.helpTitle=n,c.querySelector(".form-label").append(" ",b)}return i&&c.append(v("small",{className:"form-hint",textContent:i,style:"display:block;font-size:.78em;opacity:.7;margin-top:.25rem;line-height:1.35"})),c}function cn(n,p){const i=[["","- Everyone -"],["public","Public - anyone, incl. logged-out"],...(p||[]).map(l=>[l.name,`${l.label||l.name} and above`]),...(p||[]).filter(l=>l.level!==0).map(l=>[`=${l.name}`,`${l.label||l.name} only`]),["private","Private - super-admin only"]];n&&!i.some(([l])=>l===n)&&i.push([n,`${n} (custom)`]);const c=K(i,n||"");return c.name="visibility",c}function K(n,p){const i=v("select",{className:"form-select"});return n.forEach(([c,l])=>i.add(new Option(l,c))),i.value=p??"",i}function Me(n,p){const i=typeof p=="string"&&p.startsWith("#"),c=K([["","- none -"],["primary","primary"],["success","success"],["danger","danger"],["warning","warning"],["info","info"],["neutral","neutral"],["__custom__","Custom\u2026"]],i?"__custom__":p||""),l=v("input",{type:"color",className:"form-input me-colour-hex",value:i?p:"#000000"});l.style.display=i?"":"none",c.addEventListener("change",()=>{l.style.display=c.value==="__custom__"?"":"none"});const b=x(n,c);return b.append(l),b._read=()=>c.value==="__custom__"?l.value:c.value,b}function dn(n,p){const i=v("input",{className:"form-input me-icon",name:"icon",value:p||""}),c=v("span",{className:"me-icon-preview"});p&&c.setAttribute("data-icon",p);const l=v("button",{type:"button",className:"btn btn-sm btn-ghost",textContent:"Browse\u2026"}),b=_=>{_?c.setAttribute("data-icon",_):c.removeAttribute("data-icon"),Domma.icons.scan(c.parentNode||c)};return l.addEventListener("click",()=>_t(_=>{i.value=_,b(_)})),i.addEventListener("input",()=>b(i.value.trim())),x(n,v("div",{className:"me-icon-field"},i,l,c))}function ee(...n){return v("div",{className:"me-field-grid"},...n)}async function un(n,p,i,c,l,{cards:b=!0}={}){const _=n.text||n.tool?.label||"",u=(r,...y)=>{const C=v("section",{className:"me-item-section"},v("h4",{className:"me-item-section-title",textContent:r}),v("div",{className:"me-item-section-body"},...y));return C.setAttribute("aria-label",r),C},Y=x("Label",v("input",{className:"form-input",name:"text",value:n.text||""}),"The text shown for this item."),A=v("input",{className:"form-input",name:"url",value:n.url||""}),X=x("URL",A,n.tool||n.locked?"A Tool's address is its identity, so it cannot be changed here.":"Where it links. Must start with /, #, https://, or mailto: . Leave blank for a parent that only groups sub-items.");(n.tool||n.locked)&&(A.readOnly=!0);const N=/^#launcher-([a-z0-9][a-z0-9-]{0,39})$/,h=K([["","- not a launcher -"]],""),J=x("Launcher",h,"Opens one of your launchers instead of going to an address - choosing one fills in the URL.");J.style.display="none";const re=()=>{const r=N.exec(A.value.trim());h.value=r&&[...h.options].some(y=>y.value===r[1])?r[1]:""};h.addEventListener("change",()=>{h.value?A.value=Ct(h.value):N.test(A.value.trim())&&(A.value="")}),A.addEventListener("input",re),b&&!n.tool&&!n.locked&&Lt("/launchers/items",{method:"GET"}).then(r=>{const y=Array.isArray(r?.launchers)?r.launchers:[];if(y.length){for(const C of y)h.add(new Option(`${C.name}${C.enabled?"":" (switched off)"}`,C.id));re(),J.style.display=""}}).catch(()=>{});const ce=dn("Icon",n.icon||""),Q=cn(n.visibility||"",c),we=x("Visibility",Q,n.locked?"Always in the sidebar for everyone who may use it, so it cannot be restricted here.":'Who can see this item. "Role and above" shows it to that role and anyone more senior; "Role only" shows it to holders of that role alone (and the super-admin). Blank = everyone.');n.locked&&(Q.disabled=!0);const te=K([["","- no permission gate -"],...(p||[]).map(r=>[r.key,r.label||r.key])],n.permission||"");te.name="permission";const de=x("Permission",te,n.tool||n.locked?"A Tool is guarded by its own permission, which always applies.":"Hide unless the viewer holds this specific permission. Independent of Visibility - both must pass.");(n.tool||n.locked)&&(te.disabled=!0);const Ze=x("Badge text",v("input",{className:"form-input",name:"badgeText",value:n.badge?.text||""})),O=K([["","- none -"],...(i||[]).map(r=>[r.slug,r.title||r.slug])],n.badge?.countFrom||"");O.name="badgeCount";const ze=x("Badge count from",O,"Show a live count of this collection\u2019s entries as the badge."),$e=Me("Badge colour",n.badge?.variant||""),f=K([["link","Link"],["pill","Pill"]],n.pill?"pill":"link");f.name="renderAs";const F=x("Render as",f,"Pill draws the item as a rounded chip. Pill styling applies to top-level navbar items."),ue=x("Pill style",K([["filled","Filled"],["outline","Outline"]],n.pill?.style||"filled"));ue.querySelector("select").name="pillStyle";const Te=Me("Pill colour",n.pill?.variant||""),Se=v("div",{className:"me-pill-wrap"},ee(ue,Te));Se.style.display=n.pill?"":"none",f.addEventListener("change",()=>{Se.style.display=f.value==="pill"?"":"none"});const z=Me("Text colour",n.colour||""),T=K([["","- use the menu default -"],...pt.map(r=>[r,ft[r]||r])],n.highlight?.hover||"");T.name="hlHover";const He=x("Hover effect",T,"Overrides the menu-wide hover effect for this item only."),B=K([["","- use the menu default -"],...ht.map(r=>[r,vt[r]||r])],n.highlight?.active||"");B.name="hlActive";const me=x("When selected",B,"How this item is marked when it points at the page being viewed."),ne=Me("Highlight colour",n.highlight?.accent||""),oe=v("input",{className:"form-input",name:"class",value:n.class||"",placeholder:"nav-cta push-right",autocomplete:"off",spellcheck:!1}),_e=x("CSS classes",oe,"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."),xe=v("small",{className:"text-danger",style:"display:none;margin-top:.25rem"});_e.append(xe);const Ue=v("textarea",{className:"form-input",name:"description",rows:2,maxLength:Nt,value:n.description||"",placeholder:"Answers every new lead in under a minute."}),We=x("Description",Ue,"One short line under the label, shown when the menu's dropdowns are Cards."),q=Me("Tile colour",n.tile||""),pe=v("input",{type:"checkbox",name:"chip",checked:!!n.chip,style:"width:auto;margin:0"}),he=v("label",{className:"form-field",style:"display:flex;gap:.5rem;align-items:center;font-weight:400"},pe,v("span",{textContent:"Show as a small chip in the card's footer strip"})),Ae=v("span");Ae.dataset.helpTitle="Show as a small chip",Ae.dataset.help="Place this sub-item in the compact chip strip at the bottom of its parent Cards dropdown instead of the main entries. Its label and destination remain the same. The parent card can provide a Chip strip label. This applies to sub-items in Cards dropdowns, rather than top-level navbar links.",he.append(Ae);const fe=n.parentId==null,$=n.panel||{},U=(r,y,C,be=80)=>v("input",{className:"form-input",name:r,value:y||"",placeholder:C,maxLength:be}),et=x("Card heading",U("panelHeading",$.heading,"The crew - six agents, one job each"),"Small capitals over the entries."),tt=x("Link text",U("panelLinkText",$.link?.text,"Meet the crew",60)),nt=x("Link URL",U("panelLinkUrl",$.link?.url,"/crew",500)),Ie=K([["","Automatic"],["1","1"],["2","2"],["3","3"],["4","4"]],$.columns?String($.columns):"");Ie.name="panelColumns";const Ke=x("Columns",Ie),qe=x("Chip strip label",U("panelChipsLabel",$.chipsLabel,"Add to your crew",60),'Words before the chips - tick "Show as a small chip" on the sub-items that belong there.'),t=K([["","- no side box -"],["dark","Dark"],["light","Light"],["accent","Theme colour"]],$.feature?$.feature.tone||"dark":"");t.name="featureTone";const ve=x("Side box",t,"A box down the right of the card - a call to action or a short list."),Ge=x("Box small heading",U("featureEyebrow",$.feature?.eyebrow,"Free - 20 minutes",60)),Ee=x("Box title",U("featureTitle",$.feature?.title,"See it live")),Ne=x("Box points",v("textarea",{className:"form-input",name:"featurePoints",rows:3,value:($.feature?.points||[]).join(`
29
29
  `),placeholder:"One per line, up to six"})),Oe=x("Button text",U("featureBtnText",$.feature?.button?.text,"Book a demo",60)),ot=x("Button URL",U("featureBtnUrl",$.feature?.button?.url,"/book",500)),ae=v("div",{className:"me-feature-fields"},ee(Ge,Ee),Ne,ee(Oe,ot));ae.style.display=t.value?"":"none",t.addEventListener("change",()=>{ae.style.display=t.value?"":"none"});const Re=b?[u("Card link",v("small",{className:"form-hint",textContent:"Used with card dropdowns. Choose Cards on the Behaviour tab."}),We,ee(q,fe?null:he)),...fe?[u("Dropdown panel",et,ee(tt,nt),ee(Ke,qe)),u("Side box",ve,ae)]:[]]:[],Le=v("button",{className:"btn btn-primary",textContent:"Apply",title:"Apply to the item (Ctrl+Enter) - Save the menu to keep it"}),se=v("div",{className:"me-item-form"},u("Link",Y,X,J,ce),u("Appearance",F,Se,z),u("Hover & selection",ee(He,me),ne),...Re,u("Badge",ee(Ze,$e),ze),u("Access",ee(we,de)),u("Custom styling",_e),v("div",{className:"me-item-actions"},v("small",{className:"form-hint",textContent:"Apply updates this item. Save the menu to keep it."}),Le)),P=E.slideover({title:_?`Edit ${Fe(_)}`:"Edit menu item",size:"lg",position:"right"});P.element.appendChild(se);const Be=()=>JSON.stringify([...se.querySelectorAll("input, select, textarea")].filter(r=>r!==h).map(r=>r.type==="checkbox"?r.checked:r.value)),Pe=Be();let ge=!1,le=!1;const Ve=it(se,{position:"bottom"});Kt(P,Ve);const De=P.close.bind(P);P.close=async r=>{if(!ge&&r!==!0&&Be()!==Pe){if(le)return;le=!0;const y=await E.confirm("Discard the changes to this item?");if(le=!1,!y)return}return ge=!0,De()},se.addEventListener("keydown",r=>{(r.ctrlKey||r.metaKey)&&r.key==="Enter"&&(r.preventDefault(),Le.click())}),P.open();const Ye=P.element.closest(".dm-slideover")||P.element.querySelector(".dm-slideover")||P.element;Ye.style.setProperty("width",on+"px","important"),Ye.style.setProperty("max-width","95vw","important"),Domma.icons.scan(se);const w=r=>se.querySelector(`[name="${r}"]`)?.value||"";Le.addEventListener("click",()=>{const r=gt(w("class"));if(r.length){xe.textContent=r.join("; "),xe.style.display="block",oe.focus();return}n.class=Tt(w("class")),n.text=w("text"),n.icon=w("icon"),n.locked||(n.visibility=w("visibility")),!n.tool&&!n.locked?(n.url=w("url"),n.permission=w("permission")):n.touched=!0;const y=w("badgeText"),C=w("badgeCount"),be=$e._read();if(n.badge=y||C?{...y&&{text:y},...C&&{countFrom:C},...be&&{variant:be}}:null,w("renderAs")==="pill"){const G=Te._read();n.pill={style:w("pillStyle")||"filled",...G&&{variant:G}}}else n.pill=null;n.colour=z._read();const Ce=w("hlHover"),ye=w("hlActive"),D=ne._read();if(n.highlight=Ce||ye||D?{...Ce&&{hover:Ce},...ye&&{active:ye},...D&&{accent:D}}:null,b&&(n.description=w("description").trim(),n.tile=q._read(),n.chip=!fe&&pe.checked,fe)){const G=w("featureTone");n.panel=It({heading:w("panelHeading"),link:{text:w("panelLinkText"),url:w("panelLinkUrl")},columns:w("panelColumns"),chipsLabel:w("panelChipsLabel"),feature:G?{tone:G,eyebrow:w("featureEyebrow"),title:w("featureTitle"),points:w("featurePoints").split(`
30
- `),button:{text:w("featureBtnText"),url:w("featureBtnUrl")}}:null})}ge=!0,P.close(!0),l()})}let V=null,wt=!1;function mn(){wt||!window.R?.use||(wt=!0,R.use((n,p,i)=>{const c=p?.path||"";return!(sn.test(c)&&(n?.path||"")!==c)||!V?.dirty()?i():E.confirm(`You have unsaved changes to the menu "${Fe(V.name())}". Leave anyway? They are kept as a draft for your next visit.`).then(b=>{b?i():history.replaceState(null,"",`#${c}`)})}),M.subscribe("router:afterChange",({to:n}={})=>{if(V&&(n?.path||"")!==V.path){const p=V;V=null,p.dispose()}}))}function St(n,p){const i=n.querySelector(".dm-plugin-banner-name"),c=i?.querySelector(".dm-plugin-banner-sep");if(!(!i||!c)){for(;c.nextSibling;)c.nextSibling.remove();i.appendChild(document.createTextNode(p))}}export const menuEditorView={templateUrl:"/admin/js/templates/menu-editor.html",async onMount(n){if(mn(),V){const e=V;V=null,e.dispose()}const p=[],i=e=>(p.push(e),e);let c=!1;const l=n.get(0).querySelector(".mex")||n.get(0),b=()=>!c&&l.isConnected,_=location.hash.replace(/^#/,""),u=location.hash.match(/^#\/menus\/edit\/([^?#]+)/),Y=u?decodeURIComponent(u[1]):null,A=!Y,X=`menu-editor.draft.${Y||"new"}`,N=E.loader(n.get(0),{type:"dots"});let h,J,re,ce,Q,we,te;try{if(A)h={slug:"",name:"",description:"",items:[]};else try{h=await j.menus.get(Y)}catch(e){E.toast(`Failed to load menu: ${e.message||e}`,{type:"error"}),location.hash="#/menus";return}[J,re,ce,Q,we,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{N.destroy()}if(!l.isConnected)return;const Ze=(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,o)=>o.level-e.level),O=!A&&Y===an;let ze=[];if(O&&(ze=await H.get("/api/sidebar/registered-items").catch(()=>(E.toast("Could not load the Tools - they are not shown, and saving keeps their places as they are.",{type:"warning",duration:8e3}),[])),!l.isConnected))return;const $e=e=>bt(O?Bt(Rt(e||[],ze,{forEditor:!0}),{leaveInHiddenFolders:!0}):e);let f=$e(h.items);const F=M.observable(!1),ue=M.observable(!1),Te=M.observable(""),Se=M.observable(0);let z="";const T=l.querySelector("#me-items-list");i(()=>T._disposeMenuHelp?.());function He(){rn(T,f,O),Se.value=f.filter(e=>!ke(e)).length}const B=()=>{He(),D()},me=()=>O?kt(f):new Set,ne=e=>f.find(o=>o.id===e);function oe(e){requestAnimationFrame(()=>T.querySelector(`.menu-tree-row[data-id="${CSS.escape(e)}"]`)?.focus())}function _e(e){const o=k=>f.find(s=>!s.type&&!s.url&&!s.tool&&(s.key||"").toLowerCase()===k)||f.find(s=>!s.type&&!s.url&&!s.tool&&!s.key&&(s.text||"").toLowerCase()===k);let a=o(String(e.tool.folder||"").toLowerCase())||o(Mt);const d=String(e.tool.group||"").trim();if(a&&d){const k=Dt(a.key||jt(a.text),d),s=m=>m!==e&&!m.type&&!m.url&&!m.tool;let g=f.find(m=>s(m)&&(m.key||"").toLowerCase()===k)||f.find(m=>s(m)&&m.parentId===a.id&&(!m.key||m.key.toLowerCase()===k)&&(m.text||"").toLowerCase()===d.toLowerCase());g||([g]=bt([{text:d,key:k,icon:Ft,synthesised:!0}],a.id),f.push(g)),a=g}e.parentId=a?a.id:null,f.splice(f.indexOf(e),1),f.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 xe=e=>!me().has(e.id)&&!(e.tool&&!e.tool.orphan);async function Ue(e){const o=ne(e);if(!o||!xe(o))return;const a=m=>{let Z=m;for(;Z;){if(Z.id===e)return!0;Z=f.find(W=>W.id===Z.parentId)}return!1},d=f.filter(m=>m.id!==e&&a(m));if(d.length&&!await E.confirm(`Remove "${Fe(o.text||o.type||"this item")}" and the ${d.length} item${d.length===1?"":"s"} beneath it?`))return;const k=me(),s=d.filter(m=>m.tool),g=d.filter(m=>!m.tool&&k.has(m.id));f=f.filter(m=>!a(m)||s.includes(m)||g.includes(m));for(const m of g)m.parentId=o.parentId??null;for(const m of s)m.tool.orphan?m.parentId=o.parentId??null:_e(m);B()}function We(e){const o=ne(e);!o||ke(o)||me().has(e)||(o.hidden=!o.hidden,o.touched=!0,B())}function q(e){const o=ne(e);!o||ke(o)||(o.locked=O&&me().has(o.id),un(o,re.resources||[],ce,Ze,()=>{B(),oe(e)},{cards:!O}))}function pe(e){const o={id:Xe(),parentId:null,...e==="separator"||e==="theme-switcher"?{type:e}:e==="spacer"?{type:e,size:"md"}:{text:"",url:"/",icon:"",visibility:"",permission:"",hidden:!1,bundled:!1}};f.push(o),B(),ke(o)?oe(o.id):q(o.id)}const he=e=>o=>{e(o)&&(B(),oe(o))},Ae=he(e=>yt(f,e,-1)),fe=he(e=>yt(f,e,1)),$=he(e=>Xt(f,e)),U=he(e=>en(f,e));function et(e){const o=ne(e);if(!o)return[];const a=ke(o),d=me().has(e),k=tn(f,e),s=k.findIndex(W=>W.id===e),g=o.tool,m=g&&(g.persisted||o.touched),Z=W=>()=>{const je=Jt(f,e,W,Xe());B(),je&&!ke(je)?q(je.id):je&&oe(je.id)};return[{header:a?{separator:"Separator",spacer:"Spacer","theme-switcher":"Theme switcher"}[o.type]:o.text||g?.label||"(untitled)"},...a?[]:[{label:"Edit\u2026",icon:"edit",action:()=>q(e)}],{type:"divider"},{label:"Add item below",icon:"plus",action:Z("item")},{label:"Add sub-item",icon:"corner-down-right",disabled:a,action:()=>{const W=Gt(f,e,Xe());B(),W&&q(W.id)}},{label:"Add separator below",icon:"minus",action:Z("separator")},{label:"Add spacer below",icon:"move",action:Z("spacer")},...O?[]:[{label:"Add theme switcher below",icon:"palette",action:Z("theme-switcher")}],{type:"divider"},{label:"Move up",icon:"arrow-up",shortcut:"Alt+\u2191",disabled:s<=0,action:()=>Ae(e)},{label:"Move down",icon:"arrow-down",shortcut:"Alt+\u2193",disabled:s<0||s>=k.length-1,action:()=>fe(e)},{label:"Indent",icon:"chevron-right",shortcut:"Alt+\u2192",disabled:s<=0||ke(k[s-1]),action:()=>$(e)},{label:"Outdent",icon:"chevron-left",shortcut:"Alt+\u2190",disabled:o.parentId==null,action:()=>U(e)},{type:"divider"},...a?[]:[{label:o.hidden?"Show":"Hide",icon:o.hidden?"eye":"eye-off",disabled:d,action:()=>We(e)}],{label:"Duplicate",icon:"copy",disabled:!!g,action:()=>{const W=Yt(f,e,Xe);B(),W&&oe(W.id)}},...g&&!g.orphan&&m?[{label:"Back to its default place",icon:"rotate-ccw",action:()=>{_e(o),B()}}]:[],{label:d?"Remove - always in the sidebar":g&&!g.orphan?"Remove - a Tool is hidden, not removed":"Remove\u2026",icon:"trash",danger:!0,disabled:!xe(o),action:()=>Ue(e)}]}const tt=E.contextMenu(T,{cursor:"glyph",match:".menu-tree-row",inherit:!1,density:"compact",items:e=>et(e.dataset.id)});i(()=>tt?.destroy?.());const nt=Ot(T,()=>f,B,{items:".menu-tree-row",handle:".menu-tree-grip"});i(()=>nt?.destroy());const Ie=e=>{const o=e.target.closest(".menu-tree-row");if(!o)return;const a=o.dataset.id;if(e.target.closest(".mex-kebab")){rt(e.target.closest(".mex-kebab"));return}if(e.target.closest(".me-hidden")){We(a);return}if(e.target.closest(".me-edit")){q(a);return}e.target.closest("select, .menu-tree-grip, button")||q(a)},Ke=e=>{const o=e.target.closest(".menu-tree-row");if(!o||e.target!==o){o&&e.key==="F10"&&e.shiftKey&&(e.preventDefault(),rt(o));return}const a=o.dataset.id;if(e.key==="F10"&&e.shiftKey)e.preventDefault(),rt(o);else if(e.key==="Enter")e.preventDefault(),q(a);else if(e.key==="Delete")e.preventDefault(),Ue(a);else if(e.altKey&&e.key==="ArrowUp")e.preventDefault(),Ae(a);else if(e.altKey&&e.key==="ArrowDown")e.preventDefault(),fe(a);else if(e.altKey&&e.key==="ArrowRight")e.preventDefault(),$(a);else if(e.altKey&&e.key==="ArrowLeft")e.preventDefault(),U(a);else if(e.key==="ArrowDown"||e.key==="ArrowUp"){const d=[...T.querySelectorAll(".menu-tree-row")],k=d.indexOf(o)+(e.key==="ArrowDown"?1:-1);d[k]&&(e.preventDefault(),d[k].focus())}},qe=e=>{if(!e.target.matches(".me-spacer-size"))return;const o=ne(e.target.closest(".menu-tree-row")?.dataset.id);o&&(o.size=e.target.value,D())};T.addEventListener("click",Ie),T.addEventListener("keydown",Ke),T.addEventListener("change",qe),i(()=>{T.removeEventListener("click",Ie),T.removeEventListener("keydown",Ke),T.removeEventListener("change",qe)});const t=e=>n.find(e),ve=t("#me-fontFamily").get(0),Ge=Ut(ve,{label:"Font family"});i(()=>Ge.destroy());const Ee=t("#me-float-accent"),Ne=t("#me-float-accent-hex"),Oe=()=>{Ne.get(0).style.display=Ee.val()==="__custom__"?"":"none"},ot=()=>Ee.val()==="__custom__"?Ne.val():Ee.val(),ae=t("#me-highlight-accent"),Re=t("#me-highlight-accent-hex"),Le=()=>{Re.get(0).style.display=ae.val()==="__custom__"?"":"none"},se=()=>ae.val()==="__custom__"?Re.val():ae.val(),P=()=>{const e=!!(t("#me-entrance-enabled").get(0)||{}).checked;t(".dm-entrance-field").each(function(){this.style.display=e?"":"none"});const o=t("#me-position").val()==="floating";t(".dm-float-field").each(function(){this.style.display=o?"":"none"}),o&&Oe();const a=t("#me-orientation").val()==="vertical";t(".dm-vertical-field").each(function(){this.style.display=a?"":"none"}),t(".dm-dock-rail-field").each(function(){this.style.display=a&&!o?"":"none"}),t(".dm-dock-bar-field").each(function(){this.style.display=!a&&!o?"":"none"});const d=!!(t("#me-dock-collapsible").get(0)||{}).checked,k=!!(t("#me-dock-autohide").get(0)||{}).checked;t(".dm-dock-collapsed-field").each(function(){this.style.display=d&&!k?"":"none"});const s=!!(t("#me-float-collapsible").get(0)||{}).checked;t(".dm-float-collapsed-field").each(function(){this.style.display=o&&s?"":"none"});const g=!a&&!O;t(".dm-look-field").each(function(){this.style.display=g?"":"none"});const m=g&&t("#me-look-dropdown").val()==="cards";t(".dm-look-cards-field").each(function(){this.style.display=m?"":"none"})},Be=(e,o,a,d)=>{const k=t(e).get(0);k&&(k.innerHTML="",k.add(new Option(d,"")),o.forEach(s=>k.add(new Option(a[s]||s,s))))};Be("#me-highlight-hover",pt,ft,"- theme default -"),Be("#me-highlight-active",ht,vt,"- theme default -");{const e=t("#me-entrance-animation").get(0);e&&(e.innerHTML="",st.forEach(o=>e.add(new Option(Ht[o]||o,o))))}const Pe=t("#me-bind-slot"),ge=t("#me-bind-projects"),le=t("#me-bind-pages");Pe.get(0).innerHTML='<option value="">- not bound -</option>'+(we||[]).map(e=>`<option value="${L(e.slot)}">${L(e.label||e.slot)} (${L(e.slot)})</option>`).join(""),ge.get(0).innerHTML=J.map(e=>`<option value="${L(e.slug)}">${L(e.name||e.slug)}</option>`).join(""),t("#me-bind-page-pick").get(0).innerHTML='<option value="">- pick a page -</option>'+te.map(e=>{const o=e.urlPath||e.url||"";return o?`<option value="${L(o)}">${L(e.title||o)} - ${L(o)}</option>`:""}).join("");const Ve=()=>Vt({slot:Pe.val(),projects:Array.from(ge.get(0).selectedOptions).map(e=>e.value),pagesText:le.val()});function De(){const e=Ve(),o=t("#me-bind-summary");if(!e){o.html('<span class="text-muted">Not bound - this menu renders only where it is mapped or placed by a shortcode.</span>');return}const a=[];e.projects.length&&a.push(`pages in ${e.projects.map(s=>`<code>${L(s)}</code>`).join(", ")}`),e.pages.length&&a.push(`pages matching ${e.pages.map(s=>`<code>${L(s)}</code>`).join(", ")}`);const d=e.pages.filter(s=>!/^\/[^\s?#*]*(\/\*)?$|^\/\*$/.test(s)),k=d.length?`<div class="text-danger" style="margin-top:.4rem">Not valid page patterns: ${d.map(s=>`<code>${L(s)}</code>`).join(", ")}</div>`:"";o.html(a.length?`Takes over the <code>${L(e.slot)}</code> slot on ${a.join(" and ")}.${k}`:`<span class="text-warning">Slot <code>${L(e.slot)}</code> selected but no project or page chosen - the binding will never match.</span>`)}const{getProjectFromHash:Ye}=await import("../lib/project-context.js");if(!b())return;const w=A?Ye():null;t("#me-project").get(0).innerHTML='<option value="">- none -</option>'+J.map(e=>`<option value="${L(e.slug)}">${L(e.name||e.slug)}</option>`).join("");function r(e){f=$e(e.items),t("#me-variant").val(e.variant||""),t("#me-position").val(e.position||"");const o=t("#me-appearOnHover").get(0);o&&(o.checked=e.appearOnHover===!0),t("#me-float-anchor").val(e.float?.anchor||"TL"),t("#me-float-offsetX").val(e.float?.offsetX??""),t("#me-float-offsetY").val(e.float?.offsetY??""),t("#me-float-width").val(e.float?.width??""),t("#me-float-radius").val(e.float?.radius??""),t("#me-float-shadow").val(e.float?.shadow||""),t("#me-float-opacity").val(e.float?.opacity??""),t("#me-float-title").val(e.float?.title||"");for(const[s,g]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 m=t(s).get(0);m&&(m.checked=g===!0)}const a=e.float?.accent||"";Ee.val(a.startsWith("#")?"__custom__":a),a.startsWith("#")&&Ne.val(a),Oe(),t("#me-orientation").val(e.orientation||""),t("#me-align").val(e.align||""),t("#me-mobile-hamburger").get(0).checked=e.mobile?.hamburgerOnly===!0,t("#me-mobile-brand").get(0).checked=e.mobile?.hideBrand===!0,t("#me-look-bar").val(e.look?.bar||""),t("#me-look-brand").val(e.look?.brand||""),t("#me-look-strip").val(e.look?.strip||""),t("#me-look-icons").val(e.look?.icons||""),t("#me-look-dropdown").val(e.look?.dropdown||""),t("#me-look-tiles").val(e.look?.tiles||""),t("#me-look-morph").get(0).checked=e.look?.morph===!0,t("#me-look-shrink").get(0).checked=e.look?.shrink===!0,t("#me-side").val(e.side||"left"),t("#me-dock-width").val(e.dock?.width??"");for(const s of["collapsible","collapsed","autohide","hideOnScroll"]){const g=t(`#me-dock-${s}`).get(0);g&&(g.checked=e.dock?.[s]===!0)}t("#me-class").val(e.class||""),t("#me-highlight-hover").val(e.highlight?.hover||""),t("#me-highlight-active").val(e.highlight?.active||"");const d=e.highlight?.accent||"";ae.val(d.startsWith("#")?"__custom__":d),d.startsWith("#")&&Re.val(d),Le();{const s=t("#me-entrance-enabled").get(0);s&&(s.checked=e.entrance?.enabled===!0)}t("#me-entrance-animation").val(st.includes(e.entrance?.animation)?e.entrance.animation:st[0]),t("#me-entrance-stagger").val(e.entrance?.stagger??""),t("#me-entrance-duration").val(e.entrance?.duration??"");{const s=e.style?.fontFamily||"";if(ve.querySelector("option[data-custom]")?.remove(),s&&![...ve.options].some(g=>g.value===s)){const g=new Option(`${s} (custom)`,s);g.dataset.custom="1",ve.add(g,1)}ve.value=s,Ge.refresh()}t("#me-fontSize").val(e.style?.fontSize||""),t("#me-fontWeight").val(e.style?.fontWeight||""),t("#me-letterSpacing").val(e.style?.letterSpacing||""),t("#me-iconSize").val(e.style?.iconSize||""),Pe.val(e.binding?.slot||"");const k=new Set(e.binding?.projects||[]);Array.from(ge.get(0).options).forEach(s=>{s.selected=k.has(s.value)}),le.val((e.binding?.pages||[]).join(`
30
+ `),button:{text:w("featureBtnText"),url:w("featureBtnUrl")}}:null})}ge=!0,P.close(!0),l()})}let V=null,wt=!1;function mn(){wt||!window.R?.use||(wt=!0,R.use((n,p,i)=>{const c=p?.path||"";return!(sn.test(c)&&(n?.path||"")!==c)||!V?.dirty()?i():E.confirm(`You have unsaved changes to the menu "${Fe(V.name())}". Leave anyway? They are kept as a draft for your next visit.`).then(b=>{b?i():history.replaceState(null,"",`#${c}`)})}),M.subscribe("router:afterChange",({to:n}={})=>{if(V&&(n?.path||"")!==V.path){const p=V;V=null,p.dispose()}}))}function St(n,p){const i=n.querySelector(".dm-plugin-banner-name"),c=i?.querySelector(".dm-plugin-banner-sep");if(!(!i||!c)){for(;c.nextSibling;)c.nextSibling.remove();i.appendChild(document.createTextNode(p))}}export const menuEditorView={templateUrl:"/admin/js/templates/menu-editor.html",async onMount(n){if(mn(),V){const e=V;V=null,e.dispose()}const p=[],i=e=>(p.push(e),e);let c=!1;const l=n.get(0).querySelector(".mex")||n.get(0),b=()=>!c&&l.isConnected,_=location.hash.replace(/^#/,""),u=location.hash.match(/^#\/menus\/edit\/([^?#]+)/),Y=u?decodeURIComponent(u[1]):null,A=!Y,X=`menu-editor.draft.${Y||"new"}`,N=E.loader(n.get(0),{type:"dots"});let h,J,re,ce,Q,we,te;try{if(A)h={slug:"",name:"",description:"",items:[]};else try{h=await j.menus.get(Y)}catch(e){E.toast(`Failed to load menu: ${e.message||e}`,{type:"error"}),location.hash="#/menus";return}[J,re,ce,Q,we,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{N.destroy()}if(!l.isConnected)return;const Ze=(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,o)=>o.level-e.level),O=!A&&Y===an;let ze=[];if(O&&(ze=await H.get("/api/sidebar/registered-items?for=editor").catch(()=>(E.toast("Could not load the Tools - they are not shown, and saving keeps their places as they are.",{type:"warning",duration:8e3}),[])),!l.isConnected))return;const $e=e=>bt(O?Bt(Rt(e||[],ze,{forEditor:!0}),{leaveInHiddenFolders:!0}):e);let f=$e(h.items);const F=M.observable(!1),ue=M.observable(!1),Te=M.observable(""),Se=M.observable(0);let z="";const T=l.querySelector("#me-items-list");i(()=>T._disposeMenuHelp?.());function He(){rn(T,f,O),Se.value=f.filter(e=>!ke(e)).length}const B=()=>{He(),D()},me=()=>O?kt(f):new Set,ne=e=>f.find(o=>o.id===e);function oe(e){requestAnimationFrame(()=>T.querySelector(`.menu-tree-row[data-id="${CSS.escape(e)}"]`)?.focus())}function _e(e){const o=k=>f.find(s=>!s.type&&!s.url&&!s.tool&&(s.key||"").toLowerCase()===k)||f.find(s=>!s.type&&!s.url&&!s.tool&&!s.key&&(s.text||"").toLowerCase()===k);let a=o(String(e.tool.folder||"").toLowerCase())||o(Mt);const d=String(e.tool.group||"").trim();if(a&&d){const k=Dt(a.key||jt(a.text),d),s=m=>m!==e&&!m.type&&!m.url&&!m.tool;let g=f.find(m=>s(m)&&(m.key||"").toLowerCase()===k)||f.find(m=>s(m)&&m.parentId===a.id&&(!m.key||m.key.toLowerCase()===k)&&(m.text||"").toLowerCase()===d.toLowerCase());g||([g]=bt([{text:d,key:k,icon:Ft,synthesised:!0}],a.id),f.push(g)),a=g}e.parentId=a?a.id:null,f.splice(f.indexOf(e),1),f.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 xe=e=>!me().has(e.id)&&!(e.tool&&!e.tool.orphan);async function Ue(e){const o=ne(e);if(!o||!xe(o))return;const a=m=>{let Z=m;for(;Z;){if(Z.id===e)return!0;Z=f.find(W=>W.id===Z.parentId)}return!1},d=f.filter(m=>m.id!==e&&a(m));if(d.length&&!await E.confirm(`Remove "${Fe(o.text||o.type||"this item")}" and the ${d.length} item${d.length===1?"":"s"} beneath it?`))return;const k=me(),s=d.filter(m=>m.tool),g=d.filter(m=>!m.tool&&k.has(m.id));f=f.filter(m=>!a(m)||s.includes(m)||g.includes(m));for(const m of g)m.parentId=o.parentId??null;for(const m of s)m.tool.orphan?m.parentId=o.parentId??null:_e(m);B()}function We(e){const o=ne(e);!o||ke(o)||me().has(e)||(o.hidden=!o.hidden,o.touched=!0,B())}function q(e){const o=ne(e);!o||ke(o)||(o.locked=O&&me().has(o.id),un(o,re.resources||[],ce,Ze,()=>{B(),oe(e)},{cards:!O}))}function pe(e){const o={id:Xe(),parentId:null,...e==="separator"||e==="theme-switcher"?{type:e}:e==="spacer"?{type:e,size:"md"}:{text:"",url:"/",icon:"",visibility:"",permission:"",hidden:!1,bundled:!1}};f.push(o),B(),ke(o)?oe(o.id):q(o.id)}const he=e=>o=>{e(o)&&(B(),oe(o))},Ae=he(e=>yt(f,e,-1)),fe=he(e=>yt(f,e,1)),$=he(e=>Xt(f,e)),U=he(e=>en(f,e));function et(e){const o=ne(e);if(!o)return[];const a=ke(o),d=me().has(e),k=tn(f,e),s=k.findIndex(W=>W.id===e),g=o.tool,m=g&&(g.persisted||o.touched),Z=W=>()=>{const je=Jt(f,e,W,Xe());B(),je&&!ke(je)?q(je.id):je&&oe(je.id)};return[{header:a?{separator:"Separator",spacer:"Spacer","theme-switcher":"Theme switcher"}[o.type]:o.text||g?.label||"(untitled)"},...a?[]:[{label:"Edit\u2026",icon:"edit",action:()=>q(e)}],{type:"divider"},{label:"Add item below",icon:"plus",action:Z("item")},{label:"Add sub-item",icon:"corner-down-right",disabled:a,action:()=>{const W=Gt(f,e,Xe());B(),W&&q(W.id)}},{label:"Add separator below",icon:"minus",action:Z("separator")},{label:"Add spacer below",icon:"move",action:Z("spacer")},...O?[]:[{label:"Add theme switcher below",icon:"palette",action:Z("theme-switcher")}],{type:"divider"},{label:"Move up",icon:"arrow-up",shortcut:"Alt+\u2191",disabled:s<=0,action:()=>Ae(e)},{label:"Move down",icon:"arrow-down",shortcut:"Alt+\u2193",disabled:s<0||s>=k.length-1,action:()=>fe(e)},{label:"Indent",icon:"chevron-right",shortcut:"Alt+\u2192",disabled:s<=0||ke(k[s-1]),action:()=>$(e)},{label:"Outdent",icon:"chevron-left",shortcut:"Alt+\u2190",disabled:o.parentId==null,action:()=>U(e)},{type:"divider"},...a?[]:[{label:o.hidden?"Show":"Hide",icon:o.hidden?"eye":"eye-off",disabled:d,action:()=>We(e)}],{label:"Duplicate",icon:"copy",disabled:!!g,action:()=>{const W=Yt(f,e,Xe);B(),W&&oe(W.id)}},...g&&!g.orphan&&m?[{label:"Back to its default place",icon:"rotate-ccw",action:()=>{_e(o),B()}}]:[],{label:d?"Remove - always in the sidebar":g&&!g.orphan?"Remove - a Tool is hidden, not removed":"Remove\u2026",icon:"trash",danger:!0,disabled:!xe(o),action:()=>Ue(e)}]}const tt=E.contextMenu(T,{cursor:"glyph",match:".menu-tree-row",inherit:!1,density:"compact",items:e=>et(e.dataset.id)});i(()=>tt?.destroy?.());const nt=Ot(T,()=>f,B,{items:".menu-tree-row",handle:".menu-tree-grip"});i(()=>nt?.destroy());const Ie=e=>{const o=e.target.closest(".menu-tree-row");if(!o)return;const a=o.dataset.id;if(e.target.closest(".mex-kebab")){rt(e.target.closest(".mex-kebab"));return}if(e.target.closest(".me-hidden")){We(a);return}if(e.target.closest(".me-edit")){q(a);return}e.target.closest("select, .menu-tree-grip, button")||q(a)},Ke=e=>{const o=e.target.closest(".menu-tree-row");if(!o||e.target!==o){o&&e.key==="F10"&&e.shiftKey&&(e.preventDefault(),rt(o));return}const a=o.dataset.id;if(e.key==="F10"&&e.shiftKey)e.preventDefault(),rt(o);else if(e.key==="Enter")e.preventDefault(),q(a);else if(e.key==="Delete")e.preventDefault(),Ue(a);else if(e.altKey&&e.key==="ArrowUp")e.preventDefault(),Ae(a);else if(e.altKey&&e.key==="ArrowDown")e.preventDefault(),fe(a);else if(e.altKey&&e.key==="ArrowRight")e.preventDefault(),$(a);else if(e.altKey&&e.key==="ArrowLeft")e.preventDefault(),U(a);else if(e.key==="ArrowDown"||e.key==="ArrowUp"){const d=[...T.querySelectorAll(".menu-tree-row")],k=d.indexOf(o)+(e.key==="ArrowDown"?1:-1);d[k]&&(e.preventDefault(),d[k].focus())}},qe=e=>{if(!e.target.matches(".me-spacer-size"))return;const o=ne(e.target.closest(".menu-tree-row")?.dataset.id);o&&(o.size=e.target.value,D())};T.addEventListener("click",Ie),T.addEventListener("keydown",Ke),T.addEventListener("change",qe),i(()=>{T.removeEventListener("click",Ie),T.removeEventListener("keydown",Ke),T.removeEventListener("change",qe)});const t=e=>n.find(e),ve=t("#me-fontFamily").get(0),Ge=Ut(ve,{label:"Font family"});i(()=>Ge.destroy());const Ee=t("#me-float-accent"),Ne=t("#me-float-accent-hex"),Oe=()=>{Ne.get(0).style.display=Ee.val()==="__custom__"?"":"none"},ot=()=>Ee.val()==="__custom__"?Ne.val():Ee.val(),ae=t("#me-highlight-accent"),Re=t("#me-highlight-accent-hex"),Le=()=>{Re.get(0).style.display=ae.val()==="__custom__"?"":"none"},se=()=>ae.val()==="__custom__"?Re.val():ae.val(),P=()=>{const e=!!(t("#me-entrance-enabled").get(0)||{}).checked;t(".dm-entrance-field").each(function(){this.style.display=e?"":"none"});const o=t("#me-position").val()==="floating";t(".dm-float-field").each(function(){this.style.display=o?"":"none"}),o&&Oe();const a=t("#me-orientation").val()==="vertical";t(".dm-vertical-field").each(function(){this.style.display=a?"":"none"}),t(".dm-dock-rail-field").each(function(){this.style.display=a&&!o?"":"none"}),t(".dm-dock-bar-field").each(function(){this.style.display=!a&&!o?"":"none"});const d=!!(t("#me-dock-collapsible").get(0)||{}).checked,k=!!(t("#me-dock-autohide").get(0)||{}).checked;t(".dm-dock-collapsed-field").each(function(){this.style.display=d&&!k?"":"none"});const s=!!(t("#me-float-collapsible").get(0)||{}).checked;t(".dm-float-collapsed-field").each(function(){this.style.display=o&&s?"":"none"});const g=!a&&!O;t(".dm-look-field").each(function(){this.style.display=g?"":"none"});const m=g&&t("#me-look-dropdown").val()==="cards";t(".dm-look-cards-field").each(function(){this.style.display=m?"":"none"})},Be=(e,o,a,d)=>{const k=t(e).get(0);k&&(k.innerHTML="",k.add(new Option(d,"")),o.forEach(s=>k.add(new Option(a[s]||s,s))))};Be("#me-highlight-hover",pt,ft,"- theme default -"),Be("#me-highlight-active",ht,vt,"- theme default -");{const e=t("#me-entrance-animation").get(0);e&&(e.innerHTML="",st.forEach(o=>e.add(new Option(Ht[o]||o,o))))}const Pe=t("#me-bind-slot"),ge=t("#me-bind-projects"),le=t("#me-bind-pages");Pe.get(0).innerHTML='<option value="">- not bound -</option>'+(we||[]).map(e=>`<option value="${L(e.slot)}">${L(e.label||e.slot)} (${L(e.slot)})</option>`).join(""),ge.get(0).innerHTML=J.map(e=>`<option value="${L(e.slug)}">${L(e.name||e.slug)}</option>`).join(""),t("#me-bind-page-pick").get(0).innerHTML='<option value="">- pick a page -</option>'+te.map(e=>{const o=e.urlPath||e.url||"";return o?`<option value="${L(o)}">${L(e.title||o)} - ${L(o)}</option>`:""}).join("");const Ve=()=>Vt({slot:Pe.val(),projects:Array.from(ge.get(0).selectedOptions).map(e=>e.value),pagesText:le.val()});function De(){const e=Ve(),o=t("#me-bind-summary");if(!e){o.html('<span class="text-muted">Not bound - this menu renders only where it is mapped or placed by a shortcode.</span>');return}const a=[];e.projects.length&&a.push(`pages in ${e.projects.map(s=>`<code>${L(s)}</code>`).join(", ")}`),e.pages.length&&a.push(`pages matching ${e.pages.map(s=>`<code>${L(s)}</code>`).join(", ")}`);const d=e.pages.filter(s=>!/^\/[^\s?#*]*(\/\*)?$|^\/\*$/.test(s)),k=d.length?`<div class="text-danger" style="margin-top:.4rem">Not valid page patterns: ${d.map(s=>`<code>${L(s)}</code>`).join(", ")}</div>`:"";o.html(a.length?`Takes over the <code>${L(e.slot)}</code> slot on ${a.join(" and ")}.${k}`:`<span class="text-warning">Slot <code>${L(e.slot)}</code> selected but no project or page chosen - the binding will never match.</span>`)}const{getProjectFromHash:Ye}=await import("../lib/project-context.js");if(!b())return;const w=A?Ye():null;t("#me-project").get(0).innerHTML='<option value="">- none -</option>'+J.map(e=>`<option value="${L(e.slug)}">${L(e.name||e.slug)}</option>`).join("");function r(e){f=$e(e.items),t("#me-variant").val(e.variant||""),t("#me-position").val(e.position||"");const o=t("#me-appearOnHover").get(0);o&&(o.checked=e.appearOnHover===!0),t("#me-float-anchor").val(e.float?.anchor||"TL"),t("#me-float-offsetX").val(e.float?.offsetX??""),t("#me-float-offsetY").val(e.float?.offsetY??""),t("#me-float-width").val(e.float?.width??""),t("#me-float-radius").val(e.float?.radius??""),t("#me-float-shadow").val(e.float?.shadow||""),t("#me-float-opacity").val(e.float?.opacity??""),t("#me-float-title").val(e.float?.title||"");for(const[s,g]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 m=t(s).get(0);m&&(m.checked=g===!0)}const a=e.float?.accent||"";Ee.val(a.startsWith("#")?"__custom__":a),a.startsWith("#")&&Ne.val(a),Oe(),t("#me-orientation").val(e.orientation||""),t("#me-align").val(e.align||""),t("#me-mobile-hamburger").get(0).checked=e.mobile?.hamburgerOnly===!0,t("#me-mobile-brand").get(0).checked=e.mobile?.hideBrand===!0,t("#me-look-bar").val(e.look?.bar||""),t("#me-look-brand").val(e.look?.brand||""),t("#me-look-strip").val(e.look?.strip||""),t("#me-look-icons").val(e.look?.icons||""),t("#me-look-dropdown").val(e.look?.dropdown||""),t("#me-look-tiles").val(e.look?.tiles||""),t("#me-look-morph").get(0).checked=e.look?.morph===!0,t("#me-look-shrink").get(0).checked=e.look?.shrink===!0,t("#me-side").val(e.side||"left"),t("#me-dock-width").val(e.dock?.width??"");for(const s of["collapsible","collapsed","autohide","hideOnScroll"]){const g=t(`#me-dock-${s}`).get(0);g&&(g.checked=e.dock?.[s]===!0)}t("#me-class").val(e.class||""),t("#me-highlight-hover").val(e.highlight?.hover||""),t("#me-highlight-active").val(e.highlight?.active||"");const d=e.highlight?.accent||"";ae.val(d.startsWith("#")?"__custom__":d),d.startsWith("#")&&Re.val(d),Le();{const s=t("#me-entrance-enabled").get(0);s&&(s.checked=e.entrance?.enabled===!0)}t("#me-entrance-animation").val(st.includes(e.entrance?.animation)?e.entrance.animation:st[0]),t("#me-entrance-stagger").val(e.entrance?.stagger??""),t("#me-entrance-duration").val(e.entrance?.duration??"");{const s=e.style?.fontFamily||"";if(ve.querySelector("option[data-custom]")?.remove(),s&&![...ve.options].some(g=>g.value===s)){const g=new Option(`${s} (custom)`,s);g.dataset.custom="1",ve.add(g,1)}ve.value=s,Ge.refresh()}t("#me-fontSize").val(e.style?.fontSize||""),t("#me-fontWeight").val(e.style?.fontWeight||""),t("#me-letterSpacing").val(e.style?.letterSpacing||""),t("#me-iconSize").val(e.style?.iconSize||""),Pe.val(e.binding?.slot||"");const k=new Set(e.binding?.projects||[]);Array.from(ge.get(0).options).forEach(s=>{s.selected=k.has(s.value)}),le.val((e.binding?.pages||[]).join(`
31
31
  `)),t("#me-slug").val(e.slug||""),t("#me-name").val(e.name||""),t("#me-description").val(e.description||""),t("#me-project").val(e.meta?.project||w||""),P(),De(),He()}const y=e=>!!(t(e).get(0)||{}).checked;function C(){const e={variant:t("#me-variant").val(),position:t("#me-position").val(),appearOnHover:y("#me-appearOnHover"),floatAnchor:t("#me-float-anchor").val(),floatOffsetX:t("#me-float-offsetX").val(),floatOffsetY:t("#me-float-offsetY").val(),floatWidth:t("#me-float-width").val(),floatRadius:t("#me-float-radius").val(),floatShadow:t("#me-float-shadow").val(),floatAccent:ot(),floatOpacity:t("#me-float-opacity").val(),floatTitle:t("#me-float-title").val(),floatCollapsible:y("#me-float-collapsible"),floatCollapsed:y("#me-float-collapsed"),floatMovable:y("#me-float-movable"),floatResizable:y("#me-float-resizable"),highlightHover:t("#me-highlight-hover").val(),highlightActive:t("#me-highlight-active").val(),highlightAccent:se(),class:t("#me-class").val(),entranceEnabled:y("#me-entrance-enabled"),entranceAnimation:t("#me-entrance-animation").val(),entranceStagger:t("#me-entrance-stagger").val(),entranceDuration:t("#me-entrance-duration").val(),orientation:t("#me-orientation").val(),align:t("#me-align").val(),side:t("#me-side").val(),fontFamily:t("#me-fontFamily").val(),fontSize:t("#me-fontSize").val(),fontWeight:t("#me-fontWeight").val(),letterSpacing:t("#me-letterSpacing").val(),iconSize:t("#me-iconSize").val(),dockWidth:t("#me-dock-width").val(),dockCollapsible:y("#me-dock-collapsible"),dockCollapsed:y("#me-dock-collapsed"),dockAutohide:y("#me-dock-autohide"),mobileHamburgerOnly:y("#me-mobile-hamburger"),mobileHideBrand:y("#me-mobile-brand"),lookBar:t("#me-look-bar").val(),lookDropdown:t("#me-look-dropdown").val(),lookBrand:t("#me-look-brand").val(),lookStrip:t("#me-look-strip").val(),lookIcons:t("#me-look-icons").val(),lookTiles:t("#me-look-tiles").val(),lookMorph:y("#me-look-morph"),lookShrink:y("#me-look-shrink"),dockHideOnScroll:y("#me-dock-hideOnScroll")},o={slug:t("#me-slug").val(),name:t("#me-name").val(),description:t("#me-description").val(),project:t("#me-project").val()};return Qt(e,o,Ve(),zt(f),h.meta||{})}const be=e=>[...Zt(e),...gt(e.class).map(o=>`CSS classes: ${o} (Behaviour tab).`)];let Ce=!1,ye=null;function D(){if(!z)return;const e=C();ye=e,F.value=Je(e)!==z,Te.value=F.peek()||Ce?be(e).join(" "):""}const G=e=>{e.target.closest("#me-items-list")||(e.target.matches("#me-position, #me-orientation, #me-look-dropdown, #me-float-collapsible, #me-dock-collapsible, #me-dock-autohide, #me-entrance-enabled")&&P(),e.target.matches("#me-float-accent")&&Oe(),e.target.matches("#me-highlight-accent")&&Le(),e.target.closest("#me-binding")&&De(),D())};l.addEventListener("input",G),l.addEventListener("change",G),i(()=>{l.removeEventListener("input",G),l.removeEventListener("change",G)}),t("#me-bind-page-add").on("click",()=>{const e=t("#me-bind-page-pick").val();if(!e)return;const o=le.val().split(`
32
32
  `).map(a=>a.trim()).filter(Boolean);o.includes(e)||o.push(e),le.val(o.join(`
33
33
  `)),De(),D()}),r(h),z=Je(C()),D();const ct=()=>{try{S.remove?S.remove(X):S.set(X,null)}catch{}};async function at(){if(ue.peek())return;const e=C(),o=be(e);if(o.length){Ce=!0,D(),E.toast(o.join(" "),{type:"warning",duration:7e3});return}ue.value=!0;let a=null;try{if(A)await j.menus.create(e);else if(e.slug!==h.slug){await j.menus.create(e);const d=await j.menuLocations.get();let k=!1;for(const[s,g]of Object.entries(d))g===h.slug&&(d[s]=e.slug,k=!0);k&&await j.menuLocations.save(d),await j.menus.remove(h.slug)}else{const d=await xt(e);if(!d)return;a=d.revision}if(z=Je(e),F.value=!1,ct(),qt("#/menus"),E.toast("Saved.",{type:"success"}),A||e.slug!==h.slug)location.hash="#/menus/edit/"+encodeURIComponent(e.slug);else{h={...h,...e,revision:a};for(const d of f)d.tool&&d.touched&&(d.tool={...d.tool,persisted:!0});He(),z=Je(C()),D(),St(n.get(0),e.name||e.slug)}if(O)try{document.dispatchEvent(new CustomEvent("dm:sidebar-rebuild"))}catch{}}catch(d){E.toast(`Save failed: ${d.message||d}`,{type:"error"})}finally{ue.value=!1}}async function xt(e){try{return await j.menus.update(h.slug,{...e,revision:h.revision})}catch(a){if(a.status!==409)throw a}if(await E.confirm(`The menu "${Fe(h.name||h.slug)}" was changed somewhere else after you opened it - in another tab, by someone else, or on the server. Saving now would undo those changes.<br><br><strong>OK</strong> saves yours over them. <strong>Cancel</strong> loads the latest version, and offers your changes back as a draft.`))return j.menus.update(h.slug,e);try{S.set(X,{menu:e,base:z,at:new Date().toISOString()})}catch{}return F.value=!1,location.reload(),null}async function At(){!F.peek()||!await E.confirm("Throw away the changes you have not saved?")||(r(h),D())}E.tabs(t("#me-tabs").get(0));const Et=M.applyBindings({dirty:F,saving:ue,problems:Te,itemCount:Se},l,{methods:{save:()=>at(),discard:()=>At(),addItem:()=>pe("item"),addSeparator:()=>pe("separator"),addSpacer:()=>pe("spacer"),addSwitcher:()=>pe("theme-switcher")}});i(()=>Et.dispose()),i(it(l,{position:"bottom"})),O&&t("#me-add-switcher").hide(),St(n.get(0),A?"New menu":h.name||h.slug),lt(n,{id:"menu-editor-back",icon:"arrow-left",title:"All menus",onClick:()=>{location.hash="#/menus"}}),lt(n,{id:"menu-editor-locations",icon:"map-pin",title:"Menu locations",onClick:()=>{location.hash="#/menu-locations"}}),lt(n,{id:"menu-editor-save",icon:"save",title:"Save (Ctrl+S)",onClick:()=>at()});const dt=e=>{if(!(!(e.ctrlKey||e.metaKey)||e.key!=="s")){if(e.preventDefault(),e.stopImmediatePropagation(),document.querySelector(".me-item-form")?.offsetParent){E.toast("Apply the item first (Ctrl+Enter), then Save.",{type:"info"});return}at()}};document.addEventListener("keydown",dt,!0),i(()=>document.removeEventListener("keydown",dt,!0));const ut=()=>{if(!(!F.peek()||!ye))try{S.set(X,{menu:ye,base:z,at:new Date().toISOString()})}catch{}},mt=e=>{F.peek()&&(ut(),e.preventDefault(),e.returnValue="")};window.addEventListener("beforeunload",mt),i(()=>window.removeEventListener("beforeunload",mt)),V={path:_,dirty:()=>F.peek(),name:()=>t("#me-name").val()||h.name||h.slug||"new menu",dispose(){c=!0,ut(),p.splice(0).reverse().forEach(e=>{try{e()}catch{}})}},I.scan(l);let ie=null;try{ie=S.get(X)}catch{}if(ie?.menu){ct();const e=ie.base&&ie.base!==z,o=ie.at?` (${nn(ie.at)})`:"",a=A?"the new menu you started":`the menu "${Fe(h.name||h.slug)}"`,d=e?`You left unsaved changes to ${a}${o}, but the saved menu has changed since. Restore your version anyway?`:`You left unsaved changes to ${a}${o}. Restore them?`;await E.confirm(d)&&b()&&(r({...ie.menu,meta:{...h.meta||{},...ie.menu.meta||{}}}),D())}}};
@@ -1,4 +1,4 @@
1
- import{api as D,apiRequest as k}from"../api.js";import{placeTools as Oe}from"../lib/sidebar-grouping.js";import{addBannerAction as me}from"../lib/plugin-chrome.js";import{helpPopovers as Re}from"../lib/help-popover.js";import{openMenuAt as G,sidebarCount as fe}from"../lib/tool-kit.js";import{changedTabs as Ie,describeCacheKey as J,draftOf as Ae,expiresIn as Pe,formFromDraft as Be,siteSettingsForm as De,homeValue as $e,siteSettingsPayload as He,siteUrlError as he,settingsProblems as je,snapshot as ve,TAB_FIELDS as qe}from"../lib/site-settings-arrange.js";import{pickMedia as Ue}from"../lib/media-picker.js";import{makeIconInput as _e}from"../lib/shortcode-modal.js";import{fmtDateTime as Ke}from"../lib/dates.js";const Q=/^\/settings(\?.*)?$/,be="#/settings",g="settings.draft",Fe=`
1
+ import{api as $,apiRequest as w}from"../api.js";import{placeTools as Oe,WITHHELD_URL as Re}from"../lib/sidebar-grouping.js";import{addBannerAction as me}from"../lib/plugin-chrome.js";import{helpPopovers as Ie}from"../lib/help-popover.js";import{openMenuAt as G,sidebarCount as fe}from"../lib/tool-kit.js";import{changedTabs as Ae,describeCacheKey as J,draftOf as De,expiresIn as He,formFromDraft as Pe,siteSettingsForm as $e,homeValue as Be,siteSettingsPayload as je,siteUrlError as he,settingsProblems as Ue,snapshot as ve,TAB_FIELDS as qe}from"../lib/site-settings-arrange.js";import{pickMedia as _e}from"../lib/media-picker.js";import{makeIconInput as Ke}from"../lib/shortcode-modal.js";import{fmtDateTime as Fe}from"../lib/dates.js";const Q=/^\/settings(\?.*)?$/,be="#/settings",g="settings.draft",We=`
2
2
  <div class="stx-problem">
3
3
  <span class="stx-chip" data-bind-class="tone === 'danger' ? 'is-bad' : 'is-warn'">{{label}}</span>
4
4
  <span>{{text}}</span>
@@ -8,4 +8,4 @@ import{api as D,apiRequest as k}from"../api.js";import{placeTools as Oe}from"../
8
8
  <span class="stx-main"><strong>{{path}}</strong><small>{{meta}}</small></span>
9
9
  <span class="stx-chip">{{expires}}</span>
10
10
  <button type="button" class="stx-kebab" aria-label="Actions for {{path}}" title="Actions">\u22EE</button>
11
- </div>`,$=["general","branding","email","cookies","cache"];async function Ne(c,l){const[r,w]=await Promise.all([H.get("/api/sidebar/menu").catch(()=>({items:[]})),H.get("/api/sidebar/registered-items").catch(()=>[])]),n=new Map([["/","Dashboard (built in)"]]),i=(v,u)=>{for(const o of v||[]){if(!o||o.hidden||o.restricted)continue;const m=typeof o.url=="string"?o.url:"";m.startsWith("#/")&&m.length>2&&!n.has(m.slice(1))&&n.set(m.slice(1),`${u?`${u} \u203A `:""}${o.text||m}`),i(o.items,o.url?u:o.text||u)}};i(Oe(r?.items||[],w||[]),""),n.has(l)||n.set(l,`${l} (not in the sidebar)`),c.replaceChildren();for(const[v,u]of n){const o=document.createElement("option");o.value=v,o.textContent=u,c.appendChild(o)}}let f=null,ye=!1;function Ve(){ye||!window.R?.use||(ye=!0,R.use((c,l,r)=>!(Q.test(l?.path||"")&&!Q.test(c?.path||""))||!f?.dirty()?r():E.confirm("You have unsaved settings. Leave anyway? They are kept as a draft for your next visit (not the SMTP password).").then(n=>{n?r():history.replaceState(null,"","#/settings")})),M.subscribe("router:afterChange",({to:c}={})=>{if(f&&!Q.test(c?.path||"")){const l=f;f=null,l.dispose()}}))}export const settingsView={templateUrl:"/admin/js/templates/settings.html",async onMount(c){if(Ve(),f){const e=f;f=null,e.dispose()}const l=[],r=e=>(l.push(e),e);let w=!1;const n=c.get(0).querySelector(".stx")||c.get(0),i=()=>!w&&n.isConnected,v=E.loader(c.get(0),{type:"dots"});let u;try{u=await D.settings.get()}catch(e){v.destroy(),E.toast(`Could not load the settings: ${e.message||e}`,{type:"error"});return}if(v.destroy(),!n.isConnected)return;const o=M.observable(u||{}),m=De(u||{}),s={};for(const[e,t]of Object.entries(m))s[e]=M.observable(t);const j=()=>Object.fromEntries(Object.keys(s).map(e=>[e,s[e].value])),X=()=>Object.fromEntries(Object.keys(s).map(e=>[e,s[e].peek()])),b=M.observable(m),q=M.computed(()=>ve(b.value)),C=M.computed(()=>ve(j())!==q.value),x=M.observable(!1),T=M.observable(""),Z=M.observable(!1);D.plugins.policy().then(e=>{i()&&(Z.value=e?.signedOnly===!1)}).catch(()=>{});const U=M.observable(!1),ee=M.computed(()=>{const e=new Set(Ie(j(),b.value));return Object.fromEntries(Object.keys(qe).map(t=>[t,e.has(t)]))}),_=M.observable([]);r(M.effect(()=>{_.value=je(j(),o.value).map(e=>({...e,label:e.tone==="danger"?"Mail":"Check"}))}));const te=M.observable(""),L=M.observable(!1),O=M.observable(""),A=M.observable(""),p=M.observable(null),K=M.observable([]),F=M.observable(""),z=M.observable(!0),N=M.observable(""),ae=M.observable([]);r(M.effect(()=>{const e=F.value.trim().toLowerCase(),t=Date.now();ae.value=[...K.value].reverse().filter(a=>!e||String(a.key).toLowerCase().includes(e)||(a.tags||[]).some(d=>String(d).toLowerCase().includes(e))).map(a=>{const d=J(a.key);return{id:a.key,path:d.path,meta:[d.page?`as ${d.role}`:"not a page",(a.tags||[]).join(", ")].filter(Boolean).join(" \xB7 "),expires:Pe(a.expiresAt,t)}})}));const ge={...s,saving:x,dirty:C,tabs:ee,problems:_,testTo:te,testing:L,testResult:O,testTone:A,cacheQuery:F,cacheLoading:z,cacheError:N,cacheRows:ae,errorText:T,problemsText:M.computed(()=>_.value.length?"yes":""),siteUrlError:M.computed(()=>he(s.siteUrl.value)),noSmtp:M.computed(()=>!String(s.smtpHost.value||"").trim()),mayAllowInsecureTLS:Z,dirtyEmail:M.computed(()=>ee.value.email),cacheOn:M.computed(()=>p.value?.enabled===!0),cacheState:M.computed(()=>{const e=p.value;return e?e.enabled?`On (${e.driver})`:"Off":"Status unknown"}),cacheSize:M.computed(()=>{const e=p.value;return e?.enabled&&e.size!==null&&e.size!==void 0?`${e.size}${e.maxItems?` of ${e.maxItems}`:""} entries`:""}),cacheHits:M.computed(()=>{const e=p.value?.hitRate;return e==null?"":`${Math.round(e*100)}% served from the cache`}),cacheToggleText:M.computed(()=>p.value?.enabled?"Turn off":"Turn on"),cacheEmpty:M.computed(()=>F.value.trim()?"Nothing matches.":p.value?.enabled?"The cache is empty - pages are cached as visitors open them.":"The cache is off.")};async function V(){if(x.peek())return;const e=X(),t=b.peek(),a=he(e.siteUrl);if(a){E.toast(`Site URL: ${a}`,{type:"error"});return}x.value=!0,T.value="";const d=String(e.title).trim()!==String(t.title).trim();try{await D.settings.save(He(e,o.peek(),{adminHomeReady:U.peek()}));const B=await D.settings.get().catch(()=>null);if(!i())return;B&&(o.value=B);const Le={...e,smtpPass:""};s.smtpPass.value="",b.value=Le;try{S.remove?S.remove(g):S.set(g,null)}catch{}document.dispatchEvent(new CustomEvent("dm:admin-home-changed")),(d||["adminBrandEnabled","adminBrandTitle","adminBrandLogo","adminBrandLogoDark","adminBrandIcon"].some(pe=>e[pe]!==t[pe]))&&document.dispatchEvent(new CustomEvent("dm:sidebar-rebuild")),fe(be),E.toast("Settings saved.",{type:"success"})}catch(B){T.value=B.message||"Could not save the settings.",E.toast("Settings not saved - see the message at the top.",{type:"error"})}finally{x.value=!1}}async function we(){await E.confirm("Throw away your unsaved settings?")&&(se(b.peek()),T.value="")}function se(e){for(const[t,a]of Object.entries(e))s[t]&&(s[t].value=a)}async function ke(){if(!L.peek()){L.value=!0,A.value="",O.value="Sending\u2026";try{const e=await k("/settings/test-email",{method:"POST",body:JSON.stringify({to:te.peek().trim()||void 0})});if(!i())return;O.value=e?.message||"Test email sent.",A.value="is-ok"}catch(e){if(!i())return;O.value=e.message||"Could not send the test email.",A.value="is-bad"}finally{L.value=!1}}}async function P(){z.value=!0;try{const[e,t]=await Promise.all([k("/cache/status").catch(()=>null),k("/cache/keys")]);if(!i())return;p.value=e,K.value=Array.isArray(t?.entries)?t.entries:[],N.value=""}catch(e){if(!i())return;N.value=`Could not read the cache: ${e.message||e}`}finally{z.value=!1}}async function Ee(){if(await E.confirm("Clear the whole response cache? The next visitor to each page renders it afresh.")){try{await k("/cache/clear",{method:"POST"}),E.toast("Cache cleared.",{type:"success"})}catch(e){E.toast(e.message||"Could not clear the cache.",{type:"error"})}i()&&await P()}}async function Se(){const e=p.peek()?.enabled===!0;if(!(e&&!await E.confirm("Turn the response cache off? Every visit will render its page afresh until it is turned back on. The choice is saved (config/cache.json)."))){try{p.value=await k("/cache/toggle",{method:"POST",body:JSON.stringify({enabled:!e})}),E.toast(e?"Cache turned off.":"Cache turned on.",{type:"success"}),fe(be)}catch(t){E.toast(t.message||"Could not change the cache.",{type:"error"})}i()&&await P()}}const ne=e=>K.peek().find(t=>t.key===e);function Me(e){const t=ne(e);if(!t)return[];const a=J(t.key);return[{header:a.path},{label:"Open the page",icon:"external-link",disabled:!a.page,action:()=>window.open(a.path,"_blank","noopener")},{label:"Copy key",icon:"copy",action:async()=>{try{await navigator.clipboard.writeText(t.key),E.toast("Key copied.",{type:"success"})}catch{E.toast("Could not copy - your browser blocked the clipboard.",{type:"warning"})}}},...a.page?[{label:"Copy address",icon:"link",action:async()=>{try{await navigator.clipboard.writeText(new URL(a.path,location.origin).href),E.toast("Address copied.",{type:"success"})}catch{E.toast("Could not copy - your browser blocked the clipboard.",{type:"warning"})}}}]:[]]}n.querySelector(".stx-problems").innerHTML=Fe;const y=n.querySelector(".stx-list");y.innerHTML=ze;const W=E.tabs(n.querySelector(".stx-tabs"),{tabSelector:".tab-item",panelSelector:".tab-panel"}),oe=new URLSearchParams(location.hash.split("?")[1]||"").get("tab");$.includes(oe)&&W.activate($.indexOf(oe));const Ce=M.applyBindings(ge,n,{methods:{save:V,discard:we,sendTest:ke,refreshCache:P,clearCache:Ee,toggleCache:Se,pickBrandImage:async e=>{const t=await Ue({title:"Choose a branding image",current:s[e].peek()});t&&i()&&(s[e].value=t)},clearBrandImage:e=>{s[e].value=""},goTab:e=>{const t=$.indexOf(e);t>=0&&W.activate(t)}}});r(()=>Ce.dispose());for(const e of n.querySelectorAll("[data-brand-icon]")){const t=e.dataset.brandIcon,a=_e("Choose an icon",s[t].peek());a.input.id=`stx-${t}`,a.input.classList.add("form-input");const d=()=>{s[t].value=a.input.value};a.input.addEventListener("input",d),r(()=>a.input.removeEventListener("input",d)),r(M.effect(()=>{a.input.value=s[t].value})),e.appendChild(a.el)}r(Re(n,{position:"bottom"}));const xe=e=>{const t=e.target.closest("[data-go]");if(!t)return;const a=$.indexOf(t.dataset.go);a>=0&&W.activate(a)};n.querySelector(".stx-problems").addEventListener("click",xe);const Y=n.querySelector("#stx-admin-home");Ne(Y,$e(s.adminHome.peek())).then(()=>{i()&&(Y.value=s.adminHome.peek(),U.value=!0)}).catch(()=>{});const Te=E.contextMenu(y,{cursor:"glyph",match:".stx-row",inherit:!1,density:"compact",items:e=>Me(e.dataset.id)});r(()=>Te?.destroy?.());const re=e=>{const t=ne(e.dataset.id),a=t&&J(t.key);a?.page?window.open(a.path,"_blank","noopener"):G(e)},ie=e=>{const t=e.target.closest(".stx-row");if(!t)return;const a=e.target.closest(".stx-kebab");if(a){G(a);return}re(t)},ce=e=>{const t=e.target.closest(".stx-row");t&&(e.key==="F10"&&e.shiftKey?(e.preventDefault(),G(t)):e.key==="Enter"&&e.target===t&&re(t))};y.addEventListener("click",ie),y.addEventListener("keydown",ce),r(()=>{y.removeEventListener("click",ie),y.removeEventListener("keydown",ce)}),me(c,{id:"settings-view-site",icon:"external-link",title:"View site",onClick:()=>window.open("/","_blank","noopener")}),me(c,{id:"settings-save",icon:"save",title:"Save (Ctrl+S)",onClick:()=>V()});const le=e=>{!(e.ctrlKey||e.metaKey)||e.key!=="s"||(e.preventDefault(),e.stopImmediatePropagation(),V())};document.addEventListener("keydown",le,!0),r(()=>document.removeEventListener("keydown",le,!0));const ue=()=>{if(C.peek())try{S.set(g,{form:Ae(X()),base:q.peek(),at:new Date().toISOString()})}catch{}},de=e=>{C.peek()&&(ue(),e.preventDefault(),e.returnValue="")};window.addEventListener("beforeunload",de),r(()=>window.removeEventListener("beforeunload",de)),f={dirty:()=>C.peek(),dispose(){w=!0,ue(),l.splice(0).reverse().forEach(e=>{try{e()}catch{}})}},I.scan(n),P();let h=null;try{h=S.get(g)}catch{}if(h?.form){try{S.remove?S.remove(g):S.set(g,null)}catch{}const e=h.base&&h.base!==q.peek(),t=h.at?` (${Ke(h.at)})`:"",a=e?`You left unsaved settings${t}, but the saved settings have changed since. Restore your version anyway?`:`You left unsaved settings${t}. Restore them?`;await E.confirm(a)&&i()&&(se(Be(b.peek(),h.form)),U.peek()&&(Y.value=s.adminHome.peek()))}}};
11
+ </div>`,B=["general","branding","email","cookies","cache"];async function Ne(c,l){const[r,y]=await Promise.all([H.get("/api/sidebar/menu").catch(()=>({items:[]})),H.get("/api/sidebar/registered-items").catch(()=>[])]),n=new Map([["/","Dashboard (built in)"]]),i=(p,u)=>{for(const o of p||[]){if(!o||o.hidden||o.restricted)continue;const a=typeof o.url=="string"?o.url:"";a.startsWith(Re)||(a.startsWith("#/")&&a.length>2&&!n.has(a.slice(1))&&n.set(a.slice(1),`${u?`${u} \u203A `:""}${o.text||a}`),i(o.items,o.url?u:o.text||u))}},k=(y||[]).filter(p=>!/^~\d+$/.test(String(p?.item?.text||"")));i(Oe(r?.items||[],k),""),n.has(l)||n.set(l,`${l} (not in the sidebar)`),c.replaceChildren();for(const[p,u]of n){const o=document.createElement("option");o.value=p,o.textContent=u,c.appendChild(o)}}let f=null,ge=!1;function Ve(){ge||!window.R?.use||(ge=!0,R.use((c,l,r)=>!(Q.test(l?.path||"")&&!Q.test(c?.path||""))||!f?.dirty()?r():E.confirm("You have unsaved settings. Leave anyway? They are kept as a draft for your next visit (not the SMTP password).").then(n=>{n?r():history.replaceState(null,"","#/settings")})),M.subscribe("router:afterChange",({to:c}={})=>{if(f&&!Q.test(c?.path||"")){const l=f;f=null,l.dispose()}}))}export const settingsView={templateUrl:"/admin/js/templates/settings.html",async onMount(c){if(Ve(),f){const e=f;f=null,e.dispose()}const l=[],r=e=>(l.push(e),e);let y=!1;const n=c.get(0).querySelector(".stx")||c.get(0),i=()=>!y&&n.isConnected,k=E.loader(c.get(0),{type:"dots"});let p;try{p=await $.settings.get()}catch(e){k.destroy(),E.toast(`Could not load the settings: ${e.message||e}`,{type:"error"});return}if(k.destroy(),!n.isConnected)return;const u=M.observable(p||{}),o=$e(p||{}),a={};for(const[e,t]of Object.entries(o))a[e]=M.observable(t);const j=()=>Object.fromEntries(Object.keys(a).map(e=>[e,a[e].value])),X=()=>Object.fromEntries(Object.keys(a).map(e=>[e,a[e].peek()])),v=M.observable(o),U=M.computed(()=>ve(v.value)),x=M.computed(()=>ve(j())!==U.value),C=M.observable(!1),T=M.observable(""),Z=M.observable(!1);$.plugins.policy().then(e=>{i()&&(Z.value=e?.signedOnly===!1)}).catch(()=>{});const q=M.observable(!1),ee=M.computed(()=>{const e=new Set(Ae(j(),v.value));return Object.fromEntries(Object.keys(qe).map(t=>[t,e.has(t)]))}),_=M.observable([]);r(M.effect(()=>{_.value=Ue(j(),u.value).map(e=>({...e,label:e.tone==="danger"?"Mail":"Check"}))}));const te=M.observable(""),L=M.observable(!1),O=M.observable(""),A=M.observable(""),m=M.observable(null),K=M.observable([]),F=M.observable(""),W=M.observable(!0),z=M.observable(""),se=M.observable([]);r(M.effect(()=>{const e=F.value.trim().toLowerCase(),t=Date.now();se.value=[...K.value].reverse().filter(s=>!e||String(s.key).toLowerCase().includes(e)||(s.tags||[]).some(d=>String(d).toLowerCase().includes(e))).map(s=>{const d=J(s.key);return{id:s.key,path:d.path,meta:[d.page?`as ${d.role}`:"not a page",(s.tags||[]).join(", ")].filter(Boolean).join(" \xB7 "),expires:He(s.expiresAt,t)}})}));const ye={...a,saving:C,dirty:x,tabs:ee,problems:_,testTo:te,testing:L,testResult:O,testTone:A,cacheQuery:F,cacheLoading:W,cacheError:z,cacheRows:se,errorText:T,problemsText:M.computed(()=>_.value.length?"yes":""),siteUrlError:M.computed(()=>he(a.siteUrl.value)),noSmtp:M.computed(()=>!String(a.smtpHost.value||"").trim()),mayAllowInsecureTLS:Z,dirtyEmail:M.computed(()=>ee.value.email),cacheOn:M.computed(()=>m.value?.enabled===!0),cacheState:M.computed(()=>{const e=m.value;return e?e.enabled?`On (${e.driver})`:"Off":"Status unknown"}),cacheSize:M.computed(()=>{const e=m.value;return e?.enabled&&e.size!==null&&e.size!==void 0?`${e.size}${e.maxItems?` of ${e.maxItems}`:""} entries`:""}),cacheHits:M.computed(()=>{const e=m.value?.hitRate;return e==null?"":`${Math.round(e*100)}% served from the cache`}),cacheToggleText:M.computed(()=>m.value?.enabled?"Turn off":"Turn on"),cacheEmpty:M.computed(()=>F.value.trim()?"Nothing matches.":m.value?.enabled?"The cache is empty - pages are cached as visitors open them.":"The cache is off.")};async function N(){if(C.peek())return;const e=X(),t=v.peek(),s=he(e.siteUrl);if(s){E.toast(`Site URL: ${s}`,{type:"error"});return}C.value=!0,T.value="";const d=String(e.title).trim()!==String(t.title).trim();try{await $.settings.save(je(e,u.peek(),{adminHomeReady:q.peek()}));const P=await $.settings.get().catch(()=>null);if(!i())return;P&&(u.value=P);const Le={...e,smtpPass:""};a.smtpPass.value="",v.value=Le;try{S.remove?S.remove(g):S.set(g,null)}catch{}document.dispatchEvent(new CustomEvent("dm:admin-home-changed")),(d||["adminBrandEnabled","adminBrandTitle","adminBrandLogo","adminBrandLogoDark","adminBrandIcon"].some(pe=>e[pe]!==t[pe]))&&document.dispatchEvent(new CustomEvent("dm:sidebar-rebuild")),fe(be),E.toast("Settings saved.",{type:"success"})}catch(P){T.value=P.message||"Could not save the settings.",E.toast("Settings not saved - see the message at the top.",{type:"error"})}finally{C.value=!1}}async function we(){await E.confirm("Throw away your unsaved settings?")&&(ae(v.peek()),T.value="")}function ae(e){for(const[t,s]of Object.entries(e))a[t]&&(a[t].value=s)}async function ke(){if(!L.peek()){L.value=!0,A.value="",O.value="Sending\u2026";try{const e=await w("/settings/test-email",{method:"POST",body:JSON.stringify({to:te.peek().trim()||void 0})});if(!i())return;O.value=e?.message||"Test email sent.",A.value="is-ok"}catch(e){if(!i())return;O.value=e.message||"Could not send the test email.",A.value="is-bad"}finally{L.value=!1}}}async function D(){W.value=!0;try{const[e,t]=await Promise.all([w("/cache/status").catch(()=>null),w("/cache/keys")]);if(!i())return;m.value=e,K.value=Array.isArray(t?.entries)?t.entries:[],z.value=""}catch(e){if(!i())return;z.value=`Could not read the cache: ${e.message||e}`}finally{W.value=!1}}async function Ee(){if(await E.confirm("Clear the whole response cache? The next visitor to each page renders it afresh.")){try{await w("/cache/clear",{method:"POST"}),E.toast("Cache cleared.",{type:"success"})}catch(e){E.toast(e.message||"Could not clear the cache.",{type:"error"})}i()&&await D()}}async function Se(){const e=m.peek()?.enabled===!0;if(!(e&&!await E.confirm("Turn the response cache off? Every visit will render its page afresh until it is turned back on. The choice is saved (config/cache.json)."))){try{m.value=await w("/cache/toggle",{method:"POST",body:JSON.stringify({enabled:!e})}),E.toast(e?"Cache turned off.":"Cache turned on.",{type:"success"}),fe(be)}catch(t){E.toast(t.message||"Could not change the cache.",{type:"error"})}i()&&await D()}}const ne=e=>K.peek().find(t=>t.key===e);function Me(e){const t=ne(e);if(!t)return[];const s=J(t.key);return[{header:s.path},{label:"Open the page",icon:"external-link",disabled:!s.page,action:()=>window.open(s.path,"_blank","noopener")},{label:"Copy key",icon:"copy",action:async()=>{try{await navigator.clipboard.writeText(t.key),E.toast("Key copied.",{type:"success"})}catch{E.toast("Could not copy - your browser blocked the clipboard.",{type:"warning"})}}},...s.page?[{label:"Copy address",icon:"link",action:async()=>{try{await navigator.clipboard.writeText(new URL(s.path,location.origin).href),E.toast("Address copied.",{type:"success"})}catch{E.toast("Could not copy - your browser blocked the clipboard.",{type:"warning"})}}}]:[]]}n.querySelector(".stx-problems").innerHTML=We;const b=n.querySelector(".stx-list");b.innerHTML=ze;const V=E.tabs(n.querySelector(".stx-tabs"),{tabSelector:".tab-item",panelSelector:".tab-panel"}),oe=new URLSearchParams(location.hash.split("?")[1]||"").get("tab");B.includes(oe)&&V.activate(B.indexOf(oe));const xe=M.applyBindings(ye,n,{methods:{save:N,discard:we,sendTest:ke,refreshCache:D,clearCache:Ee,toggleCache:Se,pickBrandImage:async e=>{const t=await _e({title:"Choose a branding image",current:a[e].peek()});t&&i()&&(a[e].value=t)},clearBrandImage:e=>{a[e].value=""},goTab:e=>{const t=B.indexOf(e);t>=0&&V.activate(t)}}});r(()=>xe.dispose());for(const e of n.querySelectorAll("[data-brand-icon]")){const t=e.dataset.brandIcon,s=Ke("Choose an icon",a[t].peek());s.input.id=`stx-${t}`,s.input.classList.add("form-input");const d=()=>{a[t].value=s.input.value};s.input.addEventListener("input",d),r(()=>s.input.removeEventListener("input",d)),r(M.effect(()=>{s.input.value=a[t].value})),e.appendChild(s.el)}r(Ie(n,{position:"bottom"}));const Ce=e=>{const t=e.target.closest("[data-go]");if(!t)return;const s=B.indexOf(t.dataset.go);s>=0&&V.activate(s)};n.querySelector(".stx-problems").addEventListener("click",Ce);const Y=n.querySelector("#stx-admin-home");Ne(Y,Be(a.adminHome.peek())).then(()=>{i()&&(Y.value=a.adminHome.peek(),q.value=!0)}).catch(()=>{});const Te=E.contextMenu(b,{cursor:"glyph",match:".stx-row",inherit:!1,density:"compact",items:e=>Me(e.dataset.id)});r(()=>Te?.destroy?.());const re=e=>{const t=ne(e.dataset.id),s=t&&J(t.key);s?.page?window.open(s.path,"_blank","noopener"):G(e)},ie=e=>{const t=e.target.closest(".stx-row");if(!t)return;const s=e.target.closest(".stx-kebab");if(s){G(s);return}re(t)},ce=e=>{const t=e.target.closest(".stx-row");t&&(e.key==="F10"&&e.shiftKey?(e.preventDefault(),G(t)):e.key==="Enter"&&e.target===t&&re(t))};b.addEventListener("click",ie),b.addEventListener("keydown",ce),r(()=>{b.removeEventListener("click",ie),b.removeEventListener("keydown",ce)}),me(c,{id:"settings-view-site",icon:"external-link",title:"View site",onClick:()=>window.open("/","_blank","noopener")}),me(c,{id:"settings-save",icon:"save",title:"Save (Ctrl+S)",onClick:()=>N()});const le=e=>{!(e.ctrlKey||e.metaKey)||e.key!=="s"||(e.preventDefault(),e.stopImmediatePropagation(),N())};document.addEventListener("keydown",le,!0),r(()=>document.removeEventListener("keydown",le,!0));const ue=()=>{if(x.peek())try{S.set(g,{form:De(X()),base:U.peek(),at:new Date().toISOString()})}catch{}},de=e=>{x.peek()&&(ue(),e.preventDefault(),e.returnValue="")};window.addEventListener("beforeunload",de),r(()=>window.removeEventListener("beforeunload",de)),f={dirty:()=>x.peek(),dispose(){y=!0,ue(),l.splice(0).reverse().forEach(e=>{try{e()}catch{}})}},I.scan(n),D();let h=null;try{h=S.get(g)}catch{}if(h?.form){try{S.remove?S.remove(g):S.set(g,null)}catch{}const e=h.base&&h.base!==U.peek(),t=h.at?` (${Fe(h.at)})`:"",s=e?`You left unsaved settings${t}, but the saved settings have changed since. Restore your version anyway?`:`You left unsaved settings${t}. Restore them?`;await E.confirm(s)&&i()&&(ae(Pe(v.peek(),h.form)),q.peek()&&(Y.value=a.adminHome.peek()))}}};
@@ -930,7 +930,7 @@ The public `GET` list endpoint accepts all the same query parameters as the admi
930
930
 
931
931
  | Parameter | Description |
932
932
  |---|---|
933
- | `scope=mine` | Restrict to the current user's own entries (`createdBy = <user.id>`). Requires a JWT. Bypasses the `api.read` gate - users can always view their own data. |
933
+ | `scope=mine` | Restrict to the current user's own entries (`createdBy = <user.id>`). Requires a JWT. Bypasses the `api.read` gate - users can view their own data unless the schema sets `api.mine: false` (then 404 as for an unknown collection, here and on `render-scope`). |
934
934
 
935
935
  **`POST /api/collections/render-scope`** - renders a `[collection scope="mine"]` placeholder server-side with the
936
936
  current user's id injected. Called by the public site JS when it encounters `.dm-collection-hydrate` placeholders.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "domma-cms",
3
- "version": "1.48.1",
3
+ "version": "1.48.3",
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",
@@ -25,11 +25,11 @@ import {config, getConfig} from '../../config.js';
25
25
  import {getRegisteredSidebarItems, hooks} from '../../services/hooks.js';
26
26
  import {getMenu} from '../../services/menus.js';
27
27
  import {resolveAdminHome} from '../../services/adminHome.js';
28
+ import {adminAccessFor} from '../../services/adminAccess.js';
28
29
  import {adminBrandFor} from '../../services/adminBrand.js';
29
30
  import {authenticate, checkVisibility} from '../../middleware/auth.js';
30
- import {getAdminScope, getPermissionsForRoles, getRoleLevel} from '../../services/roles.js';
31
+ import {getRoleLevel} from '../../services/roles.js';
31
32
  import {getEffectiveRegistry, GROUP_ORDER} from '../../services/permissionRegistry.js';
32
- import {getEffectiveRoles} from '../../services/userRoles.js';
33
33
  import {
34
34
  clearResetToken,
35
35
  countUsers,
@@ -236,12 +236,9 @@ export async function authRoutes(fastify) {
236
236
  fastify.get('/auth/permissions', {preHandler: [authenticate]}, async (request) => {
237
237
  // Every role the user holds, not just the primary one - the server
238
238
  // grants on the union, so the sidebar must hide on the union too.
239
- const roles = getEffectiveRoles(request.user);
240
- const allResources = getEffectiveRegistry().map(r => r.key);
241
- const permissions = getPermissionsForRoles(roles, allResources);
242
239
  // adminScope: null = the whole admin; otherwise {home, allow} - the
243
240
  // screens this user's roles confine them to (see roles.getAdminScope).
244
- const adminScope = getAdminScope(roles);
241
+ const {permissions, adminScope} = adminAccessFor(request.user);
245
242
  // adminHome: the screen `#/` opens for this user - see services/adminHome.js.
246
243
  // The menu is read only when a site home has to be checked against it.
247
244
  let adminHome = await resolveAdminHome({
@@ -255,7 +252,9 @@ export async function authRoutes(fastify) {
255
252
  // Dashboard Pro's "Open on my boards" - for a user the admin does not confine.
256
253
  if (!adminScope && isDashboardPro() && (await readPrefs(request.user)).home) adminHome = '/dashboards';
257
254
  // adminBrand: the admin's name and mark for the top bar, sidebar header and tab title.
258
- return {permissions, adminScope, adminHome, versions: frameworkVersions(), adminBrand: adminBrandFor(getConfig('site'))};
255
+ // A confined user is shown none of the admin's chrome (versions included) - see admin-scope.js.
256
+ return {permissions, adminScope, adminHome, ...(!adminScope && {versions: frameworkVersions()}),
257
+ adminBrand: adminBrandFor(getConfig('site'))};
259
258
  });
260
259
 
261
260
  // GET /api/auth/permissions-registry - returns the full permissions registry,
@@ -129,6 +129,7 @@ import {
129
129
  isRoot,
130
130
  isUserDataPreset,
131
131
  mayReadRow,
132
+ mineAllowed,
132
133
  mayWriteRow,
133
134
  ownRowsFilter,
134
135
  pinOwner,
@@ -802,6 +803,7 @@ export async function collectionsRoutes(fastify) {
802
803
  * JWT; returns 401 if unauthenticated. Used by the
803
804
  * `[collection scope="mine"]` shortcode for per-user
804
805
  * client-side hydration (e.g. "My Applications").
806
+ * 404 when the schema says `api.mine: false`.
805
807
  */
806
808
  async function publicListEntries(request, reply) {
807
809
  // Allowed in robots.txt so Google can render pages that read it; the JSON itself is never a search result.
@@ -827,6 +829,9 @@ export async function collectionsRoutes(fastify) {
827
829
  } catch {
828
830
  return reply.status(401).send({ error: 'Authentication required' });
829
831
  }
832
+ // A collection that opts out (`api.mine: false`) is not there for this
833
+ // door at all: the unknown-slug answer, after the same 401 as any other.
834
+ if (!mineAllowed(schema)) return reply.status(404).send({ error: 'Collection not found' });
830
835
  } else {
831
836
  if (!(await checkPublicAccess(schema, 'read', request, reply))) return;
832
837
  }
@@ -900,7 +905,7 @@ export async function collectionsRoutes(fastify) {
900
905
  * Security: results are always scoped to `createdBy = <user.id>` -
901
906
  * a caller can only ever render their own entries, regardless of the
902
907
  * collection's `api.read` setting. This matches the security model
903
- * of GET /:slug/public?scope=mine.
908
+ * of GET /:slug/public?scope=mine, `api.mine: false` (404) included.
904
909
  */
905
910
  fastify.post('/collections/render-fragment', async (request, reply) => {
906
911
  /*
@@ -980,6 +985,8 @@ export async function collectionsRoutes(fastify) {
980
985
 
981
986
  const schema = await getCollection(attrs.slug);
982
987
  if (!schema) return reply.status(404).send({ error: 'Collection not found' });
988
+ // Own rows without api.read: refused where the collection opts out (api.mine: false).
989
+ if (!mineAllowed(schema)) return reply.status(404).send({ error: 'Collection not found' });
983
990
 
984
991
  // Interactive attrs come back as a Collection Browser shell scoped to
985
992
  // this viewer (transitions included); the rest as a static fragment.
@@ -35,6 +35,7 @@ import {existsSync, readFileSync} from 'node:fs';
35
35
  import {compareVersions, installPlugin} from '../../services/pluginInstaller.js';
36
36
  import {fetchCatalogue, isManaged} from '../../services/managerClient.js';
37
37
  import {packEnvelope, readEnvelope, readManifestFromTarball, tarDirectory} from '../../services/pluginEnvelope.js';
38
+ import {adminAccessFor} from '../../services/adminAccess.js';
38
39
 
39
40
  /**
40
41
  * The version of a plugin currently on disk, or null if the slug is free.
@@ -384,7 +385,17 @@ export async function pluginsRoutes(fastify, opts = {}) {
384
385
 
385
386
  // Return merged admin config (sidebar, routes, views) for enabled plugins
386
387
  fastify.get('/plugins/admin-config', { preHandler: [authenticate] }, async (request) => {
387
- return getAdminPluginConfig(request.user);
388
+ const cfg = await getAdminPluginConfig(request.user);
389
+ // A user their roles confine (role.admin) sees a plugin's screens, not
390
+ // facts about the product: no version, date, author, licence or expiry
391
+ // in its banner (admin/js/lib/plugin-chrome.js).
392
+ if (!adminAccessFor(request.user).adminScope || !cfg?.meta) return cfg;
393
+ const meta = {};
394
+ for (const [view, m] of Object.entries(cfg.meta)) {
395
+ const {version, date, author, licence, expiry, ...rest} = m || {};
396
+ meta[view] = rest;
397
+ }
398
+ return {...cfg, meta};
388
399
  });
389
400
 
390
401
  // ── In-admin code editor (plugins.develop - code execution grade) ──────
@@ -10,9 +10,13 @@
10
10
  * the admin needs a sidebar, and a role without menu-editing rights (a
11
11
  * `candidate`, say) used to get a 403 here and fall back to a hardcoded tree
12
12
  * holding a Menus link they could not open. Items gated by `visibility` are
13
- * dropped on the server, the same way the public navbar drops them; items
14
- * gated by `permission`, and `hidden` items, are dropped by the renderer - it
15
- * needs the hidden ones to know which Tools a menu has hidden.
13
+ * dropped on the server, the same way the public navbar drops them. Items the
14
+ * caller may not use (a permission they lack, a screen outside the scope their
15
+ * roles confine them to) become label-less stubs - redactSidebarMenu() in
16
+ * admin/js/lib/sidebar-grouping.js, the module the renderer filters with, so
17
+ * the two cannot drift. `hidden` items the caller may use still arrive: the
18
+ * renderer needs them to know which Tools a menu has hidden. A confined
19
+ * caller's registered items are only the Tools they may use.
16
20
  *
17
21
  * Auth middlewares are accepted as DI options so tests can supply no-ops.
18
22
  */
@@ -24,6 +28,17 @@ import {isDashboardPro} from '../../services/widgets.js';
24
28
  import {boardName, readPrefs, readSite} from '../../services/dashboardSettings.js';
25
29
  import {frequentProblems, readFrequent, writeFrequent} from '../../services/sidebarFrequent.js';
26
30
  import {sidebarCountRoutes} from './sidebar-counts.js';
31
+ import {adminAccessFor} from '../../services/adminAccess.js';
32
+
33
+ /**
34
+ * The renderer's own placement module (pure). Loaded by path at runtime rather
35
+ * than imported statically: on a child site admin/ is the manager's copy, and
36
+ * an admin/ older than this server - without redactSidebarMenu - must leave
37
+ * the sidebar as it was, not stop the server booting.
38
+ */
39
+ const grouping = await import('../../../admin/js/lib/sidebar-grouping.js')
40
+ .then(m => (typeof m.redactSidebarMenu === 'function' && typeof m.toolsForViewer === 'function' ? m : null))
41
+ .catch(() => null);
27
42
 
28
43
  export const ADMIN_SIDEBAR_SLUG = 'admin-sidebar';
29
44
 
@@ -44,6 +59,17 @@ export async function sidebarRoutes(fastify, opts = {}) {
44
59
  return Array.isArray(next.items) ? {...next, items: relabel(next.items, label)} : next;
45
60
  });
46
61
 
62
+ /**
63
+ * Every enabled Tool's entry this user may see (`visibility`, staff-only),
64
+ * and the ones their renderer is given: the same, less - for a user their
65
+ * roles confine - every Tool they may not use.
66
+ */
67
+ const toolsFor = async (request, access) => {
68
+ const all = await visibleTools(request);
69
+ const delivered = grouping ? grouping.toolsForViewer(all, access.permissions, access.adminScope) : all;
70
+ return {all, delivered};
71
+ };
72
+
47
73
  fastify.get('/sidebar/menu', signedIn, async (request) => {
48
74
  const menu = await getMenu(ADMIN_SIDEBAR_SLUG);
49
75
  if (!menu) return {items: []};
@@ -51,12 +77,27 @@ export async function sidebarRoutes(fastify, opts = {}) {
51
77
  // renderer needs them to place Tools before it drops them. An item
52
78
  // this user may not see (`visibility`) arrives as a label-less hidden
53
79
  // stub for the same reason - see restrictedStub() in menus.js.
54
- const items = withoutHiddenSidebarUrls(filterItemsForUser(menu.items || [], request.user, {keepHidden: true}));
80
+ let items = withoutHiddenSidebarUrls(filterItemsForUser(menu.items || [], request.user, {keepHidden: true}));
55
81
  const label = await dashboardsLabel(request);
56
- return {...menu, items: label ? relabel(items, label) : items};
82
+ if (label) items = relabel(items, label);
83
+ if (grouping) {
84
+ const access = adminAccessFor(request.user);
85
+ const {all} = await toolsFor(request, access);
86
+ items = grouping.redactSidebarMenu(items, {...access, tools: all});
87
+ }
88
+ return {...menu, items};
57
89
  });
58
90
 
59
91
  fastify.get('/sidebar/registered-items', signedIn, async (request) => {
92
+ const access = adminAccessFor(request.user);
93
+ const {all, delivered} = await toolsFor(request, access);
94
+ // The Menus editor and Arrange (`?for=editor`) save the menu, so they need
95
+ // the real Tools - for someone who may change menus, and only then.
96
+ if (request.query?.for === 'editor' && grouping?.canAny(access.permissions, 'menus')) return all;
97
+ return delivered;
98
+ });
99
+
100
+ async function visibleTools(request) {
60
101
  // A Tool that owns `#/` (the fleet manager's Dashboard) registers the entry itself.
61
102
  const boardLabel = await dashboardsLabel(request);
62
103
  return getRegisteredSidebarItems()
@@ -69,7 +110,7 @@ export async function sidebarRoutes(fastify, opts = {}) {
69
110
  .map(entry => Array.isArray(entry.item?.items)
70
111
  ? {...entry, item: {...entry.item, items: filterItemsForUser(entry.item.items, request.user)}}
71
112
  : entry);
72
- });
113
+ }
73
114
 
74
115
  // Each person's own, so it follows them from browser to browser (sidebarFrequent.js).
75
116
  fastify.get('/sidebar/frequent', signedIn, async (request) => readFrequent(request.user));
@@ -0,0 +1,20 @@
1
+ /**
2
+ * What a signed-in user may do in the admin: their permissions (on the union
3
+ * of every role they hold) and the admin scope their roles confine them to
4
+ * (null = the whole admin; see roles.getAdminScope). One function, so
5
+ * /api/auth/permissions - what the browser hides on - and the routes that
6
+ * filter for the caller (the sidebar, the plugin chrome) cannot disagree.
7
+ */
8
+ import {getAdminScope, getPermissionsForRoles} from './roles.js';
9
+ import {getEffectiveRegistry} from './permissionRegistry.js';
10
+ import {getEffectiveRoles} from './userRoles.js';
11
+
12
+ /**
13
+ * @param {object} user - request.user
14
+ * @returns {{roles: string[], permissions: string[], adminScope: {home: string, allow: string[]}|null}}
15
+ */
16
+ export function adminAccessFor(user) {
17
+ const roles = getEffectiveRoles(user);
18
+ const allResources = getEffectiveRegistry().map(r => r.key);
19
+ return {roles, permissions: getPermissionsForRoles(roles, allResources), adminScope: getAdminScope(roles)};
20
+ }
@@ -223,6 +223,25 @@ export function ownerOf(slug, entry) {
223
223
  return entry?.[where.in]?.[where.field] ?? null;
224
224
  }
225
225
 
226
+ /**
227
+ * Whether signed-in users may read the rows they created in this collection
228
+ * through `scope=mine` (`GET /:slug/public?scope=mine`, `/api/v1/:slug?scope=mine`
229
+ * and `POST /render-scope` for `[collection scope="mine"]`) - the one door that
230
+ * shows a user their own rows WITHOUT `api.read`. On unless the schema says
231
+ * `api.mine: false`: a collection whose rows carry fields the creator must not
232
+ * see (set by the owning plugin's routes after the user submitted) turns it off.
233
+ * Admin-built views with an owner row-level rule are a separate, explicit grant
234
+ * and do not read this flag.
235
+ *
236
+ * @param {object|null} schema
237
+ * @returns {boolean}
238
+ */
239
+ export function mineAllowed(schema) {
240
+ // Only absent or `true` leaves it on: a typo ("false", null, 0) narrows rather than opens.
241
+ const mine = schema?.api?.mine;
242
+ return mine === undefined || mine === true;
243
+ }
244
+
226
245
  /**
227
246
  * The list filter that keeps a user-data preset to the caller's own rows, or
228
247
  * null when no filter applies (not a user-data preset, root, or a preset whose
@@ -193,6 +193,13 @@ export async function updateCollection(slug, updates) {
193
193
  updatedAt: new Date().toISOString()
194
194
  };
195
195
 
196
+ // `api.mine` (see mineAllowed in collectionAccess.js) is kept when an
197
+ // update's api block does not mention it: clients that rebuild `api` from
198
+ // the four verbs would otherwise switch a collection's opt-out back on.
199
+ if (rest.api && typeof rest.api === 'object' && !('mine' in rest.api) && schema.api && 'mine' in schema.api) {
200
+ updated.api = {...rest.api, mine: schema.api.mine};
201
+ }
202
+
196
203
  // Preserve the original plugin field (never overwrite)
197
204
  if (schema.plugin) {
198
205
  updated.plugin = schema.plugin;
@@ -42,7 +42,7 @@ import {disableInstantCalls, enableInstantCalls, grantInstantCallsOnce} from './
42
42
  import {claimHosts} from './hostClaims.js';
43
43
  import {pluginSafeFetch} from './outbound.js';
44
44
  import {disableDashboardPro, enableDashboardPro, registerWidget, unregisterWidgetsFrom} from './widgets.js';
45
- import {createCollection, getCollection} from './collections.js';
45
+ import {createCollection, getCollection, updateCollection} from './collections.js';
46
46
  import * as defaultRolesService from './roles.js';
47
47
  import {getAdminScope, normaliseAdminScope} from './roles.js';
48
48
  import {pluginAuthGuards} from './pluginScope.js';
@@ -627,7 +627,7 @@ export async function registerPlugins(fastify) {
627
627
  }
628
628
 
629
629
  // Ensure plugin collections exist (idempotent - skips if already present)
630
- await setupPlugin(manifest.name, {collections: {getCollection, createCollection}})
630
+ await setupPlugin(manifest.name, {collections: {getCollection, createCollection, updateCollection}})
631
631
  .catch(err => fastify.log.warn(`[plugins] Collection setup for "${manifest.name}" failed: ${err.message}`));
632
632
 
633
633
  // Permissions are held in memory, so they are registered on every
@@ -787,6 +787,15 @@ export async function setupPlugin(pluginName, services) {
787
787
  if (!existing) {
788
788
  await services.collections.createCollection(schema);
789
789
  result.collections.push(schema.slug);
790
+ } else if (schema.api?.mine === false && existing.api?.mine !== false
791
+ && existing.plugin === pluginName && services.collections.updateCollection) {
792
+ // The plugin's schema turns scope=mine off: an existing
793
+ // install gets that too (it only ever narrows - never the
794
+ // reverse, which stays the site's choice).
795
+ await services.collections.updateCollection(schema.slug, {
796
+ api: {...(existing.api || {}), mine: false},
797
+ ...(existing.bundled && {bundled: true})
798
+ });
790
799
  }
791
800
  } catch {
792
801
  // Skip missing or invalid schema files
@@ -562,6 +562,15 @@ async function keptStorage(schemaPath) {
562
562
  return null;
563
563
  }
564
564
 
565
+ /** Whether an existing schema.json switches scope=mine off (`api.mine: false`). */
566
+ async function keptMineOff(schemaPath) {
567
+ try {
568
+ return JSON.parse(await fs.readFile(schemaPath, 'utf8'))?.api?.mine === false;
569
+ } catch {
570
+ return false;
571
+ }
572
+ }
573
+
565
574
  /**
566
575
  * Seed all preset collections at boot.
567
576
  * Always overwrites schema.json; only creates data.json if absent.
@@ -578,7 +587,12 @@ export async function seedAll() {
578
587
  // A user-data preset keeps the storage the site has (a move to or from
579
588
  // MongoDB); rewriting it would flip the site to the other store.
580
589
  const kept = USER_DATA.has(schema.slug) ? await keptStorage(schemaPath) : null;
581
- const written = kept ? {...schema, storage: kept} : schema;
590
+ let written = kept ? {...schema, storage: kept} : schema;
591
+ // A site's `api.mine: false` (own rows not readable through scope=mine)
592
+ // survives the rewrite; it only ever narrows access.
593
+ if (schema.api?.mine !== false && await keptMineOff(schemaPath)) {
594
+ written = {...written, api: {...(written.api || {}), mine: false}};
595
+ }
582
596
  await fs.writeFile(schemaPath, JSON.stringify(written, null, 2) + '\n', 'utf8');
583
597
 
584
598
  try {