domma-cms 1.48.2 → 1.49.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 +9 -0
- package/CLAUDE.md +14 -0
- package/admin/css/admin.css +1 -1
- package/admin/js/app.js +2 -2
- package/admin/js/lib/admin-scope.js +1 -1
- package/admin/js/lib/plugin-chrome.js +1 -1
- package/admin/js/lib/sidebar-arrange.js +1 -1
- package/admin/js/lib/sidebar-grouping.js +1 -1
- package/admin/js/lib/sidebar-renderer.js +5 -5
- package/admin/js/views/menu-editor.js +1 -1
- package/admin/js/views/settings.js +2 -2
- package/docs/plugin-development.md +40 -0
- package/package.json +1 -1
- package/public/js/form-embed.js +1 -0
- package/public/js/forms.js +2 -2
- package/public/js/site.js +1 -1
- package/server/routes/api/auth.js +6 -7
- package/server/routes/api/forms.js +43 -3
- package/server/routes/api/plugins.js +12 -1
- package/server/routes/api/sidebar.js +47 -6
- package/server/services/adminAccess.js +20 -0
- package/server/services/collections.js +3 -2
- package/server/services/formContext.js +166 -0
- package/server/templates/page.html +2 -2
package/admin/js/app.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{wireNotificationMenu as Q}from"./lib/topbar-notifications.js";import{installSmoothCarets as X}from"./lib/smooth-caret.js";import{viewLoaders as Z}from"./views/index.js";import{createLazyViews as ee}from"./lib/lazy-views.js";import{withPluginChrome as _}from"./lib/plugin-chrome.js";import{api as r,getUser as x,isAuthenticated as m,logout as te,sendToLogin as ae}from"./api.js";import{claimDrafts as ie}from"./lib/draft-owner.js";import{isAuthScreen as C,loginHashFor as oe}from"./lib/login-arrange.js";import{installHttpInterceptor as se}from"./http-interceptor.js";import{installResizableSlideovers as ne}from"./lib/slideover-resizable.js";import{installActivityThrobber as re}from"./lib/activity-throbber.js";import{installUpdateNotice as le,renderCmsVersion as ce}from"./lib/update-notice.js";import{renderFrameworkVersions as W,wireAccountMenu as me}from"./lib/topbar-account.js";import{refreshTopbarProject as B}from"./lib/topbar-project.js";import{isPathAllowed as pe,redirectFor as de}from"./lib/admin-scope.js";import{deliverDesktop as ue,desktopActive as he,notificationSettings as we}from"./lib/desktop-notify.js";import{avatarUrl as ge,installAccountAvatar as fe}from"./lib/avatar.js";import{installCalculator as ve}from"./lib/calculator.js";import{takeOverviewPass as be,withDashboardStrip as H}from"./lib/dashboards-strip.js";import{installHotkeys as Se}from"./lib/hotkeys-ui.js";import{applyAdminBrand as K}from"./lib/admin-brand.js";import{installRouterCatchUp as Ce}from"./lib/router-catch-up.js";import{installSidebarDrawer as Me}from"./lib/sidebar-drawer.js";$(()=>{X(document),se(),ve(),le(),re(),ne(),Me(),(async()=>{const{applyAdminTheme:e,refreshAdminTheme:i}=await import("./lib/admin-theme.js");m()?await i(r,{init:!0}):e({dommaTheme:"charcoal-dark"},{init:!0})})();let p=null,w=null,c="/",g=!1,u=null;function D(e){if(N[e])return E.toast(`${N[e]} is switched off on this site.`,{type:"info"}),"/";const[i,t]=e.split("?"),a=new URLSearchParams(t||"").get("tab");if(i==="/settings"&&["favicon","pageNavigation","breadcrumbs","motion","search"].includes(a))return`/appearance?tab=${a}`;if(e.split("?")[0]==="/my-dashboard")return"/dashboards";const o=y[e]||de(p,e);return o||((e.split("?")[0]||"/")==="/"&&c&&c!=="/"&&!be()?y[c]||c:null)}const y={},N={};R.use(async(e,i,t)=>{if(C(e.path))return t();if(!m()){ae();return}const a=D(e.path);if(a){R.navigate(a);return}t()});async function f(){try{const e=await r.get("/auth/permissions");p=e.adminScope||null,w=e.adminBrand||null,K(w),c=e.adminHome||"/",W(e.versions);const i=e.permissions||[];return g=pe(p,"/settings")&&i.some(t=>t==="settings"||t.startsWith("settings.")),u=i.some(t=>t==="notifications"||t.startsWith("notifications.")),i}catch{return p=null,c="/",w||K(null),g=!1,u=null,[]}}document.addEventListener("dm:admin-home-changed",()=>{f()});let P=null,A=!1;document.addEventListener("dm:sidebar-rebuild",()=>{if(B(r),P){A=!0;return}P=(async()=>{do{A=!1;try{await j(await f())}catch{}}while(A)})().finally(()=>{P=null})});async function j(e){const{renderAdminSidebar:i}=await import("./lib/sidebar-renderer.js");await i({mount:"#admin-sidebar",permissions:e,adminScope:p,brand:w})}M.subscribe("router:afterChange",({to:e})=>{C(e.path)&&(h&&(clearInterval(h),h=null),p=null,c="/",g=!1,u=null)});const q=[{path:"/",view:"dashboard",title:"Dashboard - Domma CMS"},{path:"/dashboards",view:"dashboards",title:"Dashboards - Domma CMS"},{path:"/my-dashboard",view:"dashboards",title:"Dashboards - Domma CMS"},{path:"/pages",view:"pages",title:"Pages - Domma CMS"},{path:"/pages/new",view:"pageEditor",title:"New Page - Domma CMS"},{path:"/pages/edit/*",view:"pageEditor",title:"Edit Page - Domma CMS"},{path:"/media",view:"media",title:"Media - Domma CMS"},{path:"/menus",view:"menus",title:"Menus - Domma CMS"},{path:"/context-menus",view:"contextMenus",title:"Context Menus - Domma CMS"},{path:"/context-menus/new",view:"contextMenuEditor",title:"New Context Menu - Domma CMS"},{path:"/context-menus/edit/:slug",view:"contextMenuEditor",title:"Edit Context Menu - Domma CMS"},{path:"/launchers",view:"launchers",title:"Launchers - Domma CMS"},{path:"/menus/new",view:"menuEditor",title:"New Menu - Domma CMS"},{path:"/menus/edit/:slug",view:"menuEditor",title:"Edit Menu - Domma CMS"},{path:"/menu-locations",view:"menuLocations",title:"Menu Locations - Domma CMS"},{path:"/navigation",view:"menusRedirect",title:"Menus - Domma CMS"},{path:"/layouts",view:"layouts",title:"Layouts - Domma CMS"},{path:"/appearance",view:"appearance",title:"Appearance - Domma CMS"},{path:"/footer",view:"footer",title:"Footer - Domma CMS"},{path:"/settings",view:"settings",title:"Settings - Domma CMS"},{path:"/theme",view:"theme",title:"Theme - Domma CMS"},{path:"/users",view:"users",title:"Users - Domma CMS"},{path:"/users/new",view:"userEditor",title:"New User - Domma CMS"},{path:"/users/edit/:id",view:"userEditor",title:"Edit User - Domma CMS"},{path:"/plugins",view:"plugins",title:"Plugins - Domma CMS"},{path:"/plugins/code/:name",view:"pluginCode",title:"Plugin Code - Domma CMS"},{path:"/documentation",view:"documentation",title:"Usage - Domma CMS"},{path:"/tutorials",view:"tutorials",title:"Tutorials - Domma CMS"},{path:"/tutorials/crud",view:"tutorialCrud",title:"Building a CRUD App - Domma CMS"},{path:"/tutorials/editor",view:"tutorialEditor",title:"The Editor - Domma CMS"},{path:"/tutorials/plugin",view:"tutorialPlugin",title:"Writing a Tool - Domma CMS"},{path:"/tutorials/forms",view:"tutorialForms",title:"Form Follow-Up - Domma CMS"},{path:"/docs/components",view:"componentsReference",title:"Components Reference - Domma CMS"},{path:"/docs/components-howto",view:"componentsHowto",title:"Components How-To - Domma CMS"},{path:"/docs/components-walkthrough",view:"componentsWalkthrough",title:"Components Walkthrough - Domma CMS"},{path:"/docs/components-rules",view:"componentsRules",title:"Components Rules - Domma CMS"},{path:"/docs/usage/pages",view:"usagePages",title:"Pages - Usage - Domma CMS"},{path:"/docs/usage/media",view:"usageMedia",title:"Media - Usage - Domma CMS"},{path:"/docs/usage/navigation",view:"usageNavigation",title:"Navigation - Usage - Domma CMS"},{path:"/docs/usage/dconfig",view:"usageDconfig",title:"DConfig - Usage - Domma CMS"},{path:"/docs/usage/shortcodes",view:"usageShortcodes",title:"Shortcodes - Usage - Domma CMS"},{path:"/docs/usage/site-settings",view:"usageSiteSettings",title:"Site Settings - Usage - Domma CMS"},{path:"/docs/usage/plugins",view:"usagePlugins",title:"Plugins - Usage - Domma CMS"},{path:"/docs/usage/users-roles",view:"usageUsersRoles",title:"Users & Roles - Usage - Domma CMS"},{path:"/docs/usage/views",view:"usageViews",title:"Views - Usage - Domma CMS"},{path:"/docs/usage/actions",view:"usageActions",title:"Actions - Usage - Domma CMS"},{path:"/docs/usage/cta-shortcode",view:"usageCtaShortcode",title:"CTA Shortcode - Usage - Domma CMS"},{path:"/docs/usage/editions",view:"usageEditions",title:"Editions & Licences - Usage - Domma CMS"},{path:"/docs/usage/collections",view:"usageCollections",title:"Collections & Forms - Usage - Domma CMS"},{path:"/docs/usage/blocks",view:"usageBlocks",title:"Blocks - Usage - Domma CMS"},{path:"/docs/usage/tools",view:"usageTools",title:"Built-in Tools - Usage - Domma CMS"},{path:"/docs/usage/dashboard",view:"usageDashboard",title:"Dashboard - Usage - Domma CMS"},{path:"/docs/usage/search-engines",view:"usageSearchEngines",title:"Search Engines & AI - Usage - Domma CMS"},{path:"/docs/usage/launchers",view:"usageLaunchers",title:"Launchers - Usage - Domma CMS"},{path:"/docs/usage/chat",view:"usageChat",title:"Chat & Knowledge - Usage - Domma CMS"},{path:"/docs/plugins",view:"pluginGuides",title:"Plugin Guides - Domma CMS"},{path:"/docs/plugins/*",view:"pluginGuide",title:"Plugin Guide - Domma CMS"},{path:"/docs/api/authentication",view:"apiRefAuthentication",title:"Authentication - API - Domma CMS"},{path:"/docs/api/pages",view:"apiRefPages",title:"Pages - API - Domma CMS"},{path:"/docs/api/settings",view:"apiRefSettings",title:"Settings - API - Domma CMS"},{path:"/docs/api/layouts",view:"apiRefLayouts",title:"Layouts - API - Domma CMS"},{path:"/docs/api/navigation",view:"apiRefNavigation",title:"Navigation - API - Domma CMS"},{path:"/docs/api/media",view:"apiRefMedia",title:"Media - API - Domma CMS"},{path:"/docs/api/users",view:"apiRefUsers",title:"Users - API - Domma CMS"},{path:"/docs/api/plugins",view:"apiRefPlugins",title:"Plugins - API - Domma CMS"},{path:"/docs/api/collections",view:"apiRefCollections",title:"Collections - API - Domma CMS"},{path:"/docs/api/views",view:"apiRefViews",title:"Views API - Domma CMS"},{path:"/docs/api/actions",view:"apiRefActions",title:"Actions API - Domma CMS"},{path:"/docs/api/forms",view:"apiRefForms",title:"Forms API - Domma CMS"},{path:"/docs/api/scaffold",view:"apiRefScaffold",title:"Scaffold API - Domma CMS"},{path:"/docs/api/external",view:"apiRefExternal",title:"External API & Tokens - Domma CMS"},{path:"/docs/api/content",view:"apiRefContent",title:"Content API - Domma CMS"},{path:"/docs/api/builder",view:"apiRefBuilder",title:"API Builder - Domma CMS"},{path:"/api-reference",view:"apiReference",title:"API Reference - Domma CMS"},{path:"/collections",view:"collections",title:"Collections - Domma CMS"},{path:"/collections/new",view:"collectionEditor",title:"New Collection - Domma CMS"},{path:"/collections/edit/:slug",view:"collectionEditor",title:"Edit Collection - Domma CMS"},{path:"/collections/:slug/entries",view:"collectionEntries",title:"Entries - Domma CMS"},{path:"/forms",view:"forms",title:"Forms - Domma CMS"},{path:"/forms/new",view:"formEditor",title:"New Form - Domma CMS"},{path:"/forms/edit/:slug",view:"formEditor",title:"Edit Form - Domma CMS"},{path:"/forms/:slug/submissions",view:"formSubmissions",title:"Submissions - Domma CMS"},{path:"/views",view:"viewsList",title:"Views - Domma CMS"},{path:"/views/new",view:"viewEditor",title:"New View - Domma CMS"},{path:"/views/edit/:slug",view:"viewEditor",title:"Edit View - Domma CMS"},{path:"/views/:slug/preview",view:"viewPreview",title:"View Preview - Domma CMS"},{path:"/actions",view:"actionsList",title:"Actions - Domma CMS"},{path:"/actions/new",view:"actionEditor",title:"New Action - Domma CMS"},{path:"/actions/edit/:slug",view:"actionEditor",title:"Edit Action - Domma CMS"},{path:"/pro/docs",view:"proDocs",title:"Pro Documentation - Domma CMS"},{path:"/blocks",view:"blocks",title:"Blocks - Domma CMS"},{path:"/blocks/new",view:"pageEditor",title:"New Block - Domma CMS"},{path:"/blocks/edit/:name",view:"pageEditor",title:"Edit Block - Domma CMS"},{path:"/components",view:"components",title:"Components - Domma CMS"},{path:"/components/new",view:"pageEditor",title:"New Component - Domma CMS"},{path:"/components/edit/:name",view:"pageEditor",title:"Edit Component - Domma CMS"},{path:"/my-profile",view:"myProfile",title:"My Profile - Domma CMS"},{path:"/roles",view:"roles",title:"Roles & Permissions - Domma CMS"},{path:"/roles/edit/:id",view:"roleEditor",title:"Edit Role - Domma CMS"},{path:"/effects",view:"effects",title:"Effects - Domma CMS"},{path:"/search",view:"search",title:"Search - Domma CMS"},{path:"/content-api",view:"contentApi",title:"Content API - Domma CMS"},{path:"/launchers/chats",view:"chats",title:"Chats - Domma CMS"},{path:"/launchers/chats/:id",view:"chats",title:"Chats - Domma CMS"},{path:"/launchers/knowledge",view:"chatKnowledge",title:"Chat Knowledge - Domma CMS"},{path:"/notes",view:"notes",title:"Notes - Domma CMS"},{path:"/todo",view:"todo",title:"Todo - Domma CMS"},{path:"/calculator",view:"calculator",title:"Calculator - Domma CMS"},{path:"/analytics",view:"analytics",title:"Analytics - Domma CMS"},{path:"/seo",view:"seo",title:"SEO - Domma CMS"},{path:"/seo/:tab",view:"seo",title:"SEO - Domma CMS"},{path:"/wordpress-import",view:"wordpressImport",title:"Import a site - Domma CMS"},{path:"/contacts",view:"contacts",title:"Contacts - Domma CMS"},{path:"/calls/new",view:"callNew",title:"Call now - Domma CMS"},{path:"/system/notifications",view:"notifications",title:"Notifications - Domma CMS"},{path:"/api-tokens",view:"apiTokens",title:"API Tokens - Domma CMS"},{path:"/api-endpoints",view:"apiEndpoints",title:"API Builder - Domma CMS"},{path:"/api-endpoints/new",view:"apiEndpointEditor",title:"New API Endpoint - Domma CMS"},{path:"/api-endpoints/edit/:id",view:"apiEndpointEditor",title:"Edit API Endpoint - Domma CMS"},{path:"/projects",view:"projects",title:"Projects - Domma CMS"},{path:"/projects/new",view:"projects",title:"New Project - Domma CMS"},{path:"/projects/edit/:slug",view:"projects",title:"Edit Project - Domma CMS"},{path:"/projects/:slug/settings",view:"projectSettings",title:"Project settings - Domma CMS"},{path:"/projects/:slug/pages",view:"pages",title:"Project pages - Domma CMS"},{path:"/projects/:slug/collections",view:"collections",title:"Project collections - Domma CMS"},{path:"/projects/:slug/forms",view:"forms",title:"Project forms - Domma CMS"},{path:"/projects/:slug/actions",view:"actionsList",title:"Project actions - Domma CMS"},{path:"/projects/:slug/menus",view:"menus",title:"Project menus - Domma CMS"},{path:"/projects/:slug/blocks",view:"blocks",title:"Project blocks - Domma CMS"},{path:"/projects/:slug/components",view:"components",title:"Project components - Domma CMS"},{path:"/projects/:slug/views",view:"viewsList",title:"Project views - Domma CMS"},{path:"/projects/:slug/roles",view:"roles",title:"Project roles - Domma CMS"},{path:"/projects/:slug/users",view:"users",title:"Project users - Domma CMS"},{path:"/projects/:slug/apis",view:"apiEndpoints",title:"Project APIs - Domma CMS"},{path:"/projects/:slug",view:"projectDetail",title:"Project - Domma CMS"},{path:"/login",view:"login",title:"Sign in - Domma CMS",onEnter:()=>{$("#admin-sidebar").hide(),$("#admin-topbar").hide()}},{path:"/reset-password",view:"login",title:"Reset Password - Domma CMS",onEnter:()=>{$("#admin-sidebar").hide(),$("#admin-topbar").hide()}}];M.subscribe("router:afterChange",async({to:e,from:i})=>{if(!C(e.path)){if($("#admin-sidebar").show(),$("#admin-topbar").show(),C(i?.path)){$("#topbar-user-name").remove(),import("./lib/admin-theme.js").then(o=>o.refreshAdminTheme(r)),await T();const t=await f(),a=D(e.path);if(a&&R.navigate(a),j(t),we.read().signInToasts)try{const o=await r.system.notifications.list().catch(()=>[]),n=(Array.isArray(o)?o:[]).filter(s=>s.unread&&["warning","critical"].includes(s.data?.severity)).slice(0,3);for(const s of n){const l=d(s.data?.title||""),L=d((s.data?.body||"").slice(0,120));E.toast(`${l} - ${L}`,{type:s.data?.severity==="critical"?"error":"warning",duration:0})}}catch{}}V()}}),M.subscribe("router:afterChange",()=>{setTimeout(()=>{$(".btn-primary, .btn-danger").length&&Domma.effects.reveal(".btn-primary, .btn-danger",{animation:"fade",stagger:40,duration:300})},50)});const z=["#field-project","#menu-project","#collection-project","#endpoint-project","#action-project","#view-project","#block-project","#component-project","#role-project",'[name="project"]','[name="ownedByProject"]'];function G(e){return/^\/(pages|menus|context-menus|collections|forms|actions|views|blocks|components|users|roles|api-endpoints)\/(new|edit\/)/.test(e)}M.subscribe("router:afterChange",({to:e})=>{const i=e?String(e.path).split("?")[0]:"";if(!e||!G(i))return;const a=new URLSearchParams(location.hash.split("?")[1]||"").get("project");if(!a||!/\/new$/.test(i))return;let o=0;const n=60,s=1500,l=()=>{o+=n;for(const L of z){const b=document.querySelector(L);if(!b)continue;if(Array.from(b.options||[]).find(Y=>Y.value===a)){b.value=a,b.dispatchEvent(new Event("change",{bubbles:!0}));return}}o<s&&setTimeout(l,n)};setTimeout(l,n)});const F="cms_card_states",k=S.get(F)||{};M.subscribe("router:afterChange",()=>{setTimeout(()=>{$("#view-container .card-collapsible").each(function(){const e=$(this).find(".card-header h2, .card-header h3").first().text().trim();e&&k[e]==="collapsed"&&$(this).addClass("card-collapsed")})},200)}),$("#view-container").on("click",".card-collapsible .card-header",function(e){if($(e.target).closest("button, a").length)return;const i=$(this).closest(".card");i.toggleClass("card-collapsed");const t=$(this).find("h2, h3").first().text().trim();t&&(k[t]=i.hasClass("card-collapsed")?"collapsed":"open",S.set(F,k))}),Se(),document.addEventListener("keydown",e=>{if(!(e.ctrlKey||e.metaKey)||e.key!=="s"||window.location.hash.startsWith("#/login")||window.location.hash.startsWith("#/reset-password"))return;const i=document.querySelector("#view-container .view-header button.btn-primary");i&&(e.preventDefault(),i.click())});const v=ee(),O=v.views,J={notes:{displayName:"Notes",icon:"edit-3"},todo:{displayName:"Todo",icon:"check-square"},calculator:{displayName:"Calculator",icon:"calculator"},analytics:{displayName:"Analytics",icon:"chart-bar"},seo:{displayName:"SEO",icon:"search"},wordpressImport:{displayName:"Import a site",icon:"download"},contacts:{displayName:"Contacts",icon:"users"},projects:{displayName:"Projects",icon:"folder"},pages:{displayName:"Pages",icon:"file-text"},media:{displayName:"Media",icon:"image"},menus:{displayName:"Site menus",icon:"menu"},contextMenus:{displayName:"Context Menus",icon:"menu"},launchers:{displayName:"Launchers",icon:"rocket"},theme:{displayName:"Theme",icon:"droplet"},collections:{displayName:"Collections",icon:"database"},forms:{displayName:"Forms",icon:"layout"},viewsList:{displayName:"Views",icon:"eye"},actionsList:{displayName:"Actions",icon:"zap"},apiEndpoints:{displayName:"API Builder",icon:"code"},blocks:{displayName:"Blocks",icon:"box"},components:{displayName:"Components",icon:"component"},notifications:{displayName:"Notifications",icon:"bell"},roles:{displayName:"Roles",icon:"shield"},users:{displayName:"Users",icon:"users"},appearance:{displayName:"Appearance",icon:"layout"},footer:{displayName:"Footer",icon:"panel-bottom"},settings:{displayName:"Site Settings",icon:"settings"},effects:{displayName:"Effects",icon:"sparkles"},layouts:{displayName:"Layouts",icon:"layout"},plugins:{displayName:"Marketplace",icon:"store"},myProfile:{displayName:"My Profile",icon:"user"},apiTokens:{displayName:"API Tokens",icon:"key"},search:{displayName:"Search",icon:"search"},contentApi:{displayName:"Content API",icon:"file-text"},chats:{displayName:"Chats",icon:"message-circle"},dashboard:{displayName:"Dashboard",icon:"home"},dashboards:{displayName:"Dashboards",icon:"home"},pageEditor:{displayName:"Pages",section:"Edit",icon:"file-text"},menuEditor:{displayName:"Site menus",section:"Edit",icon:"menu"},menuLocations:{displayName:"Site menus",section:"Locations",icon:"map-pin"},contextMenuEditor:{displayName:"Context Menus",section:"Edit",icon:"menu"},collectionEditor:{displayName:"Collections",section:"Edit",icon:"database"},collectionEntries:{displayName:"Collections",section:"Entries",icon:"database"},formEditor:{displayName:"Forms",section:"Edit",icon:"layout"},formSubmissions:{displayName:"Forms",section:"Submissions",icon:"inbox"},viewEditor:{displayName:"Views",section:"Edit",icon:"eye"},viewPreview:{displayName:"Views",section:"Preview",icon:"eye"},actionEditor:{displayName:"Actions",section:"Edit",icon:"zap"},apiEndpointEditor:{displayName:"API Builder",section:"Edit",icon:"code"},roleEditor:{displayName:"Roles",section:"Edit",icon:"shield"},userEditor:{displayName:"Users",section:"Edit",icon:"users"},projectDetail:{displayName:"Projects",section:"Overview",icon:"folder"},projectSettings:{displayName:"Projects",section:"Settings",icon:"folder"},pluginCode:{displayName:"Marketplace",section:"Code",icon:"code"},chatKnowledge:{displayName:"Chats",section:"Knowledge",icon:"book-open"}};for(const[e,i]of Object.entries(Z))v.register(e,async()=>{let t=await i();const a=J[e];return a&&(t=_(t,{plugin:e,licence:"Built in",...a})),e==="dashboard"?H(t):t});R.use(async(e,i,t)=>{try{await v.load(e.view)}catch(a){console.error("[admin] Screen failed to load",a),O[e.view]={template:'<p role="alert">This screen could not load. Reload the page to try again.</p>'}}t()});const I=[...q];async function T(){if(m())try{const e=await r.plugins.adminConfig(),i=new Set(I.map(t=>t.path));for(const t of e.routes||[])i.has(t.path)||I.push(t);for(const[t,a]of Object.entries(e.views||{})){const o=(e.meta||{})[t];v.register(t,async()=>{const s=(await import(`/plugins/${a.entry}`))[a.exportName];if(!s)throw new Error(`Missing plugin screen: ${t}`);const l=_(s,o);return t==="dashboard"?H(l):l},JSON.stringify([a,o]))}for(const[t,{route:a}]of Object.entries(e.takeovers||{}))a&&(y[`/${t}`]=a);e.mediaPicker&&(globalThis[Symbol.for("domma.media-picker")]=e.mediaPicker);for(const[t,{enabled:a,displayName:o}]of Object.entries(e.tools||{}))a===!1&&(N[`/${t}`]=o);for(const{id:t,href:a}of e.css||[])if(!document.getElementById(t)){const o=document.createElement("link");o.id=t,o.rel="stylesheet",o.href=a,document.head.appendChild(o)}}catch{}}function V(){const e=x();if(!e)return;if($("#topbar-user-name").length){B(r);return}const t={"super-admin":"Super Admin",admin:"Admin",user:"User"}[e.role]||e.role,a=ge(e);$("#topbar-user").get(0).innerHTML=`
|
|
1
|
+
import{wireNotificationMenu as X}from"./lib/topbar-notifications.js";import{installSmoothCarets as Z}from"./lib/smooth-caret.js";import{viewLoaders as ee}from"./views/index.js";import{createLazyViews as te}from"./lib/lazy-views.js";import{withPluginChrome as W}from"./lib/plugin-chrome.js";import{api as r,getUser as B,isAuthenticated as p,logout as ae,sendToLogin as ie}from"./api.js";import{claimDrafts as oe}from"./lib/draft-owner.js";import{isAuthScreen as C,loginHashFor as se}from"./lib/login-arrange.js";import{installHttpInterceptor as ne}from"./http-interceptor.js";import{installResizableSlideovers as re}from"./lib/slideover-resizable.js";import{installActivityThrobber as le}from"./lib/activity-throbber.js";import{installUpdateNotice as ce,renderCmsVersion as me}from"./lib/update-notice.js";import{renderFrameworkVersions as H,wireAccountMenu as pe}from"./lib/topbar-account.js";import{refreshTopbarProject as F}from"./lib/topbar-project.js";import{CONFINED_CLASS as de,isConfined as ue,isPathAllowed as he,redirectFor as we}from"./lib/admin-scope.js";import{deliverDesktop as ge,desktopActive as fe,notificationSettings as ve}from"./lib/desktop-notify.js";import{avatarUrl as be,installAccountAvatar as Ce}from"./lib/avatar.js";import{installCalculator as Se}from"./lib/calculator.js";import{takeOverviewPass as Me,withDashboardStrip as K}from"./lib/dashboards-strip.js";import{installHotkeys as De}from"./lib/hotkeys-ui.js";import{applyAdminBrand as q}from"./lib/admin-brand.js";import{installRouterCatchUp as ye}from"./lib/router-catch-up.js";import{installSidebarDrawer as Ee}from"./lib/sidebar-drawer.js";$(()=>{Z(document),ne(),Se(),ce(),le(),re(),Ee(),(async()=>{const{applyAdminTheme:e,refreshAdminTheme:i}=await import("./lib/admin-theme.js");p()?await i(r,{init:!0}):e({dommaTheme:"charcoal-dark"},{init:!0})})();let c=null,w=null,m="/",g=!1,u=null;function D(e){if(P[e])return E.toast(`${P[e]} is switched off on this site.`,{type:"info"}),"/";const[i,t]=e.split("?"),a=new URLSearchParams(t||"").get("tab");if(i==="/settings"&&["favicon","pageNavigation","breadcrumbs","motion","search"].includes(a))return`/appearance?tab=${a}`;if(e.split("?")[0]==="/my-dashboard")return"/dashboards";const o=N[e]||we(c,e);return o||((e.split("?")[0]||"/")==="/"&&m&&m!=="/"&&!Me()?N[m]||m:null)}function y(){document.body.classList.toggle(de,ue(c))}const N={},P={};R.use(async(e,i,t)=>{if(C(e.path))return t();if(!p()){ie();return}const a=D(e.path);if(a){R.navigate(a);return}t()});async function f(){try{const e=await r.get("/auth/permissions");c=e.adminScope||null,y(),w=e.adminBrand||null,q(w),m=e.adminHome||"/",H(e.versions||{});const i=e.permissions||[];return g=he(c,"/settings")&&i.some(t=>t==="settings"||t.startsWith("settings.")),u=i.some(t=>t==="notifications"||t.startsWith("notifications.")),i}catch{return c=null,y(),m="/",w||q(null),g=!1,u=null,[]}}document.addEventListener("dm:admin-home-changed",()=>{f()});let A=null,j=!1;document.addEventListener("dm:sidebar-rebuild",()=>{if(F(r),A){j=!0;return}A=(async()=>{do{j=!1;try{await k(await f())}catch{}}while(j)})().finally(()=>{A=null})});async function k(e){const{renderAdminSidebar:i}=await import("./lib/sidebar-renderer.js");await i({mount:"#admin-sidebar",permissions:e,adminScope:c,brand:w})}M.subscribe("router:afterChange",({to:e})=>{C(e.path)&&(h&&(clearInterval(h),h=null),c=null,y(),m="/",g=!1,u=null)});const z=[{path:"/",view:"dashboard",title:"Dashboard - Domma CMS"},{path:"/dashboards",view:"dashboards",title:"Dashboards - Domma CMS"},{path:"/my-dashboard",view:"dashboards",title:"Dashboards - Domma CMS"},{path:"/pages",view:"pages",title:"Pages - Domma CMS"},{path:"/pages/new",view:"pageEditor",title:"New Page - Domma CMS"},{path:"/pages/edit/*",view:"pageEditor",title:"Edit Page - Domma CMS"},{path:"/media",view:"media",title:"Media - Domma CMS"},{path:"/menus",view:"menus",title:"Menus - Domma CMS"},{path:"/context-menus",view:"contextMenus",title:"Context Menus - Domma CMS"},{path:"/context-menus/new",view:"contextMenuEditor",title:"New Context Menu - Domma CMS"},{path:"/context-menus/edit/:slug",view:"contextMenuEditor",title:"Edit Context Menu - Domma CMS"},{path:"/launchers",view:"launchers",title:"Launchers - Domma CMS"},{path:"/menus/new",view:"menuEditor",title:"New Menu - Domma CMS"},{path:"/menus/edit/:slug",view:"menuEditor",title:"Edit Menu - Domma CMS"},{path:"/menu-locations",view:"menuLocations",title:"Menu Locations - Domma CMS"},{path:"/navigation",view:"menusRedirect",title:"Menus - Domma CMS"},{path:"/layouts",view:"layouts",title:"Layouts - Domma CMS"},{path:"/appearance",view:"appearance",title:"Appearance - Domma CMS"},{path:"/footer",view:"footer",title:"Footer - Domma CMS"},{path:"/settings",view:"settings",title:"Settings - Domma CMS"},{path:"/theme",view:"theme",title:"Theme - Domma CMS"},{path:"/users",view:"users",title:"Users - Domma CMS"},{path:"/users/new",view:"userEditor",title:"New User - Domma CMS"},{path:"/users/edit/:id",view:"userEditor",title:"Edit User - Domma CMS"},{path:"/plugins",view:"plugins",title:"Plugins - Domma CMS"},{path:"/plugins/code/:name",view:"pluginCode",title:"Plugin Code - Domma CMS"},{path:"/documentation",view:"documentation",title:"Usage - Domma CMS"},{path:"/tutorials",view:"tutorials",title:"Tutorials - Domma CMS"},{path:"/tutorials/crud",view:"tutorialCrud",title:"Building a CRUD App - Domma CMS"},{path:"/tutorials/editor",view:"tutorialEditor",title:"The Editor - Domma CMS"},{path:"/tutorials/plugin",view:"tutorialPlugin",title:"Writing a Tool - Domma CMS"},{path:"/tutorials/forms",view:"tutorialForms",title:"Form Follow-Up - Domma CMS"},{path:"/docs/components",view:"componentsReference",title:"Components Reference - Domma CMS"},{path:"/docs/components-howto",view:"componentsHowto",title:"Components How-To - Domma CMS"},{path:"/docs/components-walkthrough",view:"componentsWalkthrough",title:"Components Walkthrough - Domma CMS"},{path:"/docs/components-rules",view:"componentsRules",title:"Components Rules - Domma CMS"},{path:"/docs/usage/pages",view:"usagePages",title:"Pages - Usage - Domma CMS"},{path:"/docs/usage/media",view:"usageMedia",title:"Media - Usage - Domma CMS"},{path:"/docs/usage/navigation",view:"usageNavigation",title:"Navigation - Usage - Domma CMS"},{path:"/docs/usage/dconfig",view:"usageDconfig",title:"DConfig - Usage - Domma CMS"},{path:"/docs/usage/shortcodes",view:"usageShortcodes",title:"Shortcodes - Usage - Domma CMS"},{path:"/docs/usage/site-settings",view:"usageSiteSettings",title:"Site Settings - Usage - Domma CMS"},{path:"/docs/usage/plugins",view:"usagePlugins",title:"Plugins - Usage - Domma CMS"},{path:"/docs/usage/users-roles",view:"usageUsersRoles",title:"Users & Roles - Usage - Domma CMS"},{path:"/docs/usage/views",view:"usageViews",title:"Views - Usage - Domma CMS"},{path:"/docs/usage/actions",view:"usageActions",title:"Actions - Usage - Domma CMS"},{path:"/docs/usage/cta-shortcode",view:"usageCtaShortcode",title:"CTA Shortcode - Usage - Domma CMS"},{path:"/docs/usage/editions",view:"usageEditions",title:"Editions & Licences - Usage - Domma CMS"},{path:"/docs/usage/collections",view:"usageCollections",title:"Collections & Forms - Usage - Domma CMS"},{path:"/docs/usage/blocks",view:"usageBlocks",title:"Blocks - Usage - Domma CMS"},{path:"/docs/usage/tools",view:"usageTools",title:"Built-in Tools - Usage - Domma CMS"},{path:"/docs/usage/dashboard",view:"usageDashboard",title:"Dashboard - Usage - Domma CMS"},{path:"/docs/usage/search-engines",view:"usageSearchEngines",title:"Search Engines & AI - Usage - Domma CMS"},{path:"/docs/usage/launchers",view:"usageLaunchers",title:"Launchers - Usage - Domma CMS"},{path:"/docs/usage/chat",view:"usageChat",title:"Chat & Knowledge - Usage - Domma CMS"},{path:"/docs/plugins",view:"pluginGuides",title:"Plugin Guides - Domma CMS"},{path:"/docs/plugins/*",view:"pluginGuide",title:"Plugin Guide - Domma CMS"},{path:"/docs/api/authentication",view:"apiRefAuthentication",title:"Authentication - API - Domma CMS"},{path:"/docs/api/pages",view:"apiRefPages",title:"Pages - API - Domma CMS"},{path:"/docs/api/settings",view:"apiRefSettings",title:"Settings - API - Domma CMS"},{path:"/docs/api/layouts",view:"apiRefLayouts",title:"Layouts - API - Domma CMS"},{path:"/docs/api/navigation",view:"apiRefNavigation",title:"Navigation - API - Domma CMS"},{path:"/docs/api/media",view:"apiRefMedia",title:"Media - API - Domma CMS"},{path:"/docs/api/users",view:"apiRefUsers",title:"Users - API - Domma CMS"},{path:"/docs/api/plugins",view:"apiRefPlugins",title:"Plugins - API - Domma CMS"},{path:"/docs/api/collections",view:"apiRefCollections",title:"Collections - API - Domma CMS"},{path:"/docs/api/views",view:"apiRefViews",title:"Views API - Domma CMS"},{path:"/docs/api/actions",view:"apiRefActions",title:"Actions API - Domma CMS"},{path:"/docs/api/forms",view:"apiRefForms",title:"Forms API - Domma CMS"},{path:"/docs/api/scaffold",view:"apiRefScaffold",title:"Scaffold API - Domma CMS"},{path:"/docs/api/external",view:"apiRefExternal",title:"External API & Tokens - Domma CMS"},{path:"/docs/api/content",view:"apiRefContent",title:"Content API - Domma CMS"},{path:"/docs/api/builder",view:"apiRefBuilder",title:"API Builder - Domma CMS"},{path:"/api-reference",view:"apiReference",title:"API Reference - Domma CMS"},{path:"/collections",view:"collections",title:"Collections - Domma CMS"},{path:"/collections/new",view:"collectionEditor",title:"New Collection - Domma CMS"},{path:"/collections/edit/:slug",view:"collectionEditor",title:"Edit Collection - Domma CMS"},{path:"/collections/:slug/entries",view:"collectionEntries",title:"Entries - Domma CMS"},{path:"/forms",view:"forms",title:"Forms - Domma CMS"},{path:"/forms/new",view:"formEditor",title:"New Form - Domma CMS"},{path:"/forms/edit/:slug",view:"formEditor",title:"Edit Form - Domma CMS"},{path:"/forms/:slug/submissions",view:"formSubmissions",title:"Submissions - Domma CMS"},{path:"/views",view:"viewsList",title:"Views - Domma CMS"},{path:"/views/new",view:"viewEditor",title:"New View - Domma CMS"},{path:"/views/edit/:slug",view:"viewEditor",title:"Edit View - Domma CMS"},{path:"/views/:slug/preview",view:"viewPreview",title:"View Preview - Domma CMS"},{path:"/actions",view:"actionsList",title:"Actions - Domma CMS"},{path:"/actions/new",view:"actionEditor",title:"New Action - Domma CMS"},{path:"/actions/edit/:slug",view:"actionEditor",title:"Edit Action - Domma CMS"},{path:"/pro/docs",view:"proDocs",title:"Pro Documentation - Domma CMS"},{path:"/blocks",view:"blocks",title:"Blocks - Domma CMS"},{path:"/blocks/new",view:"pageEditor",title:"New Block - Domma CMS"},{path:"/blocks/edit/:name",view:"pageEditor",title:"Edit Block - Domma CMS"},{path:"/components",view:"components",title:"Components - Domma CMS"},{path:"/components/new",view:"pageEditor",title:"New Component - Domma CMS"},{path:"/components/edit/:name",view:"pageEditor",title:"Edit Component - Domma CMS"},{path:"/my-profile",view:"myProfile",title:"My Profile - Domma CMS"},{path:"/roles",view:"roles",title:"Roles & Permissions - Domma CMS"},{path:"/roles/edit/:id",view:"roleEditor",title:"Edit Role - Domma CMS"},{path:"/effects",view:"effects",title:"Effects - Domma CMS"},{path:"/search",view:"search",title:"Search - Domma CMS"},{path:"/content-api",view:"contentApi",title:"Content API - Domma CMS"},{path:"/launchers/chats",view:"chats",title:"Chats - Domma CMS"},{path:"/launchers/chats/:id",view:"chats",title:"Chats - Domma CMS"},{path:"/launchers/knowledge",view:"chatKnowledge",title:"Chat Knowledge - Domma CMS"},{path:"/notes",view:"notes",title:"Notes - Domma CMS"},{path:"/todo",view:"todo",title:"Todo - Domma CMS"},{path:"/calculator",view:"calculator",title:"Calculator - Domma CMS"},{path:"/analytics",view:"analytics",title:"Analytics - Domma CMS"},{path:"/seo",view:"seo",title:"SEO - Domma CMS"},{path:"/seo/:tab",view:"seo",title:"SEO - Domma CMS"},{path:"/wordpress-import",view:"wordpressImport",title:"Import a site - Domma CMS"},{path:"/contacts",view:"contacts",title:"Contacts - Domma CMS"},{path:"/calls/new",view:"callNew",title:"Call now - Domma CMS"},{path:"/system/notifications",view:"notifications",title:"Notifications - Domma CMS"},{path:"/api-tokens",view:"apiTokens",title:"API Tokens - Domma CMS"},{path:"/api-endpoints",view:"apiEndpoints",title:"API Builder - Domma CMS"},{path:"/api-endpoints/new",view:"apiEndpointEditor",title:"New API Endpoint - Domma CMS"},{path:"/api-endpoints/edit/:id",view:"apiEndpointEditor",title:"Edit API Endpoint - Domma CMS"},{path:"/projects",view:"projects",title:"Projects - Domma CMS"},{path:"/projects/new",view:"projects",title:"New Project - Domma CMS"},{path:"/projects/edit/:slug",view:"projects",title:"Edit Project - Domma CMS"},{path:"/projects/:slug/settings",view:"projectSettings",title:"Project settings - Domma CMS"},{path:"/projects/:slug/pages",view:"pages",title:"Project pages - Domma CMS"},{path:"/projects/:slug/collections",view:"collections",title:"Project collections - Domma CMS"},{path:"/projects/:slug/forms",view:"forms",title:"Project forms - Domma CMS"},{path:"/projects/:slug/actions",view:"actionsList",title:"Project actions - Domma CMS"},{path:"/projects/:slug/menus",view:"menus",title:"Project menus - Domma CMS"},{path:"/projects/:slug/blocks",view:"blocks",title:"Project blocks - Domma CMS"},{path:"/projects/:slug/components",view:"components",title:"Project components - Domma CMS"},{path:"/projects/:slug/views",view:"viewsList",title:"Project views - Domma CMS"},{path:"/projects/:slug/roles",view:"roles",title:"Project roles - Domma CMS"},{path:"/projects/:slug/users",view:"users",title:"Project users - Domma CMS"},{path:"/projects/:slug/apis",view:"apiEndpoints",title:"Project APIs - Domma CMS"},{path:"/projects/:slug",view:"projectDetail",title:"Project - Domma CMS"},{path:"/login",view:"login",title:"Sign in - Domma CMS",onEnter:()=>{$("#admin-sidebar").hide(),$("#admin-topbar").hide()}},{path:"/reset-password",view:"login",title:"Reset Password - Domma CMS",onEnter:()=>{$("#admin-sidebar").hide(),$("#admin-topbar").hide()}}];M.subscribe("router:afterChange",async({to:e,from:i})=>{if(!C(e.path)){if($("#admin-sidebar").show(),$("#admin-topbar").show(),C(i?.path)){$("#topbar-user-name").remove(),import("./lib/admin-theme.js").then(o=>o.refreshAdminTheme(r)),await U();const t=await f(),a=D(e.path);if(a&&R.navigate(a),k(t),ve.read().signInToasts)try{const o=await r.system.notifications.list().catch(()=>[]),n=(Array.isArray(o)?o:[]).filter(s=>s.unread&&["warning","critical"].includes(s.data?.severity)).slice(0,3);for(const s of n){const l=d(s.data?.title||""),x=d((s.data?.body||"").slice(0,120));E.toast(`${l} - ${x}`,{type:s.data?.severity==="critical"?"error":"warning",duration:0})}}catch{}}_()}}),M.subscribe("router:afterChange",()=>{setTimeout(()=>{$(".btn-primary, .btn-danger").length&&Domma.effects.reveal(".btn-primary, .btn-danger",{animation:"fade",stagger:40,duration:300})},50)});const G=["#field-project","#menu-project","#collection-project","#endpoint-project","#action-project","#view-project","#block-project","#component-project","#role-project",'[name="project"]','[name="ownedByProject"]'];function J(e){return/^\/(pages|menus|context-menus|collections|forms|actions|views|blocks|components|users|roles|api-endpoints)\/(new|edit\/)/.test(e)}M.subscribe("router:afterChange",({to:e})=>{const i=e?String(e.path).split("?")[0]:"";if(!e||!J(i))return;const a=new URLSearchParams(location.hash.split("?")[1]||"").get("project");if(!a||!/\/new$/.test(i))return;let o=0;const n=60,s=1500,l=()=>{o+=n;for(const x of G){const b=document.querySelector(x);if(!b)continue;if(Array.from(b.options||[]).find(Q=>Q.value===a)){b.value=a,b.dispatchEvent(new Event("change",{bubbles:!0}));return}}o<s&&setTimeout(l,n)};setTimeout(l,n)});const O="cms_card_states",I=S.get(O)||{};M.subscribe("router:afterChange",()=>{setTimeout(()=>{$("#view-container .card-collapsible").each(function(){const e=$(this).find(".card-header h2, .card-header h3").first().text().trim();e&&I[e]==="collapsed"&&$(this).addClass("card-collapsed")})},200)}),$("#view-container").on("click",".card-collapsible .card-header",function(e){if($(e.target).closest("button, a").length)return;const i=$(this).closest(".card");i.toggleClass("card-collapsed");const t=$(this).find("h2, h3").first().text().trim();t&&(I[t]=i.hasClass("card-collapsed")?"collapsed":"open",S.set(O,I))}),De(),document.addEventListener("keydown",e=>{if(!(e.ctrlKey||e.metaKey)||e.key!=="s"||window.location.hash.startsWith("#/login")||window.location.hash.startsWith("#/reset-password"))return;const i=document.querySelector("#view-container .view-header button.btn-primary");i&&(e.preventDefault(),i.click())});const v=te(),V=v.views,Y={notes:{displayName:"Notes",icon:"edit-3"},todo:{displayName:"Todo",icon:"check-square"},calculator:{displayName:"Calculator",icon:"calculator"},analytics:{displayName:"Analytics",icon:"chart-bar"},seo:{displayName:"SEO",icon:"search"},wordpressImport:{displayName:"Import a site",icon:"download"},contacts:{displayName:"Contacts",icon:"users"},projects:{displayName:"Projects",icon:"folder"},pages:{displayName:"Pages",icon:"file-text"},media:{displayName:"Media",icon:"image"},menus:{displayName:"Site menus",icon:"menu"},contextMenus:{displayName:"Context Menus",icon:"menu"},launchers:{displayName:"Launchers",icon:"rocket"},theme:{displayName:"Theme",icon:"droplet"},collections:{displayName:"Collections",icon:"database"},forms:{displayName:"Forms",icon:"layout"},viewsList:{displayName:"Views",icon:"eye"},actionsList:{displayName:"Actions",icon:"zap"},apiEndpoints:{displayName:"API Builder",icon:"code"},blocks:{displayName:"Blocks",icon:"box"},components:{displayName:"Components",icon:"component"},notifications:{displayName:"Notifications",icon:"bell"},roles:{displayName:"Roles",icon:"shield"},users:{displayName:"Users",icon:"users"},appearance:{displayName:"Appearance",icon:"layout"},footer:{displayName:"Footer",icon:"panel-bottom"},settings:{displayName:"Site Settings",icon:"settings"},effects:{displayName:"Effects",icon:"sparkles"},layouts:{displayName:"Layouts",icon:"layout"},plugins:{displayName:"Marketplace",icon:"store"},myProfile:{displayName:"My Profile",icon:"user"},apiTokens:{displayName:"API Tokens",icon:"key"},search:{displayName:"Search",icon:"search"},contentApi:{displayName:"Content API",icon:"file-text"},chats:{displayName:"Chats",icon:"message-circle"},dashboard:{displayName:"Dashboard",icon:"home"},dashboards:{displayName:"Dashboards",icon:"home"},pageEditor:{displayName:"Pages",section:"Edit",icon:"file-text"},menuEditor:{displayName:"Site menus",section:"Edit",icon:"menu"},menuLocations:{displayName:"Site menus",section:"Locations",icon:"map-pin"},contextMenuEditor:{displayName:"Context Menus",section:"Edit",icon:"menu"},collectionEditor:{displayName:"Collections",section:"Edit",icon:"database"},collectionEntries:{displayName:"Collections",section:"Entries",icon:"database"},formEditor:{displayName:"Forms",section:"Edit",icon:"layout"},formSubmissions:{displayName:"Forms",section:"Submissions",icon:"inbox"},viewEditor:{displayName:"Views",section:"Edit",icon:"eye"},viewPreview:{displayName:"Views",section:"Preview",icon:"eye"},actionEditor:{displayName:"Actions",section:"Edit",icon:"zap"},apiEndpointEditor:{displayName:"API Builder",section:"Edit",icon:"code"},roleEditor:{displayName:"Roles",section:"Edit",icon:"shield"},userEditor:{displayName:"Users",section:"Edit",icon:"users"},projectDetail:{displayName:"Projects",section:"Overview",icon:"folder"},projectSettings:{displayName:"Projects",section:"Settings",icon:"folder"},pluginCode:{displayName:"Marketplace",section:"Code",icon:"code"},chatKnowledge:{displayName:"Chats",section:"Knowledge",icon:"book-open"}};for(const[e,i]of Object.entries(ee))v.register(e,async()=>{let t=await i();const a=Y[e];return a&&(t=W(t,{plugin:e,licence:"Built in",...a})),e==="dashboard"?K(t):t});R.use(async(e,i,t)=>{try{await v.load(e.view)}catch(a){console.error("[admin] Screen failed to load",a),V[e.view]={template:'<p role="alert">This screen could not load. Reload the page to try again.</p>'}}t()});const T=[...z];async function U(){if(p())try{const e=await r.plugins.adminConfig(),i=new Set(T.map(t=>t.path));for(const t of e.routes||[])i.has(t.path)||T.push(t);for(const[t,a]of Object.entries(e.views||{})){const o=(e.meta||{})[t];v.register(t,async()=>{const s=(await import(`/plugins/${a.entry}`))[a.exportName];if(!s)throw new Error(`Missing plugin screen: ${t}`);const l=W(s,o);return t==="dashboard"?K(l):l},JSON.stringify([a,o]))}for(const[t,{route:a}]of Object.entries(e.takeovers||{}))a&&(N[`/${t}`]=a);e.mediaPicker&&(globalThis[Symbol.for("domma.media-picker")]=e.mediaPicker);for(const[t,{enabled:a,displayName:o}]of Object.entries(e.tools||{}))a===!1&&(P[`/${t}`]=o);for(const{id:t,href:a}of e.css||[])if(!document.getElementById(t)){const o=document.createElement("link");o.id=t,o.rel="stylesheet",o.href=a,document.head.appendChild(o)}}catch{}}function _(){const e=B();if(!e)return;if($("#topbar-user-name").length){F(r);return}const t={"super-admin":"Super Admin",admin:"Admin",user:"User"}[e.role]||e.role,a=be(e);$("#topbar-user").get(0).innerHTML=`
|
|
2
2
|
<a id="topbar-project" class="topbar-action-link topbar-project" hidden>
|
|
3
3
|
<span data-icon="folder"></span>
|
|
4
4
|
<span id="topbar-project-name" class="topbar-project-name"></span>
|
|
@@ -51,4 +51,4 @@ import{wireNotificationMenu as Q}from"./lib/topbar-notifications.js";import{inst
|
|
|
51
51
|
</a>
|
|
52
52
|
</div>
|
|
53
53
|
</div>
|
|
54
|
-
`;const o=$("#topbar-settings").get(0);o&&(o.hidden=!g),$("#topbar-logout-btn").on("click",n=>{n.preventDefault(),
|
|
54
|
+
`;const o=$("#topbar-settings").get(0);o&&(o.hidden=!g),$("#topbar-logout-btn").on("click",n=>{n.preventDefault(),ae()}),Domma.icons.scan("#admin-topbar"),E.tooltip("#topbar-actions [data-tooltip]",{placement:"bottom"}),pe(e),X({refreshBadge:L,canRead:()=>u!==!1}),Ce(e),H(),me(),F(r),L(),h||(h=setInterval(L,6e4))}function d(e){return String(e).replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}let h=null;async function L(){if(!(!p()||u===!1))try{const{count:e}=await r.system.notifications.unreadCount(),i=$("#topbar-bell-badge");e>0?i.text(e>99?"99+":String(e)).removeAttr("hidden"):i.attr("hidden","").text(""),e>0&&fe()&&ge(await r.system.notifications.list().catch(()=>[]))}catch{}}(async()=>{if(!p()&&!window.location.hash.startsWith("#/reset-password"))window.location.hash.startsWith("#/login")||(window.location.hash=se(window.location.hash));else{oe(B()?.id);const a=B(),[o]=await Promise.all([a?f():Promise.resolve([]),U()]);if(a){const n=(window.location.hash||"#/").slice(1)||"/",s=D(n);s&&(window.location.hash=`#${s}`),k(o).catch(l=>console.error("[admin] Sidebar failed to load",l)),_()}}const e=R._extractParams.bind(R);R._extractParams=function(a,o){const n=o.indexOf("?");if(n!==-1&&(o=o.slice(0,n)),a.endsWith("/*")){const s=a.slice(0,-2);return o.startsWith(s+"/")?{}:null}return e(a,o)};const i=R._renderNotFound.bind(R);let t="";R._renderNotFound=async function(a){return p()&&t!==a&&(t=a,await U(),R._matchRoute(a).route)?(t="",R._handleRouteChange()):(t="",p()&&$("#admin-sidebar").get(0)?.style.display==="none"?(E.toast("That link goes nowhere - here is your home page.",{type:"warning"}),R.navigate("/")):i(a))},ye(R),R.init({container:"#view-container",routes:T,views:V,default:"/",transitions:{enter:"fadeIn",leave:"fadeOut",duration:150}})})()});
|
|
@@ -1 +1 @@
|
|
|
1
|
-
export const ALWAYS_ALLOWED=["/login","/reset-password","/my-profile"];function o(r,t){return r==="/"?t==="/":t===r||t.startsWith(`${r}/`)}export function isPathAllowed(r,t){if(!r)return!0;const
|
|
1
|
+
export const ALWAYS_ALLOWED=["/login","/reset-password","/my-profile"];function o(r,t){return r==="/"?t==="/":t===r||t.startsWith(`${r}/`)}export function isPathAllowed(r,t){if(!r)return!0;const e=String(t||"/").split("?")[0]||"/";return ALWAYS_ALLOWED.some(n=>o(n,e))?!0:(r.allow||[]).some(n=>o(n,e))}export function redirectFor(r,t){return isPathAllowed(r,t)?null:r.home||"/my-profile"}export const CONFINED_CLASS="dm-admin-confined";export function isConfined(r){return!!r}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
const
|
|
1
|
+
const h="dm-admin-confined",b=/^(built in|included\b)/i;export function formatReleased(e){if(!e||typeof e!="string"||!/^\d{4}-\d{2}-\d{2}/.test(e))return"";const n=new Date(e);if(Number.isNaN(n.getTime()))return"";const t=c=>String(c).padStart(2,"0");return`${t(n.getDate())}.${t(n.getMonth()+1)}.${n.getFullYear()}`}export function expiryFact(e,n=new Date){if(!e||typeof e!="object")return null;const t=formatReleased(e.date);if(!t)return null;const c=e.kind==="rental",a=e.state==="support-ended"||e.state==="expired"||!c&&Date.parse(e.date)<n.getTime(),s=Date.parse(e.date)-n.getTime()<30*864e5;let i;return c?i=e.state==="grace"?`Expired ${t} (grace)`:`Expires ${t}`:i=a?`Support ended ${t}`:`Support to ${t}`,{text:i,title:c?"Licence expiry":"Support and updates expiry - the licence itself does not expire",tone:a||e.state==="grace"?c?"danger":"warning":s?"warning":"ok"}}export function buildBanner(e,{facts:n=!0}={}){const t=n?e||{}:{...e,version:"",date:"",licence:"",expiry:null},c=document.createElement("header");c.className="dm-plugin-banner";const a=document.createElement("div");a.className="dm-plugin-banner-identity";const s=document.createElement("span");s.className="dm-plugin-banner-icon",s.setAttribute("data-icon",t.icon||"package"),s.setAttribute("data-icon-size","18"),a.appendChild(s);const i=document.createElement("h1");i.className="dm-plugin-banner-name";const u=t.displayName||t.plugin||"Plugin",d=String(t.section||"").trim();if(d&&d.toLowerCase()!==u.toLowerCase()){const o=document.createElement("span");o.className="dm-plugin-banner-parent",o.textContent=u;const p=document.createElement("span");p.className="dm-plugin-banner-sep",p.setAttribute("aria-hidden","true"),p.textContent="\u203A",i.append(o,p,document.createTextNode(d))}else i.textContent=u;a.appendChild(i),c.appendChild(a);const l=document.createElement("div");l.className="dm-plugin-banner-facts",((o,p)=>{if(!o)return;const g=document.createElement("span");g.className="dm-plugin-fact"+(p?" "+p:""),g.textContent=o,l.appendChild(g)})(t.version?`v${t.version}`:"","dm-plugin-fact--version");const m=formatReleased(t.date);if(m){const o=document.createElement("span");o.className="dm-plugin-fact dm-plugin-fact--date",o.title="Release date",o.textContent=m,l.appendChild(o)}if(t.licence){const o=document.createElement("span");o.className="dm-plugin-fact dm-plugin-fact--licence"+(b.test(t.licence)?" is-included":" is-licensed"),o.title="Licence",o.textContent=t.licence,l.appendChild(o)}const f=expiryFact(t.expiry);if(f){const o=document.createElement("span");o.className=`dm-plugin-fact dm-plugin-fact--expiry is-${f.tone}`,o.title=f.title,o.textContent=f.text,l.appendChild(o)}return c.appendChild(l),c}export function withPluginChrome(e,n){if(!e||typeof e!="object")return e;const t=Object.create(Object.getPrototypeOf(e));Object.assign(t,e);const c=typeof e.onMount=="function"?e.onMount:null;return t.onMount=async function(...a){const s=a[0],i=s&&typeof s.get=="function"?s.get(0):s;return i&&i.nodeType===1&&(!e.template&&!e.templateUrl&&i.replaceChildren(),i.querySelector(":scope > .dm-plugin-shell")||applyChrome(i,n)),c?c.apply(e,a):void 0},t}export function applyChrome(e,n){const t=document.createElement("section");t.className="dm-plugin-shell",n&&n.plugin&&t.setAttribute("data-plugin",n.plugin);const c=typeof document<"u"&&!!document.body?.classList.contains(h);t.appendChild(buildBanner(n,{facts:!c}));const a=document.createElement("div");for(a.className="dm-plugin-body";e.firstChild;)a.appendChild(e.firstChild);t.appendChild(a),e.appendChild(t),N(a,n),y(a),typeof I<"u"&&I.scan?I.scan(t):typeof Domma<"u"&&Domma.icons&&Domma.icons.scan()}function C(e){return[...e.children].filter(n=>!/^(STYLE|SCRIPT|TEMPLATE|LINK)$/.test(n.tagName))}function y(e){let n=e;for(let t=0;t<2;t++){const c=C(n);if(c.length!==1)return;if(n=c[0],n.classList.contains("card")){n.classList.add("dm-plugin-unwrap");return}}}function N(e,n){const t=[n&&n.displayName,n&&n.section].map(a=>String(a||"").trim().toLowerCase()).filter(Boolean),c=e.querySelector(":scope > .view-header, :scope > * > .view-header");if(c){const a=c.querySelector("h1, h2"),s=c.querySelector("button, a, input, select");a&&s?a.remove():a&&c.remove();return}if(t.length){for(const a of e.querySelectorAll("h1, h2"))if(t.includes(a.textContent.trim().toLowerCase())){a.remove();return}}}export function addBannerAction(e,{icon:n,title:t,onClick:c,id:a="",label:s=""}){const i=e&&typeof e.get=="function"?e.get(0):e;if(!i||i.nodeType!==1)return null;const u=i.querySelector(":scope > .dm-plugin-shell > .dm-plugin-banner")||i.closest(".dm-plugin-shell")?.querySelector(":scope > .dm-plugin-banner");if(!u)return null;let d=u.querySelector(":scope > .dm-plugin-banner-facts");d||(d=document.createElement("div"),d.className="dm-plugin-banner-facts",u.appendChild(d));let l=d.querySelector(":scope > .dm-plugin-banner-actions");l||(l=document.createElement("div"),l.className="dm-plugin-banner-actions",d.insertBefore(l,d.firstChild)),a&&l.querySelector(`[data-banner-action="${CSS.escape(a)}"]`)?.remove();const r=document.createElement("button");r.type="button",r.className="btn btn-sm btn-ghost dm-plugin-banner-action",r.title=t||"",r.setAttribute("aria-label",t||s||"Action"),a&&(r.dataset.bannerAction=a);const m=document.createElement("span");return m.setAttribute("data-icon",n||"settings"),m.setAttribute("data-icon-size","16"),r.appendChild(m),s&&r.appendChild(document.createTextNode(` ${s}`)),r.addEventListener("click",c),l.appendChild(r),typeof I<"u"&&I.scan?I.scan(r):typeof Domma<"u"&&Domma.icons&&Domma.icons.scan(r),r}
|
|
@@ -4,4 +4,4 @@ import{api as S}from"../api.js";import{flatten as D,nest as k}from"./menu-rows.j
|
|
|
4
4
|
<span class="sb-arr-grip" data-icon="grip-vertical" data-icon-size="14"></span>
|
|
5
5
|
${e.icon?`<span class="sb-arr-icon" data-icon="${g(e.icon)}" data-icon-size="16"></span>`:'<span class="sb-arr-icon"></span>'}
|
|
6
6
|
<span class="sb-arr-text">${g(a)}</span>
|
|
7
|
-
${b}</div>`),r(e.id,m+1)}};return r(null,0),d.join("")}export async function startArrange(n){const s=n.querySelector(".dm-admin-sidebar");if(!s||s.classList.contains("is-arranging"))return;let l,d;try{[l,d]=await Promise.all([S.menus.get($),H.get("/api/sidebar/registered-items").catch(()=>[])])}catch{E.toast("Could not load the sidebar menu to arrange.",{type:"error"});return}if(!l){E.toast("There is no admin sidebar menu to arrange yet - create one in Content > Menus.",{type:"warning"});return}let r=D(N(T(l.items||[],d||[],{forEditor:!0}),{leaveInHiddenFolders:!0}));const o=JSON.stringify(k(r)),m=()=>JSON.stringify(k(r))!==o,e=document.createElement("div");e.className="sb-arrange",e.setAttribute("role","region"),e.setAttribute("aria-label","Arrange the sidebar");const i=document.createElement("div");i.className="sb-arrange-bar",i.append(Object.assign(document.createElement("span"),{className:"sb-arrange-title",textContent:"Arrange"}),Object.assign(document.createElement("button"),{type:"button",className:"btn btn-sm btn-ghost sb-arrange-cancel",textContent:"Cancel"}),Object.assign(document.createElement("button"),{type:"button",className:"btn btn-sm btn-primary sb-arrange-done",textContent:"Done"}));const w=Object.assign(document.createElement("p"),{className:"sb-arrange-hint",textContent:"Drag an item to move it. Drop it on the middle of another to put it inside. The eye hides or shows it. Alt+arrow keys move the focused item."}),a=document.createElement("div");a.className="sb-arrange-list",e.append(i,w,a);const b=()=>{const p=document.createRange();p.selectNodeContents(a),a.replaceChildren(p.createContextualFragment(I(r))),Domma.icons.scan(a)},A=p=>requestAnimationFrame(()=>a.querySelector(`.sb-arr-row[data-id="${CSS.escape(p)}"]`)?.focus());e.style.width=`${Math.max(Math.round(s.getBoundingClientRect().width),240)}px`,s.classList.add("is-arranging"),s.querySelector(".dm-admin-sidebar-header")?.after(e),b();const f=O(a,()=>r,b,{items:".sb-arr-row",handle:null});return new Promise(p=>{let h=!1;const v=t=>{f?.destroy(),document.removeEventListener("keydown",C,!0),e.remove(),s.classList.remove("is-arranging"),t?document.dispatchEvent(new CustomEvent("dm:sidebar-rebuild")):s.querySelector(".dm-admin-sidebar-arrange")?.focus(),p(t)},x=async()=>{h||m()&&!await E.confirm("Leave Arrange without saving? Your moves will be lost.",{title:"Discard changes?",confirmText:"Discard",cancelText:"Keep arranging"})||v(!1)},q=async()=>{if(!h){if(!m()){v(!1);return}h=!0,i.querySelectorAll("button").forEach(t=>{t.disabled=!0});try{const t=await S.menus.get($);await S.menus.update($,{...t,items:k(r)}),E.toast("Sidebar arranged.",{type:"success"}),v(!0)}catch(t){h=!1,i.querySelectorAll("button").forEach(u=>{u.disabled=!1}),E.toast(`Could not save the sidebar: ${t?.message||t}`,{type:"error"})}}};i.querySelector(".sb-arrange-cancel").addEventListener("click",x),i.querySelector(".sb-arrange-done").addEventListener("click",q),a.addEventListener("click",t=>{const u=t.target.closest(".sb-arr-hide");if(!u)return;const c=r.find(y=>y.id===u.closest(".sb-arr-row")?.dataset.id);c&&(c.hidden=!c.hidden,c.touched=!0,b(),A(c.id))}),a.addEventListener("keydown",t=>{const u=t.target.closest(".sb-arr-row");if(!u||t.target!==u||!t.altKey)return;const c=u.dataset.id,y={ArrowUp:()=>L(r,c,-1),ArrowDown:()=>L(r,c,1),ArrowRight:()=>z(r,c),ArrowLeft:()=>M(r,c)};y[t.key]&&(t.preventDefault(),y[t.key]()&&(f?f.animate(b):b(),A(c)))});function C(t){t.key!=="Escape"||f?.dragging||!e.contains(document.activeElement)&&document.activeElement!==document.body||(t.preventDefault(),t.stopPropagation(),setTimeout(x,0))}document.addEventListener("keydown",C,!0),a.querySelector(".sb-arr-row")?.focus()})}
|
|
7
|
+
${b}</div>`),r(e.id,m+1)}};return r(null,0),d.join("")}export async function startArrange(n){const s=n.querySelector(".dm-admin-sidebar");if(!s||s.classList.contains("is-arranging"))return;let l,d;try{[l,d]=await Promise.all([S.menus.get($),H.get("/api/sidebar/registered-items?for=editor").catch(()=>[])])}catch{E.toast("Could not load the sidebar menu to arrange.",{type:"error"});return}if(!l){E.toast("There is no admin sidebar menu to arrange yet - create one in Content > Menus.",{type:"warning"});return}let r=D(N(T(l.items||[],d||[],{forEditor:!0}),{leaveInHiddenFolders:!0}));const o=JSON.stringify(k(r)),m=()=>JSON.stringify(k(r))!==o,e=document.createElement("div");e.className="sb-arrange",e.setAttribute("role","region"),e.setAttribute("aria-label","Arrange the sidebar");const i=document.createElement("div");i.className="sb-arrange-bar",i.append(Object.assign(document.createElement("span"),{className:"sb-arrange-title",textContent:"Arrange"}),Object.assign(document.createElement("button"),{type:"button",className:"btn btn-sm btn-ghost sb-arrange-cancel",textContent:"Cancel"}),Object.assign(document.createElement("button"),{type:"button",className:"btn btn-sm btn-primary sb-arrange-done",textContent:"Done"}));const w=Object.assign(document.createElement("p"),{className:"sb-arrange-hint",textContent:"Drag an item to move it. Drop it on the middle of another to put it inside. The eye hides or shows it. Alt+arrow keys move the focused item."}),a=document.createElement("div");a.className="sb-arrange-list",e.append(i,w,a);const b=()=>{const p=document.createRange();p.selectNodeContents(a),a.replaceChildren(p.createContextualFragment(I(r))),Domma.icons.scan(a)},A=p=>requestAnimationFrame(()=>a.querySelector(`.sb-arr-row[data-id="${CSS.escape(p)}"]`)?.focus());e.style.width=`${Math.max(Math.round(s.getBoundingClientRect().width),240)}px`,s.classList.add("is-arranging"),s.querySelector(".dm-admin-sidebar-header")?.after(e),b();const f=O(a,()=>r,b,{items:".sb-arr-row",handle:null});return new Promise(p=>{let h=!1;const v=t=>{f?.destroy(),document.removeEventListener("keydown",C,!0),e.remove(),s.classList.remove("is-arranging"),t?document.dispatchEvent(new CustomEvent("dm:sidebar-rebuild")):s.querySelector(".dm-admin-sidebar-arrange")?.focus(),p(t)},x=async()=>{h||m()&&!await E.confirm("Leave Arrange without saving? Your moves will be lost.",{title:"Discard changes?",confirmText:"Discard",cancelText:"Keep arranging"})||v(!1)},q=async()=>{if(!h){if(!m()){v(!1);return}h=!0,i.querySelectorAll("button").forEach(t=>{t.disabled=!0});try{const t=await S.menus.get($);await S.menus.update($,{...t,items:k(r)}),E.toast("Sidebar arranged.",{type:"success"}),v(!0)}catch(t){h=!1,i.querySelectorAll("button").forEach(u=>{u.disabled=!1}),E.toast(`Could not save the sidebar: ${t?.message||t}`,{type:"error"})}}};i.querySelector(".sb-arrange-cancel").addEventListener("click",x),i.querySelector(".sb-arrange-done").addEventListener("click",q),a.addEventListener("click",t=>{const u=t.target.closest(".sb-arr-hide");if(!u)return;const c=r.find(y=>y.id===u.closest(".sb-arr-row")?.dataset.id);c&&(c.hidden=!c.hidden,c.touched=!0,b(),A(c.id))}),a.addEventListener("keydown",t=>{const u=t.target.closest(".sb-arr-row");if(!u||t.target!==u||!t.altKey)return;const c=u.dataset.id,y={ArrowUp:()=>L(r,c,-1),ArrowDown:()=>L(r,c,1),ArrowRight:()=>z(r,c),ArrowLeft:()=>M(r,c)};y[t.key]&&(t.preventDefault(),y[t.key]()&&(f?f.animate(b):b(),A(c)))});function C(t){t.key!=="Escape"||f?.dragging||!e.contains(document.activeElement)&&document.activeElement!==document.body||(t.preventDefault(),t.stopPropagation(),setTimeout(x,0))}document.addEventListener("keydown",C,!0),a.querySelector(".sb-arr-row")?.focus()})}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{isPathAllowed as F}from"./admin-scope.js";export const TOOLS_FOLDER_TEXT="Tools",MANAGE_PLUGINS_URL="#/plugins",MANAGE_PLUGINS_ITEM={text:"Marketplace",url:MANAGE_PLUGINS_URL,icon:"store",permission:"plugins"};export function stripItemByUrl(e,t){const n=[];for(const r of e||[]){if(!r||r.url===t)continue;const s={...r};Array.isArray(r.items)&&r.items.length&&(s.items=stripItemByUrl(r.items,t)),n.push(s)}return n}export function managePluginsItem(){return{...MANAGE_PLUGINS_ITEM}}export const TOOLS_FOLDER_KEY="tools";const E=["countUrl","core","permission"],c=e=>String(e??"").toLowerCase();export function slugify(e){return c(e).trim().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")}export function groupKeyFor(e,t){return`${c(e)}.${slugify(t)}`}export const GROUP_ICON="folder";const P=e=>e&&(e.type==="separator"||e.type==="spacer"||e.type==="theme-switcher"),A=e=>e&&!P(e)&&!e.url;function w(e){return(e||[]).filter(Boolean).map(t=>Array.isArray(t.items)?{...t,items:w(t.items)}:{...t})}function N(e,t,n=[]){for(const r of e||[]){if(!r)continue;if(t(r))return[...n,r];const s=N(r.items,t,[...n,r]);if(s)return s}return null}function I(e,t,n=[],r=[]){for(const s of e||[])s&&(t(s)&&r.push([...n,s]),I(s.items,t,[...n,s],r));return r}const U=e=>!e.some(t=>t.hidden||t.restricted);function $(e,t){for(const n of e||[]){if(t(n))return n;const r=$(n?.items,t);if(r)return r}return null}export function findFolder(e,t){if(!t)return null;const n=c(t);return $(e,r=>A(r)&&c(r.key)===n)||$(e,r=>A(r)&&!r.key&&c(r.text)===n)}function b(e,t){const n={...t,...e};for(const r of E)t[r]!==void 0&&(n[r]=t[r]);return!(Array.isArray(e.items)&&e.items.length)&&Array.isArray(t.items)&&(n.items=t.items),e.text||(n.text=t.text),!e.icon&&t.icon&&(n.icon=t.icon),delete n.ref,delete n.folder,delete n.group,n}function O(e,{persisted:t,orphan:n=!1,node:r=null}){const s=e?.item||{};return{persisted:t,orphan:n,source:s.source||(s.core?"Built in":""),folder:e?.folder||TOOLS_FOLDER_KEY,defaults:n?{text:null,icon:null}:{text:s.text||"",icon:s.icon||""},...n&&r&&{label:r.text||r.url},...(e?.group||e?.item?.group)&&{group:e.group||e.item.group}}}export function placeTools(e,t,{forEditor:n=!1}={}){const r=w(e),s=(t||[]).filter(o=>o&&o.item&&typeof o.item.text=="string"),d=new Map;for(const o of s)o.item.url&&!d.has(o.item.url)&&d.set(o.item.url,o);const y=new Set,m=o=>{const i=[];for(const u of o){const h=u.url?d.get(u.url):null;if(h&&!y.has(u.url)){y.add(u.url);const g=b(u,h.item);Array.isArray(u.items)&&u.items.length?g.items=m(u.items):n&&(g.items=[]),n&&(g.$tool=O(h,{persisted:!0})),i.push(g);continue}if(u.ref){if(!n)continue;const{ref:g,...f}=u;i.push({...f,items:m(u.items||[]),$tool:O(null,{persisted:!0,orphan:!0,node:u})});continue}Array.isArray(u.items)&&(u.items=m(u.items)),i.push(u)}return i},a=m(r),T=new Set,S=o=>{for(const i of o||[])i.hidden&&i.text&&!i.url&&!(Array.isArray(i.items)&&i.items.length)&&T.add(c(i.text)),S(i.items)};S(a);let x=null;const L=()=>{const o=findFolder(a,TOOLS_FOLDER_KEY);if(o)return o;if(!x){x={text:TOOLS_FOLDER_TEXT,key:TOOLS_FOLDER_KEY,icon:"tool",items:[],synthesised:!0};const i=a.findIndex(u=>["system","documentation"].includes(c(u?.key||u?.text)));a.splice(i===-1?a.length:i,0,x)}return x},l=new Set,k=(o,i)=>{const u=groupKeyFor(o.key||slugify(o.text),i),h=$(a,p=>A(p)&&c(p.key)===u)||(o.items||[]).find(p=>A(p)&&(!p.key||c(p.key)===u)&&c(p.text)===c(i));if(h)return h;const g={text:String(i),key:u,icon:GROUP_ICON,items:[],synthesised:!0},f=o.items.findIndex(p=>l.has(p));return o.items.splice(f===-1?o.items.length:f,0,g),g};for(const o of s){const{item:i}=o;if(i.url&&y.has(i.url))continue;i.url&&y.add(i.url);const u=T.has(c(i.text));if(u&&!n)continue;const h=b({},i);n&&(h.items=[],h.$tool=O(o,{persisted:!1}),u&&(h.hidden=!0));let f=(o.parent?findFolder(a,o.parent)||$(a,_=>!P(_)&&c(_.text)===c(o.parent)):null)||findFolder(a,o.folder||i.folder)||L();f.items=Array.isArray(f.items)?f.items:[];const p=typeof(o.group||i.group)=="string"?(o.group||i.group).trim():"";p&&slugify(p)&&(f=k(f,p),f.items=Array.isArray(f.items)?f.items:[]),f.items.push(h),l.add(h)}return a}export const LOCKED_TOOLS=[{folder:"overview",item:{text:"Dashboard",url:"#/",icon:"home"}},{folder:"content",item:{text:"Site menus",url:"#/menus",icon:"menu",permission:"menus"}},{folder:"system",item:{text:"Users",url:"#/users",icon:"users",permission:"users"}}];export function isLockedUrl(e){return LOCKED_TOOLS.some(t=>t.item.url===e)}export function ensureLockedTools(e,{leaveInHiddenFolders:t=!1}={}){const n=w(e);for(const{folder:r,item:s}of LOCKED_TOOLS){const d=I(n,l=>l?.url===s.url),y=d.find(l=>!l.some(k=>k.restricted));if(!y&&d.length)continue;const m=y?.at(-1);if(m){if(m.hidden&&delete m.hidden,!y.slice(0,-1).some(o=>o.hidden)||t)continue;const k=y.at(-2);k.items=k.items.filter(o=>o!==m)}const a=c(r),T=I(n,l=>A(l)&&c(l.key)===a).filter(U),S=I(n,l=>A(l)&&!l.key&&c(l.text)===a).filter(U),x=(T[0]||S[0])?.at(-1)||null,L=m||{...s};x?(x.items=Array.isArray(x.items)?x.items:[],x.items.push(L)):n.push(L)}return n}export function insertFoldersBeforeSystem(e,t){const n=(t||[]).filter(Boolean);if(!n.length)return e;const r=["system","documentation"],s=e.findIndex(d=>r.includes(c(d?.key||d?.text)));return s===-1?[...e,...n]:[...e.slice(0,s),...n,...e.slice(s)]}export function canAny(e,t){return t?!e||!e.length?!1:e.includes(t)?!0:["read","create","update","delete"].some(n=>e.includes(`${t}.${n}`)):!0}export function filterByPermission(e,t,n=null){const r=[];for(const s of e){if(s.hidden||s.permission&&!canAny(t,s.permission))continue;const d=typeof s.url=="string"?s.url:"";if(n&&d.startsWith("#/")&&!F(n,d.slice(1)))continue;const y=Array.isArray(s.items)&&s.items.length>0,m=y?filterByPermission(s.items,t,n):[];y&&!m.length&&!d||r.push({...s,items:m})}return r}export function sidebarStateKey(e,t=null){const n=String(e?.text||"").replace(/\s*\(\d+\)\s*$/,"").toLowerCase().replace(/\s+/g,"-"),r=String(e?.url||"").match(/^#\/projects\/([^/]+)/);let s="";if(r)try{s=`project-${decodeURIComponent(r[1])}.`}catch{s=`project-${r[1]}.`}return t?e?.key?`sidebar.expanded.key.${c(e.key)}`:`${t}/${s}${n}`:`sidebar.expanded.${s}${n}`}export function pruneEmptyToolsFolder(e){return(e||[]).filter(t=>A(t)?!(c(t.key)===TOOLS_FOLDER_KEY||!t.key&&t.text===TOOLS_FOLDER_TEXT)||Array.isArray(t.items)&&t.items.length>0:!0)}
|
|
1
|
+
import{isPathAllowed as ot}from"./admin-scope.js";export const TOOLS_FOLDER_TEXT="Tools",MANAGE_PLUGINS_URL="#/plugins",MANAGE_PLUGINS_ITEM={text:"Marketplace",url:MANAGE_PLUGINS_URL,icon:"store",permission:"plugins"};export function stripItemByUrl(e,t){const r=[];for(const n of e||[]){if(!n||n.url===t)continue;const i={...n};Array.isArray(n.items)&&n.items.length&&(i.items=stripItemByUrl(n.items,t)),r.push(i)}return r}export function managePluginsItem(){return{...MANAGE_PLUGINS_ITEM}}export const TOOLS_FOLDER_KEY="tools";const ut=["countUrl","core","permission"],f=e=>String(e??"").toLowerCase();export function slugify(e){return f(e).trim().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")}export function groupKeyFor(e,t){return`${f(e)}.${slugify(t)}`}export const GROUP_ICON="folder";const U=e=>e&&(e.type==="separator"||e.type==="spacer"||e.type==="theme-switcher"),I=e=>e&&!U(e)&&!e.url;function C(e){return(e||[]).filter(Boolean).map(t=>Array.isArray(t.items)?{...t,items:C(t.items)}:{...t})}function ct(e,t,r=[]){for(const n of e||[]){if(!n)continue;if(t(n))return[...r,n];const i=ct(n.items,t,[...r,n]);if(i)return i}return null}function R(e,t,r=[],n=[]){for(const i of e||[])i&&(t(i)&&n.push([...r,i]),R(i.items,t,[...r,i],n));return n}const tt=e=>!e.some(t=>t.hidden||t.restricted);function B(e,t){for(const r of e||[]){if(t(r))return r;const n=B(r?.items,t);if(n)return n}return null}export function findFolder(e,t){if(!t)return null;const r=f(t);return B(e,n=>I(n)&&f(n.key)===r)||B(e,n=>I(n)&&!n.key&&f(n.text)===r)}function et(e,t){const r={...t,...e};for(const n of ut)t[n]!==void 0&&(r[n]=t[n]);return!(Array.isArray(e.items)&&e.items.length)&&Array.isArray(t.items)&&(r.items=t.items),e.text||(r.text=t.text),!e.icon&&t.icon&&(r.icon=t.icon),delete r.ref,delete r.folder,delete r.group,r}function G(e,{persisted:t,orphan:r=!1,node:n=null}){const i=e?.item||{};return{persisted:t,orphan:r,source:i.source||(i.core?"Built in":""),folder:e?.folder||TOOLS_FOLDER_KEY,defaults:r?{text:null,icon:null}:{text:i.text||"",icon:i.icon||""},...r&&n&&{label:n.text||n.url},...(e?.group||e?.item?.group)&&{group:e.group||e.item.group}}}export function placeTools(e,t,{forEditor:r=!1}={}){const n=C(e),i=(t||[]).filter(u=>u&&u.item&&typeof u.item.text=="string"),p=new Map;for(const u of i)u.item.url&&!p.has(u.item.url)&&p.set(u.item.url,u);const h=new Set,y=u=>{const c=[];for(const m of u){const $=m.url?p.get(m.url):null;if($&&!h.has(m.url)){h.add(m.url);const b=et(m,$.item);Array.isArray(m.items)&&m.items.length?b.items=y(m.items):r&&(b.items=[]),r&&(b.$tool=G($,{persisted:!0})),c.push(b);continue}if(m.ref){if(!r)continue;const{ref:b,...k}=m;c.push({...k,items:y(m.items||[]),$tool:G(null,{persisted:!0,orphan:!0,node:m})});continue}Array.isArray(m.items)&&(m.items=y(m.items)),c.push(m)}return c},x=y(n),S=new Set,_=u=>{for(const c of u||[])c.hidden&&c.text&&!c.url&&!(Array.isArray(c.items)&&c.items.length)&&S.add(f(c.text)),_(c.items)};_(x);let a=null;const M=()=>{const u=findFolder(x,TOOLS_FOLDER_KEY);if(u)return u;if(!a){a={text:TOOLS_FOLDER_TEXT,key:TOOLS_FOLDER_KEY,icon:"tool",items:[],synthesised:!0};const c=x.findIndex(m=>["system","documentation"].includes(f(m?.key||m?.text)));x.splice(c===-1?x.length:c,0,a)}return a},l=new Set,w=(u,c)=>{const m=groupKeyFor(u.key||slugify(u.text),c),$=B(x,T=>I(T)&&f(T.key)===m)||(u.items||[]).find(T=>I(T)&&(!T.key||f(T.key)===m)&&f(T.text)===f(c));if($)return $;const b={text:String(c),key:m,icon:GROUP_ICON,items:[],synthesised:!0},k=u.items.findIndex(T=>l.has(T));return u.items.splice(k===-1?u.items.length:k,0,b),b};for(const u of i){const{item:c}=u;if(c.url&&h.has(c.url))continue;c.url&&h.add(c.url);const m=S.has(f(c.text));if(m&&!r)continue;const $=et({},c);r&&($.items=[],$.$tool=G(u,{persisted:!1}),m&&($.hidden=!0));let k=(u.parent?findFolder(x,u.parent)||B(x,P=>!U(P)&&f(P.text)===f(u.parent)):null)||findFolder(x,u.folder||c.folder)||M();k.items=Array.isArray(k.items)?k.items:[];const T=typeof(u.group||c.group)=="string"?(u.group||c.group).trim():"";T&&slugify(T)&&(k=w(k,T),k.items=Array.isArray(k.items)?k.items:[]),k.items.push($),l.add($)}return x}export const LOCKED_TOOLS=[{folder:"overview",item:{text:"Dashboard",url:"#/",icon:"home"}},{folder:"content",item:{text:"Site menus",url:"#/menus",icon:"menu",permission:"menus"}},{folder:"system",item:{text:"Users",url:"#/users",icon:"users",permission:"users"}}];export function isLockedUrl(e){return LOCKED_TOOLS.some(t=>t.item.url===e)}export function ensureLockedTools(e,{leaveInHiddenFolders:t=!1}={}){const r=C(e);for(const{folder:n,item:i}of LOCKED_TOOLS){const p=R(r,l=>l?.url===i.url),h=p.find(l=>!l.some(w=>w.restricted));if(!h&&p.length)continue;const y=h?.at(-1);if(y){if(y.hidden&&delete y.hidden,!h.slice(0,-1).some(u=>u.hidden)||t)continue;const w=h.at(-2);w.items=w.items.filter(u=>u!==y)}const x=f(n),S=R(r,l=>I(l)&&f(l.key)===x).filter(tt),_=R(r,l=>I(l)&&!l.key&&f(l.text)===x).filter(tt),a=(S[0]||_[0])?.at(-1)||null,M=y||{...i};a?(a.items=Array.isArray(a.items)?a.items:[],a.items.push(M)):r.push(M)}return r}export function insertFoldersBeforeSystem(e,t){const r=(t||[]).filter(Boolean);if(!r.length)return e;const n=["system","documentation"],i=e.findIndex(p=>n.includes(f(p?.key||p?.text)));return i===-1?[...e,...r]:[...e.slice(0,i),...r,...e.slice(i)]}export function canAny(e,t){return t?!e||!e.length?!1:e.includes(t)?!0:["read","create","update","delete"].some(r=>e.includes(`${t}.${r}`)):!0}export function isDenied(e,t,r=null){if(e?.permission&&!canAny(t,e.permission))return!0;const n=typeof e?.url=="string"?e.url:"";return!!(r&&n.startsWith("#/")&&!ot(r,n.slice(1)))}export function filterByPermission(e,t,r=null){const n=[];for(const i of e){if(i.hidden||isDenied(i,t,r))continue;const p=typeof i.url=="string"?i.url:"",h=Array.isArray(i.items)&&i.items.length>0,y=h?filterByPermission(i.items,t,r):[];h&&!y.length&&!p||n.push({...i,items:y})}return n}export function sidebarStateKey(e,t=null){const r=String(e?.text||"").replace(/\s*\(\d+\)\s*$/,"").toLowerCase().replace(/\s+/g,"-"),n=String(e?.url||"").match(/^#\/projects\/([^/]+)/);let i="";if(n)try{i=`project-${decodeURIComponent(n[1])}.`}catch{i=`project-${n[1]}.`}return t?e?.key?`sidebar.expanded.key.${f(e.key)}`:`${t}/${i}${r}`:`sidebar.expanded.${i}${r}`}export function pruneEmptyToolsFolder(e){return(e||[]).filter(t=>I(t)?!(f(t.key)===TOOLS_FOLDER_KEY||!t.key&&t.text===TOOLS_FOLDER_TEXT)||Array.isArray(t.items)&&t.items.length>0:!0)}export const WITHHELD_URL="#/~";const rt=e=>(e||[]).filter(t=>t&&t.item&&typeof t.item.text=="string");export function toolsForViewer(e,t,r){return r?K(e,t,r).given:e||[]}function st(e){const t=new Set([TOOLS_FOLDER_KEY,"system","documentation","projects",...LOCKED_TOOLS.map(r=>r.folder)]);for(const r of e)for(const n of[r.parent,r.folder,r.group,r.item.folder,r.item.group])typeof n=="string"&&n.trim()&&t.add(f(n.trim()));return t}function K(e,t,r){const n=rt(e),i=st(n),p=new Map,h=new Map;n.forEach((a,M)=>{a.item.url&&!p.has(a.item.url)&&p.set(a.item.url,M),h.has(f(a.item.text))||h.set(f(a.item.text),M)});const y=new Set(n.filter(a=>!isDenied(a.item,t,r)).map(a=>f(a.item.text))),x=new Map,S=new Map;return{given:n.map((a,M)=>{const{item:l}=a;if(!isDenied(l,t,r))return a;const w=f(l.text),u=i.has(w.trim())||y.has(w)?l.text:`~${h.get(w)??M}`,c=l.url?isLockedUrl(l.url)?l.url:`${WITHHELD_URL}${p.get(l.url)??M}`:void 0;return l.url&&!x.has(l.url)&&x.set(l.url,c),S.has(w)||S.set(w,u),{parent:a.parent??null,folder:a.folder??null,...a.group&&{group:a.group},item:{text:u,...c&&{url:c},...l.permission&&{permission:l.permission},...l.folder&&{folder:l.folder},...l.group&&{group:l.group}}}}),urlFor:x,textFor:S}}export function redactSidebarMenu(e,{permissions:t=[],adminScope:r=null,tools:n=[]}={}){const i=rt(n),{urlFor:p,textFor:h}=r?K(i,t,r):{urlFor:new Map,textFor:new Map},y=new Map;for(const s of i)s.item.url&&!y.has(s.item.url)&&y.set(s.item.url,s.item.permission);const x=new Set(i.map(s=>s.item.url).filter(Boolean)),S=st(i),_=new Set(i.map(s=>f(s.item.text))),a=s=>Array.isArray(s)&&s.length>0,M=new Set(i.map(s=>f(s.parent).trim()).filter(Boolean)),l=(s,o)=>{if(U(s)||typeof s.text!="string")return!1;const A=f(s.text.trim());return(s.key?M.has(A):S.has(A))||w(s,o)},w=(s,o)=>!!(s.hidden&&!s.url&&o&&typeof s.text=="string"&&s.text&&_.has(f(s.text))),u=(s,o)=>w(s,o)&&!S.has(f(s.text.trim()))&&h.get(f(s.text))||s.text,c=s=>p.get(s)||(x.has(s)||isLockedUrl(s)?s:WITHHELD_URL),m=new Set,$=s=>{if(!s.url||!y.has(s.url)||m.has(s.url))return s;m.add(s.url);const o=y.get(s.url);return o===void 0?s:{...s,permission:o}},b=s=>!!s.ref&&!(y.has(s.url)&&!m.has(s.url)),k=()=>({hidden:!0,restricted:!0}),T=(s,o,A=!1)=>{if(isLockedUrl(s.url)&&A&&!isDenied(s,t,r)){const{items:F,ref:v,...O}=s;return{...O,...o,...Array.isArray(F)&&{items:Y(F,!1,!0)}}}const d=[];let g=0;for(const F of a(s.items)?s.items:[]){if(!F||typeof F!="object"||b(F))continue;g++;const v=T($(F),null,A||!!s.hidden);v&&d.push(v)}const L=l(s,!g),j=s.url?c(s.url):null,N=L?u(s,!g):s.text?" ":null;return!o&&(!j||j===WITHHELD_URL)&&!s.key&&!L&&!d.length?null:{...j&&{url:j},...s.key&&{key:s.key},...N&&{text:N},...s.permission&&{permission:s.permission},...s.hidden&&{hidden:!0},...s.restricted&&{restricted:!0},...o,...d.length&&{items:d}}};let P=!1;const H=(s,o={kept:0},A=!1)=>{const d=[];for(const g of s||[]){if(!g||typeof g!="object"||b(g))continue;o.kept++;const L=$(g);if(!U(L)&&isDenied(L,t,r)){P=!0;const v=L.permission&&!canAny(t,L.permission),O=T(L,v?{permission:L.permission}:{},A);O.url===WITHHELD_URL&&!O.key&&!O.items&&(!O.text||O.text===" ")||d.push(O);continue}const j=Array.isArray(g.items)?Y(g.items,!0,A||!!g.hidden):null,N=u(g,!j||!j.kept),F=N===g.text?g:{...g,text:N};d.push(j?{...F,items:j.out}:F)}return d};function Y(s,o=!1,A=!1){const d={kept:0},g=H(s,d,A),L=d.kept&&!g.length?[k()]:g;return o?{out:L,kept:d.kept}:L}const D=H(e),V=s=>(s||[]).some(o=>o&&typeof o=="object"&&(!o.hidden||o.restricted));if(V(e)&&!V(D)&&D.push(k()),!P)return D;const E="$redact";let W=0;const z=new Map,X=s=>s.map(o=>{if(!o||typeof o!="object"||U(o))return o;const A=Array.isArray(o.items)?X(o.items):o.items,d=A===o.items?{...o}:{...o,items:A};return!o.url&&typeof o.text=="string"&&o.text.trim()&&(d[E]=++W,z.set(W,d)),d}),q=X(D),J=new Set,Q=s=>{for(const o of s||[])o?.[E]&&J.add(o[E]),Q(o?.items)},nt=r?K(i,t,r).given:i;Q(arrangeSidebar(q,nt,{permissions:t,adminScope:r}));const it=canAny(t,"projects");for(const[s,o]of z){const A=f(o.text.trim());J.has(s)||(o.key?M.has(A):S.has(A))||w(o,!a(o.items))||it&&f(o.key)==="projects"||(o.text=" ")}const Z=s=>s.map(o=>{if(!o||typeof o!="object"||!(E in o||Array.isArray(o.items)))return o;const{[E]:A,...d}=o;return Array.isArray(d.items)?{...d,items:Z(d.items)}:d});return Z(q)}export function arrangeSidebar(e,t,{permissions:r=[],adminScope:n=null,beforeFilter:i=null}={}){let p=stripItemByUrl(e,MANAGE_PLUGINS_URL);return p=placeTools(p,(t||[]).filter(h=>(h?.item??h)?.url!==MANAGE_PLUGINS_URL)),p=ensureLockedTools(p),p=insertFoldersBeforeSystem(p,[managePluginsItem()]),i&&i(p),p=filterByPermission(p,r,n),pruneEmptyToolsFolder(p)}export function confinedTree(e){return(e||[]).flatMap(t=>{if(!t||U(t))return[];if(!Array.isArray(t.items)||!t.items.length)return I(t)?[]:[t];const r=confinedTree(t.items);return I(t)&&r.length===1?r:I(t)&&!r.length?[]:[{...t,items:r}]})}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import{syncThemeAwareLogos as qe}from"./theme-aware-logo.js";import{api as
|
|
1
|
+
import{syncThemeAwareLogos as qe}from"./theme-aware-logo.js";import{api as b,getUser as w,isAuthenticated as Ce}from"../api.js";import{createRequestQueue as Ae}from"./background-requests.js";import{requestSidebarCounts as Fe}from"./sidebar-counts.js";import{beginSidebarCounts as Le,publishSidebarCount as Ee}from"./sidebar-count-cache.js";import{isConfined as je,isPathAllowed as Oe}from"./admin-scope.js";import{cleanNotify as Me,noticeFromCount as Te}from"./sidebar-notify.js";import{colourToCss as ne,applyFloat as Be,applyHighlight as He,itemHighlightAttrs as Ne}from"/public/js/menu-decor.mjs?v=20261014-menu-entrance";import{arrangeSidebar as Re,sidebarStateKey as se,canAny as W,confinedTree as Ie}from"./sidebar-grouping.js";import{arrangeButtonMarkup as Pe,canArrange as _e,startArrange as Ue}from"./sidebar-arrange.js";import{collapseButtonMarkup as ze,wireSidebarSize as De,COLLAPSED_WIDTH as We}from"./sidebar-size.js";import{FREQUENT_MAX as oe,addFrequent as Ke,frequentFolder as Ve,moveFrequent as ie,readFrequent as Z,readFrequentHidden as Xe,removeFrequent as Ze,saveFrequent as Je,syncFrequent as Ye,writeFrequent as Ge,writeFrequentHidden as ae}from"./sidebar-frequent.js";import{hotkeyFor as re,hotkeyTitle as Qe,setHotkeyTree as et}from"./hotkeys-ui.js";import{hotkeyLabel as tt}from"./hotkeys.js";function m(e){return String(e??"").replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""")}const nt=[{text:"Dashboard",url:"#/",icon:"home"},{text:"Site menus",url:"#/menus",icon:"menu",permission:"menus"}];async function st(e){if(!W(e,"projects"))return[];let n=[];try{n=await b.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 c=o.enabled===!1;return{text:o.name||o.slug,key:`project.${o.slug}`,icon:o.icon||"folder",items:i,...c&&{colour:"neutral",badge:{text:"off"}}}})}function ot(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?R.set(e,n.details):R.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(),R.delete(u);continue}i||(i=document.createElement("span"),t.querySelector(".sidebar-text")?.after(i));const c=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),R.set(u,{title:c,items:r})}}const R=new Map;function it(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"],at={"#/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=Me(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 y=["xs","sm","md","lg","xl","flex"].includes(e.size)?e.size:"md";return`<div class="sidebar-spacer sidebar-spacer--${m(y)}" 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):"",c=Array.isArray(e.items)&&e.items.length>0,d=e.colour?ne(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}"`:"",k=e.url?Qe(e.url,e.text||"",{inFrequent:o}):"",q=k?` title="${m(k)}"`:"";let A="";if(e.badge&&e.badge.text!=null&&e.badge.text!==""){const y=e.badge.variant?ne(e.badge.variant):"";A=`<span class="dm-menu-badge"${y?` style="background:${m(y)};color:var(--dm-text-inverse,#fff)"`:""}>${m(String(e.badge.text))}</span>`}if(e.frequent&&e.empty){const y=se(e,t),F=S.get(y)!==!1;return`<details data-state-key="${m(y)}"${F?" 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(
|
|
5
|
-
<summary${v}${
|
|
6
|
-
<div class="sidebar-children">${
|
|
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)}))}
|
|
4
|
+
</details>`}if(c){const y=se(e,t),F=S.get(y)!==!1,L=e.items.map(O=>ue(O,n,y,{inFrequent:!!e.frequent})).join(""),P=e.frequent?' data-frequent title="Your Frequent Tools - right-click any Tool to add or remove it"':"";return`<details data-state-key="${m(y)}"${F?" open":""}${P}>
|
|
5
|
+
<summary${v}${q}>${r} <span class="sidebar-text">${u}</span>${A}</summary>
|
|
6
|
+
<div class="sidebar-children">${L}</div>
|
|
7
|
+
</details>`}return`<a href="${i}" class="sidebar-link" data-url="${i}"${v}${f}${q}>${r} <span class="sidebar-text">${u}</span>${it(e,n)}${A}</a>`}async function rt(e=[],n=[],t=null){const o=g=>g.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(g=>g.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=(g,C)=>W(n,g)&&!r.has(u[g])?C():Promise.resolve(0),[c,d,l,f,h,v,k,q,A,y,F,L,P,O]=await Promise.all([i("pages",()=>o(b.pages.list())),i("media",()=>o(b.media.list())),i("menus",()=>o(b.menus.list())),i("context-menus",()=>o(b.contextMenus.list())),i("theme",()=>b.theme.get().then(g=>(g?.overrides||[]).length).catch(()=>0)),i("collections",()=>o(b.collections.list())),i("forms",()=>o(b.forms.list())),i("views",()=>o(b.views.list())),i("actions",()=>o(b.actions.list())),i("blocks",()=>o(b.blocks.list())),i("components",()=>o(b.components.list())),i("users",()=>o(b.users.list())),i("plugins",()=>o(b.plugins.list())),i("notifications",()=>b.system?.notifications?.unreadCount?.().then(g=>g?.count??0).catch(()=>0)??Promise.resolve(0))]),D=await pe(s),V={"#/pages":c,"#/media":d,"#/menus":l,"#/context-menus":f,"#/theme":h,"#/collections":v,"#/forms":k,"#/views":q,"#/actions":A,"#/blocks":y,"#/components":F,"#/users":L,"#/plugins":P,"#/system/notifications":O},_={};for(const[g,C]of Object.entries(V)){if(r.has(g))continue;const[T,X]=at[g]??["item","items"],U=K(C);U&&(_[g]={...U,label:`${U.count} ${U.count===1?T:X}`})}return{..._,...D}}let j=[];const lt="dm:sidebar-count",ct=6e4,dt=Ae(4);function fe(e=[],n=null){const t=[],o=s=>{if(s&&!(n&&typeof s.url=="string"&&s.url.startsWith("#/")&&!Oe(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 dt(()=>!Ce()||w()?.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 J(e,n,t){Ee(n,t),t?.notify&&Te(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)}}Y.set(n,t),ce(e)}}const Y=new Map;async function pe(e){const n=await Fe(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 G(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=Y.get(r);JSON.stringify(i??null)!==JSON.stringify(u)&&J(e,r,u)}}catch{}}function ut(e){e.dataset.liveCounts||(e.dataset.liveCounts="1",window.addEventListener(lt,n=>{const t=n.detail||{};if(t.url)if(t.count!==void 0){const o=j.find(s=>s.url===t.url);J(e,t.url,K(t,{fallbackLabel:o?.countLabel||o?.text||""}))}else G(e,t.url)}),setInterval(()=>{!document.hidden&&document.body.contains(e)&&G(e)},ct),document.addEventListener("visibilitychange",()=>{document.hidden||G(e)}),ft(e))}function he(e,n,t){const o=(u,i,c)=>{const d=document.createElement(u);return i&&(d.className=i),c!=null&&(d.textContent=String(c)),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 c=o("li",i.tone==="danger"?"is-danger":null);c.appendChild(o("span","dm-badge-pop-text",i.text)),i.meta&&c.appendChild(o("span","dm-badge-pop-meta",i.meta)),u.appendChild(c)}e.appendChild(u)}else t.empty&&e.appendChild(o("p","dm-badge-pop-empty",t.empty))}function ft(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)})},c=d=>{const l=d.closest?.("a.sidebar-link, summary");return l&&e.contains(l)?l:null};e.addEventListener("mouseover",d=>{if(o()){const f=c(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=c(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 mt(e=[],n=null){if(n?.title||n?.enabled===!1)return n;if(!W(e,"settings"))return{title:"Domma CMS"};try{const t=await b.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;I=je(t);const r=I?Promise.resolve():Ye(b,w()).catch(()=>{}),u=Promise.resolve().then(()=>H.get("/api/sidebar/registered-items")).catch(()=>[]),i=st(n);let c,d=null,l=null,f=null,h=null,v=null;try{const a=await b.get("/sidebar/menu");c=Array.isArray(a?.items)?a.items:null,d=a?.variant||null,l=a?.position||null,f=a?.style||null,h=a?.float||null,v=a?.highlight||null}catch{c=null}(!c||!c.some(a=>a&&(!a.hidden||a.restricted)))&&(console.warn("[admin-sidebar] No admin-sidebar menu found; using fallback tree"),c=nt.slice());let k=[];try{k=await u||[]}catch{}const q=await i;if(c=Re(c,k,{permissions:n,adminScope:t,beforeFilter:a=>{q.length&&ot(a,q)}}),await r,I)c=Ie(c);else{const a=Ve(c,Z(w()),{hidden:Xe(w())});a&&(c=[a,...c])}et(c);const A=k.filter(a=>W(n,a?.item?.permission));j=fe(A,t);const y=Le({user:w(),permissions:n,adminScope:t,registered:A,tree:c,actions:{linkItems:ye,folderItems:ve},fetcher:()=>rt(A,n,t)}),F=y.counts,L=await mt(n,o),P=d?` dm-admin-sidebar--${m(d)}`:"";function O(a,x="px"){if(a==null)return a;const p=String(a).trim();return/^\d+(\.\d+)?$/.test(p)?`${p}${x}`:p}let D="";if(f){const a=[];f.fontFamily&&a.push(`font-family: ${f.fontFamily}, sans-serif`),f.fontSize&&a.push(`font-size: ${O(f.fontSize)}`),f.fontWeight&&a.push(`font-weight: ${f.fontWeight}`),f.letterSpacing&&a.push(`letter-spacing: ${O(f.letterSpacing,"em")}`);const x=[];if(a.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 { ${a.join("; ")} }`),f.iconSize){const p=O(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&&(D=`<style data-admin-sidebar-style>${x.join(" ")}</style>`)}const V=_e(n)&&!I?Pe():"",_=String(L.logo||"").trim(),g=/^(?:\/(?!\/)|https?:\/\/)/i.test(_)?_:"",C=String(L.logoDark||"").trim(),T=/^(?:\/(?!\/)|https?:\/\/)/i.test(C)?C:"",X=g||T?`<img src="${m(g||T)}"${g?` data-logo-light="${m(g)}"`:""}${T?` data-logo-dark="${m(T)}"`:""} 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?"":`${X}<span class="dm-admin-sidebar-title">${m(L.title)}</span>`}${V}${ze()}</div>`,$e=c.some(a=>a&&a.type==="spacer"&&a.size==="flex")?" dm-admin-sidebar--has-flex-spacer":"",we=`${D}<nav class="dm-admin-sidebar${P}${$e}">${xe}${c.map(a=>ue(a,F)).join("")}</nav>`,ee=document.createRange();ee.selectNodeContents(s);const ke=ee.createContextualFragment(we);s.replaceChildren(ke),qe(s),Domma.icons.scan(s),s.querySelector(".dm-admin-sidebar-arrange")?.addEventListener("click",()=>Ue(s));for(const a of j)Y.set(a.url,F[a.url]??null);ce(s),ut(s),y.refresh.then(a=>{if(!(!y.isActive()||!s.isConnected))for(const[x,p]of Object.entries(a))J(s,x,p)}),s.removeAttribute("data-menu-hover"),s.removeAttribute("data-menu-active"),s.style.removeProperty("--dm-menu-highlight"),He(s,{highlight:v});const B=document.querySelector(".dashboard-wrapper");["position","top","bottom","left","right","zIndex","maxHeight","transform"].forEach(a=>{s.style[a]=""}),s.classList.remove("dm-menu-floating"),B&&(B.style.paddingLeft="",B.style.paddingRight=""),s.__dmGutter=()=>{if(l!=="floating"||!B)return;const a=h&&h.anchor||"TL",x=Number.isFinite(Number(h?.offsetX))?Number(h.offsetX):16,p=s.classList.contains("is-collapsed")?We:parseInt(s.style.width,10)||s.getBoundingClientRect().width||260,N=Math.round(p+x*2)+"px";a==="R"||a==="TR"||a==="BR"?B.style.paddingRight=N:B.style.paddingLeft=N},l==="floating"&&Be(s,{position:"floating",float:h||{}}),s.querySelectorAll("details").forEach(a=>{a.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"})}})}),De(s),ht(s),s.dataset.routeWired||(s.dataset.routeWired="1",M.subscribe("router:afterChange",()=>s.__dmSetActive?.()));function te(){const a=/^#\/(dashboards|my-dashboard)\b/.test(location.hash)?"#/":location.hash||"#/";$(s).find(".sidebar-link").removeClass("active"),$(s).find(`.sidebar-link[data-url="${a}"]`).addClass("active")}te(),s.__dmSetActive=te}let I=!1;function ge(){try{document.dispatchEvent(new CustomEvent("dm:sidebar-rebuild"))}catch{}}function Q(e){return`${location.origin}${location.pathname}${e}`}function z(e,n){const t=w(),o=e(Z(t));if(!Ge(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){Je(b,e).catch(()=>E.toast("Frequent is saved in this browser only - the server could not keep it.",{type:"warning"}))}function pt(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=Z(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:tt(re(n))},action:()=>{location.hash=n}},{label:"Open in a new tab",icon:"external-link",action:()=>window.open(Q(n),"_blank","noopener")},...I?[]:[{type:"divider"},s?{label:"Remove from Frequent",icon:"star",action:()=>z(c=>Ze(c,n),`${t} removed from Frequent.`)}:{label:i?`Frequent is full (${oe})`:"Add to Frequent",icon:"star",disabled:i,action:()=>z(c=>Ke(c,n),`${t} added to Frequent.`)}],...r&&!I?[{label:"Move up",icon:"arrow-up",disabled:u<=0,action:()=>z(c=>ie(c,n,-1))},{label:"Move down",icon:"arrow-down",disabled:u<0||u>=o.length-1,action:()=>z(c=>ie(c,n,1))}]:[],{type:"divider"},{label:"Copy link",icon:"link",action:async()=>{try{await navigator.clipboard.writeText(Q(n)),E.toast("Link copied.",{type:"success",duration:2e3})}catch{E.toast(Q(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||(c=>{o&&(o.open=c)}),u=e.querySelector(".sidebar-text")?.textContent.trim()||"Folder",i=t.setAll||(c=>n.querySelectorAll("details").forEach(d=>{d.open!==c&&(d.open=c)}));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:()=>pt(!0)}]:o?.hasAttribute("data-frequent")?[{type:"divider"},{label:"Clear Frequent",icon:"x",action:()=>z(()=>[],"Frequent cleared.")}]:[]]}function ht(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)}))}
|
|
@@ -27,7 +27,7 @@ import{api as j,apiRequest as Lt}from"../api.js";import{launcherHref as Ct}from"
|
|
|
27
27
|
${Qe}
|
|
28
28
|
</div>`),b(u.id)}}b(null),n._disposeMenuHelp?.(),n.innerHTML=l.join("")||'<p class="mex-note">No items yet - Add item, or right-click an item for more.</p>',n._disposeMenuHelp=it(n),I.scan(n)}function v(n,p={},...i){const c=document.createElement(n);Object.assign(c,p);for(const l of i)l!=null&&c.append(l);return c}function x(n,p,i){const c=v("label",{className:"form-field"},v("span",{className:"form-label",textContent:n}),p),l=Wt[n];if(l){const b=v("span");b.dataset.help=l+(i?" "+i:""),b.dataset.helpTitle=n,c.querySelector(".form-label").append(" ",b)}return i&&c.append(v("small",{className:"form-hint",textContent:i,style:"display:block;font-size:.78em;opacity:.7;margin-top:.25rem;line-height:1.35"})),c}function cn(n,p){const i=[["","- Everyone -"],["public","Public - anyone, incl. logged-out"],...(p||[]).map(l=>[l.name,`${l.label||l.name} and above`]),...(p||[]).filter(l=>l.level!==0).map(l=>[`=${l.name}`,`${l.label||l.name} only`]),["private","Private - super-admin only"]];n&&!i.some(([l])=>l===n)&&i.push([n,`${n} (custom)`]);const c=K(i,n||"");return c.name="visibility",c}function K(n,p){const i=v("select",{className:"form-select"});return n.forEach(([c,l])=>i.add(new Option(l,c))),i.value=p??"",i}function Me(n,p){const i=typeof p=="string"&&p.startsWith("#"),c=K([["","- none -"],["primary","primary"],["success","success"],["danger","danger"],["warning","warning"],["info","info"],["neutral","neutral"],["__custom__","Custom\u2026"]],i?"__custom__":p||""),l=v("input",{type:"color",className:"form-input me-colour-hex",value:i?p:"#000000"});l.style.display=i?"":"none",c.addEventListener("change",()=>{l.style.display=c.value==="__custom__"?"":"none"});const b=x(n,c);return b.append(l),b._read=()=>c.value==="__custom__"?l.value:c.value,b}function dn(n,p){const i=v("input",{className:"form-input me-icon",name:"icon",value:p||""}),c=v("span",{className:"me-icon-preview"});p&&c.setAttribute("data-icon",p);const l=v("button",{type:"button",className:"btn btn-sm btn-ghost",textContent:"Browse\u2026"}),b=_=>{_?c.setAttribute("data-icon",_):c.removeAttribute("data-icon"),Domma.icons.scan(c.parentNode||c)};return l.addEventListener("click",()=>_t(_=>{i.value=_,b(_)})),i.addEventListener("input",()=>b(i.value.trim())),x(n,v("div",{className:"me-icon-field"},i,l,c))}function ee(...n){return v("div",{className:"me-field-grid"},...n)}async function un(n,p,i,c,l,{cards:b=!0}={}){const _=n.text||n.tool?.label||"",u=(r,...y)=>{const C=v("section",{className:"me-item-section"},v("h4",{className:"me-item-section-title",textContent:r}),v("div",{className:"me-item-section-body"},...y));return C.setAttribute("aria-label",r),C},Y=x("Label",v("input",{className:"form-input",name:"text",value:n.text||""}),"The text shown for this item."),A=v("input",{className:"form-input",name:"url",value:n.url||""}),X=x("URL",A,n.tool||n.locked?"A Tool's address is its identity, so it cannot be changed here.":"Where it links. Must start with /, #, https://, or mailto: . Leave blank for a parent that only groups sub-items.");(n.tool||n.locked)&&(A.readOnly=!0);const N=/^#launcher-([a-z0-9][a-z0-9-]{0,39})$/,h=K([["","- not a launcher -"]],""),J=x("Launcher",h,"Opens one of your launchers instead of going to an address - choosing one fills in the URL.");J.style.display="none";const re=()=>{const r=N.exec(A.value.trim());h.value=r&&[...h.options].some(y=>y.value===r[1])?r[1]:""};h.addEventListener("change",()=>{h.value?A.value=Ct(h.value):N.test(A.value.trim())&&(A.value="")}),A.addEventListener("input",re),b&&!n.tool&&!n.locked&&Lt("/launchers/items",{method:"GET"}).then(r=>{const y=Array.isArray(r?.launchers)?r.launchers:[];if(y.length){for(const C of y)h.add(new Option(`${C.name}${C.enabled?"":" (switched off)"}`,C.id));re(),J.style.display=""}}).catch(()=>{});const ce=dn("Icon",n.icon||""),Q=cn(n.visibility||"",c),we=x("Visibility",Q,n.locked?"Always in the sidebar for everyone who may use it, so it cannot be restricted here.":'Who can see this item. "Role and above" shows it to that role and anyone more senior; "Role only" shows it to holders of that role alone (and the super-admin). Blank = everyone.');n.locked&&(Q.disabled=!0);const te=K([["","- no permission gate -"],...(p||[]).map(r=>[r.key,r.label||r.key])],n.permission||"");te.name="permission";const de=x("Permission",te,n.tool||n.locked?"A Tool is guarded by its own permission, which always applies.":"Hide unless the viewer holds this specific permission. Independent of Visibility - both must pass.");(n.tool||n.locked)&&(te.disabled=!0);const Ze=x("Badge text",v("input",{className:"form-input",name:"badgeText",value:n.badge?.text||""})),O=K([["","- none -"],...(i||[]).map(r=>[r.slug,r.title||r.slug])],n.badge?.countFrom||"");O.name="badgeCount";const ze=x("Badge count from",O,"Show a live count of this collection\u2019s entries as the badge."),$e=Me("Badge colour",n.badge?.variant||""),f=K([["link","Link"],["pill","Pill"]],n.pill?"pill":"link");f.name="renderAs";const F=x("Render as",f,"Pill draws the item as a rounded chip. Pill styling applies to top-level navbar items."),ue=x("Pill style",K([["filled","Filled"],["outline","Outline"]],n.pill?.style||"filled"));ue.querySelector("select").name="pillStyle";const Te=Me("Pill colour",n.pill?.variant||""),Se=v("div",{className:"me-pill-wrap"},ee(ue,Te));Se.style.display=n.pill?"":"none",f.addEventListener("change",()=>{Se.style.display=f.value==="pill"?"":"none"});const z=Me("Text colour",n.colour||""),T=K([["","- use the menu default -"],...pt.map(r=>[r,ft[r]||r])],n.highlight?.hover||"");T.name="hlHover";const He=x("Hover effect",T,"Overrides the menu-wide hover effect for this item only."),B=K([["","- use the menu default -"],...ht.map(r=>[r,vt[r]||r])],n.highlight?.active||"");B.name="hlActive";const me=x("When selected",B,"How this item is marked when it points at the page being viewed."),ne=Me("Highlight colour",n.highlight?.accent||""),oe=v("input",{className:"form-input",name:"class",value:n.class||"",placeholder:"nav-cta push-right",autocomplete:"off",spellcheck:!1}),_e=x("CSS classes",oe,"Your own class names, separated by spaces, added to this item's <li> - target the link with .your-class > a. Style them in Custom CSS."),xe=v("small",{className:"text-danger",style:"display:none;margin-top:.25rem"});_e.append(xe);const Ue=v("textarea",{className:"form-input",name:"description",rows:2,maxLength:Nt,value:n.description||"",placeholder:"Answers every new lead in under a minute."}),We=x("Description",Ue,"One short line under the label, shown when the menu's dropdowns are Cards."),q=Me("Tile colour",n.tile||""),pe=v("input",{type:"checkbox",name:"chip",checked:!!n.chip,style:"width:auto;margin:0"}),he=v("label",{className:"form-field",style:"display:flex;gap:.5rem;align-items:center;font-weight:400"},pe,v("span",{textContent:"Show as a small chip in the card's footer strip"})),Ae=v("span");Ae.dataset.helpTitle="Show as a small chip",Ae.dataset.help="Place this sub-item in the compact chip strip at the bottom of its parent Cards dropdown instead of the main entries. Its label and destination remain the same. The parent card can provide a Chip strip label. This applies to sub-items in Cards dropdowns, rather than top-level navbar links.",he.append(Ae);const fe=n.parentId==null,$=n.panel||{},U=(r,y,C,be=80)=>v("input",{className:"form-input",name:r,value:y||"",placeholder:C,maxLength:be}),et=x("Card heading",U("panelHeading",$.heading,"The crew - six agents, one job each"),"Small capitals over the entries."),tt=x("Link text",U("panelLinkText",$.link?.text,"Meet the crew",60)),nt=x("Link URL",U("panelLinkUrl",$.link?.url,"/crew",500)),Ie=K([["","Automatic"],["1","1"],["2","2"],["3","3"],["4","4"]],$.columns?String($.columns):"");Ie.name="panelColumns";const Ke=x("Columns",Ie),qe=x("Chip strip label",U("panelChipsLabel",$.chipsLabel,"Add to your crew",60),'Words before the chips - tick "Show as a small chip" on the sub-items that belong there.'),t=K([["","- no side box -"],["dark","Dark"],["light","Light"],["accent","Theme colour"]],$.feature?$.feature.tone||"dark":"");t.name="featureTone";const ve=x("Side box",t,"A box down the right of the card - a call to action or a short list."),Ge=x("Box small heading",U("featureEyebrow",$.feature?.eyebrow,"Free - 20 minutes",60)),Ee=x("Box title",U("featureTitle",$.feature?.title,"See it live")),Ne=x("Box points",v("textarea",{className:"form-input",name:"featurePoints",rows:3,value:($.feature?.points||[]).join(`
|
|
29
29
|
`),placeholder:"One per line, up to six"})),Oe=x("Button text",U("featureBtnText",$.feature?.button?.text,"Book a demo",60)),ot=x("Button URL",U("featureBtnUrl",$.feature?.button?.url,"/book",500)),ae=v("div",{className:"me-feature-fields"},ee(Ge,Ee),Ne,ee(Oe,ot));ae.style.display=t.value?"":"none",t.addEventListener("change",()=>{ae.style.display=t.value?"":"none"});const Re=b?[u("Card link",v("small",{className:"form-hint",textContent:"Used with card dropdowns. Choose Cards on the Behaviour tab."}),We,ee(q,fe?null:he)),...fe?[u("Dropdown panel",et,ee(tt,nt),ee(Ke,qe)),u("Side box",ve,ae)]:[]]:[],Le=v("button",{className:"btn btn-primary",textContent:"Apply",title:"Apply to the item (Ctrl+Enter) - Save the menu to keep it"}),se=v("div",{className:"me-item-form"},u("Link",Y,X,J,ce),u("Appearance",F,Se,z),u("Hover & selection",ee(He,me),ne),...Re,u("Badge",ee(Ze,$e),ze),u("Access",ee(we,de)),u("Custom styling",_e),v("div",{className:"me-item-actions"},v("small",{className:"form-hint",textContent:"Apply updates this item. Save the menu to keep it."}),Le)),P=E.slideover({title:_?`Edit ${Fe(_)}`:"Edit menu item",size:"lg",position:"right"});P.element.appendChild(se);const Be=()=>JSON.stringify([...se.querySelectorAll("input, select, textarea")].filter(r=>r!==h).map(r=>r.type==="checkbox"?r.checked:r.value)),Pe=Be();let ge=!1,le=!1;const Ve=it(se,{position:"bottom"});Kt(P,Ve);const De=P.close.bind(P);P.close=async r=>{if(!ge&&r!==!0&&Be()!==Pe){if(le)return;le=!0;const y=await E.confirm("Discard the changes to this item?");if(le=!1,!y)return}return ge=!0,De()},se.addEventListener("keydown",r=>{(r.ctrlKey||r.metaKey)&&r.key==="Enter"&&(r.preventDefault(),Le.click())}),P.open();const Ye=P.element.closest(".dm-slideover")||P.element.querySelector(".dm-slideover")||P.element;Ye.style.setProperty("width",on+"px","important"),Ye.style.setProperty("max-width","95vw","important"),Domma.icons.scan(se);const w=r=>se.querySelector(`[name="${r}"]`)?.value||"";Le.addEventListener("click",()=>{const r=gt(w("class"));if(r.length){xe.textContent=r.join("; "),xe.style.display="block",oe.focus();return}n.class=Tt(w("class")),n.text=w("text"),n.icon=w("icon"),n.locked||(n.visibility=w("visibility")),!n.tool&&!n.locked?(n.url=w("url"),n.permission=w("permission")):n.touched=!0;const y=w("badgeText"),C=w("badgeCount"),be=$e._read();if(n.badge=y||C?{...y&&{text:y},...C&&{countFrom:C},...be&&{variant:be}}:null,w("renderAs")==="pill"){const G=Te._read();n.pill={style:w("pillStyle")||"filled",...G&&{variant:G}}}else n.pill=null;n.colour=z._read();const Ce=w("hlHover"),ye=w("hlActive"),D=ne._read();if(n.highlight=Ce||ye||D?{...Ce&&{hover:Ce},...ye&&{active:ye},...D&&{accent:D}}:null,b&&(n.description=w("description").trim(),n.tile=q._read(),n.chip=!fe&&pe.checked,fe)){const G=w("featureTone");n.panel=It({heading:w("panelHeading"),link:{text:w("panelLinkText"),url:w("panelLinkUrl")},columns:w("panelColumns"),chipsLabel:w("panelChipsLabel"),feature:G?{tone:G,eyebrow:w("featureEyebrow"),title:w("featureTitle"),points:w("featurePoints").split(`
|
|
30
|
-
`),button:{text:w("featureBtnText"),url:w("featureBtnUrl")}}:null})}ge=!0,P.close(!0),l()})}let V=null,wt=!1;function mn(){wt||!window.R?.use||(wt=!0,R.use((n,p,i)=>{const c=p?.path||"";return!(sn.test(c)&&(n?.path||"")!==c)||!V?.dirty()?i():E.confirm(`You have unsaved changes to the menu "${Fe(V.name())}". Leave anyway? They are kept as a draft for your next visit.`).then(b=>{b?i():history.replaceState(null,"",`#${c}`)})}),M.subscribe("router:afterChange",({to:n}={})=>{if(V&&(n?.path||"")!==V.path){const p=V;V=null,p.dispose()}}))}function St(n,p){const i=n.querySelector(".dm-plugin-banner-name"),c=i?.querySelector(".dm-plugin-banner-sep");if(!(!i||!c)){for(;c.nextSibling;)c.nextSibling.remove();i.appendChild(document.createTextNode(p))}}export const menuEditorView={templateUrl:"/admin/js/templates/menu-editor.html",async onMount(n){if(mn(),V){const e=V;V=null,e.dispose()}const p=[],i=e=>(p.push(e),e);let c=!1;const l=n.get(0).querySelector(".mex")||n.get(0),b=()=>!c&&l.isConnected,_=location.hash.replace(/^#/,""),u=location.hash.match(/^#\/menus\/edit\/([^?#]+)/),Y=u?decodeURIComponent(u[1]):null,A=!Y,X=`menu-editor.draft.${Y||"new"}`,N=E.loader(n.get(0),{type:"dots"});let h,J,re,ce,Q,we,te;try{if(A)h={slug:"",name:"",description:"",items:[]};else try{h=await j.menus.get(Y)}catch(e){E.toast(`Failed to load menu: ${e.message||e}`,{type:"error"}),location.hash="#/menus";return}[J,re,ce,Q,we,te]=await Promise.all([j.projects.list().catch(()=>[]),H.get("/api/auth/permissions-registry").catch(()=>({resources:[]})),j.collections.list().catch(()=>[]),j.get("/collections/roles/entries?limit=100").catch(()=>null),j.menuLocations.registry().catch(()=>[]),j.pages.list().catch(()=>[])])}finally{N.destroy()}if(!l.isConnected)return;const Ze=(Array.isArray(Q)?Q:Q?.entries||[]).map(e=>({name:e.data?.name,label:e.data?.label,level:e.data?.level??99})).filter(e=>e.name).sort((e,o)=>o.level-e.level),O=!A&&Y===an;let ze=[];if(O&&(ze=await H.get("/api/sidebar/registered-items").catch(()=>(E.toast("Could not load the Tools - they are not shown, and saving keeps their places as they are.",{type:"warning",duration:8e3}),[])),!l.isConnected))return;const $e=e=>bt(O?Bt(Rt(e||[],ze,{forEditor:!0}),{leaveInHiddenFolders:!0}):e);let f=$e(h.items);const F=M.observable(!1),ue=M.observable(!1),Te=M.observable(""),Se=M.observable(0);let z="";const T=l.querySelector("#me-items-list");i(()=>T._disposeMenuHelp?.());function He(){rn(T,f,O),Se.value=f.filter(e=>!ke(e)).length}const B=()=>{He(),D()},me=()=>O?kt(f):new Set,ne=e=>f.find(o=>o.id===e);function oe(e){requestAnimationFrame(()=>T.querySelector(`.menu-tree-row[data-id="${CSS.escape(e)}"]`)?.focus())}function _e(e){const o=k=>f.find(s=>!s.type&&!s.url&&!s.tool&&(s.key||"").toLowerCase()===k)||f.find(s=>!s.type&&!s.url&&!s.tool&&!s.key&&(s.text||"").toLowerCase()===k);let a=o(String(e.tool.folder||"").toLowerCase())||o(Mt);const d=String(e.tool.group||"").trim();if(a&&d){const k=Dt(a.key||jt(a.text),d),s=m=>m!==e&&!m.type&&!m.url&&!m.tool;let g=f.find(m=>s(m)&&(m.key||"").toLowerCase()===k)||f.find(m=>s(m)&&m.parentId===a.id&&(!m.key||m.key.toLowerCase()===k)&&(m.text||"").toLowerCase()===d.toLowerCase());g||([g]=bt([{text:d,key:k,icon:Ft,synthesised:!0}],a.id),f.push(g)),a=g}e.parentId=a?a.id:null,f.splice(f.indexOf(e),1),f.push(e),Object.assign(e,{text:e.tool.defaults.text,icon:e.tool.defaults.icon,visibility:"",hidden:!1,badge:null,pill:null,colour:"",highlight:null,touched:!1}),e.tool={...e.tool,persisted:!1}}const xe=e=>!me().has(e.id)&&!(e.tool&&!e.tool.orphan);async function Ue(e){const o=ne(e);if(!o||!xe(o))return;const a=m=>{let Z=m;for(;Z;){if(Z.id===e)return!0;Z=f.find(W=>W.id===Z.parentId)}return!1},d=f.filter(m=>m.id!==e&&a(m));if(d.length&&!await E.confirm(`Remove "${Fe(o.text||o.type||"this item")}" and the ${d.length} item${d.length===1?"":"s"} beneath it?`))return;const k=me(),s=d.filter(m=>m.tool),g=d.filter(m=>!m.tool&&k.has(m.id));f=f.filter(m=>!a(m)||s.includes(m)||g.includes(m));for(const m of g)m.parentId=o.parentId??null;for(const m of s)m.tool.orphan?m.parentId=o.parentId??null:_e(m);B()}function We(e){const o=ne(e);!o||ke(o)||me().has(e)||(o.hidden=!o.hidden,o.touched=!0,B())}function q(e){const o=ne(e);!o||ke(o)||(o.locked=O&&me().has(o.id),un(o,re.resources||[],ce,Ze,()=>{B(),oe(e)},{cards:!O}))}function pe(e){const o={id:Xe(),parentId:null,...e==="separator"||e==="theme-switcher"?{type:e}:e==="spacer"?{type:e,size:"md"}:{text:"",url:"/",icon:"",visibility:"",permission:"",hidden:!1,bundled:!1}};f.push(o),B(),ke(o)?oe(o.id):q(o.id)}const he=e=>o=>{e(o)&&(B(),oe(o))},Ae=he(e=>yt(f,e,-1)),fe=he(e=>yt(f,e,1)),$=he(e=>Xt(f,e)),U=he(e=>en(f,e));function et(e){const o=ne(e);if(!o)return[];const a=ke(o),d=me().has(e),k=tn(f,e),s=k.findIndex(W=>W.id===e),g=o.tool,m=g&&(g.persisted||o.touched),Z=W=>()=>{const je=Jt(f,e,W,Xe());B(),je&&!ke(je)?q(je.id):je&&oe(je.id)};return[{header:a?{separator:"Separator",spacer:"Spacer","theme-switcher":"Theme switcher"}[o.type]:o.text||g?.label||"(untitled)"},...a?[]:[{label:"Edit\u2026",icon:"edit",action:()=>q(e)}],{type:"divider"},{label:"Add item below",icon:"plus",action:Z("item")},{label:"Add sub-item",icon:"corner-down-right",disabled:a,action:()=>{const W=Gt(f,e,Xe());B(),W&&q(W.id)}},{label:"Add separator below",icon:"minus",action:Z("separator")},{label:"Add spacer below",icon:"move",action:Z("spacer")},...O?[]:[{label:"Add theme switcher below",icon:"palette",action:Z("theme-switcher")}],{type:"divider"},{label:"Move up",icon:"arrow-up",shortcut:"Alt+\u2191",disabled:s<=0,action:()=>Ae(e)},{label:"Move down",icon:"arrow-down",shortcut:"Alt+\u2193",disabled:s<0||s>=k.length-1,action:()=>fe(e)},{label:"Indent",icon:"chevron-right",shortcut:"Alt+\u2192",disabled:s<=0||ke(k[s-1]),action:()=>$(e)},{label:"Outdent",icon:"chevron-left",shortcut:"Alt+\u2190",disabled:o.parentId==null,action:()=>U(e)},{type:"divider"},...a?[]:[{label:o.hidden?"Show":"Hide",icon:o.hidden?"eye":"eye-off",disabled:d,action:()=>We(e)}],{label:"Duplicate",icon:"copy",disabled:!!g,action:()=>{const W=Yt(f,e,Xe);B(),W&&oe(W.id)}},...g&&!g.orphan&&m?[{label:"Back to its default place",icon:"rotate-ccw",action:()=>{_e(o),B()}}]:[],{label:d?"Remove - always in the sidebar":g&&!g.orphan?"Remove - a Tool is hidden, not removed":"Remove\u2026",icon:"trash",danger:!0,disabled:!xe(o),action:()=>Ue(e)}]}const tt=E.contextMenu(T,{cursor:"glyph",match:".menu-tree-row",inherit:!1,density:"compact",items:e=>et(e.dataset.id)});i(()=>tt?.destroy?.());const nt=Ot(T,()=>f,B,{items:".menu-tree-row",handle:".menu-tree-grip"});i(()=>nt?.destroy());const Ie=e=>{const o=e.target.closest(".menu-tree-row");if(!o)return;const a=o.dataset.id;if(e.target.closest(".mex-kebab")){rt(e.target.closest(".mex-kebab"));return}if(e.target.closest(".me-hidden")){We(a);return}if(e.target.closest(".me-edit")){q(a);return}e.target.closest("select, .menu-tree-grip, button")||q(a)},Ke=e=>{const o=e.target.closest(".menu-tree-row");if(!o||e.target!==o){o&&e.key==="F10"&&e.shiftKey&&(e.preventDefault(),rt(o));return}const a=o.dataset.id;if(e.key==="F10"&&e.shiftKey)e.preventDefault(),rt(o);else if(e.key==="Enter")e.preventDefault(),q(a);else if(e.key==="Delete")e.preventDefault(),Ue(a);else if(e.altKey&&e.key==="ArrowUp")e.preventDefault(),Ae(a);else if(e.altKey&&e.key==="ArrowDown")e.preventDefault(),fe(a);else if(e.altKey&&e.key==="ArrowRight")e.preventDefault(),$(a);else if(e.altKey&&e.key==="ArrowLeft")e.preventDefault(),U(a);else if(e.key==="ArrowDown"||e.key==="ArrowUp"){const d=[...T.querySelectorAll(".menu-tree-row")],k=d.indexOf(o)+(e.key==="ArrowDown"?1:-1);d[k]&&(e.preventDefault(),d[k].focus())}},qe=e=>{if(!e.target.matches(".me-spacer-size"))return;const o=ne(e.target.closest(".menu-tree-row")?.dataset.id);o&&(o.size=e.target.value,D())};T.addEventListener("click",Ie),T.addEventListener("keydown",Ke),T.addEventListener("change",qe),i(()=>{T.removeEventListener("click",Ie),T.removeEventListener("keydown",Ke),T.removeEventListener("change",qe)});const t=e=>n.find(e),ve=t("#me-fontFamily").get(0),Ge=Ut(ve,{label:"Font family"});i(()=>Ge.destroy());const Ee=t("#me-float-accent"),Ne=t("#me-float-accent-hex"),Oe=()=>{Ne.get(0).style.display=Ee.val()==="__custom__"?"":"none"},ot=()=>Ee.val()==="__custom__"?Ne.val():Ee.val(),ae=t("#me-highlight-accent"),Re=t("#me-highlight-accent-hex"),Le=()=>{Re.get(0).style.display=ae.val()==="__custom__"?"":"none"},se=()=>ae.val()==="__custom__"?Re.val():ae.val(),P=()=>{const e=!!(t("#me-entrance-enabled").get(0)||{}).checked;t(".dm-entrance-field").each(function(){this.style.display=e?"":"none"});const o=t("#me-position").val()==="floating";t(".dm-float-field").each(function(){this.style.display=o?"":"none"}),o&&Oe();const a=t("#me-orientation").val()==="vertical";t(".dm-vertical-field").each(function(){this.style.display=a?"":"none"}),t(".dm-dock-rail-field").each(function(){this.style.display=a&&!o?"":"none"}),t(".dm-dock-bar-field").each(function(){this.style.display=!a&&!o?"":"none"});const d=!!(t("#me-dock-collapsible").get(0)||{}).checked,k=!!(t("#me-dock-autohide").get(0)||{}).checked;t(".dm-dock-collapsed-field").each(function(){this.style.display=d&&!k?"":"none"});const s=!!(t("#me-float-collapsible").get(0)||{}).checked;t(".dm-float-collapsed-field").each(function(){this.style.display=o&&s?"":"none"});const g=!a&&!O;t(".dm-look-field").each(function(){this.style.display=g?"":"none"});const m=g&&t("#me-look-dropdown").val()==="cards";t(".dm-look-cards-field").each(function(){this.style.display=m?"":"none"})},Be=(e,o,a,d)=>{const k=t(e).get(0);k&&(k.innerHTML="",k.add(new Option(d,"")),o.forEach(s=>k.add(new Option(a[s]||s,s))))};Be("#me-highlight-hover",pt,ft,"- theme default -"),Be("#me-highlight-active",ht,vt,"- theme default -");{const e=t("#me-entrance-animation").get(0);e&&(e.innerHTML="",st.forEach(o=>e.add(new Option(Ht[o]||o,o))))}const Pe=t("#me-bind-slot"),ge=t("#me-bind-projects"),le=t("#me-bind-pages");Pe.get(0).innerHTML='<option value="">- not bound -</option>'+(we||[]).map(e=>`<option value="${L(e.slot)}">${L(e.label||e.slot)} (${L(e.slot)})</option>`).join(""),ge.get(0).innerHTML=J.map(e=>`<option value="${L(e.slug)}">${L(e.name||e.slug)}</option>`).join(""),t("#me-bind-page-pick").get(0).innerHTML='<option value="">- pick a page -</option>'+te.map(e=>{const o=e.urlPath||e.url||"";return o?`<option value="${L(o)}">${L(e.title||o)} - ${L(o)}</option>`:""}).join("");const Ve=()=>Vt({slot:Pe.val(),projects:Array.from(ge.get(0).selectedOptions).map(e=>e.value),pagesText:le.val()});function De(){const e=Ve(),o=t("#me-bind-summary");if(!e){o.html('<span class="text-muted">Not bound - this menu renders only where it is mapped or placed by a shortcode.</span>');return}const a=[];e.projects.length&&a.push(`pages in ${e.projects.map(s=>`<code>${L(s)}</code>`).join(", ")}`),e.pages.length&&a.push(`pages matching ${e.pages.map(s=>`<code>${L(s)}</code>`).join(", ")}`);const d=e.pages.filter(s=>!/^\/[^\s?#*]*(\/\*)?$|^\/\*$/.test(s)),k=d.length?`<div class="text-danger" style="margin-top:.4rem">Not valid page patterns: ${d.map(s=>`<code>${L(s)}</code>`).join(", ")}</div>`:"";o.html(a.length?`Takes over the <code>${L(e.slot)}</code> slot on ${a.join(" and ")}.${k}`:`<span class="text-warning">Slot <code>${L(e.slot)}</code> selected but no project or page chosen - the binding will never match.</span>`)}const{getProjectFromHash:Ye}=await import("../lib/project-context.js");if(!b())return;const w=A?Ye():null;t("#me-project").get(0).innerHTML='<option value="">- none -</option>'+J.map(e=>`<option value="${L(e.slug)}">${L(e.name||e.slug)}</option>`).join("");function r(e){f=$e(e.items),t("#me-variant").val(e.variant||""),t("#me-position").val(e.position||"");const o=t("#me-appearOnHover").get(0);o&&(o.checked=e.appearOnHover===!0),t("#me-float-anchor").val(e.float?.anchor||"TL"),t("#me-float-offsetX").val(e.float?.offsetX??""),t("#me-float-offsetY").val(e.float?.offsetY??""),t("#me-float-width").val(e.float?.width??""),t("#me-float-radius").val(e.float?.radius??""),t("#me-float-shadow").val(e.float?.shadow||""),t("#me-float-opacity").val(e.float?.opacity??""),t("#me-float-title").val(e.float?.title||"");for(const[s,g]of[["#me-float-collapsible",e.float?.collapsible],["#me-float-collapsed",e.float?.collapsed],["#me-float-movable",e.float?.movable],["#me-float-resizable",e.float?.resizable]]){const m=t(s).get(0);m&&(m.checked=g===!0)}const a=e.float?.accent||"";Ee.val(a.startsWith("#")?"__custom__":a),a.startsWith("#")&&Ne.val(a),Oe(),t("#me-orientation").val(e.orientation||""),t("#me-align").val(e.align||""),t("#me-mobile-hamburger").get(0).checked=e.mobile?.hamburgerOnly===!0,t("#me-mobile-brand").get(0).checked=e.mobile?.hideBrand===!0,t("#me-look-bar").val(e.look?.bar||""),t("#me-look-brand").val(e.look?.brand||""),t("#me-look-strip").val(e.look?.strip||""),t("#me-look-icons").val(e.look?.icons||""),t("#me-look-dropdown").val(e.look?.dropdown||""),t("#me-look-tiles").val(e.look?.tiles||""),t("#me-look-morph").get(0).checked=e.look?.morph===!0,t("#me-look-shrink").get(0).checked=e.look?.shrink===!0,t("#me-side").val(e.side||"left"),t("#me-dock-width").val(e.dock?.width??"");for(const s of["collapsible","collapsed","autohide","hideOnScroll"]){const g=t(`#me-dock-${s}`).get(0);g&&(g.checked=e.dock?.[s]===!0)}t("#me-class").val(e.class||""),t("#me-highlight-hover").val(e.highlight?.hover||""),t("#me-highlight-active").val(e.highlight?.active||"");const d=e.highlight?.accent||"";ae.val(d.startsWith("#")?"__custom__":d),d.startsWith("#")&&Re.val(d),Le();{const s=t("#me-entrance-enabled").get(0);s&&(s.checked=e.entrance?.enabled===!0)}t("#me-entrance-animation").val(st.includes(e.entrance?.animation)?e.entrance.animation:st[0]),t("#me-entrance-stagger").val(e.entrance?.stagger??""),t("#me-entrance-duration").val(e.entrance?.duration??"");{const s=e.style?.fontFamily||"";if(ve.querySelector("option[data-custom]")?.remove(),s&&![...ve.options].some(g=>g.value===s)){const g=new Option(`${s} (custom)`,s);g.dataset.custom="1",ve.add(g,1)}ve.value=s,Ge.refresh()}t("#me-fontSize").val(e.style?.fontSize||""),t("#me-fontWeight").val(e.style?.fontWeight||""),t("#me-letterSpacing").val(e.style?.letterSpacing||""),t("#me-iconSize").val(e.style?.iconSize||""),Pe.val(e.binding?.slot||"");const k=new Set(e.binding?.projects||[]);Array.from(ge.get(0).options).forEach(s=>{s.selected=k.has(s.value)}),le.val((e.binding?.pages||[]).join(`
|
|
30
|
+
`),button:{text:w("featureBtnText"),url:w("featureBtnUrl")}}:null})}ge=!0,P.close(!0),l()})}let V=null,wt=!1;function mn(){wt||!window.R?.use||(wt=!0,R.use((n,p,i)=>{const c=p?.path||"";return!(sn.test(c)&&(n?.path||"")!==c)||!V?.dirty()?i():E.confirm(`You have unsaved changes to the menu "${Fe(V.name())}". Leave anyway? They are kept as a draft for your next visit.`).then(b=>{b?i():history.replaceState(null,"",`#${c}`)})}),M.subscribe("router:afterChange",({to:n}={})=>{if(V&&(n?.path||"")!==V.path){const p=V;V=null,p.dispose()}}))}function St(n,p){const i=n.querySelector(".dm-plugin-banner-name"),c=i?.querySelector(".dm-plugin-banner-sep");if(!(!i||!c)){for(;c.nextSibling;)c.nextSibling.remove();i.appendChild(document.createTextNode(p))}}export const menuEditorView={templateUrl:"/admin/js/templates/menu-editor.html",async onMount(n){if(mn(),V){const e=V;V=null,e.dispose()}const p=[],i=e=>(p.push(e),e);let c=!1;const l=n.get(0).querySelector(".mex")||n.get(0),b=()=>!c&&l.isConnected,_=location.hash.replace(/^#/,""),u=location.hash.match(/^#\/menus\/edit\/([^?#]+)/),Y=u?decodeURIComponent(u[1]):null,A=!Y,X=`menu-editor.draft.${Y||"new"}`,N=E.loader(n.get(0),{type:"dots"});let h,J,re,ce,Q,we,te;try{if(A)h={slug:"",name:"",description:"",items:[]};else try{h=await j.menus.get(Y)}catch(e){E.toast(`Failed to load menu: ${e.message||e}`,{type:"error"}),location.hash="#/menus";return}[J,re,ce,Q,we,te]=await Promise.all([j.projects.list().catch(()=>[]),H.get("/api/auth/permissions-registry").catch(()=>({resources:[]})),j.collections.list().catch(()=>[]),j.get("/collections/roles/entries?limit=100").catch(()=>null),j.menuLocations.registry().catch(()=>[]),j.pages.list().catch(()=>[])])}finally{N.destroy()}if(!l.isConnected)return;const Ze=(Array.isArray(Q)?Q:Q?.entries||[]).map(e=>({name:e.data?.name,label:e.data?.label,level:e.data?.level??99})).filter(e=>e.name).sort((e,o)=>o.level-e.level),O=!A&&Y===an;let ze=[];if(O&&(ze=await H.get("/api/sidebar/registered-items?for=editor").catch(()=>(E.toast("Could not load the Tools - they are not shown, and saving keeps their places as they are.",{type:"warning",duration:8e3}),[])),!l.isConnected))return;const $e=e=>bt(O?Bt(Rt(e||[],ze,{forEditor:!0}),{leaveInHiddenFolders:!0}):e);let f=$e(h.items);const F=M.observable(!1),ue=M.observable(!1),Te=M.observable(""),Se=M.observable(0);let z="";const T=l.querySelector("#me-items-list");i(()=>T._disposeMenuHelp?.());function He(){rn(T,f,O),Se.value=f.filter(e=>!ke(e)).length}const B=()=>{He(),D()},me=()=>O?kt(f):new Set,ne=e=>f.find(o=>o.id===e);function oe(e){requestAnimationFrame(()=>T.querySelector(`.menu-tree-row[data-id="${CSS.escape(e)}"]`)?.focus())}function _e(e){const o=k=>f.find(s=>!s.type&&!s.url&&!s.tool&&(s.key||"").toLowerCase()===k)||f.find(s=>!s.type&&!s.url&&!s.tool&&!s.key&&(s.text||"").toLowerCase()===k);let a=o(String(e.tool.folder||"").toLowerCase())||o(Mt);const d=String(e.tool.group||"").trim();if(a&&d){const k=Dt(a.key||jt(a.text),d),s=m=>m!==e&&!m.type&&!m.url&&!m.tool;let g=f.find(m=>s(m)&&(m.key||"").toLowerCase()===k)||f.find(m=>s(m)&&m.parentId===a.id&&(!m.key||m.key.toLowerCase()===k)&&(m.text||"").toLowerCase()===d.toLowerCase());g||([g]=bt([{text:d,key:k,icon:Ft,synthesised:!0}],a.id),f.push(g)),a=g}e.parentId=a?a.id:null,f.splice(f.indexOf(e),1),f.push(e),Object.assign(e,{text:e.tool.defaults.text,icon:e.tool.defaults.icon,visibility:"",hidden:!1,badge:null,pill:null,colour:"",highlight:null,touched:!1}),e.tool={...e.tool,persisted:!1}}const xe=e=>!me().has(e.id)&&!(e.tool&&!e.tool.orphan);async function Ue(e){const o=ne(e);if(!o||!xe(o))return;const a=m=>{let Z=m;for(;Z;){if(Z.id===e)return!0;Z=f.find(W=>W.id===Z.parentId)}return!1},d=f.filter(m=>m.id!==e&&a(m));if(d.length&&!await E.confirm(`Remove "${Fe(o.text||o.type||"this item")}" and the ${d.length} item${d.length===1?"":"s"} beneath it?`))return;const k=me(),s=d.filter(m=>m.tool),g=d.filter(m=>!m.tool&&k.has(m.id));f=f.filter(m=>!a(m)||s.includes(m)||g.includes(m));for(const m of g)m.parentId=o.parentId??null;for(const m of s)m.tool.orphan?m.parentId=o.parentId??null:_e(m);B()}function We(e){const o=ne(e);!o||ke(o)||me().has(e)||(o.hidden=!o.hidden,o.touched=!0,B())}function q(e){const o=ne(e);!o||ke(o)||(o.locked=O&&me().has(o.id),un(o,re.resources||[],ce,Ze,()=>{B(),oe(e)},{cards:!O}))}function pe(e){const o={id:Xe(),parentId:null,...e==="separator"||e==="theme-switcher"?{type:e}:e==="spacer"?{type:e,size:"md"}:{text:"",url:"/",icon:"",visibility:"",permission:"",hidden:!1,bundled:!1}};f.push(o),B(),ke(o)?oe(o.id):q(o.id)}const he=e=>o=>{e(o)&&(B(),oe(o))},Ae=he(e=>yt(f,e,-1)),fe=he(e=>yt(f,e,1)),$=he(e=>Xt(f,e)),U=he(e=>en(f,e));function et(e){const o=ne(e);if(!o)return[];const a=ke(o),d=me().has(e),k=tn(f,e),s=k.findIndex(W=>W.id===e),g=o.tool,m=g&&(g.persisted||o.touched),Z=W=>()=>{const je=Jt(f,e,W,Xe());B(),je&&!ke(je)?q(je.id):je&&oe(je.id)};return[{header:a?{separator:"Separator",spacer:"Spacer","theme-switcher":"Theme switcher"}[o.type]:o.text||g?.label||"(untitled)"},...a?[]:[{label:"Edit\u2026",icon:"edit",action:()=>q(e)}],{type:"divider"},{label:"Add item below",icon:"plus",action:Z("item")},{label:"Add sub-item",icon:"corner-down-right",disabled:a,action:()=>{const W=Gt(f,e,Xe());B(),W&&q(W.id)}},{label:"Add separator below",icon:"minus",action:Z("separator")},{label:"Add spacer below",icon:"move",action:Z("spacer")},...O?[]:[{label:"Add theme switcher below",icon:"palette",action:Z("theme-switcher")}],{type:"divider"},{label:"Move up",icon:"arrow-up",shortcut:"Alt+\u2191",disabled:s<=0,action:()=>Ae(e)},{label:"Move down",icon:"arrow-down",shortcut:"Alt+\u2193",disabled:s<0||s>=k.length-1,action:()=>fe(e)},{label:"Indent",icon:"chevron-right",shortcut:"Alt+\u2192",disabled:s<=0||ke(k[s-1]),action:()=>$(e)},{label:"Outdent",icon:"chevron-left",shortcut:"Alt+\u2190",disabled:o.parentId==null,action:()=>U(e)},{type:"divider"},...a?[]:[{label:o.hidden?"Show":"Hide",icon:o.hidden?"eye":"eye-off",disabled:d,action:()=>We(e)}],{label:"Duplicate",icon:"copy",disabled:!!g,action:()=>{const W=Yt(f,e,Xe);B(),W&&oe(W.id)}},...g&&!g.orphan&&m?[{label:"Back to its default place",icon:"rotate-ccw",action:()=>{_e(o),B()}}]:[],{label:d?"Remove - always in the sidebar":g&&!g.orphan?"Remove - a Tool is hidden, not removed":"Remove\u2026",icon:"trash",danger:!0,disabled:!xe(o),action:()=>Ue(e)}]}const tt=E.contextMenu(T,{cursor:"glyph",match:".menu-tree-row",inherit:!1,density:"compact",items:e=>et(e.dataset.id)});i(()=>tt?.destroy?.());const nt=Ot(T,()=>f,B,{items:".menu-tree-row",handle:".menu-tree-grip"});i(()=>nt?.destroy());const Ie=e=>{const o=e.target.closest(".menu-tree-row");if(!o)return;const a=o.dataset.id;if(e.target.closest(".mex-kebab")){rt(e.target.closest(".mex-kebab"));return}if(e.target.closest(".me-hidden")){We(a);return}if(e.target.closest(".me-edit")){q(a);return}e.target.closest("select, .menu-tree-grip, button")||q(a)},Ke=e=>{const o=e.target.closest(".menu-tree-row");if(!o||e.target!==o){o&&e.key==="F10"&&e.shiftKey&&(e.preventDefault(),rt(o));return}const a=o.dataset.id;if(e.key==="F10"&&e.shiftKey)e.preventDefault(),rt(o);else if(e.key==="Enter")e.preventDefault(),q(a);else if(e.key==="Delete")e.preventDefault(),Ue(a);else if(e.altKey&&e.key==="ArrowUp")e.preventDefault(),Ae(a);else if(e.altKey&&e.key==="ArrowDown")e.preventDefault(),fe(a);else if(e.altKey&&e.key==="ArrowRight")e.preventDefault(),$(a);else if(e.altKey&&e.key==="ArrowLeft")e.preventDefault(),U(a);else if(e.key==="ArrowDown"||e.key==="ArrowUp"){const d=[...T.querySelectorAll(".menu-tree-row")],k=d.indexOf(o)+(e.key==="ArrowDown"?1:-1);d[k]&&(e.preventDefault(),d[k].focus())}},qe=e=>{if(!e.target.matches(".me-spacer-size"))return;const o=ne(e.target.closest(".menu-tree-row")?.dataset.id);o&&(o.size=e.target.value,D())};T.addEventListener("click",Ie),T.addEventListener("keydown",Ke),T.addEventListener("change",qe),i(()=>{T.removeEventListener("click",Ie),T.removeEventListener("keydown",Ke),T.removeEventListener("change",qe)});const t=e=>n.find(e),ve=t("#me-fontFamily").get(0),Ge=Ut(ve,{label:"Font family"});i(()=>Ge.destroy());const Ee=t("#me-float-accent"),Ne=t("#me-float-accent-hex"),Oe=()=>{Ne.get(0).style.display=Ee.val()==="__custom__"?"":"none"},ot=()=>Ee.val()==="__custom__"?Ne.val():Ee.val(),ae=t("#me-highlight-accent"),Re=t("#me-highlight-accent-hex"),Le=()=>{Re.get(0).style.display=ae.val()==="__custom__"?"":"none"},se=()=>ae.val()==="__custom__"?Re.val():ae.val(),P=()=>{const e=!!(t("#me-entrance-enabled").get(0)||{}).checked;t(".dm-entrance-field").each(function(){this.style.display=e?"":"none"});const o=t("#me-position").val()==="floating";t(".dm-float-field").each(function(){this.style.display=o?"":"none"}),o&&Oe();const a=t("#me-orientation").val()==="vertical";t(".dm-vertical-field").each(function(){this.style.display=a?"":"none"}),t(".dm-dock-rail-field").each(function(){this.style.display=a&&!o?"":"none"}),t(".dm-dock-bar-field").each(function(){this.style.display=!a&&!o?"":"none"});const d=!!(t("#me-dock-collapsible").get(0)||{}).checked,k=!!(t("#me-dock-autohide").get(0)||{}).checked;t(".dm-dock-collapsed-field").each(function(){this.style.display=d&&!k?"":"none"});const s=!!(t("#me-float-collapsible").get(0)||{}).checked;t(".dm-float-collapsed-field").each(function(){this.style.display=o&&s?"":"none"});const g=!a&&!O;t(".dm-look-field").each(function(){this.style.display=g?"":"none"});const m=g&&t("#me-look-dropdown").val()==="cards";t(".dm-look-cards-field").each(function(){this.style.display=m?"":"none"})},Be=(e,o,a,d)=>{const k=t(e).get(0);k&&(k.innerHTML="",k.add(new Option(d,"")),o.forEach(s=>k.add(new Option(a[s]||s,s))))};Be("#me-highlight-hover",pt,ft,"- theme default -"),Be("#me-highlight-active",ht,vt,"- theme default -");{const e=t("#me-entrance-animation").get(0);e&&(e.innerHTML="",st.forEach(o=>e.add(new Option(Ht[o]||o,o))))}const Pe=t("#me-bind-slot"),ge=t("#me-bind-projects"),le=t("#me-bind-pages");Pe.get(0).innerHTML='<option value="">- not bound -</option>'+(we||[]).map(e=>`<option value="${L(e.slot)}">${L(e.label||e.slot)} (${L(e.slot)})</option>`).join(""),ge.get(0).innerHTML=J.map(e=>`<option value="${L(e.slug)}">${L(e.name||e.slug)}</option>`).join(""),t("#me-bind-page-pick").get(0).innerHTML='<option value="">- pick a page -</option>'+te.map(e=>{const o=e.urlPath||e.url||"";return o?`<option value="${L(o)}">${L(e.title||o)} - ${L(o)}</option>`:""}).join("");const Ve=()=>Vt({slot:Pe.val(),projects:Array.from(ge.get(0).selectedOptions).map(e=>e.value),pagesText:le.val()});function De(){const e=Ve(),o=t("#me-bind-summary");if(!e){o.html('<span class="text-muted">Not bound - this menu renders only where it is mapped or placed by a shortcode.</span>');return}const a=[];e.projects.length&&a.push(`pages in ${e.projects.map(s=>`<code>${L(s)}</code>`).join(", ")}`),e.pages.length&&a.push(`pages matching ${e.pages.map(s=>`<code>${L(s)}</code>`).join(", ")}`);const d=e.pages.filter(s=>!/^\/[^\s?#*]*(\/\*)?$|^\/\*$/.test(s)),k=d.length?`<div class="text-danger" style="margin-top:.4rem">Not valid page patterns: ${d.map(s=>`<code>${L(s)}</code>`).join(", ")}</div>`:"";o.html(a.length?`Takes over the <code>${L(e.slot)}</code> slot on ${a.join(" and ")}.${k}`:`<span class="text-warning">Slot <code>${L(e.slot)}</code> selected but no project or page chosen - the binding will never match.</span>`)}const{getProjectFromHash:Ye}=await import("../lib/project-context.js");if(!b())return;const w=A?Ye():null;t("#me-project").get(0).innerHTML='<option value="">- none -</option>'+J.map(e=>`<option value="${L(e.slug)}">${L(e.name||e.slug)}</option>`).join("");function r(e){f=$e(e.items),t("#me-variant").val(e.variant||""),t("#me-position").val(e.position||"");const o=t("#me-appearOnHover").get(0);o&&(o.checked=e.appearOnHover===!0),t("#me-float-anchor").val(e.float?.anchor||"TL"),t("#me-float-offsetX").val(e.float?.offsetX??""),t("#me-float-offsetY").val(e.float?.offsetY??""),t("#me-float-width").val(e.float?.width??""),t("#me-float-radius").val(e.float?.radius??""),t("#me-float-shadow").val(e.float?.shadow||""),t("#me-float-opacity").val(e.float?.opacity??""),t("#me-float-title").val(e.float?.title||"");for(const[s,g]of[["#me-float-collapsible",e.float?.collapsible],["#me-float-collapsed",e.float?.collapsed],["#me-float-movable",e.float?.movable],["#me-float-resizable",e.float?.resizable]]){const m=t(s).get(0);m&&(m.checked=g===!0)}const a=e.float?.accent||"";Ee.val(a.startsWith("#")?"__custom__":a),a.startsWith("#")&&Ne.val(a),Oe(),t("#me-orientation").val(e.orientation||""),t("#me-align").val(e.align||""),t("#me-mobile-hamburger").get(0).checked=e.mobile?.hamburgerOnly===!0,t("#me-mobile-brand").get(0).checked=e.mobile?.hideBrand===!0,t("#me-look-bar").val(e.look?.bar||""),t("#me-look-brand").val(e.look?.brand||""),t("#me-look-strip").val(e.look?.strip||""),t("#me-look-icons").val(e.look?.icons||""),t("#me-look-dropdown").val(e.look?.dropdown||""),t("#me-look-tiles").val(e.look?.tiles||""),t("#me-look-morph").get(0).checked=e.look?.morph===!0,t("#me-look-shrink").get(0).checked=e.look?.shrink===!0,t("#me-side").val(e.side||"left"),t("#me-dock-width").val(e.dock?.width??"");for(const s of["collapsible","collapsed","autohide","hideOnScroll"]){const g=t(`#me-dock-${s}`).get(0);g&&(g.checked=e.dock?.[s]===!0)}t("#me-class").val(e.class||""),t("#me-highlight-hover").val(e.highlight?.hover||""),t("#me-highlight-active").val(e.highlight?.active||"");const d=e.highlight?.accent||"";ae.val(d.startsWith("#")?"__custom__":d),d.startsWith("#")&&Re.val(d),Le();{const s=t("#me-entrance-enabled").get(0);s&&(s.checked=e.entrance?.enabled===!0)}t("#me-entrance-animation").val(st.includes(e.entrance?.animation)?e.entrance.animation:st[0]),t("#me-entrance-stagger").val(e.entrance?.stagger??""),t("#me-entrance-duration").val(e.entrance?.duration??"");{const s=e.style?.fontFamily||"";if(ve.querySelector("option[data-custom]")?.remove(),s&&![...ve.options].some(g=>g.value===s)){const g=new Option(`${s} (custom)`,s);g.dataset.custom="1",ve.add(g,1)}ve.value=s,Ge.refresh()}t("#me-fontSize").val(e.style?.fontSize||""),t("#me-fontWeight").val(e.style?.fontWeight||""),t("#me-letterSpacing").val(e.style?.letterSpacing||""),t("#me-iconSize").val(e.style?.iconSize||""),Pe.val(e.binding?.slot||"");const k=new Set(e.binding?.projects||[]);Array.from(ge.get(0).options).forEach(s=>{s.selected=k.has(s.value)}),le.val((e.binding?.pages||[]).join(`
|
|
31
31
|
`)),t("#me-slug").val(e.slug||""),t("#me-name").val(e.name||""),t("#me-description").val(e.description||""),t("#me-project").val(e.meta?.project||w||""),P(),De(),He()}const y=e=>!!(t(e).get(0)||{}).checked;function C(){const e={variant:t("#me-variant").val(),position:t("#me-position").val(),appearOnHover:y("#me-appearOnHover"),floatAnchor:t("#me-float-anchor").val(),floatOffsetX:t("#me-float-offsetX").val(),floatOffsetY:t("#me-float-offsetY").val(),floatWidth:t("#me-float-width").val(),floatRadius:t("#me-float-radius").val(),floatShadow:t("#me-float-shadow").val(),floatAccent:ot(),floatOpacity:t("#me-float-opacity").val(),floatTitle:t("#me-float-title").val(),floatCollapsible:y("#me-float-collapsible"),floatCollapsed:y("#me-float-collapsed"),floatMovable:y("#me-float-movable"),floatResizable:y("#me-float-resizable"),highlightHover:t("#me-highlight-hover").val(),highlightActive:t("#me-highlight-active").val(),highlightAccent:se(),class:t("#me-class").val(),entranceEnabled:y("#me-entrance-enabled"),entranceAnimation:t("#me-entrance-animation").val(),entranceStagger:t("#me-entrance-stagger").val(),entranceDuration:t("#me-entrance-duration").val(),orientation:t("#me-orientation").val(),align:t("#me-align").val(),side:t("#me-side").val(),fontFamily:t("#me-fontFamily").val(),fontSize:t("#me-fontSize").val(),fontWeight:t("#me-fontWeight").val(),letterSpacing:t("#me-letterSpacing").val(),iconSize:t("#me-iconSize").val(),dockWidth:t("#me-dock-width").val(),dockCollapsible:y("#me-dock-collapsible"),dockCollapsed:y("#me-dock-collapsed"),dockAutohide:y("#me-dock-autohide"),mobileHamburgerOnly:y("#me-mobile-hamburger"),mobileHideBrand:y("#me-mobile-brand"),lookBar:t("#me-look-bar").val(),lookDropdown:t("#me-look-dropdown").val(),lookBrand:t("#me-look-brand").val(),lookStrip:t("#me-look-strip").val(),lookIcons:t("#me-look-icons").val(),lookTiles:t("#me-look-tiles").val(),lookMorph:y("#me-look-morph"),lookShrink:y("#me-look-shrink"),dockHideOnScroll:y("#me-dock-hideOnScroll")},o={slug:t("#me-slug").val(),name:t("#me-name").val(),description:t("#me-description").val(),project:t("#me-project").val()};return Qt(e,o,Ve(),zt(f),h.meta||{})}const be=e=>[...Zt(e),...gt(e.class).map(o=>`CSS classes: ${o} (Behaviour tab).`)];let Ce=!1,ye=null;function D(){if(!z)return;const e=C();ye=e,F.value=Je(e)!==z,Te.value=F.peek()||Ce?be(e).join(" "):""}const G=e=>{e.target.closest("#me-items-list")||(e.target.matches("#me-position, #me-orientation, #me-look-dropdown, #me-float-collapsible, #me-dock-collapsible, #me-dock-autohide, #me-entrance-enabled")&&P(),e.target.matches("#me-float-accent")&&Oe(),e.target.matches("#me-highlight-accent")&&Le(),e.target.closest("#me-binding")&&De(),D())};l.addEventListener("input",G),l.addEventListener("change",G),i(()=>{l.removeEventListener("input",G),l.removeEventListener("change",G)}),t("#me-bind-page-add").on("click",()=>{const e=t("#me-bind-page-pick").val();if(!e)return;const o=le.val().split(`
|
|
32
32
|
`).map(a=>a.trim()).filter(Boolean);o.includes(e)||o.push(e),le.val(o.join(`
|
|
33
33
|
`)),De(),D()}),r(h),z=Je(C()),D();const ct=()=>{try{S.remove?S.remove(X):S.set(X,null)}catch{}};async function at(){if(ue.peek())return;const e=C(),o=be(e);if(o.length){Ce=!0,D(),E.toast(o.join(" "),{type:"warning",duration:7e3});return}ue.value=!0;let a=null;try{if(A)await j.menus.create(e);else if(e.slug!==h.slug){await j.menus.create(e);const d=await j.menuLocations.get();let k=!1;for(const[s,g]of Object.entries(d))g===h.slug&&(d[s]=e.slug,k=!0);k&&await j.menuLocations.save(d),await j.menus.remove(h.slug)}else{const d=await xt(e);if(!d)return;a=d.revision}if(z=Je(e),F.value=!1,ct(),qt("#/menus"),E.toast("Saved.",{type:"success"}),A||e.slug!==h.slug)location.hash="#/menus/edit/"+encodeURIComponent(e.slug);else{h={...h,...e,revision:a};for(const d of f)d.tool&&d.touched&&(d.tool={...d.tool,persisted:!0});He(),z=Je(C()),D(),St(n.get(0),e.name||e.slug)}if(O)try{document.dispatchEvent(new CustomEvent("dm:sidebar-rebuild"))}catch{}}catch(d){E.toast(`Save failed: ${d.message||d}`,{type:"error"})}finally{ue.value=!1}}async function xt(e){try{return await j.menus.update(h.slug,{...e,revision:h.revision})}catch(a){if(a.status!==409)throw a}if(await E.confirm(`The menu "${Fe(h.name||h.slug)}" was changed somewhere else after you opened it - in another tab, by someone else, or on the server. Saving now would undo those changes.<br><br><strong>OK</strong> saves yours over them. <strong>Cancel</strong> loads the latest version, and offers your changes back as a draft.`))return j.menus.update(h.slug,e);try{S.set(X,{menu:e,base:z,at:new Date().toISOString()})}catch{}return F.value=!1,location.reload(),null}async function At(){!F.peek()||!await E.confirm("Throw away the changes you have not saved?")||(r(h),D())}E.tabs(t("#me-tabs").get(0));const Et=M.applyBindings({dirty:F,saving:ue,problems:Te,itemCount:Se},l,{methods:{save:()=>at(),discard:()=>At(),addItem:()=>pe("item"),addSeparator:()=>pe("separator"),addSpacer:()=>pe("spacer"),addSwitcher:()=>pe("theme-switcher")}});i(()=>Et.dispose()),i(it(l,{position:"bottom"})),O&&t("#me-add-switcher").hide(),St(n.get(0),A?"New menu":h.name||h.slug),lt(n,{id:"menu-editor-back",icon:"arrow-left",title:"All menus",onClick:()=>{location.hash="#/menus"}}),lt(n,{id:"menu-editor-locations",icon:"map-pin",title:"Menu locations",onClick:()=>{location.hash="#/menu-locations"}}),lt(n,{id:"menu-editor-save",icon:"save",title:"Save (Ctrl+S)",onClick:()=>at()});const dt=e=>{if(!(!(e.ctrlKey||e.metaKey)||e.key!=="s")){if(e.preventDefault(),e.stopImmediatePropagation(),document.querySelector(".me-item-form")?.offsetParent){E.toast("Apply the item first (Ctrl+Enter), then Save.",{type:"info"});return}at()}};document.addEventListener("keydown",dt,!0),i(()=>document.removeEventListener("keydown",dt,!0));const ut=()=>{if(!(!F.peek()||!ye))try{S.set(X,{menu:ye,base:z,at:new Date().toISOString()})}catch{}},mt=e=>{F.peek()&&(ut(),e.preventDefault(),e.returnValue="")};window.addEventListener("beforeunload",mt),i(()=>window.removeEventListener("beforeunload",mt)),V={path:_,dirty:()=>F.peek(),name:()=>t("#me-name").val()||h.name||h.slug||"new menu",dispose(){c=!0,ut(),p.splice(0).reverse().forEach(e=>{try{e()}catch{}})}},I.scan(l);let ie=null;try{ie=S.get(X)}catch{}if(ie?.menu){ct();const e=ie.base&&ie.base!==z,o=ie.at?` (${nn(ie.at)})`:"",a=A?"the new menu you started":`the menu "${Fe(h.name||h.slug)}"`,d=e?`You left unsaved changes to ${a}${o}, but the saved menu has changed since. Restore your version anyway?`:`You left unsaved changes to ${a}${o}. Restore them?`;await E.confirm(d)&&b()&&(r({...ie.menu,meta:{...h.meta||{},...ie.menu.meta||{}}}),D())}}};
|