domma-cms 1.31.0 → 1.33.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.
- package/CHANGELOG.md +15 -0
- package/CLAUDE.md +20 -2
- package/admin/js/lib/admin-brand.js +1 -1
- package/admin/js/lib/admin-theme.js +1 -1
- package/admin/js/lib/block-packs.js +26 -0
- package/admin/js/lib/block-tags.js +6 -1
- package/admin/js/lib/shortcode-context-menu.js +2 -2
- package/admin/js/lib/shortcode-form.js +7 -4
- package/admin/js/lib/shortcode-registry.js +1 -1
- package/admin/js/lib/sidebar-frequent.js +1 -1
- package/admin/js/lib/sidebar-renderer.js +4 -4
- package/admin/js/lib/site-settings-arrange.js +2 -2
- package/admin/js/lib/theme-aware-logo.js +1 -0
- package/admin/js/templates/docs/usage-blocks.html +28 -1
- package/admin/js/templates/settings.html +7 -1
- package/admin/js/views/blocks.js +4 -4
- package/admin/js/views/settings.js +2 -2
- package/docs/DommaFeatures.md +87 -8
- package/docs/markdown-shortcodes.md +35 -1
- package/docs/starter-blocks.md +106 -1
- package/package.json +1 -1
- package/server/blocks/catalog.json +30 -0
- package/server/blocks/domma-block-comparison-card.css +20 -0
- package/server/blocks/domma-block-comparison-card.html +18 -0
- package/server/blocks/domma-block-comparison-card.meta.json +7 -0
- package/server/blocks/domma-block-cta-card.css +20 -0
- package/server/blocks/domma-block-cta-card.html +15 -0
- package/server/blocks/domma-block-cta-card.meta.json +7 -0
- package/server/blocks/domma-block-cushion-card.css +30 -0
- package/server/blocks/domma-block-cushion-card.html +11 -0
- package/server/blocks/domma-block-cushion-card.meta.json +7 -0
- package/server/blocks/domma-block-feature-card.css +20 -0
- package/server/blocks/domma-block-feature-card.html +15 -0
- package/server/blocks/domma-block-feature-card.meta.json +7 -0
- package/server/blocks/domma-block-image-card.css +20 -0
- package/server/blocks/domma-block-image-card.html +17 -0
- package/server/blocks/domma-block-image-card.meta.json +7 -0
- package/server/routes/api/block-packs.js +55 -0
- package/server/routes/api/blocks.js +4 -1
- package/server/services/adminBrand.js +4 -1
- package/server/services/block-pack-assets.js +6 -0
- package/server/services/block-packs.js +291 -0
- package/server/services/block-slots.js +43 -0
- package/server/services/block-write-lock.js +44 -0
- package/server/services/blocks.js +18 -3
- package/server/services/embedCsp.js +1 -1
- package/server/services/markdown.js +166 -14
- package/server/services/sidebarFrequent.js +1 -1
- package/server/services/starter-block-packs.js +22 -0
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import{api as g,getUser as
|
|
1
|
+
import{syncThemeAwareLogos as qe}from"./theme-aware-logo.js";import{api as g,getUser as k,isAuthenticated as Ce}from"../api.js";import{createRequestQueue as Ae}from"./background-requests.js";import{requestSidebarCounts as Le}from"./sidebar-counts.js";import{beginSidebarCounts as Fe,publishSidebarCount as Ee}from"./sidebar-count-cache.js";import{isPathAllowed as je}from"./admin-scope.js";import{cleanNotify as Be,noticeFromCount as Oe}from"./sidebar-notify.js";import{colourToCss as te,applyFloat as Te,applyHighlight as Me,itemHighlightAttrs as Ne}from"/public/js/menu-decor.mjs?v=20261014-menu-entrance";import{placeTools as He,ensureLockedTools as Re,managePluginsItem as Ie,stripItemByUrl as Pe,insertFoldersBeforeSystem as _e,pruneEmptyToolsFolder as Ue,sidebarStateKey as ne,canAny as G,filterByPermission as ze,MANAGE_PLUGINS_URL as se}from"./sidebar-grouping.js";import{arrangeButtonMarkup as De,canArrange as We,startArrange as Ge}from"./sidebar-arrange.js";import{collapseButtonMarkup as Ke,wireSidebarSize as Ve,COLLAPSED_WIDTH as Xe}from"./sidebar-size.js";import{FREQUENT_MAX as oe,addFrequent as Ze,frequentFolder as Je,moveFrequent as ie,readFrequent as V,readFrequentHidden as Ye,removeFrequent as Qe,saveFrequent as et,syncFrequent as tt,writeFrequent as nt,writeFrequentHidden as ae}from"./sidebar-frequent.js";import{hotkeyFor as re,hotkeyTitle as st,setHotkeyTree as ot}from"./hotkeys-ui.js";import{hotkeyLabel as it}from"./hotkeys.js";function m(e){return String(e??"").replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""")}const at=[{text:"Dashboard",url:"#/",icon:"home"},{text:"Site menus",url:"#/menus",icon:"menu",permission:"menus"}];async function rt(e){if(!G(e,"projects"))return[];let n=[];try{n=await g.projects.listWithCounts()}catch{return[]}if(!Array.isArray(n))return[];const t=[{key:"pages",text:"Pages",icon:"file-text",path:"/pages"},{key:"collections",text:"Collections",icon:"database",path:"/collections"},{key:"forms",text:"Forms",icon:"layout",path:"/forms"},{key:"actions",text:"Actions",icon:"zap",path:"/actions"},{key:"menus",text:"Site menus",icon:"menu",path:"/menus"},{key:"blocks",text:"Blocks",icon:"box",path:"/blocks"},{key:"components",text:"Components",icon:"component",path:"/components"},{key:"views",text:"Views",icon:"eye",path:"/views"},{key:"roles",text:"Roles",icon:"shield",path:"/roles"},{key:"users",text:"Users",icon:"users",path:"/users"},{key:"apis",text:"APIs",icon:"code",path:"/apis"}];return n.map(o=>{const r="#/projects/"+encodeURIComponent(o.slug),u=o.counts||{},i=[{text:"Overview",url:r,icon:o.icon||"folder"}];for(const d of t){const l=Number(u[d.key])||0;l<=0||i.push({text:`${d.text} (${l})`,url:r+d.path,icon:d.icon})}i.push({text:"Settings",url:r+"/settings",icon:"settings"});const a=o.enabled===!1;return{text:o.name||o.slug,key:`project.${o.slug}`,icon:o.icon||"folder",items:i,...a&&{colour:"neutral",badge:{text:"off"}}}})}function lt(e,n){for(const t of e)if(!t.hidden&&(t.key==="projects"||!t.key&&(t.text||"").toLowerCase()==="projects")){t.items=Array.isArray(t.items)?t.items.slice():[],t.items.push(...n);return}}function le(e,n){const t=de.includes(n.tone)?n.tone:"info",o=n.label||String(n.count);n.details?I.set(e,n.details):I.delete(e);const s=!n.inventory&&j.some(r=>r.url===e&&!r.inventory)?" data-live":"";return`<span class="sidebar-badge sidebar-badge--${t}" data-count-for="${m(e)}"${s} data-badge-label="${m(o)}" aria-label="${m(o)}">${m(String(n.count))}</span>`}function ce(e){for(const n of e.querySelectorAll("details")){const t=n.querySelector(":scope > summary");if(!t)continue;let o=0,s=!1;const r=[];for(const l of n.querySelectorAll(":scope > .sidebar-children .sidebar-badge[data-live]")){const f=Number(l.textContent)||0;f&&(o+=f,s||(s=l.classList.contains("sidebar-badge--danger")),r.push({text:l.closest("a")?.querySelector(".sidebar-text")?.textContent.trim()??"",meta:l.dataset.badgeLabel,tone:l.classList.contains("sidebar-badge--danger")?"danger":void 0}))}const u=`folder:${n.dataset.stateKey||t.textContent.trim()}`;let i=t.querySelector(":scope > .sidebar-badge--sum");if(!o){i?.remove(),I.delete(u);continue}i||(i=document.createElement("span"),t.querySelector(".sidebar-text")?.after(i));const a=t.querySelector(".sidebar-text")?.textContent.trim()||"This folder",d=r.map(l=>`${l.text}: ${l.meta}`).join(" \xB7 ");i.className=`sidebar-badge sidebar-badge--sum sidebar-badge--${s?"danger":"info"}`,i.dataset.countFor=u,i.dataset.badgeLabel=d,i.setAttribute("aria-label",d),i.textContent=String(o),I.set(u,{title:a,items:r})}}const I=new Map;function ct(e,n){if(!e.url||!n)return"";const t=n[e.url];return!t||!(t.count>0)&&!t.showZero?"":le(e.url,t)}const de=["info","attention","danger","live"],dt={"#/pages":["page","pages"],"#/media":["file in the media library","files in the media library"],"#/menus":["menu","menus"],"#/context-menus":["context menu","context menus"],"#/theme":["element override in the theme","element overrides in the theme"],"#/collections":["collection","collections"],"#/forms":["form","forms"],"#/views":["view","views"],"#/actions":["action","actions"],"#/blocks":["block","blocks"],"#/components":["component","components"],"#/users":["user","users"],"#/plugins":["plugin installed","plugins installed"],"#/system/notifications":["unread notification","unread notifications"]};function K(e,{fallbackLabel:n="",tone:t="info"}={}){const o=Number(typeof e=="object"&&e!==null?e.count:e);if(!Number.isFinite(o)||o<0)return null;const s=typeof e?.label=="string"&&e.label||(n?`${o} - ${n}`:String(o)),r={count:Math.round(o),label:s,tone:de.includes(e?.tone)?e.tone:t};e?.details&&typeof e.details=="object"&&(r.details=e.details),e?.inventory===!0&&(r.inventory=!0),e?.showZero===!0&&(r.showZero=!0);const u=Be(e?.notify);return u&&(r.notify=u),r}function ue(e,n,t=null,{inFrequent:o=!1}={}){if(e&&e.type==="separator")return'<hr class="sidebar-divider">';if(e&&e.type==="theme-switcher")return"";if(e&&e.type==="spacer"){const b=["xs","sm","md","lg","xl","flex"].includes(e.size)?e.size:"md";return`<div class="sidebar-spacer sidebar-spacer--${m(b)}" aria-hidden="true"></div>`}const s=String(e.text||"?").trim().charAt(0).toUpperCase()||"?",r=e.icon?`<span data-icon="${m(e.icon)}"></span>`:`<span class="sidebar-initial" aria-hidden="true">${m(s)}</span>`,u=m(e.text||""),i=e.url?m(e.url):"",a=Array.isArray(e.items)&&e.items.length>0,d=e.colour?te(e.colour):"",l=Ne(e),f=[l.hover&&` data-menu-item-hover="${m(l.hover)}"`,l.active&&` data-menu-item-active="${m(l.active)}"`].filter(Boolean).join(""),h=[d&&`color:${m(d)}`,l.accent&&`--dm-menu-highlight:${m(l.accent)}`].filter(Boolean).join(";"),v=h?` style="${h}"`:"",q=e.url?st(e.url,e.text||"",{inFrequent:o}):"",C=q?` title="${m(q)}"`:"";let F="";if(e.badge&&e.badge.text!=null&&e.badge.text!==""){const b=e.badge.variant?te(e.badge.variant):"";F=`<span class="dm-menu-badge"${b?` style="background:${m(b)};color:var(--dm-text-inverse,#fff)"`:""}>${m(String(e.badge.text))}</span>`}if(e.frequent&&e.empty){const b=ne(e,t),A=S.get(b)!==!1;return`<details data-state-key="${m(b)}"${A?" open":""} data-frequent data-frequent-empty>
|
|
2
2
|
<summary${v}>${r} <span class="sidebar-text">${u}</span></summary>
|
|
3
3
|
<div class="sidebar-children"><p class="sidebar-frequent-empty">Right-click any Tool and choose <strong>Add to Frequent</strong> to keep it here.</p></div>
|
|
4
|
-
</details>`}if(a){const b=ne(e,t),A=S.get(b)!==!1,B=e.items.map(
|
|
5
|
-
<summary${v}${
|
|
4
|
+
</details>`}if(a){const b=ne(e,t),A=S.get(b)!==!1,B=e.items.map(P=>ue(P,n,b,{inFrequent:!!e.frequent})).join(""),L=e.frequent?' data-frequent title="Your Frequent Tools - right-click any Tool to add or remove it"':"";return`<details data-state-key="${m(b)}"${A?" open":""}${L}>
|
|
5
|
+
<summary${v}${C}>${r} <span class="sidebar-text">${u}</span>${F}</summary>
|
|
6
6
|
<div class="sidebar-children">${B}</div>
|
|
7
|
-
</details>`}return`<a href="${i}" class="sidebar-link" data-url="${i}"${v}${f}${q}>${r} <span class="sidebar-text">${u}</span>${rt(e,n)}${F}</a>`}async function ct(e=[],n=[],t=null){const o=y=>y.then(C=>Array.isArray(C)?C.length:Array.isArray(C?.entries)?C.entries.length:0).catch(()=>0),s=fe(e,t),r=new Set(s.map(y=>y.url)),u={pages:"#/pages",media:"#/media",menus:"#/menus","context-menus":"#/context-menus",theme:"#/theme",collections:"#/collections",forms:"#/forms",views:"#/views",actions:"#/actions",blocks:"#/blocks",components:"#/components",users:"#/users",plugins:"#/plugins",notifications:"#/system/notifications"},i=(y,C)=>W(n,y)&&!r.has(u[y])?C():Promise.resolve(0),[a,d,l,f,h,v,k,q,F,b,A,B,L,I]=await Promise.all([i("pages",()=>o(g.pages.list())),i("media",()=>o(g.media.list())),i("menus",()=>o(g.menus.list())),i("context-menus",()=>o(g.contextMenus.list())),i("theme",()=>g.theme.get().then(y=>(y?.overrides||[]).length).catch(()=>0)),i("collections",()=>o(g.collections.list())),i("forms",()=>o(g.forms.list())),i("views",()=>o(g.views.list())),i("actions",()=>o(g.actions.list())),i("blocks",()=>o(g.blocks.list())),i("components",()=>o(g.components.list())),i("users",()=>o(g.users.list())),i("plugins",()=>o(g.plugins.list())),i("notifications",()=>g.system?.notifications?.unreadCount?.().then(y=>y?.count??0).catch(()=>0)??Promise.resolve(0))]),P=await pe(s),U={"#/pages":a,"#/media":d,"#/menus":l,"#/context-menus":f,"#/theme":h,"#/collections":v,"#/forms":k,"#/views":q,"#/actions":F,"#/blocks":b,"#/components":A,"#/users":B,"#/plugins":L,"#/system/notifications":I},z={};for(const[y,C]of Object.entries(U)){if(r.has(y))continue;const[G,Y]=lt[y]??["item","items"],O=D(C);O&&(z[y]={...O,label:`${O.count} ${O.count===1?G:Y}`})}return{...z,...P}}let j=[];const dt="dm:sidebar-count",ut=6e4,ft=qe(4);function fe(e=[],n=null){const t=[],o=s=>{if(s&&!(n&&typeof s.url=="string"&&s.url.startsWith("#/")&&!Le(n,s.url.slice(1)))){s.url&&typeof s.countUrl=="string"&&s.countUrl&&t.push({url:s.url,countUrl:s.countUrl,text:s.text||"",countLabel:s.countLabel||"",inventory:s.inventory===!0});for(const r of[...s.children||[],...s.items||[]])o(r)}};for(const s of e??[])o(s?.item??s);return t}async function me(e,{priority:n=!1}={}){try{const t=new Date,o=`${t.getFullYear()}-${String(t.getMonth()+1).padStart(2,"0")}-${String(t.getDate()).padStart(2,"0")}`,s=e.countUrl+(e.countUrl.includes("?")?"&":"?")+`today=${o}`,r=w()?.id,u=await ft(()=>!ke()||w()?.id!==r?null:H.get(s,{priority:"low"}),{key:JSON.stringify([r,s]),priority:n});return D(u,{fallbackLabel:e.countLabel||e.text})}catch{return null}}function V(e,n,t){Fe(n,t),t?.notify&&je(w()?.id??null,n,t.notify);const o=[...e.querySelectorAll("a.sidebar-link")].filter(s=>s.dataset.url===n);if(o.length){for(const s of o){const r=s.querySelector(".sidebar-badge[data-count-for]");if(!t||!(t.count>0)&&!t.showZero)r?.remove();else{const u=document.createRange();u.selectNodeContents(s);const i=u.createContextualFragment(le(n,t)).firstElementChild;r?r.replaceWith(i):s.querySelector(".sidebar-text")?.after(i)}}X.set(n,t),ce(e)}}const X=new Map;async function pe(e){const n=await Ce(e,{legacy:async t=>{const o=await Promise.all(t.map(async s=>[s.url,await me(s)]));return Object.fromEntries(o)}});return Object.fromEntries(e.map(t=>[t.url,n[t.url]==null?null:D(n[t.url],{fallbackLabel:t.countLabel||t.text})]))}async function Z(e,n=null){const t=w()?.id,o=j;try{const s=n?{[n]:await me(j.find(r=>r.url===n),{priority:!0})}:await pe(j);if(w()?.id!==t||j!==o)return;for(const[r,u]of Object.entries(s)){const i=X.get(r);JSON.stringify(i??null)!==JSON.stringify(u)&&V(e,r,u)}}catch{}}function mt(e){e.dataset.liveCounts||(e.dataset.liveCounts="1",window.addEventListener(dt,n=>{const t=n.detail||{};if(t.url)if(t.count!==void 0){const o=j.find(s=>s.url===t.url);V(e,t.url,D(t,{fallbackLabel:o?.countLabel||o?.text||""}))}else Z(e,t.url)}),setInterval(()=>{!document.hidden&&document.body.contains(e)&&Z(e)},ut),document.addEventListener("visibilitychange",()=>{document.hidden||Z(e)}),pt(e))}function he(e,n,t){const o=(u,i,a)=>{const d=document.createElement(u);return i&&(d.className=i),a!=null&&(d.textContent=String(a)),d};if(!t){e.textContent=n;return}e.appendChild(o("strong","dm-badge-pop-title",t.title||n)),(t.rows?.length||!t.items?.length)&&e.appendChild(o("p","dm-badge-pop-sub",n));const s=Array.isArray(t.rows)?t.rows.slice(0,6):[];if(s.length){const u=o("dl","dm-badge-pop-rows");for(const i of s)u.appendChild(o("dt",null,i.label)),u.appendChild(o("dd",i.tone==="danger"?"is-danger":null,i.value));e.appendChild(u)}const r=Array.isArray(t.items)?t.items.slice(0,6):[];if(r.length){const u=o("ul","dm-badge-pop-items");for(const i of r){const a=o("li",i.tone==="danger"?"is-danger":null);a.appendChild(o("span","dm-badge-pop-text",i.text)),i.meta&&a.appendChild(o("span","dm-badge-pop-meta",i.meta)),u.appendChild(a)}e.appendChild(u)}else t.empty&&e.appendChild(o("p","dm-badge-pop-empty",t.empty))}function pt(e){let n=null,t=null;const o=()=>e.classList.contains("is-collapsed"),s=()=>{clearTimeout(t),n?.remove(),n=null},r=(d,l)=>{s(),t=setTimeout(()=>{n=document.createElement("div"),n.className="dm-help-pop dm-badge-pop",n.setAttribute("role","tooltip"),l(n),document.body.appendChild(n);const f=d.getBoundingClientRect(),h=n.getBoundingClientRect(),v=Math.min(f.right+10,innerWidth-h.width-8);n.style.left=`${Math.max(8,v)}px`,n.style.top=`${Math.max(8,Math.min(f.top+f.height/2-h.height/2,innerHeight-h.height-8))}px`},150)},u=d=>{const l=d?.dataset.badgeLabel;if(!l)return s();r(d,f=>he(f,l,R.get(d.dataset.countFor)))},i=d=>{const l=d.querySelector(":scope > .sidebar-text")?.textContent.trim()||"",f=d.querySelector(":scope > .sidebar-badge[data-badge-label]:not([hidden])");r(d,h=>{const v=f&&R.get(f.dataset.countFor);if(v)return he(h,f.dataset.badgeLabel,{...v,title:v.title||l});if(!f){h.textContent=l;return}const k=document.createElement("strong");k.className="dm-badge-pop-title",k.textContent=l;const q=document.createElement("p");q.className="dm-badge-pop-sub",q.textContent=f.dataset.badgeLabel,h.append(k,q)})},a=d=>{const l=d.closest?.("a.sidebar-link, summary");return l&&e.contains(l)?l:null};e.addEventListener("mouseover",d=>{if(o()){const f=a(d.target);f&&!f.contains(d.relatedTarget)&&i(f);return}const l=d.target.closest?.(".sidebar-badge[data-badge-label]");l&&u(l)}),e.addEventListener("mouseout",d=>{if(o()){const l=a(d.target);l&&!l.contains(d.relatedTarget)&&s();return}d.target.closest?.(".sidebar-badge[data-badge-label]")&&s()}),e.addEventListener("focusin",d=>{const l=d.target.closest?.("a, summary");if(o()&&l&&e.contains(l)&&l.querySelector(":scope > .sidebar-text"))return i(l);const f=l?.querySelector(":scope > .sidebar-badge[data-badge-label]:not([hidden])");f?u(f):s()}),e.addEventListener("focusout",s),e.addEventListener("click",s),window.addEventListener("scroll",s,!0),window.addEventListener("hashchange",s)}async function ht(e=[],n=null){if(n?.title||n?.enabled===!1)return n;if(!W(e,"settings"))return{title:"Domma CMS"};try{const t=await g.settings.get();return{...t?.adminBrand,title:t?.adminBrand?.title||t?.title||"Domma CMS"}}catch{return{title:"Domma CMS"}}}export async function renderAdminSidebar({mount:e,permissions:n,adminScope:t=null,brand:o=null}){const s=$(e).get(0);if(!s)return;const r=Qe(g,w()).catch(()=>{}),u=Promise.resolve().then(()=>H.get("/api/sidebar/registered-items")).catch(()=>[]),i=it(n);let a,d=null,l=null,f=null,h=null,v=null;try{const c=await g.get("/sidebar/menu");a=Array.isArray(c?.items)?c.items:null,d=c?.variant||null,l=c?.position||null,f=c?.style||null,h=c?.float||null,v=c?.highlight||null}catch{a=null}(!a||!a.some(c=>c&&(!c.hidden||c.restricted)))&&(console.warn("[admin-sidebar] No admin-sidebar menu found; using fallback tree"),a=ot.slice());let k=[];try{k=await u||[]}catch{}a=Re(a,se),a=Te(a,k.filter(c=>(c?.item??c)?.url!==se)),a=Ne(a),a=Ie(a,[He()]);const q=await i;q.length&&at(a,q),a=_e(a,n,t),a=Pe(a),await r;const F=Xe(a,K(w()),{hidden:Ze(w())});F&&(a=[F,...a]),nt(a);const b=k.filter(c=>W(n,c?.item?.permission));j=fe(b,t);const A=Ae({user:w(),permissions:n,adminScope:t,registered:b,tree:a,actions:{linkItems:ye,folderItems:ve},fetcher:()=>ct(b,n,t)}),B=A.counts,L=await ht(n,o),I=d?` dm-admin-sidebar--${m(d)}`:"";function P(c,x="px"){if(c==null)return c;const p=String(c).trim();return/^\d+(\.\d+)?$/.test(p)?`${p}${x}`:p}let U="";if(f){const c=[];f.fontFamily&&c.push(`font-family: ${f.fontFamily}, sans-serif`),f.fontSize&&c.push(`font-size: ${P(f.fontSize)}`),f.fontWeight&&c.push(`font-weight: ${f.fontWeight}`),f.letterSpacing&&c.push(`letter-spacing: ${P(f.letterSpacing,"em")}`);const x=[];if(c.length&&x.push(`#admin-sidebar .dm-admin-sidebar, #admin-sidebar .dm-admin-sidebar .sidebar-link, #admin-sidebar .dm-admin-sidebar summary, #admin-sidebar .dm-admin-sidebar .sidebar-text { ${c.join("; ")} }`),f.iconSize){const p=P(f.iconSize);x.push(`#admin-sidebar .dm-admin-sidebar [data-icon], #admin-sidebar .dm-admin-sidebar [data-icon] svg { width: ${p} !important; height: ${p} !important; }`)}x.length&&(U=`<style data-admin-sidebar-style>${x.join(" ")}</style>`)}const z=ze(n)?Ue():"",y=String(L.logo||"").trim(),C=/^(?:\/(?!\/)|https?:\/\/)/i.test(y)?y:"",G=C?`<img src="${m(C)}" alt="" style="width:28px;height:28px;object-fit:contain;flex-shrink:0;">`:`<span data-icon="${m(L.icon||"layout")}"></span>`,O=`<div class="dm-admin-sidebar-header">${L.enabled===!1?"":`${G}<span class="dm-admin-sidebar-title">${m(L.title)}</span>`}${z}${De()}</div>`,xe=a.some(c=>c&&c.type==="spacer"&&c.size==="flex")?" dm-admin-sidebar--has-flex-spacer":"",$e=`${U}<nav class="dm-admin-sidebar${I}${xe}">${O}${a.map(c=>ue(c,B)).join("")}</nav>`,Q=document.createRange();Q.selectNodeContents(s);const we=Q.createContextualFragment($e);s.replaceChildren(we),Domma.icons.scan(s),s.querySelector(".dm-admin-sidebar-arrange")?.addEventListener("click",()=>We(s));for(const c of j)X.set(c.url,B[c.url]??null);ce(s),mt(s),A.refresh.then(c=>{if(!(!A.isActive()||!s.isConnected))for(const[x,p]of Object.entries(c))V(s,x,p)}),s.removeAttribute("data-menu-hover"),s.removeAttribute("data-menu-active"),s.style.removeProperty("--dm-menu-highlight"),Oe(s,{highlight:v});const T=document.querySelector(".dashboard-wrapper");["position","top","bottom","left","right","zIndex","maxHeight","transform"].forEach(c=>{s.style[c]=""}),s.classList.remove("dm-menu-floating"),T&&(T.style.paddingLeft="",T.style.paddingRight=""),s.__dmGutter=()=>{if(l!=="floating"||!T)return;const c=h&&h.anchor||"TL",x=Number.isFinite(Number(h?.offsetX))?Number(h.offsetX):16,p=s.classList.contains("is-collapsed")?Ke:parseInt(s.style.width,10)||s.getBoundingClientRect().width||260,N=Math.round(p+x*2)+"px";c==="R"||c==="TR"||c==="BR"?T.style.paddingRight=N:T.style.paddingLeft=N},l==="floating"&&Be(s,{position:"floating",float:h||{}}),s.querySelectorAll("details").forEach(c=>{c.addEventListener("toggle",function(){const x=this.getAttribute("data-state-key");x&&S.set(x,this.open);const p=this.querySelector(":scope > .sidebar-children");if(p)if(this.open){const N=p.scrollHeight;p.style.maxHeight="0",requestAnimationFrame(()=>{p.style.maxHeight=N+"px",p.addEventListener("transitionend",function Se(){p.style.maxHeight="none",p.removeEventListener("transitionend",Se)})})}else{const N=p.scrollHeight;p.style.maxHeight=N+"px",requestAnimationFrame(()=>{p.style.maxHeight="0"})}})}),Ge(s),bt(s),s.dataset.routeWired||(s.dataset.routeWired="1",M.subscribe("router:afterChange",()=>s.__dmSetActive?.()));function ee(){const c=/^#\/(dashboards|my-dashboard)\b/.test(location.hash)?"#/":location.hash||"#/";$(s).find(".sidebar-link").removeClass("active"),$(s).find(`.sidebar-link[data-url="${c}"]`).addClass("active")}ee(),s.__dmSetActive=ee}function ge(){try{document.dispatchEvent(new CustomEvent("dm:sidebar-rebuild"))}catch{}}function J(e){return`${location.origin}${location.pathname}${e}`}function _(e,n){const t=w(),o=e(K(t));if(!et(t,o)){E.toast("Frequent could not be saved - this browser is blocking storage.",{type:"error"});return}o.length&&ae(t,!1),be(t),n&&E.toast(n,{type:"success",duration:2500}),ge()}function be(e){Ye(g,e).catch(()=>E.toast("Frequent is saved in this browser only - the server could not keep it.",{type:"warning"}))}function gt(e){if(!ae(w(),e)){E.toast("Frequent could not be saved - this browser is blocking storage.",{type:"error"});return}be(w()),E.toast(e?"Frequent hidden. Add a Tool to it from its right-click menu to bring it back.":"Frequent shown.",{type:"success",duration:3500}),ge()}function ye(e){const n=e.dataset.url;if(!n)return[];const t=e.querySelector(".sidebar-text")?.textContent.trim()||n,o=K(w()),s=o.includes(n),r=!!e.closest("[data-frequent]"),u=o.indexOf(n),i=!s&&o.length>=oe;return[{header:t},{label:"Open",icon:"arrow-right",...re(n)&&{shortcut:st(re(n))},action:()=>{location.hash=n}},{label:"Open in a new tab",icon:"external-link",action:()=>window.open(J(n),"_blank","noopener")},{type:"divider"},s?{label:"Remove from Frequent",icon:"star",action:()=>_(a=>Je(a,n),`${t} removed from Frequent.`)}:{label:i?`Frequent is full (${oe})`:"Add to Frequent",icon:"star",disabled:i,action:()=>_(a=>Ve(a,n),`${t} added to Frequent.`)},...r?[{label:"Move up",icon:"arrow-up",disabled:u<=0,action:()=>_(a=>ie(a,n,-1))},{label:"Move down",icon:"arrow-down",disabled:u<0||u>=o.length-1,action:()=>_(a=>ie(a,n,1))}]:[],{type:"divider"},{label:"Copy link",icon:"link",action:async()=>{try{await navigator.clipboard.writeText(J(n)),E.toast("Link copied.",{type:"success",duration:2e3})}catch{E.toast(J(n),{type:"info",duration:8e3})}}}]}function ve(e,n,t={}){const o=e.closest("details, [data-frequent]"),s=t.isOpen||(()=>!!o?.open),r=t.setOpen||(a=>{o&&(o.open=a)}),u=e.querySelector(".sidebar-text")?.textContent.trim()||"Folder",i=t.setAll||(a=>n.querySelectorAll("details").forEach(d=>{d.open!==a&&(d.open=a)}));return[{header:u},{label:s()?"Close":"Open",icon:s()?"chevron-up":"chevron-down",action:()=>r(!s())},...t.singleBranch?[]:[{label:"Open every folder",icon:"chevrons-down",action:()=>i(!0)}],{label:t.singleBranch?"Close all menus":"Close every folder",icon:"chevrons-up",action:()=>i(!1)},...o?.hasAttribute("data-frequent-empty")?[{type:"divider"},{label:"Hide Frequent until I add a Tool",icon:"eye-off",action:()=>gt(!0)}]:o?.hasAttribute("data-frequent")?[{type:"divider"},{label:"Clear Frequent",icon:"x",action:()=>_(()=>[],"Frequent cleared.")}]:[]]}function bt(e){e.dataset.ctxWired||typeof E>"u"||!E.contextMenu||(e.dataset.ctxWired="1",E.contextMenu(e,{match:"a.sidebar-link, details > summary",inherit:!1,density:"compact",items:n=>n.matches("summary")?ve(n,e):ye(n)}))}
|
|
7
|
+
</details>`}return`<a href="${i}" class="sidebar-link" data-url="${i}"${v}${f}${C}>${r} <span class="sidebar-text">${u}</span>${ct(e,n)}${F}</a>`}async function ut(e=[],n=[],t=null){const o=y=>y.then(x=>Array.isArray(x)?x.length:Array.isArray(x?.entries)?x.entries.length:0).catch(()=>0),s=fe(e,t),r=new Set(s.map(y=>y.url)),u={pages:"#/pages",media:"#/media",menus:"#/menus","context-menus":"#/context-menus",theme:"#/theme",collections:"#/collections",forms:"#/forms",views:"#/views",actions:"#/actions",blocks:"#/blocks",components:"#/components",users:"#/users",plugins:"#/plugins",notifications:"#/system/notifications"},i=(y,x)=>G(n,y)&&!r.has(u[y])?x():Promise.resolve(0),[a,d,l,f,h,v,q,C,F,b,A,B,L,P]=await Promise.all([i("pages",()=>o(g.pages.list())),i("media",()=>o(g.media.list())),i("menus",()=>o(g.menus.list())),i("context-menus",()=>o(g.contextMenus.list())),i("theme",()=>g.theme.get().then(y=>(y?.overrides||[]).length).catch(()=>0)),i("collections",()=>o(g.collections.list())),i("forms",()=>o(g.forms.list())),i("views",()=>o(g.views.list())),i("actions",()=>o(g.actions.list())),i("blocks",()=>o(g.blocks.list())),i("components",()=>o(g.components.list())),i("users",()=>o(g.users.list())),i("plugins",()=>o(g.plugins.list())),i("notifications",()=>g.system?.notifications?.unreadCount?.().then(y=>y?.count??0).catch(()=>0)??Promise.resolve(0))]),_=await pe(s),z={"#/pages":a,"#/media":d,"#/menus":l,"#/context-menus":f,"#/theme":h,"#/collections":v,"#/forms":q,"#/views":C,"#/actions":F,"#/blocks":b,"#/components":A,"#/users":B,"#/plugins":L,"#/system/notifications":P},D={};for(const[y,x]of Object.entries(z)){if(r.has(y))continue;const[W,O]=dt[y]??["item","items"],T=K(x);T&&(D[y]={...T,label:`${T.count} ${T.count===1?W:O}`})}return{...D,..._}}let j=[];const ft="dm:sidebar-count",mt=6e4,pt=Ae(4);function fe(e=[],n=null){const t=[],o=s=>{if(s&&!(n&&typeof s.url=="string"&&s.url.startsWith("#/")&&!je(n,s.url.slice(1)))){s.url&&typeof s.countUrl=="string"&&s.countUrl&&t.push({url:s.url,countUrl:s.countUrl,text:s.text||"",countLabel:s.countLabel||"",inventory:s.inventory===!0});for(const r of[...s.children||[],...s.items||[]])o(r)}};for(const s of e??[])o(s?.item??s);return t}async function me(e,{priority:n=!1}={}){try{const t=new Date,o=`${t.getFullYear()}-${String(t.getMonth()+1).padStart(2,"0")}-${String(t.getDate()).padStart(2,"0")}`,s=e.countUrl+(e.countUrl.includes("?")?"&":"?")+`today=${o}`,r=k()?.id,u=await pt(()=>!Ce()||k()?.id!==r?null:H.get(s,{priority:"low"}),{key:JSON.stringify([r,s]),priority:n});return K(u,{fallbackLabel:e.countLabel||e.text})}catch{return null}}function X(e,n,t){Ee(n,t),t?.notify&&Oe(k()?.id??null,n,t.notify);const o=[...e.querySelectorAll("a.sidebar-link")].filter(s=>s.dataset.url===n);if(o.length){for(const s of o){const r=s.querySelector(".sidebar-badge[data-count-for]");if(!t||!(t.count>0)&&!t.showZero)r?.remove();else{const u=document.createRange();u.selectNodeContents(s);const i=u.createContextualFragment(le(n,t)).firstElementChild;r?r.replaceWith(i):s.querySelector(".sidebar-text")?.after(i)}}Z.set(n,t),ce(e)}}const Z=new Map;async function pe(e){const n=await Le(e,{legacy:async t=>{const o=await Promise.all(t.map(async s=>[s.url,await me(s)]));return Object.fromEntries(o)}});return Object.fromEntries(e.map(t=>[t.url,n[t.url]==null?null:K(n[t.url],{fallbackLabel:t.countLabel||t.text})]))}async function J(e,n=null){const t=k()?.id,o=j;try{const s=n?{[n]:await me(j.find(r=>r.url===n),{priority:!0})}:await pe(j);if(k()?.id!==t||j!==o)return;for(const[r,u]of Object.entries(s)){const i=Z.get(r);JSON.stringify(i??null)!==JSON.stringify(u)&&X(e,r,u)}}catch{}}function ht(e){e.dataset.liveCounts||(e.dataset.liveCounts="1",window.addEventListener(ft,n=>{const t=n.detail||{};if(t.url)if(t.count!==void 0){const o=j.find(s=>s.url===t.url);X(e,t.url,K(t,{fallbackLabel:o?.countLabel||o?.text||""}))}else J(e,t.url)}),setInterval(()=>{!document.hidden&&document.body.contains(e)&&J(e)},mt),document.addEventListener("visibilitychange",()=>{document.hidden||J(e)}),gt(e))}function he(e,n,t){const o=(u,i,a)=>{const d=document.createElement(u);return i&&(d.className=i),a!=null&&(d.textContent=String(a)),d};if(!t){e.textContent=n;return}e.appendChild(o("strong","dm-badge-pop-title",t.title||n)),(t.rows?.length||!t.items?.length)&&e.appendChild(o("p","dm-badge-pop-sub",n));const s=Array.isArray(t.rows)?t.rows.slice(0,6):[];if(s.length){const u=o("dl","dm-badge-pop-rows");for(const i of s)u.appendChild(o("dt",null,i.label)),u.appendChild(o("dd",i.tone==="danger"?"is-danger":null,i.value));e.appendChild(u)}const r=Array.isArray(t.items)?t.items.slice(0,6):[];if(r.length){const u=o("ul","dm-badge-pop-items");for(const i of r){const a=o("li",i.tone==="danger"?"is-danger":null);a.appendChild(o("span","dm-badge-pop-text",i.text)),i.meta&&a.appendChild(o("span","dm-badge-pop-meta",i.meta)),u.appendChild(a)}e.appendChild(u)}else t.empty&&e.appendChild(o("p","dm-badge-pop-empty",t.empty))}function gt(e){let n=null,t=null;const o=()=>e.classList.contains("is-collapsed"),s=()=>{clearTimeout(t),n?.remove(),n=null},r=(d,l)=>{s(),t=setTimeout(()=>{n=document.createElement("div"),n.className="dm-help-pop dm-badge-pop",n.setAttribute("role","tooltip"),l(n),document.body.appendChild(n);const f=d.getBoundingClientRect(),h=n.getBoundingClientRect(),v=Math.min(f.right+10,innerWidth-h.width-8);n.style.left=`${Math.max(8,v)}px`,n.style.top=`${Math.max(8,Math.min(f.top+f.height/2-h.height/2,innerHeight-h.height-8))}px`},150)},u=d=>{const l=d?.dataset.badgeLabel;if(!l)return s();r(d,f=>he(f,l,I.get(d.dataset.countFor)))},i=d=>{const l=d.querySelector(":scope > .sidebar-text")?.textContent.trim()||"",f=d.querySelector(":scope > .sidebar-badge[data-badge-label]:not([hidden])");r(d,h=>{const v=f&&I.get(f.dataset.countFor);if(v)return he(h,f.dataset.badgeLabel,{...v,title:v.title||l});if(!f){h.textContent=l;return}const q=document.createElement("strong");q.className="dm-badge-pop-title",q.textContent=l;const C=document.createElement("p");C.className="dm-badge-pop-sub",C.textContent=f.dataset.badgeLabel,h.append(q,C)})},a=d=>{const l=d.closest?.("a.sidebar-link, summary");return l&&e.contains(l)?l:null};e.addEventListener("mouseover",d=>{if(o()){const f=a(d.target);f&&!f.contains(d.relatedTarget)&&i(f);return}const l=d.target.closest?.(".sidebar-badge[data-badge-label]");l&&u(l)}),e.addEventListener("mouseout",d=>{if(o()){const l=a(d.target);l&&!l.contains(d.relatedTarget)&&s();return}d.target.closest?.(".sidebar-badge[data-badge-label]")&&s()}),e.addEventListener("focusin",d=>{const l=d.target.closest?.("a, summary");if(o()&&l&&e.contains(l)&&l.querySelector(":scope > .sidebar-text"))return i(l);const f=l?.querySelector(":scope > .sidebar-badge[data-badge-label]:not([hidden])");f?u(f):s()}),e.addEventListener("focusout",s),e.addEventListener("click",s),window.addEventListener("scroll",s,!0),window.addEventListener("hashchange",s)}async function bt(e=[],n=null){if(n?.title||n?.enabled===!1)return n;if(!G(e,"settings"))return{title:"Domma CMS"};try{const t=await g.settings.get();return{...t?.adminBrand,title:t?.adminBrand?.title||t?.title||"Domma CMS"}}catch{return{title:"Domma CMS"}}}export async function renderAdminSidebar({mount:e,permissions:n,adminScope:t=null,brand:o=null}){const s=$(e).get(0);if(!s)return;const r=tt(g,k()).catch(()=>{}),u=Promise.resolve().then(()=>H.get("/api/sidebar/registered-items")).catch(()=>[]),i=rt(n);let a,d=null,l=null,f=null,h=null,v=null;try{const c=await g.get("/sidebar/menu");a=Array.isArray(c?.items)?c.items:null,d=c?.variant||null,l=c?.position||null,f=c?.style||null,h=c?.float||null,v=c?.highlight||null}catch{a=null}(!a||!a.some(c=>c&&(!c.hidden||c.restricted)))&&(console.warn("[admin-sidebar] No admin-sidebar menu found; using fallback tree"),a=at.slice());let q=[];try{q=await u||[]}catch{}a=Pe(a,se),a=He(a,q.filter(c=>(c?.item??c)?.url!==se)),a=Re(a),a=_e(a,[Ie()]);const C=await i;C.length&<(a,C),a=ze(a,n,t),a=Ue(a),await r;const F=Je(a,V(k()),{hidden:Ye(k())});F&&(a=[F,...a]),ot(a);const b=q.filter(c=>G(n,c?.item?.permission));j=fe(b,t);const A=Fe({user:k(),permissions:n,adminScope:t,registered:b,tree:a,actions:{linkItems:ye,folderItems:ve},fetcher:()=>ut(b,n,t)}),B=A.counts,L=await bt(n,o),P=d?` dm-admin-sidebar--${m(d)}`:"";function _(c,w="px"){if(c==null)return c;const p=String(c).trim();return/^\d+(\.\d+)?$/.test(p)?`${p}${w}`:p}let z="";if(f){const c=[];f.fontFamily&&c.push(`font-family: ${f.fontFamily}, sans-serif`),f.fontSize&&c.push(`font-size: ${_(f.fontSize)}`),f.fontWeight&&c.push(`font-weight: ${f.fontWeight}`),f.letterSpacing&&c.push(`letter-spacing: ${_(f.letterSpacing,"em")}`);const w=[];if(c.length&&w.push(`#admin-sidebar .dm-admin-sidebar, #admin-sidebar .dm-admin-sidebar .sidebar-link, #admin-sidebar .dm-admin-sidebar summary, #admin-sidebar .dm-admin-sidebar .sidebar-text { ${c.join("; ")} }`),f.iconSize){const p=_(f.iconSize);w.push(`#admin-sidebar .dm-admin-sidebar [data-icon], #admin-sidebar .dm-admin-sidebar [data-icon] svg { width: ${p} !important; height: ${p} !important; }`)}w.length&&(z=`<style data-admin-sidebar-style>${w.join(" ")}</style>`)}const D=We(n)?De():"",y=String(L.logo||"").trim(),x=/^(?:\/(?!\/)|https?:\/\/)/i.test(y)?y:"",W=String(L.logoDark||"").trim(),O=/^(?:\/(?!\/)|https?:\/\/)/i.test(W)?W:"",T=x||O?`<img src="${m(x||O)}"${x?` data-logo-light="${m(x)}"`:""}${O?` data-logo-dark="${m(O)}"`:""} alt="" style="width:28px;height:28px;object-fit:contain;flex-shrink:0;">`:`<span data-icon="${m(L.icon||"layout")}"></span>`,xe=`<div class="dm-admin-sidebar-header">${L.enabled===!1?"":`${T}<span class="dm-admin-sidebar-title">${m(L.title)}</span>`}${D}${Ke()}</div>`,$e=a.some(c=>c&&c.type==="spacer"&&c.size==="flex")?" dm-admin-sidebar--has-flex-spacer":"",we=`${z}<nav class="dm-admin-sidebar${P}${$e}">${xe}${a.map(c=>ue(c,B)).join("")}</nav>`,Q=document.createRange();Q.selectNodeContents(s);const ke=Q.createContextualFragment(we);s.replaceChildren(ke),qe(s),Domma.icons.scan(s),s.querySelector(".dm-admin-sidebar-arrange")?.addEventListener("click",()=>Ge(s));for(const c of j)Z.set(c.url,B[c.url]??null);ce(s),ht(s),A.refresh.then(c=>{if(!(!A.isActive()||!s.isConnected))for(const[w,p]of Object.entries(c))X(s,w,p)}),s.removeAttribute("data-menu-hover"),s.removeAttribute("data-menu-active"),s.style.removeProperty("--dm-menu-highlight"),Me(s,{highlight:v});const N=document.querySelector(".dashboard-wrapper");["position","top","bottom","left","right","zIndex","maxHeight","transform"].forEach(c=>{s.style[c]=""}),s.classList.remove("dm-menu-floating"),N&&(N.style.paddingLeft="",N.style.paddingRight=""),s.__dmGutter=()=>{if(l!=="floating"||!N)return;const c=h&&h.anchor||"TL",w=Number.isFinite(Number(h?.offsetX))?Number(h.offsetX):16,p=s.classList.contains("is-collapsed")?Xe:parseInt(s.style.width,10)||s.getBoundingClientRect().width||260,R=Math.round(p+w*2)+"px";c==="R"||c==="TR"||c==="BR"?N.style.paddingRight=R:N.style.paddingLeft=R},l==="floating"&&Te(s,{position:"floating",float:h||{}}),s.querySelectorAll("details").forEach(c=>{c.addEventListener("toggle",function(){const w=this.getAttribute("data-state-key");w&&S.set(w,this.open);const p=this.querySelector(":scope > .sidebar-children");if(p)if(this.open){const R=p.scrollHeight;p.style.maxHeight="0",requestAnimationFrame(()=>{p.style.maxHeight=R+"px",p.addEventListener("transitionend",function Se(){p.style.maxHeight="none",p.removeEventListener("transitionend",Se)})})}else{const R=p.scrollHeight;p.style.maxHeight=R+"px",requestAnimationFrame(()=>{p.style.maxHeight="0"})}})}),Ve(s),vt(s),s.dataset.routeWired||(s.dataset.routeWired="1",M.subscribe("router:afterChange",()=>s.__dmSetActive?.()));function ee(){const c=/^#\/(dashboards|my-dashboard)\b/.test(location.hash)?"#/":location.hash||"#/";$(s).find(".sidebar-link").removeClass("active"),$(s).find(`.sidebar-link[data-url="${c}"]`).addClass("active")}ee(),s.__dmSetActive=ee}function ge(){try{document.dispatchEvent(new CustomEvent("dm:sidebar-rebuild"))}catch{}}function Y(e){return`${location.origin}${location.pathname}${e}`}function U(e,n){const t=k(),o=e(V(t));if(!nt(t,o)){E.toast("Frequent could not be saved - this browser is blocking storage.",{type:"error"});return}o.length&&ae(t,!1),be(t),n&&E.toast(n,{type:"success",duration:2500}),ge()}function be(e){et(g,e).catch(()=>E.toast("Frequent is saved in this browser only - the server could not keep it.",{type:"warning"}))}function yt(e){if(!ae(k(),e)){E.toast("Frequent could not be saved - this browser is blocking storage.",{type:"error"});return}be(k()),E.toast(e?"Frequent hidden. Add a Tool to it from its right-click menu to bring it back.":"Frequent shown.",{type:"success",duration:3500}),ge()}function ye(e){const n=e.dataset.url;if(!n)return[];const t=e.querySelector(".sidebar-text")?.textContent.trim()||n,o=V(k()),s=o.includes(n),r=!!e.closest("[data-frequent]"),u=o.indexOf(n),i=!s&&o.length>=oe;return[{header:t},{label:"Open",icon:"arrow-right",...re(n)&&{shortcut:it(re(n))},action:()=>{location.hash=n}},{label:"Open in a new tab",icon:"external-link",action:()=>window.open(Y(n),"_blank","noopener")},{type:"divider"},s?{label:"Remove from Frequent",icon:"star",action:()=>U(a=>Qe(a,n),`${t} removed from Frequent.`)}:{label:i?`Frequent is full (${oe})`:"Add to Frequent",icon:"star",disabled:i,action:()=>U(a=>Ze(a,n),`${t} added to Frequent.`)},...r?[{label:"Move up",icon:"arrow-up",disabled:u<=0,action:()=>U(a=>ie(a,n,-1))},{label:"Move down",icon:"arrow-down",disabled:u<0||u>=o.length-1,action:()=>U(a=>ie(a,n,1))}]:[],{type:"divider"},{label:"Copy link",icon:"link",action:async()=>{try{await navigator.clipboard.writeText(Y(n)),E.toast("Link copied.",{type:"success",duration:2e3})}catch{E.toast(Y(n),{type:"info",duration:8e3})}}}]}function ve(e,n,t={}){const o=e.closest("details, [data-frequent]"),s=t.isOpen||(()=>!!o?.open),r=t.setOpen||(a=>{o&&(o.open=a)}),u=e.querySelector(".sidebar-text")?.textContent.trim()||"Folder",i=t.setAll||(a=>n.querySelectorAll("details").forEach(d=>{d.open!==a&&(d.open=a)}));return[{header:u},{label:s()?"Close":"Open",icon:s()?"chevron-up":"chevron-down",action:()=>r(!s())},...t.singleBranch?[]:[{label:"Open every folder",icon:"chevrons-down",action:()=>i(!0)}],{label:t.singleBranch?"Close all menus":"Close every folder",icon:"chevrons-up",action:()=>i(!1)},...o?.hasAttribute("data-frequent-empty")?[{type:"divider"},{label:"Hide Frequent until I add a Tool",icon:"eye-off",action:()=>yt(!0)}]:o?.hasAttribute("data-frequent")?[{type:"divider"},{label:"Clear Frequent",icon:"x",action:()=>U(()=>[],"Frequent cleared.")}]:[]]}function vt(e){e.dataset.ctxWired||typeof E>"u"||!E.contextMenu||(e.dataset.ctxWired="1",E.contextMenu(e,{match:"a.sidebar-link, details > summary",inherit:!1,density:"compact",items:n=>n.matches("summary")?ve(n,e):ye(n)}))}
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
export const TAB_FIELDS={general:["title","tagline","siteUrl","adminHome","spacerSize","bodyClass"],branding:["brandEnabled","brandText","brandLogo","brandIcon","brandUrl","adminBrandEnabled","adminBrandTitle","adminBrandLogo","adminBrandIcon"],favicon:["favicon"],footer:["footerCopyright","footerLayout","footerBlurb","footerBlocks","footerClass","footerSocialClass","footerLook","footerCtaText","footerCtaHighlight","footerCtaUrl","footerCtaSub","footerWatermark","footerStatus","footerFacts","footerTagline","footerEmail","footerAddress","footerGradFrom","footerGradTo","socialTwitter","socialFacebook","socialInstagram","socialLinkedin","socialGithub","socialYoutube"],email:["smtpHost","smtpPort","smtpUser","smtpPass","smtpSecure","smtpInsecureTLS","smtpFromAddress","smtpFromName"],pageNavigation:["bttEnabled","bttSmooth","bttLabel","bttThreshold","bttPosition","bttOffset","bttBottomOffset","gtbEnabled","gtbSmooth","gtbLabel","gtbThreshold","gtbPosition","gtbOffset","gtbBottomOffset"],cookies:["ccEnabled","ccMessage","ccAcceptAll","ccRejectAll","ccCustomize","ccSavePrefs","ccPrivacyText","ccPrivacyUrl","ccCookieText","ccCookieUrl","ccPosition","ccLayout","ccTheme","ccShowFunctional","ccShowAnalytics","ccShowMarketing","ccVersion","ccSettingsLink","ccSettingsLinkText"],breadcrumbs:["bcEnabled","bcHomeLabel","bcPosition","bcOffsetX","bcOffsetY"],motion:["mtEnabled","mtLabel","mtDefault","mtControl","mtPlacement","mtTriggerStyle","mtPosition","mtOffsetX","mtOffsetY","mtIconSize","mtIconRadius","mtClass"]},SECRET_FIELDS=["smtpPass"],BREADCRUMB_POSITIONS=["TL","TR","BL","BR"],MOTION_PLACEMENTS=["footer","floating","navbar"],MOTION_LABEL="Reduce motion";const d=["system","off","on"],c=(t,r,n,o)=>{const a=Number.parseInt(t,10);return Number.isFinite(a)?Math.min(o,Math.max(n,a)):r};export function motionFromSettings(t={}){const r=t.motion&&typeof t.motion=="object"?t.motion:{},n=t.footer||{},o=m=>r[m]!==void 0&&r[m]!==null,a=o("default")?r.default:n.motionDefault,i=o("control")?r.control:n.motionControl,l=c(r.iconSize,52,32,96);return{mtEnabled:(o("enabled")?r.enabled:n.showMotionToggle)!==!1,mtLabel:typeof r.label=="string"&&r.label.trim()?r.label.trim():MOTION_LABEL,mtDefault:d.includes(a)?a:"system",mtControl:i==="checkbox"?"checkbox":"switch",mtPlacement:MOTION_PLACEMENTS.includes(r.placement)?r.placement:"footer",mtTriggerStyle:r.triggerStyle==="icon-text"?"icon-text":"icon",mtPosition:BREADCRUMB_POSITIONS.includes(r.position)?r.position:"BL",mtOffsetX:e(c(r.offsetX,32,0,500)),mtOffsetY:e(c(r.offsetY,32,0,500)),mtIconSize:e(l),mtIconRadius:e(c(r.iconRadius,26,0,Math.floor(l/2))),mtClass:e(r.class)}}export function motionFromForm(t){const r=c(t.mtIconSize,52,32,96);return{enabled:t.mtEnabled===!0,default:d.includes(t.mtDefault)?t.mtDefault:"system",placement:MOTION_PLACEMENTS.includes(t.mtPlacement)?t.mtPlacement:"footer",control:t.mtControl==="checkbox"?"checkbox":"switch",triggerStyle:t.mtTriggerStyle==="icon-text"?"icon-text":"icon",label:e(t.mtLabel).trim().replace(/\s+/g," ").slice(0,40)||MOTION_LABEL,position:BREADCRUMB_POSITIONS.includes(t.mtPosition)?t.mtPosition:"BL",offsetX:c(t.mtOffsetX,32,0,500),offsetY:c(t.mtOffsetY,32,0,500),iconSize:r,iconRadius:c(t.mtIconRadius,26,0,Math.floor(r/2)),class:e(t.mtClass).trim()}}export function footerBlockNames(t){return[...new Set(String(t??"").split(/[\s,]+/).map(r=>r.trim().toLowerCase()).filter(Boolean))]}export function gaIdError(t){const r=e(t).trim();return!r||/^G-[A-Z0-9]{4,20}$/i.test(r)?"":"A measurement ID looks like G-XXXXXXXXXX (Google Analytics > Admin > Data streams)."}export const FOOTER_LAYOUTS=["auto","columns","row"],FOOTER_LOOKS=["","showcase"],FOOTER_FACTS_MAX=4;const p=/^(\/|#|https?:\/\/|mailto:)/,g=/^#[0-9a-f]{6}$/i;export function footerShowcaseErrors(t){const r=[],n=e(t.footerCtaUrl).trim();n&&!p.test(n)&&r.push("The footer call to action link must start with /, #, https:// or mailto: (Footer tool).");for(const[o,a]of[["from",t.footerGradFrom],["to",t.footerGradTo]]){const i=e(a).trim();i&&!g.test(i)&&r.push(`The footer gradient "${o}" colour must look like #f26b3a (Footer tool).`)}return r}const e=(t,r="")=>t==null?r:String(t),s=(t,r)=>{const n=Number.parseInt(t,10);return Number.isFinite(n)?n:r};export function homeValue(t){return/^\/[A-Za-z0-9\-_/]*$/.test(t||"")&&String(t).replace(/\/+$/,"")||"/"}export function formFromSettings(t={}){const r=t.backToTop||{},n=t.goToBottom||{},o=t.cookieConsent||{},a=t.breadcrumbs||{};return{title:e(t.title),tagline:e(t.tagline),siteUrl:e(t.baseUrl),adminHome:homeValue(t.adminHome),spacerSize:e(t.layoutOptions?.spacerSize??40),bodyClass:e(t.bodyClass),brandEnabled:t.brand?.enabled!==!1,brandText:e(t.brand?.text),brandLogo:e(t.brand?.logo),brandIcon:e(t.brand?.icon),brandUrl:e(t.brand?.url,"/"),favicon:e(t.favicon),adminBrandEnabled:t.adminBrand?.enabled!==!1,adminBrandTitle:e(t.adminBrand?.title),adminBrandLogo:e(t.adminBrand?.logo),adminBrandIcon:e(t.adminBrand?.icon),footerCopyright:e(t.footer?.copyright),footerLayout:FOOTER_LAYOUTS.includes(t.footer?.layout)?t.footer.layout:"auto",footerBlurb:e(t.footer?.blurb),footerBlocks:Array.isArray(t.footer?.blocks)?t.footer.blocks.filter(i=>typeof i=="string").join(", "):"",footerClass:e(t.footer?.class),footerSocialClass:e(t.footer?.socialClass),footerLook:FOOTER_LOOKS.includes(t.footer?.look)?t.footer.look:"",footerCtaText:e(t.footer?.cta?.text),footerCtaHighlight:e(t.footer?.cta?.highlight),footerCtaUrl:e(t.footer?.cta?.url),footerCtaSub:e(t.footer?.cta?.sub),footerWatermark:e(t.footer?.watermark),footerStatus:e(t.footer?.status),footerFacts:Array.isArray(t.footer?.facts)?t.footer.facts.filter(i=>typeof i=="string").join(`
|
|
2
|
-
`):"",footerTagline:e(t.footer?.tagline),footerEmail:e(t.footer?.email),footerAddress:e(t.footer?.address),footerGradFrom:e(t.footer?.gradient?.from),footerGradTo:e(t.footer?.gradient?.to),socialTwitter:e(t.social?.twitter),socialFacebook:e(t.social?.facebook),socialInstagram:e(t.social?.instagram),socialLinkedin:e(t.social?.linkedin),socialGithub:e(t.social?.github),socialYoutube:e(t.social?.youtube),smtpHost:e(t.smtp?.host),smtpPort:e(t.smtp?.port||587),smtpUser:e(t.smtp?.user),smtpPass:"",smtpSecure:t.smtp?.secure===!0,smtpInsecureTLS:t.smtp?.allowInsecureTLS===!0,smtpFromAddress:e(t.smtp?.fromAddress),smtpFromName:e(t.smtp?.fromName),bttEnabled:r.enabled!==!1,bttSmooth:r.smooth!==!1,bttLabel:e(r.label),bttThreshold:e(r.scrollThreshold??300),bttPosition:e(r.position,"bottom-right"),bttOffset:e(r.offset??32),bttBottomOffset:e(r.bottomOffset??r.offset??32),gtbEnabled:n.enabled===!0,gtbSmooth:n.smooth!==!1,gtbLabel:e(n.label),gtbThreshold:e(n.scrollThreshold??300),gtbPosition:e(n.position,"bottom-right"),gtbOffset:e(n.offset??32),gtbBottomOffset:e(n.bottomOffset??n.offset??32),ccEnabled:o.enabled!==!1,ccMessage:e(o.message),ccAcceptAll:e(o.acceptAllText,"Accept All"),ccRejectAll:e(o.rejectAllText,"Reject All"),ccCustomize:e(o.customizeText,"Customize"),ccSavePrefs:e(o.savePreferencesText,"Save Preferences"),ccPrivacyText:e(o.privacyPolicyText,"Privacy Policy"),ccPrivacyUrl:e(o.privacyPolicyUrl),ccCookieText:e(o.cookiePolicyText,"Cookie Policy"),ccCookieUrl:e(o.cookiePolicyUrl),ccPosition:e(o.position,"bottom"),ccLayout:e(o.layout,"bar"),ccTheme:e(o.theme,"dark"),ccShowFunctional:o.showFunctional!==!1,ccShowAnalytics:o.showAnalytics!==!1,ccShowMarketing:o.showMarketing!==!1,ccVersion:e(o.consentVersion,"1.0"),ccSettingsLink:o.showSettingsLink!==!1,ccSettingsLinkText:e(o.settingsLinkText,"Cookie settings"),bcEnabled:a.enabled===!0,bcHomeLabel:e(a.homeLabel,"Home"),bcPosition:BREADCRUMB_POSITIONS.includes(a.position)?a.position:"TL",bcOffsetX:e(a.offsetX??8),bcOffsetY:e(a.offsetY??8),...motionFromSettings(t)}}export function payloadFromForm(t,r={},{adminHomeReady:n=!0}={}){const o=i=>e(i).trim(),a=motionFromForm(t);return{title:o(t.title),tagline:o(t.tagline),baseUrl:o(t.siteUrl).replace(/\/+$/,""),...n&&{adminHome:o(t.adminHome)||"/"},layoutOptions:{spacerSize:s(t.spacerSize,40)||40},bodyClass:o(t.bodyClass),brand:{...r.brand,enabled:t.brandEnabled!==!1,text:o(t.brandText),logo:o(t.brandLogo),icon:o(t.brandIcon),url:o(t.brandUrl)||"/"},favicon:o(t.favicon),adminBrand:{...r.adminBrand,enabled:t.adminBrandEnabled!==!1,title:o(t.adminBrandTitle),logo:o(t.adminBrandLogo),icon:o(t.adminBrandIcon)},footer:{copyright:o(t.footerCopyright),layout:FOOTER_LAYOUTS.includes(t.footerLayout)?t.footerLayout:"auto",blurb:o(t.footerBlurb),blocks:footerBlockNames(t.footerBlocks),links:r.footer?.links||[],showMotionToggle:a.enabled,motionDefault:a.default,motionControl:a.control,class:o(t.footerClass),socialClass:o(t.footerSocialClass),look:FOOTER_LOOKS.includes(t.footerLook)?t.footerLook:"",cta:{text:o(t.footerCtaText),highlight:o(t.footerCtaHighlight),url:o(t.footerCtaUrl),sub:o(t.footerCtaSub)},watermark:o(t.footerWatermark),status:o(t.footerStatus),facts:String(t.footerFacts??"").split(`
|
|
1
|
+
export const TAB_FIELDS={general:["title","tagline","siteUrl","adminHome","spacerSize","bodyClass"],branding:["brandEnabled","brandText","brandLogo","brandIcon","brandUrl","adminBrandEnabled","adminBrandTitle","adminBrandLogo","adminBrandLogoDark","adminBrandIcon"],favicon:["favicon"],footer:["footerCopyright","footerLayout","footerBlurb","footerBlocks","footerClass","footerSocialClass","footerLook","footerCtaText","footerCtaHighlight","footerCtaUrl","footerCtaSub","footerWatermark","footerStatus","footerFacts","footerTagline","footerEmail","footerAddress","footerGradFrom","footerGradTo","socialTwitter","socialFacebook","socialInstagram","socialLinkedin","socialGithub","socialYoutube"],email:["smtpHost","smtpPort","smtpUser","smtpPass","smtpSecure","smtpInsecureTLS","smtpFromAddress","smtpFromName"],pageNavigation:["bttEnabled","bttSmooth","bttLabel","bttThreshold","bttPosition","bttOffset","bttBottomOffset","gtbEnabled","gtbSmooth","gtbLabel","gtbThreshold","gtbPosition","gtbOffset","gtbBottomOffset"],cookies:["ccEnabled","ccMessage","ccAcceptAll","ccRejectAll","ccCustomize","ccSavePrefs","ccPrivacyText","ccPrivacyUrl","ccCookieText","ccCookieUrl","ccPosition","ccLayout","ccTheme","ccShowFunctional","ccShowAnalytics","ccShowMarketing","ccVersion","ccSettingsLink","ccSettingsLinkText"],breadcrumbs:["bcEnabled","bcHomeLabel","bcPosition","bcOffsetX","bcOffsetY"],motion:["mtEnabled","mtLabel","mtDefault","mtControl","mtPlacement","mtTriggerStyle","mtPosition","mtOffsetX","mtOffsetY","mtIconSize","mtIconRadius","mtClass"]},SECRET_FIELDS=["smtpPass"],BREADCRUMB_POSITIONS=["TL","TR","BL","BR"],MOTION_PLACEMENTS=["footer","floating","navbar"],MOTION_LABEL="Reduce motion";const d=["system","off","on"],c=(t,r,n,o)=>{const a=Number.parseInt(t,10);return Number.isFinite(a)?Math.min(o,Math.max(n,a)):r};export function motionFromSettings(t={}){const r=t.motion&&typeof t.motion=="object"?t.motion:{},n=t.footer||{},o=m=>r[m]!==void 0&&r[m]!==null,a=o("default")?r.default:n.motionDefault,i=o("control")?r.control:n.motionControl,l=c(r.iconSize,52,32,96);return{mtEnabled:(o("enabled")?r.enabled:n.showMotionToggle)!==!1,mtLabel:typeof r.label=="string"&&r.label.trim()?r.label.trim():MOTION_LABEL,mtDefault:d.includes(a)?a:"system",mtControl:i==="checkbox"?"checkbox":"switch",mtPlacement:MOTION_PLACEMENTS.includes(r.placement)?r.placement:"footer",mtTriggerStyle:r.triggerStyle==="icon-text"?"icon-text":"icon",mtPosition:BREADCRUMB_POSITIONS.includes(r.position)?r.position:"BL",mtOffsetX:e(c(r.offsetX,32,0,500)),mtOffsetY:e(c(r.offsetY,32,0,500)),mtIconSize:e(l),mtIconRadius:e(c(r.iconRadius,26,0,Math.floor(l/2))),mtClass:e(r.class)}}export function motionFromForm(t){const r=c(t.mtIconSize,52,32,96);return{enabled:t.mtEnabled===!0,default:d.includes(t.mtDefault)?t.mtDefault:"system",placement:MOTION_PLACEMENTS.includes(t.mtPlacement)?t.mtPlacement:"footer",control:t.mtControl==="checkbox"?"checkbox":"switch",triggerStyle:t.mtTriggerStyle==="icon-text"?"icon-text":"icon",label:e(t.mtLabel).trim().replace(/\s+/g," ").slice(0,40)||MOTION_LABEL,position:BREADCRUMB_POSITIONS.includes(t.mtPosition)?t.mtPosition:"BL",offsetX:c(t.mtOffsetX,32,0,500),offsetY:c(t.mtOffsetY,32,0,500),iconSize:r,iconRadius:c(t.mtIconRadius,26,0,Math.floor(r/2)),class:e(t.mtClass).trim()}}export function footerBlockNames(t){return[...new Set(String(t??"").split(/[\s,]+/).map(r=>r.trim().toLowerCase()).filter(Boolean))]}export function gaIdError(t){const r=e(t).trim();return!r||/^G-[A-Z0-9]{4,20}$/i.test(r)?"":"A measurement ID looks like G-XXXXXXXXXX (Google Analytics > Admin > Data streams)."}export const FOOTER_LAYOUTS=["auto","columns","row"],FOOTER_LOOKS=["","showcase"],FOOTER_FACTS_MAX=4;const p=/^(\/|#|https?:\/\/|mailto:)/,g=/^#[0-9a-f]{6}$/i;export function footerShowcaseErrors(t){const r=[],n=e(t.footerCtaUrl).trim();n&&!p.test(n)&&r.push("The footer call to action link must start with /, #, https:// or mailto: (Footer tool).");for(const[o,a]of[["from",t.footerGradFrom],["to",t.footerGradTo]]){const i=e(a).trim();i&&!g.test(i)&&r.push(`The footer gradient "${o}" colour must look like #f26b3a (Footer tool).`)}return r}const e=(t,r="")=>t==null?r:String(t),s=(t,r)=>{const n=Number.parseInt(t,10);return Number.isFinite(n)?n:r};export function homeValue(t){return/^\/[A-Za-z0-9\-_/]*$/.test(t||"")&&String(t).replace(/\/+$/,"")||"/"}export function formFromSettings(t={}){const r=t.backToTop||{},n=t.goToBottom||{},o=t.cookieConsent||{},a=t.breadcrumbs||{};return{title:e(t.title),tagline:e(t.tagline),siteUrl:e(t.baseUrl),adminHome:homeValue(t.adminHome),spacerSize:e(t.layoutOptions?.spacerSize??40),bodyClass:e(t.bodyClass),brandEnabled:t.brand?.enabled!==!1,brandText:e(t.brand?.text),brandLogo:e(t.brand?.logo),brandIcon:e(t.brand?.icon),brandUrl:e(t.brand?.url,"/"),favicon:e(t.favicon),adminBrandEnabled:t.adminBrand?.enabled!==!1,adminBrandTitle:e(t.adminBrand?.title),adminBrandLogo:e(t.adminBrand?.logo),adminBrandLogoDark:e(t.adminBrand?.logoDark),adminBrandIcon:e(t.adminBrand?.icon),footerCopyright:e(t.footer?.copyright),footerLayout:FOOTER_LAYOUTS.includes(t.footer?.layout)?t.footer.layout:"auto",footerBlurb:e(t.footer?.blurb),footerBlocks:Array.isArray(t.footer?.blocks)?t.footer.blocks.filter(i=>typeof i=="string").join(", "):"",footerClass:e(t.footer?.class),footerSocialClass:e(t.footer?.socialClass),footerLook:FOOTER_LOOKS.includes(t.footer?.look)?t.footer.look:"",footerCtaText:e(t.footer?.cta?.text),footerCtaHighlight:e(t.footer?.cta?.highlight),footerCtaUrl:e(t.footer?.cta?.url),footerCtaSub:e(t.footer?.cta?.sub),footerWatermark:e(t.footer?.watermark),footerStatus:e(t.footer?.status),footerFacts:Array.isArray(t.footer?.facts)?t.footer.facts.filter(i=>typeof i=="string").join(`
|
|
2
|
+
`):"",footerTagline:e(t.footer?.tagline),footerEmail:e(t.footer?.email),footerAddress:e(t.footer?.address),footerGradFrom:e(t.footer?.gradient?.from),footerGradTo:e(t.footer?.gradient?.to),socialTwitter:e(t.social?.twitter),socialFacebook:e(t.social?.facebook),socialInstagram:e(t.social?.instagram),socialLinkedin:e(t.social?.linkedin),socialGithub:e(t.social?.github),socialYoutube:e(t.social?.youtube),smtpHost:e(t.smtp?.host),smtpPort:e(t.smtp?.port||587),smtpUser:e(t.smtp?.user),smtpPass:"",smtpSecure:t.smtp?.secure===!0,smtpInsecureTLS:t.smtp?.allowInsecureTLS===!0,smtpFromAddress:e(t.smtp?.fromAddress),smtpFromName:e(t.smtp?.fromName),bttEnabled:r.enabled!==!1,bttSmooth:r.smooth!==!1,bttLabel:e(r.label),bttThreshold:e(r.scrollThreshold??300),bttPosition:e(r.position,"bottom-right"),bttOffset:e(r.offset??32),bttBottomOffset:e(r.bottomOffset??r.offset??32),gtbEnabled:n.enabled===!0,gtbSmooth:n.smooth!==!1,gtbLabel:e(n.label),gtbThreshold:e(n.scrollThreshold??300),gtbPosition:e(n.position,"bottom-right"),gtbOffset:e(n.offset??32),gtbBottomOffset:e(n.bottomOffset??n.offset??32),ccEnabled:o.enabled!==!1,ccMessage:e(o.message),ccAcceptAll:e(o.acceptAllText,"Accept All"),ccRejectAll:e(o.rejectAllText,"Reject All"),ccCustomize:e(o.customizeText,"Customize"),ccSavePrefs:e(o.savePreferencesText,"Save Preferences"),ccPrivacyText:e(o.privacyPolicyText,"Privacy Policy"),ccPrivacyUrl:e(o.privacyPolicyUrl),ccCookieText:e(o.cookiePolicyText,"Cookie Policy"),ccCookieUrl:e(o.cookiePolicyUrl),ccPosition:e(o.position,"bottom"),ccLayout:e(o.layout,"bar"),ccTheme:e(o.theme,"dark"),ccShowFunctional:o.showFunctional!==!1,ccShowAnalytics:o.showAnalytics!==!1,ccShowMarketing:o.showMarketing!==!1,ccVersion:e(o.consentVersion,"1.0"),ccSettingsLink:o.showSettingsLink!==!1,ccSettingsLinkText:e(o.settingsLinkText,"Cookie settings"),bcEnabled:a.enabled===!0,bcHomeLabel:e(a.homeLabel,"Home"),bcPosition:BREADCRUMB_POSITIONS.includes(a.position)?a.position:"TL",bcOffsetX:e(a.offsetX??8),bcOffsetY:e(a.offsetY??8),...motionFromSettings(t)}}export function payloadFromForm(t,r={},{adminHomeReady:n=!0}={}){const o=i=>e(i).trim(),a=motionFromForm(t);return{title:o(t.title),tagline:o(t.tagline),baseUrl:o(t.siteUrl).replace(/\/+$/,""),...n&&{adminHome:o(t.adminHome)||"/"},layoutOptions:{spacerSize:s(t.spacerSize,40)||40},bodyClass:o(t.bodyClass),brand:{...r.brand,enabled:t.brandEnabled!==!1,text:o(t.brandText),logo:o(t.brandLogo),icon:o(t.brandIcon),url:o(t.brandUrl)||"/"},favicon:o(t.favicon),adminBrand:{...r.adminBrand,enabled:t.adminBrandEnabled!==!1,title:o(t.adminBrandTitle),logo:o(t.adminBrandLogo),logoDark:o(t.adminBrandLogoDark),icon:o(t.adminBrandIcon)},footer:{copyright:o(t.footerCopyright),layout:FOOTER_LAYOUTS.includes(t.footerLayout)?t.footerLayout:"auto",blurb:o(t.footerBlurb),blocks:footerBlockNames(t.footerBlocks),links:r.footer?.links||[],showMotionToggle:a.enabled,motionDefault:a.default,motionControl:a.control,class:o(t.footerClass),socialClass:o(t.footerSocialClass),look:FOOTER_LOOKS.includes(t.footerLook)?t.footerLook:"",cta:{text:o(t.footerCtaText),highlight:o(t.footerCtaHighlight),url:o(t.footerCtaUrl),sub:o(t.footerCtaSub)},watermark:o(t.footerWatermark),status:o(t.footerStatus),facts:String(t.footerFacts??"").split(`
|
|
3
3
|
`).map(i=>i.trim()).filter(Boolean).slice(0,FOOTER_FACTS_MAX),tagline:o(t.footerTagline),email:o(t.footerEmail),address:o(t.footerAddress),gradient:{from:o(t.footerGradFrom),to:o(t.footerGradTo)}},social:{twitter:o(t.socialTwitter),facebook:o(t.socialFacebook),instagram:o(t.socialInstagram),linkedin:o(t.socialLinkedin),github:o(t.socialGithub),youtube:o(t.socialYoutube)},smtp:{host:o(t.smtpHost),port:s(t.smtpPort,587)||587,user:o(t.smtpUser),pass:e(t.smtpPass),secure:t.smtpSecure===!0,allowInsecureTLS:t.smtpInsecureTLS===!0,fromAddress:o(t.smtpFromAddress),fromName:o(t.smtpFromName)},backToTop:{enabled:t.bttEnabled===!0,scrollThreshold:s(t.bttThreshold,300),position:e(t.bttPosition)||"bottom-right",offset:s(t.bttOffset,32),bottomOffset:s(t.bttBottomOffset,32),label:o(t.bttLabel),smooth:t.bttSmooth===!0},goToBottom:{enabled:t.gtbEnabled===!0,scrollThreshold:s(t.gtbThreshold,300),position:e(t.gtbPosition)||"bottom-right",offset:s(t.gtbOffset,32),bottomOffset:s(t.gtbBottomOffset,32),label:o(t.gtbLabel),smooth:t.gtbSmooth===!0},cookieConsent:{enabled:t.ccEnabled===!0,message:o(t.ccMessage),acceptAllText:o(t.ccAcceptAll),rejectAllText:o(t.ccRejectAll),customizeText:o(t.ccCustomize),savePreferencesText:o(t.ccSavePrefs),privacyPolicyText:o(t.ccPrivacyText),privacyPolicyUrl:o(t.ccPrivacyUrl),cookiePolicyText:o(t.ccCookieText),cookiePolicyUrl:o(t.ccCookieUrl),position:e(t.ccPosition)||"bottom",layout:e(t.ccLayout)||"bar",theme:e(t.ccTheme)||"dark",showFunctional:t.ccShowFunctional===!0,showAnalytics:t.ccShowAnalytics===!0,showMarketing:t.ccShowMarketing===!0,consentVersion:o(t.ccVersion)||"1.0",showSettingsLink:t.ccSettingsLink===!0,settingsLinkText:o(t.ccSettingsLinkText)||"Cookie settings"},breadcrumbs:{enabled:t.bcEnabled===!0,homeLabel:o(t.bcHomeLabel)||"Home",position:BREADCRUMB_POSITIONS.includes(t.bcPosition)?t.bcPosition:"TL",offsetX:s(t.bcOffsetX,8),offsetY:s(t.bcOffsetY,8)},motion:a}}export function siteUrlError(t){const r=e(t).trim().replace(/\/+$/,"");return r?/^https?:\/\//i.test(r)?/^https?:\/\/([a-z0-9.\-]+|\[[0-9a-f:.]+\])(:\d{1,5})?$/i.test(r)?"":"Just the address, like https://example.com - no page path after it.":"Start with https:// (or http://).":""}const b=t=>typeof t=="boolean"?t:e(t);export function snapshot(t){return JSON.stringify(Object.keys(t).sort().map(r=>[r,b(t[r])]))}export function changedTabs(t,r){const n=[];for(const[o,a]of Object.entries(TAB_FIELDS))a.some(i=>b(t[i])!==b(r[i]))&&n.push(o);return n}export function draftOf(t){return Object.fromEntries(Object.entries(t).filter(([r])=>!SECRET_FIELDS.includes(r)))}const h={footerMotionToggle:"mtEnabled",footerMotionDefault:"mtDefault",footerMotionControl:"mtControl"};export function formFromDraft(t,r={}){const n={...r};for(const[a,i]of Object.entries(h))a in n&&!(i in n)&&(n[i]=n[a]),delete n[a];const o={...t};for(const[a,i]of Object.entries(n))a in o&&!SECRET_FIELDS.includes(a)&&(o[a]=i);return o}export function settingsProblems(t,r={}){const n=[];return e(t.smtpHost).trim()?e(t.smtpFromAddress).trim()||n.push({tone:"warn",tab:"email",text:"No From address - mail has no sender and many servers refuse it."}):n.push({tone:"danger",tab:"email",text:"No SMTP host - mail goes to a throwaway test inbox and reaches no one (password resets, form notifications)."}),(t.ccEnabled===!0||e(r.googleAnalytics?.measurementId).trim())&&!e(t.ccPrivacyUrl).trim()&&n.push({tone:"warn",tab:"cookies",text:"The cookie banner is on but links to no privacy policy."}),n}export function describeCacheKey(t){const r=/^page:(.*?):m\d+:role([^:]*):/.exec(String(t||""));return r?{path:r[1]||"/",role:r[2]||"anon",page:!0}:{path:String(t||""),role:"",page:!1}}export function expiresIn(t,r=Date.now()){if(t==null)return"no expiry";const n=t-r;return n<=0?"expired":n<6e4?`${Math.round(n/1e3)}s`:n<36e5?`${Math.round(n/6e4)}m`:`${Math.round(n/36e5)}h`}export function footerForm(t={}){const r=formFromSettings(t);return Object.fromEntries(TAB_FIELDS.footer.map(n=>[n,r[n]]))}export function footerPayload(t){const{footer:r,social:n}=payloadFromForm(t);return delete r.links,delete r.showMotionToggle,delete r.motionDefault,delete r.motionControl,{footer:r,social:n}}export function siteSettingsForm(t={}){return Object.fromEntries(Object.entries(formFromSettings(t)).filter(([r])=>!TAB_FIELDS.footer.includes(r)&&!u.includes(r)))}export function siteSettingsPayload(...t){const{footer:r,social:n,favicon:o,backToTop:a,goToBottom:i,breadcrumbs:l,motion:m,...f}=payloadFromForm(...t);return f}export const APPEARANCE_TABS=["favicon","pageNavigation","breadcrumbs","motion","search"];const u=APPEARANCE_TABS.flatMap(t=>TAB_FIELDS[t]||[]);export function appearanceForm(t={}){const r=formFromSettings(t);return Object.fromEntries(u.map(n=>[n,r[n]]))}export function appearancePayload(t){const{favicon:r,backToTop:n,goToBottom:o,breadcrumbs:a,motion:i}=payloadFromForm(t);return{favicon:r,backToTop:n,goToBottom:o,breadcrumbs:a,motion:i}}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export function isDarkAdminTheme(){if(typeof document>"u")return!1;const e=getComputedStyle(document.body),n=e.getPropertyValue("--dm-background").trim()||e.backgroundColor,t=document.createElement("canvas").getContext("2d",{willReadFrequently:!0});if(!t)return!1;t.fillStyle=n,t.fillRect(0,0,1,1);const[o,r,a]=t.getImageData(0,0,1,1).data,l=[o,r,a].map(i=>{const s=i/255;return s<=.04045?s/12.92:((s+.055)/1.055)**2.4});return .2126*l[0]+.7152*l[1]+.0722*l[2]<.5}export function syncThemeAwareLogos(e=typeof document>"u"?null:document){if(!e)return;const n=[];if(e.matches?.("img[data-logo-light], img[data-logo-dark]")&&n.push(e),n.push(...e.querySelectorAll?.("img[data-logo-light], img[data-logo-dark]")||[]),!n.length)return;let c=!1;try{c=isDarkAdminTheme()}catch{}for(const t of n){const o=t.dataset.logoLight||"",r=t.dataset.logoDark||"",a=c?r||o:o||r;a&&t.getAttribute("src")!==a&&t.setAttribute("src",a)}}
|
|
@@ -17,7 +17,7 @@
|
|
|
17
17
|
<code><name>.meta.json</code> its project and bundled flag (optional).</p>
|
|
18
18
|
|
|
19
19
|
<h3>A free library to start your site</h3>
|
|
20
|
-
<p>Every site includes
|
|
20
|
+
<p>Every site includes 17 editable <code>domma-block-*</code> blocks. Search for
|
|
21
21
|
<code>domma-block-</code> in Blocks or use <strong>Add block</strong> in the editor.
|
|
22
22
|
Each includes its own styling, documented parameters and an example to copy.</p>
|
|
23
23
|
<table class="table table-sm"><thead><tr><th>Block</th><th>Use it for</th></tr></thead><tbody>
|
|
@@ -37,6 +37,7 @@
|
|
|
37
37
|
<tr><td><code>domma-block-team-card</code></td><td>A team member photo, role and short introduction.</td></tr>
|
|
38
38
|
<tr><td><code>domma-block-image</code></td><td>An uncropped image with an optional caption.</td></tr>
|
|
39
39
|
<tr><td><code>domma-block-logos</code></td><td>A responsive row of up to four organisation logos.</td></tr>
|
|
40
|
+
<tr><td><code>domma-block-cushion-card</code></td><td>A softly rounded card with an inset panel and rich content slots.</td></tr>
|
|
40
41
|
</tbody></table>
|
|
41
42
|
<p>Start with a banner or hero, add sections and cards, then finish with a call to action.
|
|
42
43
|
Change the text and choose your own pictures from Media. Use one main heading per page.
|
|
@@ -45,6 +46,32 @@
|
|
|
45
46
|
<p>Blocks follow your theme and adapt to smaller screens. You can edit or duplicate them;
|
|
46
47
|
updates add missing library files without replacing your existing customisations.</p>
|
|
47
48
|
|
|
49
|
+
<h3>Rich content slots</h3>
|
|
50
|
+
<p>Custom Blocks can keep their normal parameters and also declare a default slot with
|
|
51
|
+
<code><slot>Fallback</slot></code>, or a named slot with
|
|
52
|
+
<code><slot name="footer"></slot></code>. Slot content accepts Markdown, built-in and
|
|
53
|
+
plugin shortcodes, and nested blocks. Code examples remain literal.</p>
|
|
54
|
+
<pre><code>[domma-block-cushion-card heading="Made for you"]
|
|
55
|
+
Your **formatted content** goes here.
|
|
56
|
+
[slot name="footer"]
|
|
57
|
+
[button url="/contact"]Get in touch[/button]
|
|
58
|
+
[/slot]
|
|
59
|
+
[/domma-block-cushion-card]</code></pre>
|
|
60
|
+
<p>Add block inserts the slots for you. The shortcode insert form provides separate slot fields.
|
|
61
|
+
Existing self-closing calls continue working; slotted blocks use their fallback content.</p>
|
|
62
|
+
<h3>Block packs and sharing</h3>
|
|
63
|
+
<p>The package action in Blocks opens the pack catalogue. Create a pack from selected blocks,
|
|
64
|
+
publish an immutable version, or share a <code>.dmblockpack.json</code> file. Import adds a
|
|
65
|
+
version to the catalogue; preview and apply install it. Site settings permissions are required.</p>
|
|
66
|
+
<p>Preview checks compatibility, naming conflicts and local edits. A changed site needs a fresh
|
|
67
|
+
preview. Duplicate a block before customising it to keep its pack original updatable.
|
|
68
|
+
Installation history supports rollback with the same local edit protection. Select local media when assembling a pack to bundle raster images or webfonts.
|
|
69
|
+
Those references become versioned media URLs, retained for rollback. Remote media and SVG
|
|
70
|
+
URLs remain references. Each asset is limited to 1 MB; a complete pack is limited to 2 MB.</p>
|
|
71
|
+
<p>DCM adds <strong>Site Manager > Block packs</strong> for distribution to selected sites.
|
|
72
|
+
Each site's changes are reviewed first. Running sites restart briefly when a pack is applied.
|
|
73
|
+
Publishing a pack does not automatically change any managed site.</p>
|
|
74
|
+
|
|
48
75
|
<h3>Three ways to place a block</h3>
|
|
49
76
|
<table class="table table-sm">
|
|
50
77
|
<thead>
|
|
@@ -119,10 +119,16 @@
|
|
|
119
119
|
<button type="button" class="btn btn-sm btn-ghost" data-on-click="clearBrandImage('adminBrandLogo')">Remove</button>
|
|
120
120
|
<img data-bind-src="adminBrandLogo.value" data-bind-hidden="!adminBrandLogo.value" alt="Admin logo image preview" style="display:block;max-width:180px;max-height:80px;object-fit:contain;margin-top:.75rem;">
|
|
121
121
|
</div>
|
|
122
|
+
<div><label class="form-label" for="stx-adminBrandLogoDark">Admin logo for dark themes</label>
|
|
123
|
+
<input id="stx-adminBrandLogoDark" type="text" class="form-input" placeholder="Optional - uses the main logo when empty" data-model="adminBrandLogoDark.value">
|
|
124
|
+
<button type="button" class="btn btn-sm btn-ghost" data-on-click="pickBrandImage('adminBrandLogoDark')">Choose or upload image</button>
|
|
125
|
+
<button type="button" class="btn btn-sm btn-ghost" data-on-click="clearBrandImage('adminBrandLogoDark')">Remove</button>
|
|
126
|
+
<img data-bind-src="adminBrandLogoDark.value" data-bind-hidden="!adminBrandLogoDark.value" alt="Dark theme admin logo preview" style="display:block;max-width:180px;max-height:80px;object-fit:contain;margin-top:.75rem;background:#1f2430;padding:.25rem;border-radius:4px;">
|
|
127
|
+
</div>
|
|
122
128
|
<div><label class="form-label" for="stx-adminBrandIcon">Admin icon</label>
|
|
123
129
|
<div data-brand-icon="adminBrandIcon"></div>
|
|
124
130
|
</div>
|
|
125
|
-
</div><p class="text-muted">The logo takes priority over the icon. Leave both empty to use the default icon.</p></div>
|
|
131
|
+
</div><p class="text-muted">The logo takes priority over the icon. The optional dark theme logo is used when the admin theme has a dark background. Leave both empty to use the default icon.</p></div>
|
|
126
132
|
</div>
|
|
127
133
|
</div>
|
|
128
134
|
|
package/admin/js/views/blocks.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{api as h,apiRequest as Ue}from"../api.js";import{addBannerAction as
|
|
1
|
+
import{api as h,apiRequest as Ue}from"../api.js";import{openBlockPacks as He}from"../lib/block-packs.js";import{addBannerAction as $}from"../lib/plugin-chrome.js";import{helpPopovers as pe}from"../lib/help-popover.js";import{onceClosed as me,openMenuAt as be,sidebarCount as Oe,viewLifetime as Pe}from"../lib/tool-kit.js";import{filterByProject as Ke,getProjectFromHash as _e,renderProjectFilterNotice as ze}from"../lib/project-context.js";import{FILTERS as We,arrangeBlocks as Ye,blockRow as Ge,checkNewName as Je,copyName as he,shortcodeFor as fe,usageCount as Y,usageText as ge}from"../lib/blocks-arrange.js";import{fmtDate as Ve}from"../lib/dates.js";import{activeNote as ve,askManualTagName as Qe,manualNames as Xe,openTagSettings as Ze,same as et,sharedTagFilter as tt,tagCounts as at,tagMenuItems as st,tagsOf as R}from"../lib/list-tags.js";const ye=/^#\/(blocks|projects\/[^/?#]+\/blocks)\/?(\?.*)?$/,ot="#/blocks",q="blocks.draft",G="blocks.filter",nt="blocks.tag",lt=`
|
|
2
2
|
<div class="blx-row" data-name="{{name}}" tabindex="0" data-bind-class="unused && 'is-unused'">
|
|
3
3
|
<span class="blx-icon" aria-hidden="true"><span data-icon="box" data-icon-size="16"></span></span>
|
|
4
4
|
<span class="blx-main"><strong>{{name}}</strong><span data-bind-hidden="!description">{{description}}</span><small>{{meta}}</small></span>
|
|
@@ -12,13 +12,13 @@ import{api as h,apiRequest as Ue}from"../api.js";import{addBannerAction as F}fro
|
|
|
12
12
|
</span>
|
|
13
13
|
<span class="blx-uses" title="Pages and views that use it">{{uses}}</span>
|
|
14
14
|
<button type="button" class="blx-kebab" aria-label="Actions for {{name}}" title="Actions">\u22EE</button>
|
|
15
|
-
</div>`,w=
|
|
15
|
+
</div>`,w=c=>String(c??"").replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""");function ke(c){const n=document.createElement("template");return n.innerHTML=c.trim(),n.content.firstElementChild}const d=Pe(ye);async function ct(c){try{return await navigator.clipboard.writeText(c),!0}catch{const n=document.createElement("textarea");n.value=c,n.style.cssText="position:fixed;opacity:0;",document.body.appendChild(n),n.select();let f=!1;try{f=document.execCommand("copy")}catch{}return n.remove(),f}}export const blocksView={templateUrl:"/admin/js/templates/blocks.html",async onMount(c){d.reset();const n=c.get(0).querySelector(".blx")||c.get(0),f=()=>ye.test(location.hash)&&n.isConnected,x=_e(),u=M.observable([]),J=M.observable(!0),U=M.observable("");let V="all";try{V=We.includes(S.get(G))?S.get(G):"all"}catch{}const g=M.observable(V),H=M.observable("");d.add(M.effect(()=>{const e=g.value;try{S.set(G,e)}catch{}}));let Q="";try{Q=S.get(nt)}catch{}const X=tt(Q),y=X.tag;d.add(X.dispose);const T=M.observable([]),k=M.observable({}),we=Ve,A=M.observable([]);d.add(M.effect(()=>{A.value=Ye(u.value,{filter:g.value,query:H.value,tag:y.value,tools:k.value})}));const O=M.observable([]);d.add(M.effect(()=>{const e=k.value;O.value=A.value.map(t=>Ge(t,we,e))}));const P=M.computed(()=>at(T.value,u.value,k.value)),xe=M.computed(()=>ve(y.value,A.value.length,"blocks")),Ee=M.computed(()=>{const e=u.value,t=e.filter(a=>Y(a)>0).length;return{all:e.length,used:t,unused:e.length-t}}),Z=M.computed(()=>!!y.value&&u.value.length>0&&!A.value.length),Te=M.computed(()=>Z.value&&!H.value.trim()&&g.value==="all"?ve(y.value,0,"blocks"):u.value.length?"No blocks match.":"No blocks yet - New block in the banner makes one, or Import brings one in."),K=e=>u.peek().find(t=>t.name===e),Ce=x?`#/blocks/new?project=${encodeURIComponent(x)}`:"#/blocks/new",ee=e=>`#/blocks/edit/${encodeURIComponent(e)}`;async function _(){try{let e=await Ue("/blocks?usage=1",{method:"GET"});if(!f())return;if(e=Array.isArray(e)?e:[],x){const t=e.length;e=Ke(e,x),ze(n,{total:t,shown:e.length,slug:x,allHref:"#/blocks",noun:"blocks"})}u.value=e,U.value="",await Se()}catch(e){U.value=`Could not load the blocks: ${e.message||e}`}finally{J.value=!1}}async function Se(){try{const e=await h.listTags.load("blocks");k.value=e.tools,T.value=e.tags}catch{}}async function te(e,t){try{const a=await h.listTags.changeItem("blocks",e.name,t);u.value=u.peek().map(s=>s.name===e.name?{...s,meta:{...s.meta||{},adminTags:a}}:s);const o=a.filter(s=>!T.peek().some(i=>et(i.name,s)));o.length&&(T.value=[...T.peek(),...o.map(s=>({name:s}))])}catch(a){E.toast(`Tags not saved: ${a.message||a}`,{type:"error"})}}const Me=()=>Ze({kind:"blocks",noun:"blocks",title:"Blocks settings - tags",tags:P,tools:k,active:y,reload:_}),C=async()=>{Oe(ot),f()&&await _()};async function Ne(e){const a=Y(e)||0?` It is ${w(ge(e).toLowerCase())} - they will show nothing where it was.`:"";if(await E.confirm(`Delete the block "${w(e.name)}"?${a} This cannot be undone.`))try{await h.blocks.delete(e.name),E.toast(`Deleted "${e.name}".`,{type:"success"}),await C()}catch(o){E.toast(o.message||"Failed to delete block.",{type:"error"})}}async function Le(e){try{await h.blocks.exportBundle(e.name)}catch(t){E.toast(t.message||"Export failed.",{type:"error"})}}async function Ie(e){const t=fe(e),a=await ct(t);E.toast(a?`Copied ${t}`:`Could not copy - your browser refused. The shortcode is ${t}`,{type:a?"success":"error"})}const N=n.querySelector(".blx-import-file");async function ae(){const e=N.files?.[0];if(!e)return;N.value="";let t;try{t=JSON.parse(await e.text())}catch{E.toast("Not a valid .dmblock.json file (could not parse JSON).",{type:"error"});return}if(!t||typeof t!="object"||!t.name||typeof t.html!="string"){E.toast("Bundle is missing a name or html field.",{type:"error"});return}try{const a=await h.blocks.importBundle(t);E.toast(`Imported "${a.name}".`,{type:"success"}),await C()}catch(a){if(a.code==="CONFLICT"){if(!await E.confirm(`A block named "${w(a.name)}" already exists. Overwrite it with the imported version?`)){E.toast("Import cancelled.",{type:"info"});return}try{const o=await h.blocks.importBundle(t,{overwrite:!0});E.toast(`Overwrote "${o.name}".`,{type:"success"}),await C()}catch(o){E.toast(o.message||"Import failed.",{type:"error"})}return}E.toast(a.message||"Import failed.",{type:"error"})}}N.addEventListener("change",ae),d.add(()=>N.removeEventListener("change",ae));const L=new Set;let v=null,se=!1;function Be(e){const t=E.slideover({title:`Where ${w(e.name)} is used`,size:"sm",position:"right"}),a=ke(`
|
|
16
16
|
<div class="blx-form">
|
|
17
17
|
<p class="blx-note blx-where-sum"></p>
|
|
18
18
|
<ul class="blx-where"></ul>
|
|
19
19
|
<div><div class="form-label">Shortcode</div><div class="blx-code"></div>
|
|
20
20
|
<small class="blx-hint">Right-click the block in the list and Copy shortcode to paste it into a page.</small></div>
|
|
21
|
-
</div>`);a.querySelector(".blx-where-sum").textContent=ge(e)+".",a.querySelector(".blx-code").textContent=fe(e);const o=a.querySelector(".blx-where"),s=(
|
|
21
|
+
</div>`);a.querySelector(".blx-where-sum").textContent=ge(e)+".",a.querySelector(".blx-code").textContent=fe(e);const o=a.querySelector(".blx-where"),s=(i,D,F)=>{const j=document.createElement("li"),l=document.createElement("a");l.href=i,l.textContent=D,l.addEventListener("click",()=>t.close());const m=document.createElement("small");m.textContent=F,j.append(l,m),o.appendChild(j)};e.usage?.footer&&s("#/settings","Site Settings \u203A Footer","footer");for(const i of e.usage?.pages||[])s(`#/pages/edit${i}`,i,"page");for(const i of e.usage?.views||[])s(`#/views/edit/${encodeURIComponent(i)}`,i,"view");t.element.appendChild(a),L.add(t),me(t,()=>L.delete(t)),t.open()}function oe(e,t=null){const a=()=>u.peek().map(p=>p.name),o=t?.name??he(e.name,a()),s=M.observable(o),i=M.observable(!1),D=M.computed(()=>Je(s.value,u.value.map(p=>p.name))),F={name:s,saving:i,err:D,cannot:M.computed(()=>i.value||!!D.value)},j=()=>s.peek()!==he(e.name,a())||!!t,l=E.slideover({title:`Duplicate ${w(e.name)}`,size:"sm",position:"right"}),m=ke(`
|
|
22
22
|
<div class="blx-form">
|
|
23
23
|
<div>
|
|
24
24
|
<label class="form-label" for="blx-dup-name">Name of the copy
|
|
@@ -33,4 +33,4 @@ import{api as h,apiRequest as Ue}from"../api.js";import{addBannerAction as F}fro
|
|
|
33
33
|
<button type="button" class="btn btn-sm btn-primary" data-on-click="save" data-bind-disabled="cannot.value">
|
|
34
34
|
<span data-icon="copy" data-icon-size="13"></span> Duplicate</button>
|
|
35
35
|
</div>
|
|
36
|
-
</div>`);let z=!1;async function re(){if(
|
|
36
|
+
</div>`);let z=!1;async function re(){if(F.cannot.peek())return;i.value=!0;const p=s.peek().trim();try{const r=await h.blocks.get(e.name);await h.blocks.put(p,{content:r.content,css:r.css||"",...(r.meta?.project||R(r).length)&&{meta:{...r.meta?.project&&{project:r.meta.project},...R(r).length&&{adminTags:R(r)}}}}),E.toast(`Made "${p}".`,{type:"success"}),z=!0,l.close(),await C()}catch(r){E.toast(`Not duplicated: ${r.message||r}`,{type:"error"})}finally{i.value=!1}}l.element.appendChild(m);const De=pe(m),Fe=M.applyBindings(F,m,{methods:{save:re,cancel:()=>l.close()}}),Re=p=>{p.key==="Enter"&&p.target.matches("input")&&(p.preventDefault(),re())};m.addEventListener("keydown",Re);const de={dirty:j,values:()=>({name:s.peek()}),source:e.name};v=de,L.add(l),me(l,()=>{Fe.dispose(),De(),L.delete(l),v===de&&(v=null)});const qe=l.close.bind(l);let W=!1;l.close=async p=>{if(!z&&!se&&p!==!0&&j()){if(W)return;W=!0;const r=await E.confirm("Discard the name you typed?");if(W=!1,!r)return}return z=!0,qe()},I.scan(m),l.open();const ue=m.querySelector("#blx-dup-name");ue?.focus(),ue?.select()}function je(e){const t=K(e);if(!t)return[];const a=Y(t)||0;return[{header:t.name},{label:"Edit",icon:"edit",action:()=>{location.hash=ee(t.name)}},{label:"Copy shortcode",icon:"copy",action:()=>Ie(t)},{label:a?`Where it is used (${a})\u2026`:"Where it is used\u2026",icon:"link",action:()=>Be(t)},{type:"divider"},...st({all:Xe(P.peek()),current:R(t),change:o=>te(t,o),newTag:async()=>{const o=await Qe(P.peek(),k.peek());o&&await te(t,{add:[o]})}}),{type:"divider"},{label:"Duplicate\u2026",icon:"layers",action:()=>oe(t)},{label:"Export (.dmblock.json)",icon:"download",action:()=>Le(t)},{type:"divider"},{label:"Delete\u2026",icon:"trash",danger:!0,action:()=>Ne(t)}]}const b=n.querySelector(".blx-list");b.innerHTML=lt;const $e=M.applyBindings({blocks:u,loading:J,loadError:U,filter:g,query:H,rows:O,counts:Ee,emptyText:Te,tagNote:xe,tagEmpty:Z},n,{methods:{showAllTags:()=>{y.value=""},showAll:()=>{g.value="all"},showUsed:()=>{g.value="used"},showUnused:()=>{g.value="unused"}}});d.add(()=>$e.dispose()),d.add(pe(n,{position:"bottom"})),d.add(M.effect(()=>{O.value,requestAnimationFrame(()=>{b.isConnected&&I.scan(b)})}));const Ae=E.contextMenu(b,{cursor:"glyph",match:".blx-row",inherit:!1,density:"compact",items:e=>je(e.dataset.name)});d.add(()=>Ae?.destroy?.());const ne=e=>{K(e)&&(location.hash=ee(e))},le=e=>{const t=e.target.closest(".blx-row");if(!t)return;const a=e.target.closest(".blx-kebab");if(a){be(a);return}ne(t.dataset.name)},ce=e=>{const t=e.target.closest(".blx-row");t&&(e.key==="F10"&&e.shiftKey?(e.preventDefault(),be(t)):e.key==="Enter"&&e.target===t&&ne(t.dataset.name))};b.addEventListener("click",le),b.addEventListener("keydown",ce),d.add(()=>{b.removeEventListener("click",le),b.removeEventListener("keydown",ce)}),$(c,{id:"blocks-packs",icon:"package",title:"Block packs - create, share and install",onClick:()=>He({changed:C})}),$(c,{id:"blocks-settings",icon:"settings",title:"Blocks settings - tags",onClick:Me}),$(c,{id:"blocks-guide",icon:"book",title:"Blocks guide",onClick:()=>{location.hash="#/docs/usage/blocks"}}),$(c,{id:"blocks-import",icon:"upload",title:"Import a .dmblock.json bundle",onClick:()=>N.click()}),$(c,{id:"blocks-new",icon:"plus",title:"New block",onClick:()=>{location.hash=Ce}});const ie=e=>{v?.dirty()&&(e.preventDefault(),e.returnValue="")};if(window.addEventListener("beforeunload",ie),d.add(()=>window.removeEventListener("beforeunload",ie)),d.add(()=>{if(v?.dirty())try{S.set(q,{source:v.source,values:v.values(),at:new Date().toISOString()})}catch{}se=!0,[...L].forEach(e=>{try{e.close(!0)}catch{}})}),I.scan(n),await _(),!f())return;let B=null;try{B=S.get(q)}catch{}if(B?.values&&B.source){try{S.remove?S.remove(q):S.set(q,null)}catch{}const e=K(B.source);e&&await E.confirm(`You were duplicating "${w(e.name)}" and left it unfinished. Pick up where you left off?`)&&f()&&oe(e,B.values)}}};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{api as
|
|
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=`
|
|
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 B,apiRequest as k}from"../api.js";import{placeTools as Le}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>`,D=["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(Le(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 B.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=Be(u||{}),a={};for(const[e,t]of Object.entries(m))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()])),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);B.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(""),O=M.observable(!1),L=M.observable(""),A=M.observable(""),p=M.observable(null),K=M.observable([]),F=M.observable(""),z=M.observable(!0),N=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:Pe(s.expiresAt,t)}})}));const ge={...a,saving:x,dirty:C,tabs:ee,problems:_,testTo:te,testing:O,testResult:L,testTone:A,cacheQuery:F,cacheLoading:z,cacheError:N,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(()=>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(),s=he(e.siteUrl);if(s){E.toast(`Site URL: ${s}`,{type:"error"});return}x.value=!0,T.value="";const d=String(e.title).trim()!==String(t.title).trim();try{await B.settings.save(He(e,o.peek(),{adminHomeReady:U.peek()}));const $=await B.settings.get().catch(()=>null);if(!i())return;$&&(o.value=$);const Oe={...e,smtpPass:""};a.smtpPass.value="",b.value=Oe;try{S.remove?S.remove(g):S.set(g,null)}catch{}document.dispatchEvent(new CustomEvent("dm:admin-home-changed")),(d||["adminBrandEnabled","adminBrandTitle","adminBrandLogo","adminBrandIcon"].some(pe=>e[pe]!==t[pe]))&&document.dispatchEvent(new CustomEvent("dm:sidebar-rebuild")),fe(be),E.toast("Settings saved.",{type:"success"})}catch($){T.value=$.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?")&&(ae(b.peek()),T.value="")}function ae(e){for(const[t,s]of Object.entries(e))a[t]&&(a[t].value=s)}async function ke(){if(!O.peek()){O.value=!0,A.value="",L.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;L.value=e?.message||"Test email sent.",A.value="is-ok"}catch(e){if(!i())return;L.value=e.message||"Could not send the test email.",A.value="is-bad"}finally{O.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 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=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");D.includes(oe)&&W.activate(D.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:a[e].peek()});t&&i()&&(a[e].value=t)},clearBrandImage:e=>{a[e].value=""},goTab:e=>{const t=D.indexOf(e);t>=0&&W.activate(t)}}});r(()=>Ce.dispose());for(const e of n.querySelectorAll("[data-brand-icon]")){const t=e.dataset.brandIcon,s=_e("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(Re(n,{position:"bottom"}));const xe=e=>{const t=e.target.closest("[data-go]");if(!t)return;const s=D.indexOf(t.dataset.go);s>=0&&W.activate(s)};n.querySelector(".stx-problems").addEventListener("click",xe);const Y=n.querySelector("#stx-admin-home");Ne(Y,De(a.adminHome.peek())).then(()=>{i()&&(Y.value=a.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),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))};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)})`:"",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($e(b.peek(),h.form)),U.peek()&&(Y.value=a.adminHome.peek()))}}};
|
|
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()))}}};
|