domma-cms 1.52.0 → 1.53.1

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 CHANGED
@@ -1,9 +1,18 @@
1
1
  # Changelog
2
2
 
3
+ ## [1.53.1] - 2026-11-10
4
+
5
+ - A chat launcher that uses Della can give her another name for that chat (**Call her**, under Use Della; `chat.characterName`, up to 40 characters). The name is shown on her answers and used by the AI, with Della's artwork - Dash on the jobs board. Empty keeps her own name.
6
+
7
+ ## [1.53.0] - 2026-11-10
8
+
9
+ - Add an opt-in AI assistant inside admin, enabled through Site Settings, for tool help and copyable drafts. Conversations are separate from visitor chats and clear on account changes. Plugins can supply static, permission-scoped guidance and assistant identities. Requires the matching Manager AI mode update.
10
+
3
11
  ## [1.52.0] - 2026-11-10
4
12
 
5
13
  - Choose the allowed public themes in the Theme tool and optionally offer Follow system with a selected light/dark pair. Visitor choices persist, follow live device preference changes when requested, and take precedence over scheduled day/night defaults. Floating, menu and page switchers share the same restrictions.
6
14
 
15
+
7
16
  ## [1.51.3] - 2026-11-10
8
17
 
9
18
  - Keep the Job Board's records about people out of site repos: companies and their teams, jobs, applications, CVs, messages, interviews, notes, reviews, testimonials, alerts, saved jobs and searches, credits and orders, the talent pool, proposals, quotes and its public copies. Bookings and waiting lists, onboarding enrolments and e-card buyers, sends and opt-outs are kept out too. Regenerating a site's .gitignore (Site Manager's site-gitignore script) stops tracking their data.json; the files stay on disk.
@@ -0,0 +1 @@
1
+ .admin-assistant-trigger{position:fixed;right:24px;bottom:24px;z-index:1000;display:flex;align-items:center;gap:8px;padding:10px 16px;border:1px solid var(--dm-border);border-radius:30px;background:var(--dm-surface);color:var(--dm-text);box-shadow:0 4px 20px #0002;cursor:pointer;font:inherit}.admin-assistant-trigger .dm-character{width:40px;height:40px;flex:none}.admin-assistant-panel{padding:20px;display:flex;flex-direction:column;gap:12px;min-width:0}.admin-assistant-messages{max-height:50vh;overflow:auto;display:flex;flex-direction:column;gap:12px}.admin-assistant-message{padding:12px;border:1px solid var(--dm-border);border-radius:12px;background:var(--dm-surface)}.admin-assistant-message.is-visitor{margin-left:24px}.admin-assistant-message p{white-space:pre-wrap;overflow-wrap:anywhere;margin:8px 0}.admin-assistant-form{display:flex;flex-direction:column;gap:8px}.admin-assistant-actions{display:flex;flex-wrap:wrap;gap:8px}@media(max-width:600px){.admin-assistant-trigger{right:12px;bottom:12px}.admin-assistant-panel{padding:12px}.admin-assistant-messages{max-height:42vh}}
package/admin/index.html CHANGED
@@ -29,6 +29,7 @@
29
29
  like any other, so it honours the same `highlight` block. -->
30
30
  <link rel="stylesheet" href="/public/css/menu-highlight.css?v=20261024-menu-highlight-fix">
31
31
  <link rel="stylesheet" href="/admin/css/calculator.css">
32
+ <link rel="stylesheet" href="/admin/css/admin-assistant.css?v=20261110-admin-assistant">
32
33
  </head>
33
34
  <body class="dm-cloaked dm-theme-charcoal-dark dashboard-layout">
34
35
 
package/admin/js/app.js CHANGED
@@ -1,4 +1,4 @@
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=`
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{installAdminAssistant as Me}from"./lib/admin-assistant.js";import{takeOverviewPass as De,withDashboardStrip as K}from"./lib/dashboards-strip.js";import{installHotkeys as ye}from"./lib/hotkeys-ui.js";import{applyAdminBrand as q}from"./lib/admin-brand.js";import{installRouterCatchUp as Ee}from"./lib/router-catch-up.js";import{installSidebarDrawer as Ne}from"./lib/sidebar-drawer.js";$(()=>{Z(document),ne(),Se(),Me(),ce(),le(),re(),Ne(),(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!=="/"&&!De()?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))}),ye(),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 X}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(),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,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#039;")}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}})})()});
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,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#039;")}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))},Ee(R),R.init({container:"#view-container",routes:T,views:V,default:"/",transitions:{enter:"fadeIn",leave:"fadeOut",duration:150}})})()});
@@ -0,0 +1,9 @@
1
+ import{api as $,getUser as x,isAuthenticated as k}from"../api.js";import{onceClosed as T}from"./tool-kit.js";import{mountCharacter as H}from"/public/js/character-view.mjs?v=20261110-builder-characters";export function installAdminAssistant(){let v=null,u=0,w=0,s=null,t=null,i=null,h=null;const l=M.observable([]),g=M.observable(""),m=M.observable(!1),d=M.observable(""),A=()=>location.hash.slice(1).split("?")[0]||"/",C=()=>/^#\/(login|reset-password)(\?|\/|$)/.test(location.hash);function p(){u++,i?.element?.querySelector(".admin-assistant-panel")?.replaceChildren(),i?.close(!0),i=null,h?.destroy(),h=null,t?.remove(),t=null,l.value=[],g.value="",m.value=!1,d.value=""}async function I(){const a=g.peek().trim();if(!a||a.length>1e3||m.peek())return;const n=v,e=u,o=l.peek().slice(-10).map(c=>({from:c.from,text:c.text.slice(0,1e3)}));g.value="",d.value="",m.value=!0,l.value=[...l.peek(),{from:"visitor",text:a}].slice(-30);try{const c=await $.post("/admin-assistant/ask",{question:a,history:o,route:A()});if(u!==e||x()?.id!==n||!k())return;l.value=[...l.peek(),{from:"bot",text:c.answer}].slice(-30)}catch(c){u===e&&x()?.id===n&&(d.value=c.message||"Could not get an answer.")}finally{u===e&&(m.value=!1)}}function N(){if(!s?.enabled||!t)return;if(i){i.open();return}const a=s.name.replace(/[&<>"']/g,r=>({"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"})[r]),n=E.slideover({title:`Ask ${a}`,size:"md",position:"right"}),e=document.createElement("div");e.className="admin-assistant-panel",e.innerHTML=`<p class="text-muted">Help and drafts for the current tool. You choose what to copy and save.</p>
2
+ <div class="admin-assistant-messages" role="log" aria-live="polite" aria-label="Assistant conversation"></div>
3
+ <p role="status" data-bind-hidden="!busy.value">Thinking...</p>
4
+ <p class="text-danger" role="alert" data-bind-text="error.value"></p>
5
+ <form class="admin-assistant-form"><label for="admin-assistant-question">Your question</label>
6
+ <textarea id="admin-assistant-question" class="form-input" maxlength="1000" rows="3" data-model="question.value" placeholder="Ask for help or a draft..."></textarea>
7
+ <div class="admin-assistant-actions"><button type="submit" class="btn btn-primary" data-bind-disabled="busy.value">Ask</button>
8
+ <button type="button" class="btn btn-secondary" data-on-click="reset" data-bind-disabled="busy.value">Clear conversation</button></div></form>
9
+ <small class="text-muted">Questions are sent to the site's AI service. Current page records are not attached automatically.</small>`;const o=e.querySelector('[role="log"]'),c=M.effect(()=>{o.replaceChildren();for(const r of l.value){const y=document.createElement("article");y.className=`admin-assistant-message is-${r.from}`;const q=document.createElement("strong");q.textContent=r.from==="visitor"?"You":s.name;const L=document.createElement("p");if(L.textContent=r.text,y.append(q,L),r.from==="bot"){const b=document.createElement("button");b.type="button",b.className="btn btn-sm btn-secondary",b.textContent="Copy",b.addEventListener("click",async()=>{try{await navigator.clipboard.writeText(r.text),E.toast("Copied.",{type:"success"})}catch{E.toast("Select the text to copy it.",{type:"info"})}}),y.append(b)}o.append(y)}o.scrollTop=o.scrollHeight});e.querySelector("form").addEventListener("submit",r=>{r.preventDefault(),I()});const S=M.applyBindings({question:g,busy:m,error:d},e,{methods:{reset:()=>{l.value=[],d.value=""}}});n.element.append(e),i=n,T(n,()=>{S.dispose(),c(),i===n&&(i=null)}),s.available||(d.value="AI answers are not configured or are unavailable on this site."),n.open()}async function f(){const a=k()&&!C()?x()?.id:null;if(a!==v&&(p(),v=a),!a)return;const n=++w;try{const e=await $.get(`/admin-assistant/config?route=${encodeURIComponent(A())}`);if(n!==w||a!==x()?.id||!k()||C())return;if(!e.enabled){p(),s=null;return}s&&(s.name!==e.name||s.character!==e.character)&&p(),s=e,t||(t=document.createElement("button"),t.type="button",t.className="admin-assistant-trigger",t.addEventListener("click",async()=>{await f(),N()}),document.body.append(t)),t.replaceChildren(),h?.destroy(),e.character&&(h=H(t,{id:e.character,portrait:!0,animated:e.animated}));const o=document.createElement("span");o.textContent=`Ask ${e.name}`,t.append(o),t.setAttribute("aria-label",`Ask ${e.name}`)}catch{n===w&&(p(),s=null)}}M.subscribe("router:afterChange",f),window.addEventListener("admin-assistant:settings",f),window.addEventListener("storage",f),window.addEventListener("hashchange",()=>{C()&&(p(),v=null)}),f()}
@@ -1,5 +1,5 @@
1
1
  import{LAUNCHER_DEFAULTS as b,LAUNCHER_LIMITS as r,LAUNCHER_POSITION_LABEL as u,launcherColourCss as p,launcherReady as x,launcherSpot as f,launcherAvatar as y,normaliseLauncher as l,normaliseLauncherPath as g}from"../../../public/js/launcher-settings.mjs";export const FILTERS=["all","on","off"];const m={modal:"Modal",slideover:"Slideover",chat:"Chat"},w={page:"page",form:"form",block:"block"};export function describeAction(e){const t=e.action;return t.type==="chat"?`Chat${e.chat.bot?" (bot first)":""}`:t.ref?`${m[t.type]}: ${t.kind==="page"?t.ref:`${w[t.kind]} ${t.ref}`}`:`${m[t.type]}: nothing chosen yet`}export function describeWhere(e){const t=e.pages.paths.length,o=e.pages.mode==="all"?"every page":e.pages.mode==="only"?t?`${t} page rule${t===1?"":"s"}`:"no pages":`every page but ${t} rule${t===1?"":"s"}`,a=e.audience==="signed-in"?", signed-in only":e.audience==="signed-out"?", signed-out only":"",n=e.devices==="desktop"?", desktop only":e.devices==="phone"?", phones only":"";return`${o}${a}${n}`}export function launcherProblem(e){return x(e)?e.pages.mode==="only"&&!e.pages.paths.length?"Shows on no pages":"":"Choose what it opens"}export function launcherRow(e){const t=launcherProblem(e),o=e.triggerStyle==="icon-text",a=p(e.colours.background)||"var(--dm-primary)",n=p(e.colours.text)||"var(--dm-primary-text)";return{id:e.id,name:e.name,meta:`${e.showDisc?u[e.position]:"No disc - opened from links"} \xB7 ${describeAction(e)} \xB7 ${describeWhere(e)}`,label:e.label,icon:e.icon,pill:o,off:!e.enabled,on:e.enabled,problem:t,rowCls:[e.enabled?"":"is-off",t&&e.enabled?"is-warn":""].filter(Boolean).join(" "),discStyle:{"--lnx-bg":a,"--lnx-fg":n,"border-radius":o?"999px":`${Math.round(e.radius/e.size*100)}%`}}}export function arrangeLaunchers(e,{filter:t="all",query:o=""}={}){const a=String(o||"").trim().toLowerCase();return e.filter(n=>t==="on"?n.enabled:t==="off"?!n.enabled:!0).filter(n=>!a||[n.name,n.label,n.action.ref,n.action.title].some(i=>String(i||"").toLowerCase().includes(a)))}export function countLaunchers(e){const t=e.filter(o=>o.enabled).length;return{all:e.length,on:t,off:e.length-t}}export function moveItem(e,t,o){const a=[...e];if(t<0||t>=a.length||o<0||o>=a.length||t===o)return a;const[n]=a.splice(t,1);return a.splice(o,0,n),a}export function blankLauncher(e=[]){const t=new Set(e.map(a=>a.name));let o="New launcher";for(let a=2;t.has(o);a++)o=`New launcher ${a}`;return l({name:o})}export function duplicateLauncher(e,t=[]){const o=new Set(t.map(n=>n.name));let a=`${e.name} (copy)`.slice(0,r.nameMax);for(let n=2;o.has(a);n++)a=`${e.name} (copy ${n})`.slice(0,r.nameMax);return l({...structuredClone(e),id:"",name:a,enabled:!1})}export function formFromLauncher(e){const t=l(e);return{enabled:t.enabled,showDisc:t.showDisc,name:t.name,label:t.label,tooltipMode:t.tooltipMode,tooltip:t.tooltip,icon:t.icon,triggerStyle:t.triggerStyle,position:t.position,offsetX:t.offsetX,offsetY:t.offsetY,size:t.size,radius:t.radius,devices:t.devices,phoneOverride:t.phone.override,phonePosition:t.phone.position,phoneOffsetX:t.phone.offsetX,phoneOffsetY:t.phone.offsetY,phoneSize:t.phone.size,background:t.colours.background,text:t.colours.text,cls:t.class,pagesMode:t.pages.mode,paths:t.pages.paths.join(`
2
- `),audience:t.audience,actionType:t.action.type,kind:t.action.kind,ref:t.action.ref,title:t.action.title,modalSize:t.action.size,side:t.action.side,width:t.action.width,customWidth:t.action.customWidth,widthUnit:t.action.widthUnit,modalHeight:t.action.height,customHeight:t.action.customHeight,heightUnit:t.action.heightUnit,useDella:t.chat.character==="della",greeting:t.chat.greeting,botName:t.chat.botName,bot:t.chat.bot,staff:t.chat.staff,askDetails:t.chat.askDetails,ai:t.chat.ai,aiUseSite:t.chat.aiUseSite,aiContext:t.chat.aiContext,aiRules:t.chat.aiRules,accent:t.chat.accent,accentText:t.chat.accentText,avatar:t.chat.avatar,chatSize:t.chat.size,chatWidth:t.chat.width,chatHeight:t.chat.height,chatResizable:t.chat.resizable,starters:t.chat.starters.join(`
3
- `),aiMaxPerChat:t.chat.aiMaxPerChat,personButton:t.chat.personButton,keepOwn:t.chat.keepDays>0,keepDays:t.chat.keepDays||90,times:t.chat.times}}export function launcherFromForm(e,t=""){return l({id:t,enabled:e.enabled,showDisc:e.showDisc,name:e.name,label:e.label,tooltipMode:e.tooltipMode,tooltip:e.tooltip,icon:e.icon,triggerStyle:e.triggerStyle,position:e.position,offsetX:e.offsetX,offsetY:e.offsetY,size:e.size,radius:e.radius,devices:e.devices,phone:{override:e.phoneOverride,position:e.phonePosition,offsetX:e.phoneOffsetX,offsetY:e.phoneOffsetY,size:e.phoneSize},colours:{background:e.background,text:e.text},class:e.cls,pages:{mode:e.pagesMode,paths:String(e.paths||"").split(/\n+/)},audience:e.audience,action:{type:e.actionType,kind:e.kind,ref:e.ref,title:e.title,size:e.modalSize,side:e.side,width:e.width,customWidth:e.customWidth,widthUnit:e.widthUnit,height:e.modalHeight,customHeight:e.customHeight,heightUnit:e.heightUnit},chat:{character:e.useDella?"della":"",greeting:e.greeting,botName:e.botName,bot:e.bot,staff:e.staff,askDetails:e.askDetails,ai:e.ai,aiUseSite:e.aiUseSite,aiContext:e.aiContext,aiRules:e.aiRules,accent:e.accent,accentText:e.accentText,avatar:e.avatar,size:e.chatSize,width:e.chatWidth,height:e.chatHeight,resizable:e.chatResizable,starters:String(e.starters||"").split(`
2
+ `),audience:t.audience,actionType:t.action.type,kind:t.action.kind,ref:t.action.ref,title:t.action.title,modalSize:t.action.size,side:t.action.side,width:t.action.width,customWidth:t.action.customWidth,widthUnit:t.action.widthUnit,modalHeight:t.action.height,customHeight:t.action.customHeight,heightUnit:t.action.heightUnit,useDella:t.chat.character==="della",characterName:t.chat.characterName||"",greeting:t.chat.greeting,botName:t.chat.botName,bot:t.chat.bot,staff:t.chat.staff,askDetails:t.chat.askDetails,ai:t.chat.ai,aiUseSite:t.chat.aiUseSite,aiContext:t.chat.aiContext,aiRules:t.chat.aiRules,accent:t.chat.accent,accentText:t.chat.accentText,avatar:t.chat.avatar,chatSize:t.chat.size,chatWidth:t.chat.width,chatHeight:t.chat.height,chatResizable:t.chat.resizable,starters:t.chat.starters.join(`
3
+ `),aiMaxPerChat:t.chat.aiMaxPerChat,personButton:t.chat.personButton,keepOwn:t.chat.keepDays>0,keepDays:t.chat.keepDays||90,times:t.chat.times}}export function launcherFromForm(e,t=""){return l({id:t,enabled:e.enabled,showDisc:e.showDisc,name:e.name,label:e.label,tooltipMode:e.tooltipMode,tooltip:e.tooltip,icon:e.icon,triggerStyle:e.triggerStyle,position:e.position,offsetX:e.offsetX,offsetY:e.offsetY,size:e.size,radius:e.radius,devices:e.devices,phone:{override:e.phoneOverride,position:e.phonePosition,offsetX:e.phoneOffsetX,offsetY:e.phoneOffsetY,size:e.phoneSize},colours:{background:e.background,text:e.text},class:e.cls,pages:{mode:e.pagesMode,paths:String(e.paths||"").split(/\n+/)},audience:e.audience,action:{type:e.actionType,kind:e.kind,ref:e.ref,title:e.title,size:e.modalSize,side:e.side,width:e.width,customWidth:e.customWidth,widthUnit:e.widthUnit,height:e.modalHeight,customHeight:e.customHeight,heightUnit:e.heightUnit},chat:{character:e.useDella?"della":"",characterName:String(e.characterName||"").trim(),greeting:e.greeting,botName:e.botName,bot:e.bot,staff:e.staff,askDetails:e.askDetails,ai:e.ai,aiUseSite:e.aiUseSite,aiContext:e.aiContext,aiRules:e.aiRules,accent:e.accent,accentText:e.accentText,avatar:e.avatar,size:e.chatSize,width:e.chatWidth,height:e.chatHeight,resizable:e.chatResizable,starters:String(e.starters||"").split(`
4
4
  `),aiMaxPerChat:e.aiMaxPerChat,personButton:e.personButton,keepDays:e.keepOwn?e.keepDays:0,times:e.times}})}export function checkLauncherForm(e){const t={},o={};if(String(e.name||"").trim()||(t.name="Give it a name - only you see it."),String(e.label||"").trim()||(t.label="Visitors need words for it: they are read out, and shown on a pill."),e.actionType!=="chat"){const i=String(e.ref||"").trim();i?e.kind==="page"&&(!g(i)||i.includes("*"))?t.ref="A page address starts with / - e.g. /about.":e.kind!=="page"&&!/^[a-z0-9][a-z0-9_-]*$/i.test(i)&&(t.ref="Choose one from the list."):o.ref="Nothing chosen yet - the launcher stays off the page until it opens something."}const a=String(e.paths||"").split(/\n+/).map(i=>i.trim()).filter(Boolean),n=a.filter(i=>!g(i));n.length?t.paths=`Not an address: ${n.slice(0,3).join(", ")}`:a.length>r.pathsMax?t.paths=`At most ${r.pathsMax} rules.`:e.pagesMode==="only"&&!a.length&&(o.paths="With no pages listed it shows nowhere.");for(const i of["background","text","accent","accentText"]){const s=String(e[i]||"").trim();s&&!p(s)&&(t[i]="A theme colour, or a hex colour such as #3366ff.")}if(e.actionType==="chat"){const i=String(e.starters||"").split(`
5
5
  `).map(s=>s.trim()).filter(Boolean);if(i.length>r.startersMax?t.starters=`At most ${r.startersMax} questions.`:i.some(s=>s.length>r.starterMax)&&(t.starters=`Keep each to ${r.starterMax} characters.`),e.keepOwn&&!(Number(e.keepDays)>=1&&Number(e.keepDays)<=730)&&(t.keepDays="Between 1 and 730 days."),e.chatSize==="custom"){const[s,c]=r.chatWidth,[h,d]=r.chatHeight;Number(e.chatWidth)>=s&&Number(e.chatWidth)<=c||(t.chatWidth=`Between ${s} and ${c} pixels.`),Number(e.chatHeight)>=h&&Number(e.chatHeight)<=d||(t.chatHeight=`Between ${h} and ${d} pixels.`)}}return e.actionType==="chat"&&String(e.avatar||"").trim()&&!y(e.avatar)&&(t.avatar="Choose a picture from Media (an address on this site)."),{errors:t,warnings:o}}export function previewSpot(e,{vw:t=320,vh:o=200,scale:a=.5,phone:n=!1}={}){const i=n&&e.phoneOverride,s=Math.max(10,Math.round((i?e.phoneSize:e.size)*a)),c=e.triggerStyle==="icon-text"?Math.round(s*2.4):s,h=f(i?e.phonePosition:e.position,{w:c,h:s,vw:t,vh:o,offsetX:Math.round((i?e.phoneOffsetX:e.offsetX)*a),offsetY:Math.round((i?e.phoneOffsetY:e.offsetY)*a)});return{left:Math.max(0,Math.min(t-c,h.left)),top:Math.max(0,Math.min(o-s,h.top)),size:s,w:c}}export{b as LAUNCHER_DEFAULTS,u as LAUNCHER_POSITION_LABEL};
@@ -1,3 +1,3 @@
1
- export const TAB_FIELDS={general:["title","tagline","siteUrl","adminHome","spacerSize","bodyClass","aiContext","aiRules","charactersEnabled","charactersAnimated","charactersLaunchers","charactersChats","charactersBuilders","charactersDot","charactersDaisy"],branding:["brandEnabled","brandText","brandLogo","brandIcon","brandUrl","adminBrandEnabled","adminBrandTitle","adminBrandLogo","adminBrandLogoDark","adminBrandIcon"],favicon:["favicon"],footer:["footerCopyright","footerLayout","footerBlurb","footerBlocks","footerClass","footerSocialClass","footerLook","footerCtaText","footerCtaHighlight","footerCtaUrl","footerCtaSub","footerWatermark","footerStatus","footerFacts","footerTagline","footerEmail","footerAddress","footerGradFrom","footerGradTo","socialTwitter","socialFacebook","socialInstagram","socialLinkedin","socialGithub","socialYoutube"],email:["smtpHost","smtpPort","smtpUser","smtpPass","smtpSecure","smtpInsecureTLS","smtpFromAddress","smtpFromName"],pageNavigation:["bttEnabled","bttSmooth","bttLabel","bttThreshold","bttPosition","bttOffset","bttBottomOffset","gtbEnabled","gtbSmooth","gtbLabel","gtbThreshold","gtbPosition","gtbOffset","gtbBottomOffset"],cookies:["ccEnabled","ccMessage","ccAcceptAll","ccRejectAll","ccCustomize","ccSavePrefs","ccPrivacyText","ccPrivacyUrl","ccCookieText","ccCookieUrl","ccPosition","ccLayout","ccTheme","ccShowFunctional","ccShowAnalytics","ccShowMarketing","ccVersion","ccSettingsLink","ccSettingsLinkText"],breadcrumbs:["bcEnabled","bcHomeLabel","bcPosition","bcOffsetX","bcOffsetY"],motion:["mtEnabled","mtLabel","mtDefault","mtControl","mtPlacement","mtTriggerStyle","mtPosition","mtOffsetX","mtOffsetY","mtIconSize","mtIconRadius","mtClass"]},SECRET_FIELDS=["smtpPass"],BREADCRUMB_POSITIONS=["TL","TR","BL","BR"],MOTION_PLACEMENTS=["footer","floating","navbar"],MOTION_LABEL="Reduce motion";const b=["system","off","on"],i=(t,r,a,o)=>{const n=Number.parseInt(t,10);return Number.isFinite(n)?Math.min(o,Math.max(a,n)):r};export function motionFromSettings(t={}){const r=t.motion&&typeof t.motion=="object"?t.motion:{},a=t.footer||{},o=m=>r[m]!==void 0&&r[m]!==null,n=o("default")?r.default:a.motionDefault,s=o("control")?r.control:a.motionControl,l=i(r.iconSize,52,32,96);return{mtEnabled:(o("enabled")?r.enabled:a.showMotionToggle)!==!1,mtLabel:typeof r.label=="string"&&r.label.trim()?r.label.trim():MOTION_LABEL,mtDefault:b.includes(n)?n:"system",mtControl:s==="checkbox"?"checkbox":"switch",mtPlacement:MOTION_PLACEMENTS.includes(r.placement)?r.placement:"footer",mtTriggerStyle:r.triggerStyle==="icon-text"?"icon-text":"icon",mtPosition:BREADCRUMB_POSITIONS.includes(r.position)?r.position:"BL",mtOffsetX:e(i(r.offsetX,32,0,500)),mtOffsetY:e(i(r.offsetY,32,0,500)),mtIconSize:e(l),mtIconRadius:e(i(r.iconRadius,26,0,Math.floor(l/2))),mtClass:e(r.class)}}export function motionFromForm(t){const r=i(t.mtIconSize,52,32,96);return{enabled:t.mtEnabled===!0,default:b.includes(t.mtDefault)?t.mtDefault:"system",placement:MOTION_PLACEMENTS.includes(t.mtPlacement)?t.mtPlacement:"footer",control:t.mtControl==="checkbox"?"checkbox":"switch",triggerStyle:t.mtTriggerStyle==="icon-text"?"icon-text":"icon",label:e(t.mtLabel).trim().replace(/\s+/g," ").slice(0,40)||MOTION_LABEL,position:BREADCRUMB_POSITIONS.includes(t.mtPosition)?t.mtPosition:"BL",offsetX:i(t.mtOffsetX,32,0,500),offsetY:i(t.mtOffsetY,32,0,500),iconSize:r,iconRadius:i(t.mtIconRadius,26,0,Math.floor(r/2)),class:e(t.mtClass).trim()}}export function footerBlockNames(t){return[...new Set(String(t??"").split(/[\s,]+/).map(r=>r.trim().toLowerCase()).filter(Boolean))]}export function gaIdError(t){const r=e(t).trim();return!r||/^G-[A-Z0-9]{4,20}$/i.test(r)?"":"A measurement ID looks like G-XXXXXXXXXX (Google Analytics > Admin > Data streams)."}export const FOOTER_LAYOUTS=["auto","columns","row"],FOOTER_LOOKS=["","showcase"],FOOTER_FACTS_MAX=4;const h=/^(\/|#|https?:\/\/|mailto:)/,p=/^#[0-9a-f]{6}$/i;export function footerShowcaseErrors(t){const r=[],a=e(t.footerCtaUrl).trim();a&&!h.test(a)&&r.push("The footer call to action link must start with /, #, https:// or mailto: (Footer tool).");for(const[o,n]of[["from",t.footerGradFrom],["to",t.footerGradTo]]){const s=e(n).trim();s&&!p.test(s)&&r.push(`The footer gradient "${o}" colour must look like #f26b3a (Footer tool).`)}return r}const e=(t,r="")=>t==null?r:String(t),c=(t,r)=>{const a=Number.parseInt(t,10);return Number.isFinite(a)?a:r};export function homeValue(t){return/^\/[A-Za-z0-9\-_/]*$/.test(t||"")&&String(t).replace(/\/+$/,"")||"/"}export function formFromSettings(t={}){const r=t.backToTop||{},a=t.goToBottom||{},o=t.cookieConsent||{},n=t.breadcrumbs||{};return{title:e(t.title),tagline:e(t.tagline),siteUrl:e(t.baseUrl),adminHome:homeValue(t.adminHome),spacerSize:e(t.layoutOptions?.spacerSize??40),bodyClass:e(t.bodyClass),aiContext:e(t.assistant?.context),aiRules:e(t.assistant?.rules),charactersEnabled:t.characters?.enabled!==!1,charactersAnimated:t.characters?.animated!==!1,charactersLaunchers:t.characters?.launchers!==!1,charactersChats:t.characters?.chats!==!1,charactersBuilders:t.characters?.builders!==!1,charactersDot:t.characters?.dot!==!1,charactersDaisy:t.characters?.daisy!==!1,brandEnabled:t.brand?.enabled!==!1,brandText:e(t.brand?.text),brandLogo:e(t.brand?.logo),brandIcon:e(t.brand?.icon),brandUrl:e(t.brand?.url,"/"),favicon:e(t.favicon),adminBrandEnabled:t.adminBrand?.enabled!==!1,adminBrandTitle:e(t.adminBrand?.title),adminBrandLogo:e(t.adminBrand?.logo),adminBrandLogoDark:e(t.adminBrand?.logoDark),adminBrandIcon:e(t.adminBrand?.icon),footerCopyright:e(t.footer?.copyright),footerLayout:FOOTER_LAYOUTS.includes(t.footer?.layout)?t.footer.layout:"auto",footerBlurb:e(t.footer?.blurb),footerBlocks:Array.isArray(t.footer?.blocks)?t.footer.blocks.filter(s=>typeof s=="string").join(", "):"",footerClass:e(t.footer?.class),footerSocialClass:e(t.footer?.socialClass),footerLook:FOOTER_LOOKS.includes(t.footer?.look)?t.footer.look:"",footerCtaText:e(t.footer?.cta?.text),footerCtaHighlight:e(t.footer?.cta?.highlight),footerCtaUrl:e(t.footer?.cta?.url),footerCtaSub:e(t.footer?.cta?.sub),footerWatermark:e(t.footer?.watermark),footerStatus:e(t.footer?.status),footerFacts:Array.isArray(t.footer?.facts)?t.footer.facts.filter(s=>typeof s=="string").join(`
2
- `):"",footerTagline:e(t.footer?.tagline),footerEmail:e(t.footer?.email),footerAddress:e(t.footer?.address),footerGradFrom:e(t.footer?.gradient?.from),footerGradTo:e(t.footer?.gradient?.to),socialTwitter:e(t.social?.twitter),socialFacebook:e(t.social?.facebook),socialInstagram:e(t.social?.instagram),socialLinkedin:e(t.social?.linkedin),socialGithub:e(t.social?.github),socialYoutube:e(t.social?.youtube),smtpHost:e(t.smtp?.host),smtpPort:e(t.smtp?.port||587),smtpUser:e(t.smtp?.user),smtpPass:"",smtpSecure:t.smtp?.secure===!0,smtpInsecureTLS:t.smtp?.allowInsecureTLS===!0,smtpFromAddress:e(t.smtp?.fromAddress),smtpFromName:e(t.smtp?.fromName),bttEnabled:r.enabled!==!1,bttSmooth:r.smooth!==!1,bttLabel:e(r.label),bttThreshold:e(r.scrollThreshold??300),bttPosition:e(r.position,"bottom-right"),bttOffset:e(r.offset??32),bttBottomOffset:e(r.bottomOffset??r.offset??32),gtbEnabled:a.enabled===!0,gtbSmooth:a.smooth!==!1,gtbLabel:e(a.label),gtbThreshold:e(a.scrollThreshold??300),gtbPosition:e(a.position,"bottom-right"),gtbOffset:e(a.offset??32),gtbBottomOffset:e(a.bottomOffset??a.offset??32),ccEnabled:o.enabled!==!1,ccMessage:e(o.message),ccAcceptAll:e(o.acceptAllText,"Accept All"),ccRejectAll:e(o.rejectAllText,"Reject All"),ccCustomize:e(o.customizeText,"Customize"),ccSavePrefs:e(o.savePreferencesText,"Save Preferences"),ccPrivacyText:e(o.privacyPolicyText,"Privacy Policy"),ccPrivacyUrl:e(o.privacyPolicyUrl),ccCookieText:e(o.cookiePolicyText,"Cookie Policy"),ccCookieUrl:e(o.cookiePolicyUrl),ccPosition:e(o.position,"bottom"),ccLayout:e(o.layout,"bar"),ccTheme:e(o.theme,"dark"),ccShowFunctional:o.showFunctional!==!1,ccShowAnalytics:o.showAnalytics!==!1,ccShowMarketing:o.showMarketing!==!1,ccVersion:e(o.consentVersion,"1.0"),ccSettingsLink:o.showSettingsLink!==!1,ccSettingsLinkText:e(o.settingsLinkText,"Cookie settings"),bcEnabled:n.enabled===!0,bcHomeLabel:e(n.homeLabel,"Home"),bcPosition:BREADCRUMB_POSITIONS.includes(n.position)?n.position:"TL",bcOffsetX:e(n.offsetX??8),bcOffsetY:e(n.offsetY??8),...motionFromSettings(t)}}export function payloadFromForm(t,r={},{adminHomeReady:a=!0}={}){const o=s=>e(s).trim(),n=motionFromForm(t);return{title:o(t.title),tagline:o(t.tagline),baseUrl:o(t.siteUrl).replace(/\/+$/,""),...a&&{adminHome:o(t.adminHome)||"/"},layoutOptions:{spacerSize:c(t.spacerSize,40)||40},bodyClass:o(t.bodyClass),assistant:{context:o(t.aiContext),rules:o(t.aiRules)},characters:{enabled:t.charactersEnabled!==!1,animated:t.charactersAnimated!==!1,launchers:t.charactersLaunchers!==!1,chats:t.charactersChats!==!1,builders:t.charactersBuilders!==!1,dot:t.charactersDot!==!1,daisy:t.charactersDaisy!==!1},brand:{...r.brand,enabled:t.brandEnabled!==!1,text:o(t.brandText),logo:o(t.brandLogo),icon:o(t.brandIcon),url:o(t.brandUrl)||"/"},favicon:o(t.favicon),adminBrand:{...r.adminBrand,enabled:t.adminBrandEnabled!==!1,title:o(t.adminBrandTitle),logo:o(t.adminBrandLogo),logoDark:o(t.adminBrandLogoDark),icon:o(t.adminBrandIcon)},footer:{copyright:o(t.footerCopyright),layout:FOOTER_LAYOUTS.includes(t.footerLayout)?t.footerLayout:"auto",blurb:o(t.footerBlurb),blocks:footerBlockNames(t.footerBlocks),links:r.footer?.links||[],showMotionToggle:n.enabled,motionDefault:n.default,motionControl:n.control,class:o(t.footerClass),socialClass:o(t.footerSocialClass),look:FOOTER_LOOKS.includes(t.footerLook)?t.footerLook:"",cta:{text:o(t.footerCtaText),highlight:o(t.footerCtaHighlight),url:o(t.footerCtaUrl),sub:o(t.footerCtaSub)},watermark:o(t.footerWatermark),status:o(t.footerStatus),facts:String(t.footerFacts??"").split(`
3
- `).map(s=>s.trim()).filter(Boolean).slice(0,FOOTER_FACTS_MAX),tagline:o(t.footerTagline),email:o(t.footerEmail),address:o(t.footerAddress),gradient:{from:o(t.footerGradFrom),to:o(t.footerGradTo)}},social:{twitter:o(t.socialTwitter),facebook:o(t.socialFacebook),instagram:o(t.socialInstagram),linkedin:o(t.socialLinkedin),github:o(t.socialGithub),youtube:o(t.socialYoutube)},smtp:{host:o(t.smtpHost),port:c(t.smtpPort,587)||587,user:o(t.smtpUser),pass:e(t.smtpPass),secure:t.smtpSecure===!0,allowInsecureTLS:t.smtpInsecureTLS===!0,fromAddress:o(t.smtpFromAddress),fromName:o(t.smtpFromName)},backToTop:{enabled:t.bttEnabled===!0,scrollThreshold:c(t.bttThreshold,300),position:e(t.bttPosition)||"bottom-right",offset:c(t.bttOffset,32),bottomOffset:c(t.bttBottomOffset,32),label:o(t.bttLabel),smooth:t.bttSmooth===!0},goToBottom:{enabled:t.gtbEnabled===!0,scrollThreshold:c(t.gtbThreshold,300),position:e(t.gtbPosition)||"bottom-right",offset:c(t.gtbOffset,32),bottomOffset:c(t.gtbBottomOffset,32),label:o(t.gtbLabel),smooth:t.gtbSmooth===!0},cookieConsent:{enabled:t.ccEnabled===!0,message:o(t.ccMessage),acceptAllText:o(t.ccAcceptAll),rejectAllText:o(t.ccRejectAll),customizeText:o(t.ccCustomize),savePreferencesText:o(t.ccSavePrefs),privacyPolicyText:o(t.ccPrivacyText),privacyPolicyUrl:o(t.ccPrivacyUrl),cookiePolicyText:o(t.ccCookieText),cookiePolicyUrl:o(t.ccCookieUrl),position:e(t.ccPosition)||"bottom",layout:e(t.ccLayout)||"bar",theme:e(t.ccTheme)||"dark",showFunctional:t.ccShowFunctional===!0,showAnalytics:t.ccShowAnalytics===!0,showMarketing:t.ccShowMarketing===!0,consentVersion:o(t.ccVersion)||"1.0",showSettingsLink:t.ccSettingsLink===!0,settingsLinkText:o(t.ccSettingsLinkText)||"Cookie settings"},breadcrumbs:{enabled:t.bcEnabled===!0,homeLabel:o(t.bcHomeLabel)||"Home",position:BREADCRUMB_POSITIONS.includes(t.bcPosition)?t.bcPosition:"TL",offsetX:c(t.bcOffsetX,8),offsetY:c(t.bcOffsetY,8)},motion:n}}export function siteUrlError(t){const r=e(t).trim().replace(/\/+$/,"");return r?/^https?:\/\//i.test(r)?/^https?:\/\/([a-z0-9.\-]+|\[[0-9a-f:.]+\])(:\d{1,5})?$/i.test(r)?"":"Just the address, like https://example.com - no page path after it.":"Start with https:// (or http://).":""}const d=t=>typeof t=="boolean"?t:e(t);export function snapshot(t){return JSON.stringify(Object.keys(t).sort().map(r=>[r,d(t[r])]))}export function changedTabs(t,r){const a=[];for(const[o,n]of Object.entries(TAB_FIELDS))n.some(s=>d(t[s])!==d(r[s]))&&a.push(o);return a}export function draftOf(t){return Object.fromEntries(Object.entries(t).filter(([r])=>!SECRET_FIELDS.includes(r)))}const g={footerMotionToggle:"mtEnabled",footerMotionDefault:"mtDefault",footerMotionControl:"mtControl"};export function formFromDraft(t,r={}){const a={...r};for(const[n,s]of Object.entries(g))n in a&&!(s in a)&&(a[s]=a[n]),delete a[n];const o={...t};for(const[n,s]of Object.entries(a))n in o&&!SECRET_FIELDS.includes(n)&&(o[n]=s);return o}export function settingsProblems(t,r={}){const a=[];return e(t.smtpHost).trim()?e(t.smtpFromAddress).trim()||a.push({tone:"warn",tab:"email",text:"No From address - mail has no sender and many servers refuse it."}):a.push({tone:"danger",tab:"email",text:"No SMTP host - mail goes to a throwaway test inbox and reaches no one (password resets, form notifications)."}),(t.ccEnabled===!0||e(r.googleAnalytics?.measurementId).trim())&&!e(t.ccPrivacyUrl).trim()&&a.push({tone:"warn",tab:"cookies",text:"The cookie banner is on but links to no privacy policy."}),a}export function describeCacheKey(t){const r=/^page:(.*?):m\d+:role([^:]*):/.exec(String(t||""));return r?{path:r[1]||"/",role:r[2]||"anon",page:!0}:{path:String(t||""),role:"",page:!1}}export function expiresIn(t,r=Date.now()){if(t==null)return"no expiry";const a=t-r;return a<=0?"expired":a<6e4?`${Math.round(a/1e3)}s`:a<36e5?`${Math.round(a/6e4)}m`:`${Math.round(a/36e5)}h`}export function footerForm(t={}){const r=formFromSettings(t);return Object.fromEntries(TAB_FIELDS.footer.map(a=>[a,r[a]]))}export function footerPayload(t){const{footer:r,social:a}=payloadFromForm(t);return delete r.links,delete r.showMotionToggle,delete r.motionDefault,delete r.motionControl,{footer:r,social:a}}export function siteSettingsForm(t={}){return Object.fromEntries(Object.entries(formFromSettings(t)).filter(([r])=>!TAB_FIELDS.footer.includes(r)&&!u.includes(r)))}export function siteSettingsPayload(...t){const{footer:r,social:a,favicon:o,backToTop:n,goToBottom:s,breadcrumbs:l,motion:m,...f}=payloadFromForm(...t);return f}export const APPEARANCE_TABS=["favicon","pageNavigation","breadcrumbs","motion","search"];const u=APPEARANCE_TABS.flatMap(t=>TAB_FIELDS[t]||[]);export function appearanceForm(t={}){const r=formFromSettings(t);return Object.fromEntries(u.map(a=>[a,r[a]]))}export function appearancePayload(t){const{favicon:r,backToTop:a,goToBottom:o,breadcrumbs:n,motion:s}=payloadFromForm(t);return{favicon:r,backToTop:a,goToBottom:o,breadcrumbs:n,motion:s}}
1
+ export const TAB_FIELDS={general:["title","tagline","siteUrl","adminHome","spacerSize","bodyClass","aiContext","aiRules","adminAssistantEnabled","adminAssistantName","adminAssistantCharacter","adminAssistantContext","adminAssistantRules","charactersEnabled","charactersAnimated","charactersLaunchers","charactersChats","charactersBuilders","charactersDot","charactersDaisy"],branding:["brandEnabled","brandText","brandLogo","brandIcon","brandUrl","adminBrandEnabled","adminBrandTitle","adminBrandLogo","adminBrandLogoDark","adminBrandIcon"],favicon:["favicon"],footer:["footerCopyright","footerLayout","footerBlurb","footerBlocks","footerClass","footerSocialClass","footerLook","footerCtaText","footerCtaHighlight","footerCtaUrl","footerCtaSub","footerWatermark","footerStatus","footerFacts","footerTagline","footerEmail","footerAddress","footerGradFrom","footerGradTo","socialTwitter","socialFacebook","socialInstagram","socialLinkedin","socialGithub","socialYoutube"],email:["smtpHost","smtpPort","smtpUser","smtpPass","smtpSecure","smtpInsecureTLS","smtpFromAddress","smtpFromName"],pageNavigation:["bttEnabled","bttSmooth","bttLabel","bttThreshold","bttPosition","bttOffset","bttBottomOffset","gtbEnabled","gtbSmooth","gtbLabel","gtbThreshold","gtbPosition","gtbOffset","gtbBottomOffset"],cookies:["ccEnabled","ccMessage","ccAcceptAll","ccRejectAll","ccCustomize","ccSavePrefs","ccPrivacyText","ccPrivacyUrl","ccCookieText","ccCookieUrl","ccPosition","ccLayout","ccTheme","ccShowFunctional","ccShowAnalytics","ccShowMarketing","ccVersion","ccSettingsLink","ccSettingsLinkText"],breadcrumbs:["bcEnabled","bcHomeLabel","bcPosition","bcOffsetX","bcOffsetY"],motion:["mtEnabled","mtLabel","mtDefault","mtControl","mtPlacement","mtTriggerStyle","mtPosition","mtOffsetX","mtOffsetY","mtIconSize","mtIconRadius","mtClass"]},SECRET_FIELDS=["smtpPass"],BREADCRUMB_POSITIONS=["TL","TR","BL","BR"],MOTION_PLACEMENTS=["footer","floating","navbar"],MOTION_LABEL="Reduce motion";const b=["system","off","on"],c=(t,a,r,o)=>{const n=Number.parseInt(t,10);return Number.isFinite(n)?Math.min(o,Math.max(r,n)):a};export function motionFromSettings(t={}){const a=t.motion&&typeof t.motion=="object"?t.motion:{},r=t.footer||{},o=m=>a[m]!==void 0&&a[m]!==null,n=o("default")?a.default:r.motionDefault,s=o("control")?a.control:r.motionControl,l=c(a.iconSize,52,32,96);return{mtEnabled:(o("enabled")?a.enabled:r.showMotionToggle)!==!1,mtLabel:typeof a.label=="string"&&a.label.trim()?a.label.trim():MOTION_LABEL,mtDefault:b.includes(n)?n:"system",mtControl:s==="checkbox"?"checkbox":"switch",mtPlacement:MOTION_PLACEMENTS.includes(a.placement)?a.placement:"footer",mtTriggerStyle:a.triggerStyle==="icon-text"?"icon-text":"icon",mtPosition:BREADCRUMB_POSITIONS.includes(a.position)?a.position:"BL",mtOffsetX:e(c(a.offsetX,32,0,500)),mtOffsetY:e(c(a.offsetY,32,0,500)),mtIconSize:e(l),mtIconRadius:e(c(a.iconRadius,26,0,Math.floor(l/2))),mtClass:e(a.class)}}export function motionFromForm(t){const a=c(t.mtIconSize,52,32,96);return{enabled:t.mtEnabled===!0,default:b.includes(t.mtDefault)?t.mtDefault:"system",placement:MOTION_PLACEMENTS.includes(t.mtPlacement)?t.mtPlacement:"footer",control:t.mtControl==="checkbox"?"checkbox":"switch",triggerStyle:t.mtTriggerStyle==="icon-text"?"icon-text":"icon",label:e(t.mtLabel).trim().replace(/\s+/g," ").slice(0,40)||MOTION_LABEL,position:BREADCRUMB_POSITIONS.includes(t.mtPosition)?t.mtPosition:"BL",offsetX:c(t.mtOffsetX,32,0,500),offsetY:c(t.mtOffsetY,32,0,500),iconSize:a,iconRadius:c(t.mtIconRadius,26,0,Math.floor(a/2)),class:e(t.mtClass).trim()}}export function footerBlockNames(t){return[...new Set(String(t??"").split(/[\s,]+/).map(a=>a.trim().toLowerCase()).filter(Boolean))]}export function gaIdError(t){const a=e(t).trim();return!a||/^G-[A-Z0-9]{4,20}$/i.test(a)?"":"A measurement ID looks like G-XXXXXXXXXX (Google Analytics > Admin > Data streams)."}export const FOOTER_LAYOUTS=["auto","columns","row"],FOOTER_LOOKS=["","showcase"],FOOTER_FACTS_MAX=4;const h=/^(\/|#|https?:\/\/|mailto:)/,p=/^#[0-9a-f]{6}$/i;export function footerShowcaseErrors(t){const a=[],r=e(t.footerCtaUrl).trim();r&&!h.test(r)&&a.push("The footer call to action link must start with /, #, https:// or mailto: (Footer tool).");for(const[o,n]of[["from",t.footerGradFrom],["to",t.footerGradTo]]){const s=e(n).trim();s&&!p.test(s)&&a.push(`The footer gradient "${o}" colour must look like #f26b3a (Footer tool).`)}return a}const e=(t,a="")=>t==null?a:String(t),i=(t,a)=>{const r=Number.parseInt(t,10);return Number.isFinite(r)?r:a};export function homeValue(t){return/^\/[A-Za-z0-9\-_/]*$/.test(t||"")&&String(t).replace(/\/+$/,"")||"/"}export function formFromSettings(t={}){const a=t.backToTop||{},r=t.goToBottom||{},o=t.cookieConsent||{},n=t.breadcrumbs||{};return{title:e(t.title),tagline:e(t.tagline),siteUrl:e(t.baseUrl),adminHome:homeValue(t.adminHome),spacerSize:e(t.layoutOptions?.spacerSize??40),bodyClass:e(t.bodyClass),aiContext:e(t.assistant?.context),aiRules:e(t.assistant?.rules),adminAssistantEnabled:t.adminAssistant?.enabled===!0,adminAssistantName:e(t.adminAssistant?.name,"Della"),adminAssistantCharacter:e(t.adminAssistant?.character,"della"),adminAssistantContext:e(t.adminAssistant?.context),adminAssistantRules:e(t.adminAssistant?.rules),charactersEnabled:t.characters?.enabled!==!1,charactersAnimated:t.characters?.animated!==!1,charactersLaunchers:t.characters?.launchers!==!1,charactersChats:t.characters?.chats!==!1,charactersBuilders:t.characters?.builders!==!1,charactersDot:t.characters?.dot!==!1,charactersDaisy:t.characters?.daisy!==!1,brandEnabled:t.brand?.enabled!==!1,brandText:e(t.brand?.text),brandLogo:e(t.brand?.logo),brandIcon:e(t.brand?.icon),brandUrl:e(t.brand?.url,"/"),favicon:e(t.favicon),adminBrandEnabled:t.adminBrand?.enabled!==!1,adminBrandTitle:e(t.adminBrand?.title),adminBrandLogo:e(t.adminBrand?.logo),adminBrandLogoDark:e(t.adminBrand?.logoDark),adminBrandIcon:e(t.adminBrand?.icon),footerCopyright:e(t.footer?.copyright),footerLayout:FOOTER_LAYOUTS.includes(t.footer?.layout)?t.footer.layout:"auto",footerBlurb:e(t.footer?.blurb),footerBlocks:Array.isArray(t.footer?.blocks)?t.footer.blocks.filter(s=>typeof s=="string").join(", "):"",footerClass:e(t.footer?.class),footerSocialClass:e(t.footer?.socialClass),footerLook:FOOTER_LOOKS.includes(t.footer?.look)?t.footer.look:"",footerCtaText:e(t.footer?.cta?.text),footerCtaHighlight:e(t.footer?.cta?.highlight),footerCtaUrl:e(t.footer?.cta?.url),footerCtaSub:e(t.footer?.cta?.sub),footerWatermark:e(t.footer?.watermark),footerStatus:e(t.footer?.status),footerFacts:Array.isArray(t.footer?.facts)?t.footer.facts.filter(s=>typeof s=="string").join(`
2
+ `):"",footerTagline:e(t.footer?.tagline),footerEmail:e(t.footer?.email),footerAddress:e(t.footer?.address),footerGradFrom:e(t.footer?.gradient?.from),footerGradTo:e(t.footer?.gradient?.to),socialTwitter:e(t.social?.twitter),socialFacebook:e(t.social?.facebook),socialInstagram:e(t.social?.instagram),socialLinkedin:e(t.social?.linkedin),socialGithub:e(t.social?.github),socialYoutube:e(t.social?.youtube),smtpHost:e(t.smtp?.host),smtpPort:e(t.smtp?.port||587),smtpUser:e(t.smtp?.user),smtpPass:"",smtpSecure:t.smtp?.secure===!0,smtpInsecureTLS:t.smtp?.allowInsecureTLS===!0,smtpFromAddress:e(t.smtp?.fromAddress),smtpFromName:e(t.smtp?.fromName),bttEnabled:a.enabled!==!1,bttSmooth:a.smooth!==!1,bttLabel:e(a.label),bttThreshold:e(a.scrollThreshold??300),bttPosition:e(a.position,"bottom-right"),bttOffset:e(a.offset??32),bttBottomOffset:e(a.bottomOffset??a.offset??32),gtbEnabled:r.enabled===!0,gtbSmooth:r.smooth!==!1,gtbLabel:e(r.label),gtbThreshold:e(r.scrollThreshold??300),gtbPosition:e(r.position,"bottom-right"),gtbOffset:e(r.offset??32),gtbBottomOffset:e(r.bottomOffset??r.offset??32),ccEnabled:o.enabled!==!1,ccMessage:e(o.message),ccAcceptAll:e(o.acceptAllText,"Accept All"),ccRejectAll:e(o.rejectAllText,"Reject All"),ccCustomize:e(o.customizeText,"Customize"),ccSavePrefs:e(o.savePreferencesText,"Save Preferences"),ccPrivacyText:e(o.privacyPolicyText,"Privacy Policy"),ccPrivacyUrl:e(o.privacyPolicyUrl),ccCookieText:e(o.cookiePolicyText,"Cookie Policy"),ccCookieUrl:e(o.cookiePolicyUrl),ccPosition:e(o.position,"bottom"),ccLayout:e(o.layout,"bar"),ccTheme:e(o.theme,"dark"),ccShowFunctional:o.showFunctional!==!1,ccShowAnalytics:o.showAnalytics!==!1,ccShowMarketing:o.showMarketing!==!1,ccVersion:e(o.consentVersion,"1.0"),ccSettingsLink:o.showSettingsLink!==!1,ccSettingsLinkText:e(o.settingsLinkText,"Cookie settings"),bcEnabled:n.enabled===!0,bcHomeLabel:e(n.homeLabel,"Home"),bcPosition:BREADCRUMB_POSITIONS.includes(n.position)?n.position:"TL",bcOffsetX:e(n.offsetX??8),bcOffsetY:e(n.offsetY??8),...motionFromSettings(t)}}export function payloadFromForm(t,a={},{adminHomeReady:r=!0}={}){const o=s=>e(s).trim(),n=motionFromForm(t);return{title:o(t.title),tagline:o(t.tagline),baseUrl:o(t.siteUrl).replace(/\/+$/,""),...r&&{adminHome:o(t.adminHome)||"/"},layoutOptions:{spacerSize:i(t.spacerSize,40)||40},bodyClass:o(t.bodyClass),assistant:{context:o(t.aiContext),rules:o(t.aiRules)},adminAssistant:{enabled:t.adminAssistantEnabled===!0,name:o(t.adminAssistantName)||"Della",character:o(t.adminAssistantCharacter),context:o(t.adminAssistantContext),rules:o(t.adminAssistantRules)},characters:{enabled:t.charactersEnabled!==!1,animated:t.charactersAnimated!==!1,launchers:t.charactersLaunchers!==!1,chats:t.charactersChats!==!1,builders:t.charactersBuilders!==!1,dot:t.charactersDot!==!1,daisy:t.charactersDaisy!==!1},brand:{...a.brand,enabled:t.brandEnabled!==!1,text:o(t.brandText),logo:o(t.brandLogo),icon:o(t.brandIcon),url:o(t.brandUrl)||"/"},favicon:o(t.favicon),adminBrand:{...a.adminBrand,enabled:t.adminBrandEnabled!==!1,title:o(t.adminBrandTitle),logo:o(t.adminBrandLogo),logoDark:o(t.adminBrandLogoDark),icon:o(t.adminBrandIcon)},footer:{copyright:o(t.footerCopyright),layout:FOOTER_LAYOUTS.includes(t.footerLayout)?t.footerLayout:"auto",blurb:o(t.footerBlurb),blocks:footerBlockNames(t.footerBlocks),links:a.footer?.links||[],showMotionToggle:n.enabled,motionDefault:n.default,motionControl:n.control,class:o(t.footerClass),socialClass:o(t.footerSocialClass),look:FOOTER_LOOKS.includes(t.footerLook)?t.footerLook:"",cta:{text:o(t.footerCtaText),highlight:o(t.footerCtaHighlight),url:o(t.footerCtaUrl),sub:o(t.footerCtaSub)},watermark:o(t.footerWatermark),status:o(t.footerStatus),facts:String(t.footerFacts??"").split(`
3
+ `).map(s=>s.trim()).filter(Boolean).slice(0,FOOTER_FACTS_MAX),tagline:o(t.footerTagline),email:o(t.footerEmail),address:o(t.footerAddress),gradient:{from:o(t.footerGradFrom),to:o(t.footerGradTo)}},social:{twitter:o(t.socialTwitter),facebook:o(t.socialFacebook),instagram:o(t.socialInstagram),linkedin:o(t.socialLinkedin),github:o(t.socialGithub),youtube:o(t.socialYoutube)},smtp:{host:o(t.smtpHost),port:i(t.smtpPort,587)||587,user:o(t.smtpUser),pass:e(t.smtpPass),secure:t.smtpSecure===!0,allowInsecureTLS:t.smtpInsecureTLS===!0,fromAddress:o(t.smtpFromAddress),fromName:o(t.smtpFromName)},backToTop:{enabled:t.bttEnabled===!0,scrollThreshold:i(t.bttThreshold,300),position:e(t.bttPosition)||"bottom-right",offset:i(t.bttOffset,32),bottomOffset:i(t.bttBottomOffset,32),label:o(t.bttLabel),smooth:t.bttSmooth===!0},goToBottom:{enabled:t.gtbEnabled===!0,scrollThreshold:i(t.gtbThreshold,300),position:e(t.gtbPosition)||"bottom-right",offset:i(t.gtbOffset,32),bottomOffset:i(t.gtbBottomOffset,32),label:o(t.gtbLabel),smooth:t.gtbSmooth===!0},cookieConsent:{enabled:t.ccEnabled===!0,message:o(t.ccMessage),acceptAllText:o(t.ccAcceptAll),rejectAllText:o(t.ccRejectAll),customizeText:o(t.ccCustomize),savePreferencesText:o(t.ccSavePrefs),privacyPolicyText:o(t.ccPrivacyText),privacyPolicyUrl:o(t.ccPrivacyUrl),cookiePolicyText:o(t.ccCookieText),cookiePolicyUrl:o(t.ccCookieUrl),position:e(t.ccPosition)||"bottom",layout:e(t.ccLayout)||"bar",theme:e(t.ccTheme)||"dark",showFunctional:t.ccShowFunctional===!0,showAnalytics:t.ccShowAnalytics===!0,showMarketing:t.ccShowMarketing===!0,consentVersion:o(t.ccVersion)||"1.0",showSettingsLink:t.ccSettingsLink===!0,settingsLinkText:o(t.ccSettingsLinkText)||"Cookie settings"},breadcrumbs:{enabled:t.bcEnabled===!0,homeLabel:o(t.bcHomeLabel)||"Home",position:BREADCRUMB_POSITIONS.includes(t.bcPosition)?t.bcPosition:"TL",offsetX:i(t.bcOffsetX,8),offsetY:i(t.bcOffsetY,8)},motion:n}}export function siteUrlError(t){const a=e(t).trim().replace(/\/+$/,"");return a?/^https?:\/\//i.test(a)?/^https?:\/\/([a-z0-9.\-]+|\[[0-9a-f:.]+\])(:\d{1,5})?$/i.test(a)?"":"Just the address, like https://example.com - no page path after it.":"Start with https:// (or http://).":""}const d=t=>typeof t=="boolean"?t:e(t);export function snapshot(t){return JSON.stringify(Object.keys(t).sort().map(a=>[a,d(t[a])]))}export function changedTabs(t,a){const r=[];for(const[o,n]of Object.entries(TAB_FIELDS))n.some(s=>d(t[s])!==d(a[s]))&&r.push(o);return r}export function draftOf(t){return Object.fromEntries(Object.entries(t).filter(([a])=>!SECRET_FIELDS.includes(a)))}const g={footerMotionToggle:"mtEnabled",footerMotionDefault:"mtDefault",footerMotionControl:"mtControl"};export function formFromDraft(t,a={}){const r={...a};for(const[n,s]of Object.entries(g))n in r&&!(s in r)&&(r[s]=r[n]),delete r[n];const o={...t};for(const[n,s]of Object.entries(r))n in o&&!SECRET_FIELDS.includes(n)&&(o[n]=s);return o}export function settingsProblems(t,a={}){const r=[];return e(t.smtpHost).trim()?e(t.smtpFromAddress).trim()||r.push({tone:"warn",tab:"email",text:"No From address - mail has no sender and many servers refuse it."}):r.push({tone:"danger",tab:"email",text:"No SMTP host - mail goes to a throwaway test inbox and reaches no one (password resets, form notifications)."}),(t.ccEnabled===!0||e(a.googleAnalytics?.measurementId).trim())&&!e(t.ccPrivacyUrl).trim()&&r.push({tone:"warn",tab:"cookies",text:"The cookie banner is on but links to no privacy policy."}),r}export function describeCacheKey(t){const a=/^page:(.*?):m\d+:role([^:]*):/.exec(String(t||""));return a?{path:a[1]||"/",role:a[2]||"anon",page:!0}:{path:String(t||""),role:"",page:!1}}export function expiresIn(t,a=Date.now()){if(t==null)return"no expiry";const r=t-a;return r<=0?"expired":r<6e4?`${Math.round(r/1e3)}s`:r<36e5?`${Math.round(r/6e4)}m`:`${Math.round(r/36e5)}h`}export function footerForm(t={}){const a=formFromSettings(t);return Object.fromEntries(TAB_FIELDS.footer.map(r=>[r,a[r]]))}export function footerPayload(t){const{footer:a,social:r}=payloadFromForm(t);return delete a.links,delete a.showMotionToggle,delete a.motionDefault,delete a.motionControl,{footer:a,social:r}}export function siteSettingsForm(t={}){return Object.fromEntries(Object.entries(formFromSettings(t)).filter(([a])=>!TAB_FIELDS.footer.includes(a)&&!u.includes(a)))}export function siteSettingsPayload(...t){const{footer:a,social:r,favicon:o,backToTop:n,goToBottom:s,breadcrumbs:l,motion:m,...f}=payloadFromForm(...t);return f}export const APPEARANCE_TABS=["favicon","pageNavigation","breadcrumbs","motion","search"];const u=APPEARANCE_TABS.flatMap(t=>TAB_FIELDS[t]||[]);export function appearanceForm(t={}){const a=formFromSettings(t);return Object.fromEntries(u.map(r=>[r,a[r]]))}export function appearancePayload(t){const{favicon:a,backToTop:r,goToBottom:o,breadcrumbs:n,motion:s}=payloadFromForm(t);return{favicon:a,backToTop:r,goToBottom:o,breadcrumbs:n,motion:s}}
@@ -89,6 +89,17 @@
89
89
  </div>
90
90
  </div>
91
91
  </div>
92
+ <div class="stx-card dm-settings-section">
93
+ <div class="stx-card-title dm-settings-section-title"><span data-icon="sparkles" data-icon-size="16" aria-hidden="true"></span>Admin assistant</div>
94
+ <div class="stx-setting"><label class="form-label" for="stx-admin-assistant">Enable AI assistant inside admin</label><input id="stx-admin-assistant" type="checkbox" class="form-switch" data-model="adminAssistantEnabled.value"></div>
95
+ <p class="text-muted">A shared help and drafting panel for signed-in users. It follows their tool access and cannot save, publish or send. Uses the site's existing AI service and allowance.</p>
96
+ <div class="stx-grid" data-bind-hidden="!adminAssistantEnabled.value">
97
+ <div><label class="form-label" for="stx-admin-assistant-name">Assistant name</label><input id="stx-admin-assistant-name" class="form-input" maxlength="40" data-model="adminAssistantName.value"></div>
98
+ <div><label class="form-label" for="stx-admin-assistant-character">Character artwork</label><select id="stx-admin-assistant-character" class="form-select" data-model="adminAssistantCharacter.value"><option value="">No character</option><option value="della">Della</option><option value="dot">Dot</option><option value="daisy">Daisy</option></select></div>
99
+ <div class="stx-wide"><label class="form-label" for="stx-admin-assistant-context">Admin assistant context</label><textarea id="stx-admin-assistant-context" class="form-input" rows="3" maxlength="4000" data-model="adminAssistantContext.value"></textarea></div>
100
+ <div class="stx-wide"><label class="form-label" for="stx-admin-assistant-rules">Admin assistant rules</label><textarea id="stx-admin-assistant-rules" class="form-input" rows="3" maxlength="2000" data-model="adminAssistantRules.value"></textarea></div>
101
+ </div>
102
+ </div>
92
103
  <div class="stx-card dm-settings-section">
93
104
  <div class="stx-card-title dm-settings-section-title"><span data-icon="smile" data-icon-size="16" aria-hidden="true"></span>Builders and Bots</div>
94
105
  <p class="text-muted">Choose where character artwork appears. Select Use Della in a chat launcher, or Use Dot and Use Daisy in their tools. Hiding artwork keeps the tools and chats working.</p>
@@ -1,4 +1,4 @@
1
- import{apiRequest as V,api as ye}from"../api.js";import{addBannerAction as we}from"../lib/plugin-chrome.js";import{helpPopovers as ke}from"../lib/help-popover.js";import{onceClosed as Ve,openMenuAt as Se,sidebarCount as Ce,viewLifetime as Ge}from"../lib/tool-kit.js";import{rowPlaceKeeper as Je}from"../lib/menu-drag.js";import{FILTERS as Qe,LAUNCHER_POSITION_LABEL as Te,arrangeLaunchers as Ze,blankLauncher as ea,checkLauncherForm as aa,countLaunchers as ta,duplicateLauncher as la,formFromLauncher as na,launcherFromForm as sa,launcherRow as ia,moveItem as oa,previewSpot as da}from"../lib/launchers-arrange.js";import{LAUNCHER_LIMITS as s,LAUNCHER_TOKENS as G,launcherChatAccentCss as ra,launcherColourCss as $e,launcherHref as J}from"../../../public/js/launcher-settings.mjs";const Me=/^#\/launchers\/?(\?.*)?$/,Ee="#/launchers",Q="launchers.filter",D="launchers.draft",ca=`
1
+ import{apiRequest as G,api as ye}from"../api.js";import{addBannerAction as we}from"../lib/plugin-chrome.js";import{helpPopovers as ke}from"../lib/help-popover.js";import{onceClosed as Ge,openMenuAt as Se,sidebarCount as Ce,viewLifetime as Ve}from"../lib/tool-kit.js";import{rowPlaceKeeper as Je}from"../lib/menu-drag.js";import{FILTERS as Qe,LAUNCHER_POSITION_LABEL as Te,arrangeLaunchers as Ze,blankLauncher as ea,checkLauncherForm as aa,countLaunchers as ta,duplicateLauncher as la,formFromLauncher as na,launcherFromForm as sa,launcherRow as ia,moveItem as oa,previewSpot as da}from"../lib/launchers-arrange.js";import{LAUNCHER_LIMITS as s,LAUNCHER_TOKENS as V,launcherChatAccentCss as ra,launcherColourCss as $e,launcherHref as J}from"../../../public/js/launcher-settings.mjs";const Me=/^#\/launchers\/?(\?.*)?$/,Ee="#/launchers",Q="launchers.filter",U="launchers.draft",ca=`
2
2
  <div class="lnx-row" data-id="{{id}}" tabindex="0" data-bind-class="rowCls">
3
3
  <span class="lnx-grip" title="Drag to reorder" aria-hidden="true"><span data-icon="menu" data-icon-size="14"></span></span>
4
4
  <span class="lnx-disc" data-bind-class="pill && 'is-pill'" data-bind-style="discStyle" aria-hidden="true"><span data-icon="{{icon}}"></span><span data-bind-hidden="!pill">{{label}}</span></span>
@@ -9,7 +9,7 @@ import{apiRequest as V,api as ye}from"../api.js";import{addBannerAction as we}fr
9
9
  </span>
10
10
  <label class="lnx-switch" title="On or off"><input type="checkbox" class="form-switch lnx-toggle" data-bind-checked="on" aria-label="{{name}} on or off"></label>
11
11
  <button type="button" class="lnx-kebab" aria-label="Actions for {{name}}" title="Actions">\u22EE</button>
12
- </div>`,c={triggerStyle:[["icon","Disc - icon only"],["icon-text","Pill - icon and label"]],tooltipMode:[["label","The label"],["custom","Words of its own"],["off","None"]],actionType:[["modal","A page, form or block, in a modal"],["slideover","A page, form or block, in a slideover"],["chat","A chat"]],kind:[["page","Page"],["form","Form"],["block","Block"]],modalSize:[["xs","Extra small (320px)"],["sm","Small (400px)"],["md","Medium (600px)"],["lg","Large (800px)"],["xl","Extra large (1140px)"],["xxl","Huge (1400px)"],["full","Nearly full width (90%)"],["screen","Full screen"],["custom","Custom\u2026"]],modalHeight:[["auto","Fit the page"],["sm","Short (40% of the window)"],["md","Medium (60%)"],["lg","Tall (80%)"],["full","Nearly full height (90%)"],["custom","Custom\u2026"]],widthUnit:[["px","px"],["%","% of window"]],heightUnit:[["vh","% of window"],["px","px"]],side:[["right","Right"],["left","Left"]],width:[["sm","Narrow (360px)"],["md","Medium (480px)"],["lg","Wide (640px)"],["xl","Extra wide (860px)"]],devices:[["all","Phones and desktops"],["desktop","Desktops only"],["phone","Phones only"]],pagesMode:[["all","Every page"],["only","Only these pages"],["except","Every page except these"]],audience:[["everyone","Everyone"],["signed-in","Signed-in people only"],["signed-out","Signed-out visitors only"]],askDetails:[["offline","When nobody is there to answer"],["always","Before the chat starts"],["never","Never"]],times:[["time","The time (09:42)"],["datetime","The date and time (10 Nov, 09:42)"],["none","Nothing"]],personButton:[["below","A button under the conversation"],["header","An icon in the chat heading"]],chatSize:[["sm","Small (340 x 500)"],["md","Medium (400 x 600)"],["lg","Large (480 x 720)"],["custom","Custom\u2026"]],background:[["","Theme (primary)"],...G.map(i=>[i,i.charAt(0).toUpperCase()+i.slice(1)]),["custom","Custom hex\u2026"]],foreground:[["","Theme (reads on the background)"],...G.map(i=>[i,i.charAt(0).toUpperCase()+i.slice(1)]),["custom","Custom hex\u2026"]]},ha=["TL","TC","TR","ML","","MR","BL","BC","BR"],h=i=>i.map(([p,A])=>`<option value="${p}">${A}</option>`).join(""),Ae=i=>ha.map(p=>p?`<button type="button" data-pos="${p}" data-bind-class="${i}.value === '${p}' && 'is-on'" title="${Te[p]}" aria-label="${Te[p]}">${p}</button>`:'<button type="button" class="lnx-corner-mid" tabindex="-1" aria-hidden="true"></button>').join(""),pa=`
12
+ </div>`,c={triggerStyle:[["icon","Disc - icon only"],["icon-text","Pill - icon and label"]],tooltipMode:[["label","The label"],["custom","Words of its own"],["off","None"]],actionType:[["modal","A page, form or block, in a modal"],["slideover","A page, form or block, in a slideover"],["chat","A chat"]],kind:[["page","Page"],["form","Form"],["block","Block"]],modalSize:[["xs","Extra small (320px)"],["sm","Small (400px)"],["md","Medium (600px)"],["lg","Large (800px)"],["xl","Extra large (1140px)"],["xxl","Huge (1400px)"],["full","Nearly full width (90%)"],["screen","Full screen"],["custom","Custom\u2026"]],modalHeight:[["auto","Fit the page"],["sm","Short (40% of the window)"],["md","Medium (60%)"],["lg","Tall (80%)"],["full","Nearly full height (90%)"],["custom","Custom\u2026"]],widthUnit:[["px","px"],["%","% of window"]],heightUnit:[["vh","% of window"],["px","px"]],side:[["right","Right"],["left","Left"]],width:[["sm","Narrow (360px)"],["md","Medium (480px)"],["lg","Wide (640px)"],["xl","Extra wide (860px)"]],devices:[["all","Phones and desktops"],["desktop","Desktops only"],["phone","Phones only"]],pagesMode:[["all","Every page"],["only","Only these pages"],["except","Every page except these"]],audience:[["everyone","Everyone"],["signed-in","Signed-in people only"],["signed-out","Signed-out visitors only"]],askDetails:[["offline","When nobody is there to answer"],["always","Before the chat starts"],["never","Never"]],times:[["time","The time (09:42)"],["datetime","The date and time (10 Nov, 09:42)"],["none","Nothing"]],personButton:[["below","A button under the conversation"],["header","An icon in the chat heading"]],chatSize:[["sm","Small (340 x 500)"],["md","Medium (400 x 600)"],["lg","Large (480 x 720)"],["custom","Custom\u2026"]],background:[["","Theme (primary)"],...V.map(i=>[i,i.charAt(0).toUpperCase()+i.slice(1)]),["custom","Custom hex\u2026"]],foreground:[["","Theme (reads on the background)"],...V.map(i=>[i,i.charAt(0).toUpperCase()+i.slice(1)]),["custom","Custom hex\u2026"]]},ha=["TL","TC","TR","ML","","MR","BL","BC","BR"],h=i=>i.map(([p,A])=>`<option value="${p}">${A}</option>`).join(""),Ae=i=>ha.map(p=>p?`<button type="button" data-pos="${p}" data-bind-class="${i}.value === '${p}' && 'is-on'" title="${Te[p]}" aria-label="${Te[p]}">${p}</button>`:'<button type="button" class="lnx-corner-mid" tabindex="-1" aria-hidden="true"></button>').join(""),pa=`
13
13
  <div class="lnx-form">
14
14
  <div class="lnx-section">
15
15
  <h6><span data-icon="message-circle" data-icon-size="14"></span> The disc</h6>
@@ -140,6 +140,10 @@ import{apiRequest as V,api as ye}from"../api.js";import{addBannerAction as we}fr
140
140
  <div class="lnx-field" style="grid-column: 1 / -1">
141
141
  <label class="lnx-check"><input id="lnx-f-della" type="checkbox" class="form-switch" data-model="useDella.value"> Use Della</label>
142
142
  <small>Use Della's name, portrait and animated character. Site Settings controls visibility and motion. Your custom name and picture are kept when this is switched off.</small>
143
+ <div data-bind-hidden="!useDella.value">
144
+ <label class="form-label" for="lnx-f-charname">Call her <span data-help-title="Call her" data-help="Leave empty and she is Della. Give her another name for this chat - Dash on a jobs board, say - and that name is shown and used in her answers, with Della's artwork."></span></label>
145
+ <input id="lnx-f-charname" class="form-input" maxlength="${s.botNameMax}" placeholder="Della" data-model="characterName.value">
146
+ </div>
143
147
  <label class="form-label" for="lnx-f-greeting">Greeting <span data-help-title="Greeting" data-help="The first message a visitor sees when the chat opens. Words in braces are filled in from the visitor's own clock: {greeting} (Good morning / afternoon / evening), {timeofday} (morning / afternoon / evening), {day} (Monday...), {date} (10 November), {time} (09:42), {botname} and {site}. For example: {greeting}! I'm {botname} - how can I help this {timeofday}?"></span></label>
144
148
  <textarea id="lnx-f-greeting" class="form-input" rows="2" maxlength="${s.greetingMax}" data-model="greeting.value"></textarea>
145
149
  </div>
@@ -301,4 +305,4 @@ import{apiRequest as V,api as ye}from"../api.js";import{addBannerAction as we}fr
301
305
  <button type="button" class="btn btn-sm btn-primary" data-on-click="save" data-bind-disabled="cannot.value">
302
306
  <span data-icon="check" data-icon-size="13"></span> <span data-bind-text="saveText"></span></button>
303
307
  </div>
304
- </div>`,Z=i=>String(i??"").replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;");function ua(i){const p=document.createElement("template");return p.innerHTML=i.trim(),p.content.firstElementChild}const T=i=>i?G.includes(i)?i:"custom":"",x=Ge(Me),ee={list:()=>V("/launchers/items",{method:"GET"}),save:i=>V("/launchers/items",{method:"PUT",body:JSON.stringify({launchers:i})}),patch:(i,p)=>V(`/launchers/items/${encodeURIComponent(i)}`,{method:"PATCH",body:JSON.stringify(p)})};export const launchersView={templateUrl:"/admin/js/templates/launchers.html",async onMount(i){x.reset();const p=i.get(0).querySelector(".lnx")||i.get(0),A=()=>p.isConnected&&Me.test(location.hash),u=M.observable([]),ae=M.observable(!0),F=M.observable(""),B=M.observable(!0);let te="all";try{te=Qe.includes(S.get(Q))?S.get(Q):"all"}catch{}const $=M.observable(te),W=M.observable("");x.add(M.effect(()=>{const a=$.value;try{S.set(Q,a)}catch{}}));const K=M.observable([]);x.add(M.effect(()=>{K.value=Ze(u.value,{filter:$.value,query:W.value}).map(ia)}));const Oe=M.computed(()=>ta(u.value)),ze=M.computed(()=>u.value.length?"No launchers match.":"No launchers yet - New launcher in the banner makes one."),le=M.computed(()=>u.value.length>1&&($.value!=="all"||!!W.value.trim())),O=a=>u.peek().find(t=>t.id===a);let L=null;const Ne=async()=>{if(L)return L;const[a,t]=await Promise.all([ye.forms.list().catch(()=>[]),ye.blocks.list().catch(()=>[])]);return L={forms:(Array.isArray(a)?a:[]).map(l=>({value:l.slug,text:l.title?`${l.title} (${l.slug})`:l.slug})),blocks:(Array.isArray(t)?t:[]).map(l=>({value:l.name,text:l.description?`${l.name} - ${l.description}`:l.name}))},L};async function Le(){try{const a=await ee.list();if(!A())return;u.value=Array.isArray(a?.launchers)?a.launchers:[],F.value="",B.value=!0}catch(a){const t=String(a?.message||a);/switched off/i.test(t)?B.value=!1:F.value=`Could not load the launchers: ${t}`}finally{ae.value=!1}}async function P(a,t){try{const l=await ee.save(a);return A()&&(u.value=l.launchers),Ce(Ee),t&&E.toast(t,{type:"success"}),l.launchers}catch(l){return E.toast(`Not saved: ${l.message||l}`,{type:"error"}),null}}async function q(a,t){try{const l=await ee.patch(a.id,{enabled:t});u.value=u.peek().map(m=>m.id===a.id?l.launcher:m),Ce(Ee),E.toast(`"${a.name}" ${t?"switched on":"switched off"}.`,{type:"success",duration:2e3})}catch(l){E.toast(`Not changed: ${l.message||l}`,{type:"error"}),u.value=[...u.peek()]}}async function Pe(a){const t=u.peek(),l=t.findIndex(o=>o.id===a.id),m=la(a,t);await P([...t.slice(0,l+1),m,...t.slice(l+1)],`Duplicated as "${m.name}" - switched off until you are ready.`)}async function Ie(a){await E.confirm(`Delete the launcher "${Z(a.name)}"? It goes from every page. This cannot be undone.`)&&await P(u.peek().filter(t=>t.id!==a.id),"Launcher deleted.")}function He(a){if(a.action.type==="chat"){E.toast("A chat has nothing to open on its own - see it on any page it shows on.",{type:"info"});return}if(!a.action.ref){E.toast("Choose what it opens first.",{type:"warning"});return}window.open(`/_launcher/${encodeURIComponent(a.id)}`,"_blank","noopener")}function Re(a){const t=O(a);return t?[{header:t.name},{label:"Edit",icon:"edit",action:()=>z(t.id)},t.enabled?{label:"Switch off",icon:"pause",action:()=>q(t,!1)}:{label:"Switch on",icon:"play",action:()=>q(t,!0)},{label:"Open what it shows",icon:"external-link",action:()=>He(t)},{type:"divider"},{label:"Duplicate",icon:"copy",action:()=>Pe(t)},{type:"divider"},{label:"Delete\u2026",icon:"trash",danger:!0,action:()=>Ie(t)}]:[]}let w=null;const Y=new Set;function Ue(a,t,l){const m=a.close.bind(a);let o=!1,b=!1;return a.close=async r=>{if(!o&&r!==!0&&t()){if(b)return;b=!0;const N=await E.confirm(l);if(b=!1,!N)return}return o=!0,m()},()=>{o=!0}}async function z(a=null,t=null){const l=a?O(a):null;if(a&&!l){E.toast("That launcher is no longer there.",{type:"warning"});return}if(w){E.toast("Finish the launcher you have open first.",{type:"info"});return}const m=!l,o=na(l||ea(u.peek())),b={...o,refPage:o.kind==="page"?o.ref:"",refForm:o.kind==="form"?o.ref:"",refBlock:o.kind==="block"?o.ref:"",bgChoice:T(o.background),bgHex:T(o.background)==="custom"?o.background:"",fgChoice:T(o.text),fgHex:T(o.text)==="custom"?o.text:"",accentChoice:T(o.accent),accentHex:T(o.accent)==="custom"?o.accent:"",accentTextChoice:T(o.accentText),accentTextHex:T(o.accentText)==="custom"?o.accentText:"",...t||{}};delete b.ref,delete b.background,delete b.text,delete b.accent,delete b.accentText;const r=Object.fromEntries(Object.entries(b).map(([e,d])=>[e,M.observable(d)])),N=()=>Object.fromEntries(Object.keys(r).map(e=>[e,r[e].peek()])),de=e=>JSON.stringify(Object.fromEntries(Object.entries(e).map(([d,n])=>[d,typeof n=="boolean"?n:String(n??"")]))),Be=de(b),re=()=>de(N())!==Be||!!t,ce=e=>{const d=e.actionType==="chat"?"page":e.kind;return{...e,kind:d,ref:d==="form"?e.refForm:d==="block"?e.refBlock:String(e.refPage||"").trim(),background:e.bgChoice==="custom"?String(e.bgHex||"").trim():e.bgChoice,text:e.fgChoice==="custom"?String(e.fgHex||"").trim():e.fgChoice,accent:e.accentChoice==="custom"?String(e.accentHex||"").trim():e.accentChoice,accentText:e.accentTextChoice==="custom"?String(e.accentTextHex||"").trim():e.accentTextChoice}},H=()=>ce(Object.fromEntries(Object.keys(r).map(e=>[e,r[e].value]))),j=M.computed(()=>aa(H())),R=M.observable(!1),he=(e,d)=>{const n=da({...e,size:Number(e.size),offsetX:Number(e.offsetX),offsetY:Number(e.offsetY),phoneSize:Number(e.phoneSize),phoneOffsetX:Number(e.phoneOffsetX),phoneOffsetY:Number(e.phoneOffsetY)},d?{vw:120,vh:220,scale:.5,phone:!0}:{vw:320,vh:200,scale:.5}),f=e.triggerStyle==="icon-text"&&!d;return{left:`${n.left}px`,top:`${n.top}px`,height:`${n.size}px`,width:f?"auto":`${n.size}px`,padding:f?"0 6px":"0","border-radius":f?"999px":`${Math.round(Math.min(Number(e.radius),Number(e.size)/2)/Number(e.size)*100)}%`,"--lnx-bg":$e(e.background)||"var(--dm-primary)","--lnx-fg":$e(e.text)||"var(--dm-primary-text)"}},pe={...r,saving:R,err:M.computed(()=>j.value.errors),warn:M.computed(()=>j.value.warnings),cannot:M.computed(()=>R.value||Object.keys(j.value.errors).length>0),maxRadius:M.computed(()=>Math.floor(Number(r.size.value)/2)),previewStyle:M.computed(()=>he(H(),!1)),phonePreviewStyle:M.computed(()=>he(H(),!0)),botInitial:M.computed(()=>(String(r.botName.value||"").trim()[0]||"?").toUpperCase()),avatarPreview:M.computed(()=>{const e=ra(H());return{background:e.accent||"var(--dm-primary)",color:e.accentText||"var(--dm-primary-text, #fff)"}}),saveText:m?"Create launcher":"Save",linkHref:m?"":J(l.id),linkText:m?"Create the launcher first - then it has a link":J(l.id)},We=M.effect(()=>{const e=Math.floor(Number(r.size.value)/2);Number(r.radius.peek())>e&&(r.radius.value=e)}),ue=(e,d,n)=>{let f=e.peek();return M.effect(()=>{const C=e.value;C!==f&&(f=C,d.value=n(C))})},Ke=ue(r.widthUnit,r.customWidth,e=>e==="%"?90:900),qe=ue(r.heightUnit,r.customHeight,e=>e==="px"?600:70),k=E.slideover({title:m?"New launcher":`Edit ${Z(l.name)}`,size:"lg",position:"right"}),v=ua(pa),me=await Ne().catch(()=>({forms:[],blocks:[]})),fe=(e,d,n)=>{const f=document.createElement("option");f.value="",f.textContent=d.length?"Choose\u2026":"None yet",e.appendChild(f);const C=n&&!d.some(U=>U.value===n)?[...d,{value:n,text:`${n} (missing)`}]:d;for(const U of C){const X=document.createElement("option");X.value=U.value,X.textContent=U.text,e.appendChild(X)}};fe(v.querySelector(".lnx-form-select"),me.forms,b.refForm),fe(v.querySelector(".lnx-block-select"),me.blocks,b.refBlock);let be=()=>{};async function ve(){if(!pe.cannot.peek()){R.value=!0;try{const e=sa(ce(N()),l?.id||""),d=u.peek(),n=m?[...d,e]:d.map(C=>C.id===l.id?e:C);if(!await P(n,m?`Created "${e.name}".`:"Saved."))return;be(),k.close()}finally{R.value=!1}}}k.element.appendChild(v);const Ye=ke(v),je=M.applyBindings(pe,v,{methods:{save:ve,cancel:()=>k.close()}}),_e=e=>{(e.ctrlKey||e.metaKey)&&e.key==="Enter"&&(e.preventDefault(),ve())};v.addEventListener("keydown",_e);const xe=async e=>{const d=e.target.closest(".lnx-corners button[data-pos]");if(d){const n=d.closest(".lnx-corners-phone")?"phonePosition":"position";r[n].value=d.dataset.pos;return}if(e.target.closest(".lnx-pick-icon")){const{openIconPicker:n}=await import("../lib/card-builder.js");n(f=>{r.icon.value=f});return}if(e.target.closest(".lnx-copy-link")&&!m){let n=!1;try{n=await _.copyToClipboard(J(l.id))!==!1}catch{}E.toast(n?"Link copied.":"Could not copy - select the link and copy it.",{type:n?"success":"warning"});return}if(e.target.closest(".lnx-pick-avatar")){const{pickMedia:n}=await import("../lib/media-picker.js"),f=await n({title:"Choose the bot's picture",current:r.avatar.peek()});f&&(r.avatar.value=String(f).replace(/^https?:\/\/[^/]+/i,""));return}if(e.target.closest(".lnx-clear-avatar")){r.avatar.value="";return}if(e.target.closest(".lnx-pick-page")){const{openPagePicker:n}=await import("../lib/page-picker.js");n(f=>{r.refPage.value=f})}};v.addEventListener("click",xe);const Xe=M.effect(()=>{const e=r.icon.value;v.querySelectorAll(".lnx-preview-disc").forEach(d=>{const n=document.createElement("span");n.setAttribute("data-icon",e||"message-circle"),n.className="lnx-preview-icon",d.querySelector(".lnx-preview-icon")?.replaceWith(n),I.scan(d)})}),ge={id:l?.id??null,dirty:re,values:N};w=ge,Y.add(k),Ve(k,()=>{je.dispose(),Ye(),We?.(),Ke?.(),qe?.(),Xe?.(),v.removeEventListener("click",xe),Y.delete(k),w===ge&&(w=null)}),be=Ue(k,re,"Discard the changes you have not saved?"),I.scan(v),k.open(),v.querySelector("#lnx-f-name")?.focus()}const g=p.querySelector(".lnx-list");g.innerHTML=ca;const De=M.applyBindings({launchers:u,loading:ae,loadError:F,toolOn:B,filter:$,query:W,rows:K,counts:Oe,emptyText:ze,dragNote:le},p,{methods:{showAll:()=>{$.value="all"},showOn:()=>{$.value="on"},showOff:()=>{$.value="off"}}});x.add(()=>De.dispose()),x.add(ke(p,{position:"bottom"})),x.add(M.effect(()=>{K.value,requestAnimationFrame(()=>{p.isConnected&&I.scan(g)})}));const Fe=E.contextMenu(g,{cursor:"glyph",match:".lnx-row",inherit:!1,density:"compact",items:a=>Re(a.dataset.id)});x.add(()=>Fe?.destroy?.());const ne=a=>{const t=a.target.closest(".lnx-row");if(!t||a.target.closest(".lnx-switch"))return;const l=a.target.closest(".lnx-kebab");if(l){Se(l);return}z(t.dataset.id)},se=a=>{const t=a.target.closest(".lnx-toggle"),l=t?.closest(".lnx-row"),m=l&&O(l.dataset.id);m&&q(m,t.checked)},ie=a=>{const t=a.target.closest(".lnx-row");t&&(a.key==="F10"&&a.shiftKey?(a.preventDefault(),Se(t)):a.key==="Enter"&&a.target===t&&z(t.dataset.id))};if(g.addEventListener("click",ne),g.addEventListener("change",se),g.addEventListener("keydown",ie),x.add(()=>{g.removeEventListener("click",ne),g.removeEventListener("change",se),g.removeEventListener("keydown",ie)}),typeof E.sortable=="function"){const a=Je(),t=E.sortable(g,{items:".lnx-row",handle:".lnx-grip",key:null,keyboard:!1,onStart:a.start,onEnd:({item:l})=>a.restore(l),onSort:({item:l,from:m,to:o})=>{if(a.restore(l),le.peek()){E.toast("Clear the search and show All to reorder.",{type:"info"}),u.value=[...u.peek()];return}const b=oa(u.peek(),m,o);u.value=b,P(b)}});x.add(()=>t.destroy())}we(i,{id:"launchers-new",icon:"plus",title:"New launcher",onClick:()=>z()}),we(i,{id:"launchers-chats",icon:"message-square",title:"Chats - the conversations from chat launchers",onClick:()=>{location.hash="#/launchers/chats"}});const oe=a=>{w?.dirty()&&(a.preventDefault(),a.returnValue="")};if(window.addEventListener("beforeunload",oe),x.add(()=>window.removeEventListener("beforeunload",oe)),x.add(()=>{if(w?.dirty())try{S.set(D,{id:w.id,values:w.values(),at:new Date().toISOString()})}catch{}[...Y].forEach(a=>{try{a.close(!0)}catch{}})}),I.scan(p),await Le(),!A())return;let y=null;try{y=S.get(D)}catch{}if(y?.values){try{S.remove?S.remove(D):S.set(D,null)}catch{}const a=y.id&&O(y.id)?`your changes to "${Z(O(y.id).name)}"`:"the new launcher you started";await E.confirm(`You left ${a} unsaved. Pick up where you left off?`)&&A()&&z(y.id&&O(y.id)?y.id:null,y.values)}}};
308
+ </div>`,Z=i=>String(i??"").replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;");function ua(i){const p=document.createElement("template");return p.innerHTML=i.trim(),p.content.firstElementChild}const T=i=>i?V.includes(i)?i:"custom":"",x=Ve(Me),ee={list:()=>G("/launchers/items",{method:"GET"}),save:i=>G("/launchers/items",{method:"PUT",body:JSON.stringify({launchers:i})}),patch:(i,p)=>G(`/launchers/items/${encodeURIComponent(i)}`,{method:"PATCH",body:JSON.stringify(p)})};export const launchersView={templateUrl:"/admin/js/templates/launchers.html",async onMount(i){x.reset();const p=i.get(0).querySelector(".lnx")||i.get(0),A=()=>p.isConnected&&Me.test(location.hash),u=M.observable([]),ae=M.observable(!0),F=M.observable(""),B=M.observable(!0);let te="all";try{te=Qe.includes(S.get(Q))?S.get(Q):"all"}catch{}const $=M.observable(te),W=M.observable("");x.add(M.effect(()=>{const a=$.value;try{S.set(Q,a)}catch{}}));const K=M.observable([]);x.add(M.effect(()=>{K.value=Ze(u.value,{filter:$.value,query:W.value}).map(ia)}));const Oe=M.computed(()=>ta(u.value)),ze=M.computed(()=>u.value.length?"No launchers match.":"No launchers yet - New launcher in the banner makes one."),le=M.computed(()=>u.value.length>1&&($.value!=="all"||!!W.value.trim())),O=a=>u.peek().find(t=>t.id===a);let L=null;const Ne=async()=>{if(L)return L;const[a,t]=await Promise.all([ye.forms.list().catch(()=>[]),ye.blocks.list().catch(()=>[])]);return L={forms:(Array.isArray(a)?a:[]).map(l=>({value:l.slug,text:l.title?`${l.title} (${l.slug})`:l.slug})),blocks:(Array.isArray(t)?t:[]).map(l=>({value:l.name,text:l.description?`${l.name} - ${l.description}`:l.name}))},L};async function Le(){try{const a=await ee.list();if(!A())return;u.value=Array.isArray(a?.launchers)?a.launchers:[],F.value="",B.value=!0}catch(a){const t=String(a?.message||a);/switched off/i.test(t)?B.value=!1:F.value=`Could not load the launchers: ${t}`}finally{ae.value=!1}}async function P(a,t){try{const l=await ee.save(a);return A()&&(u.value=l.launchers),Ce(Ee),t&&E.toast(t,{type:"success"}),l.launchers}catch(l){return E.toast(`Not saved: ${l.message||l}`,{type:"error"}),null}}async function q(a,t){try{const l=await ee.patch(a.id,{enabled:t});u.value=u.peek().map(m=>m.id===a.id?l.launcher:m),Ce(Ee),E.toast(`"${a.name}" ${t?"switched on":"switched off"}.`,{type:"success",duration:2e3})}catch(l){E.toast(`Not changed: ${l.message||l}`,{type:"error"}),u.value=[...u.peek()]}}async function Pe(a){const t=u.peek(),l=t.findIndex(o=>o.id===a.id),m=la(a,t);await P([...t.slice(0,l+1),m,...t.slice(l+1)],`Duplicated as "${m.name}" - switched off until you are ready.`)}async function Ie(a){await E.confirm(`Delete the launcher "${Z(a.name)}"? It goes from every page. This cannot be undone.`)&&await P(u.peek().filter(t=>t.id!==a.id),"Launcher deleted.")}function He(a){if(a.action.type==="chat"){E.toast("A chat has nothing to open on its own - see it on any page it shows on.",{type:"info"});return}if(!a.action.ref){E.toast("Choose what it opens first.",{type:"warning"});return}window.open(`/_launcher/${encodeURIComponent(a.id)}`,"_blank","noopener")}function De(a){const t=O(a);return t?[{header:t.name},{label:"Edit",icon:"edit",action:()=>z(t.id)},t.enabled?{label:"Switch off",icon:"pause",action:()=>q(t,!1)}:{label:"Switch on",icon:"play",action:()=>q(t,!0)},{label:"Open what it shows",icon:"external-link",action:()=>He(t)},{type:"divider"},{label:"Duplicate",icon:"copy",action:()=>Pe(t)},{type:"divider"},{label:"Delete\u2026",icon:"trash",danger:!0,action:()=>Ie(t)}]:[]}let w=null;const j=new Set;function Re(a,t,l){const m=a.close.bind(a);let o=!1,b=!1;return a.close=async r=>{if(!o&&r!==!0&&t()){if(b)return;b=!0;const N=await E.confirm(l);if(b=!1,!N)return}return o=!0,m()},()=>{o=!0}}async function z(a=null,t=null){const l=a?O(a):null;if(a&&!l){E.toast("That launcher is no longer there.",{type:"warning"});return}if(w){E.toast("Finish the launcher you have open first.",{type:"info"});return}const m=!l,o=na(l||ea(u.peek())),b={...o,refPage:o.kind==="page"?o.ref:"",refForm:o.kind==="form"?o.ref:"",refBlock:o.kind==="block"?o.ref:"",bgChoice:T(o.background),bgHex:T(o.background)==="custom"?o.background:"",fgChoice:T(o.text),fgHex:T(o.text)==="custom"?o.text:"",accentChoice:T(o.accent),accentHex:T(o.accent)==="custom"?o.accent:"",accentTextChoice:T(o.accentText),accentTextHex:T(o.accentText)==="custom"?o.accentText:"",...t||{}};delete b.ref,delete b.background,delete b.text,delete b.accent,delete b.accentText;const r=Object.fromEntries(Object.entries(b).map(([e,d])=>[e,M.observable(d)])),N=()=>Object.fromEntries(Object.keys(r).map(e=>[e,r[e].peek()])),de=e=>JSON.stringify(Object.fromEntries(Object.entries(e).map(([d,n])=>[d,typeof n=="boolean"?n:String(n??"")]))),Be=de(b),re=()=>de(N())!==Be||!!t,ce=e=>{const d=e.actionType==="chat"?"page":e.kind;return{...e,kind:d,ref:d==="form"?e.refForm:d==="block"?e.refBlock:String(e.refPage||"").trim(),background:e.bgChoice==="custom"?String(e.bgHex||"").trim():e.bgChoice,text:e.fgChoice==="custom"?String(e.fgHex||"").trim():e.fgChoice,accent:e.accentChoice==="custom"?String(e.accentHex||"").trim():e.accentChoice,accentText:e.accentTextChoice==="custom"?String(e.accentTextHex||"").trim():e.accentTextChoice}},H=()=>ce(Object.fromEntries(Object.keys(r).map(e=>[e,r[e].value]))),Y=M.computed(()=>aa(H())),D=M.observable(!1),he=(e,d)=>{const n=da({...e,size:Number(e.size),offsetX:Number(e.offsetX),offsetY:Number(e.offsetY),phoneSize:Number(e.phoneSize),phoneOffsetX:Number(e.phoneOffsetX),phoneOffsetY:Number(e.phoneOffsetY)},d?{vw:120,vh:220,scale:.5,phone:!0}:{vw:320,vh:200,scale:.5}),f=e.triggerStyle==="icon-text"&&!d;return{left:`${n.left}px`,top:`${n.top}px`,height:`${n.size}px`,width:f?"auto":`${n.size}px`,padding:f?"0 6px":"0","border-radius":f?"999px":`${Math.round(Math.min(Number(e.radius),Number(e.size)/2)/Number(e.size)*100)}%`,"--lnx-bg":$e(e.background)||"var(--dm-primary)","--lnx-fg":$e(e.text)||"var(--dm-primary-text)"}},pe={...r,saving:D,err:M.computed(()=>Y.value.errors),warn:M.computed(()=>Y.value.warnings),cannot:M.computed(()=>D.value||Object.keys(Y.value.errors).length>0),maxRadius:M.computed(()=>Math.floor(Number(r.size.value)/2)),previewStyle:M.computed(()=>he(H(),!1)),phonePreviewStyle:M.computed(()=>he(H(),!0)),botInitial:M.computed(()=>(String(r.botName.value||"").trim()[0]||"?").toUpperCase()),avatarPreview:M.computed(()=>{const e=ra(H());return{background:e.accent||"var(--dm-primary)",color:e.accentText||"var(--dm-primary-text, #fff)"}}),saveText:m?"Create launcher":"Save",linkHref:m?"":J(l.id),linkText:m?"Create the launcher first - then it has a link":J(l.id)},We=M.effect(()=>{const e=Math.floor(Number(r.size.value)/2);Number(r.radius.peek())>e&&(r.radius.value=e)}),ue=(e,d,n)=>{let f=e.peek();return M.effect(()=>{const C=e.value;C!==f&&(f=C,d.value=n(C))})},Ke=ue(r.widthUnit,r.customWidth,e=>e==="%"?90:900),qe=ue(r.heightUnit,r.customHeight,e=>e==="px"?600:70),k=E.slideover({title:m?"New launcher":`Edit ${Z(l.name)}`,size:"lg",position:"right"}),v=ua(pa),me=await Ne().catch(()=>({forms:[],blocks:[]})),fe=(e,d,n)=>{const f=document.createElement("option");f.value="",f.textContent=d.length?"Choose\u2026":"None yet",e.appendChild(f);const C=n&&!d.some(R=>R.value===n)?[...d,{value:n,text:`${n} (missing)`}]:d;for(const R of C){const X=document.createElement("option");X.value=R.value,X.textContent=R.text,e.appendChild(X)}};fe(v.querySelector(".lnx-form-select"),me.forms,b.refForm),fe(v.querySelector(".lnx-block-select"),me.blocks,b.refBlock);let be=()=>{};async function ve(){if(!pe.cannot.peek()){D.value=!0;try{const e=sa(ce(N()),l?.id||""),d=u.peek(),n=m?[...d,e]:d.map(C=>C.id===l.id?e:C);if(!await P(n,m?`Created "${e.name}".`:"Saved."))return;be(),k.close()}finally{D.value=!1}}}k.element.appendChild(v);const je=ke(v),Ye=M.applyBindings(pe,v,{methods:{save:ve,cancel:()=>k.close()}}),_e=e=>{(e.ctrlKey||e.metaKey)&&e.key==="Enter"&&(e.preventDefault(),ve())};v.addEventListener("keydown",_e);const xe=async e=>{const d=e.target.closest(".lnx-corners button[data-pos]");if(d){const n=d.closest(".lnx-corners-phone")?"phonePosition":"position";r[n].value=d.dataset.pos;return}if(e.target.closest(".lnx-pick-icon")){const{openIconPicker:n}=await import("../lib/card-builder.js");n(f=>{r.icon.value=f});return}if(e.target.closest(".lnx-copy-link")&&!m){let n=!1;try{n=await _.copyToClipboard(J(l.id))!==!1}catch{}E.toast(n?"Link copied.":"Could not copy - select the link and copy it.",{type:n?"success":"warning"});return}if(e.target.closest(".lnx-pick-avatar")){const{pickMedia:n}=await import("../lib/media-picker.js"),f=await n({title:"Choose the bot's picture",current:r.avatar.peek()});f&&(r.avatar.value=String(f).replace(/^https?:\/\/[^/]+/i,""));return}if(e.target.closest(".lnx-clear-avatar")){r.avatar.value="";return}if(e.target.closest(".lnx-pick-page")){const{openPagePicker:n}=await import("../lib/page-picker.js");n(f=>{r.refPage.value=f})}};v.addEventListener("click",xe);const Xe=M.effect(()=>{const e=r.icon.value;v.querySelectorAll(".lnx-preview-disc").forEach(d=>{const n=document.createElement("span");n.setAttribute("data-icon",e||"message-circle"),n.className="lnx-preview-icon",d.querySelector(".lnx-preview-icon")?.replaceWith(n),I.scan(d)})}),ge={id:l?.id??null,dirty:re,values:N};w=ge,j.add(k),Ge(k,()=>{Ye.dispose(),je(),We?.(),Ke?.(),qe?.(),Xe?.(),v.removeEventListener("click",xe),j.delete(k),w===ge&&(w=null)}),be=Re(k,re,"Discard the changes you have not saved?"),I.scan(v),k.open(),v.querySelector("#lnx-f-name")?.focus()}const g=p.querySelector(".lnx-list");g.innerHTML=ca;const Ue=M.applyBindings({launchers:u,loading:ae,loadError:F,toolOn:B,filter:$,query:W,rows:K,counts:Oe,emptyText:ze,dragNote:le},p,{methods:{showAll:()=>{$.value="all"},showOn:()=>{$.value="on"},showOff:()=>{$.value="off"}}});x.add(()=>Ue.dispose()),x.add(ke(p,{position:"bottom"})),x.add(M.effect(()=>{K.value,requestAnimationFrame(()=>{p.isConnected&&I.scan(g)})}));const Fe=E.contextMenu(g,{cursor:"glyph",match:".lnx-row",inherit:!1,density:"compact",items:a=>De(a.dataset.id)});x.add(()=>Fe?.destroy?.());const ne=a=>{const t=a.target.closest(".lnx-row");if(!t||a.target.closest(".lnx-switch"))return;const l=a.target.closest(".lnx-kebab");if(l){Se(l);return}z(t.dataset.id)},se=a=>{const t=a.target.closest(".lnx-toggle"),l=t?.closest(".lnx-row"),m=l&&O(l.dataset.id);m&&q(m,t.checked)},ie=a=>{const t=a.target.closest(".lnx-row");t&&(a.key==="F10"&&a.shiftKey?(a.preventDefault(),Se(t)):a.key==="Enter"&&a.target===t&&z(t.dataset.id))};if(g.addEventListener("click",ne),g.addEventListener("change",se),g.addEventListener("keydown",ie),x.add(()=>{g.removeEventListener("click",ne),g.removeEventListener("change",se),g.removeEventListener("keydown",ie)}),typeof E.sortable=="function"){const a=Je(),t=E.sortable(g,{items:".lnx-row",handle:".lnx-grip",key:null,keyboard:!1,onStart:a.start,onEnd:({item:l})=>a.restore(l),onSort:({item:l,from:m,to:o})=>{if(a.restore(l),le.peek()){E.toast("Clear the search and show All to reorder.",{type:"info"}),u.value=[...u.peek()];return}const b=oa(u.peek(),m,o);u.value=b,P(b)}});x.add(()=>t.destroy())}we(i,{id:"launchers-new",icon:"plus",title:"New launcher",onClick:()=>z()}),we(i,{id:"launchers-chats",icon:"message-square",title:"Chats - the conversations from chat launchers",onClick:()=>{location.hash="#/launchers/chats"}});const oe=a=>{w?.dirty()&&(a.preventDefault(),a.returnValue="")};if(window.addEventListener("beforeunload",oe),x.add(()=>window.removeEventListener("beforeunload",oe)),x.add(()=>{if(w?.dirty())try{S.set(U,{id:w.id,values:w.values(),at:new Date().toISOString()})}catch{}[...j].forEach(a=>{try{a.close(!0)}catch{}})}),I.scan(p),await Le(),!A())return;let y=null;try{y=S.get(U)}catch{}if(y?.values){try{S.remove?S.remove(U):S.set(U,null)}catch{}const a=y.id&&O(y.id)?`your changes to "${Z(O(y.id).name)}"`:"the new launcher you started";await E.confirm(`You left ${a} unsaved. Pick up where you left off?`)&&A()&&z(y.id&&O(y.id)?y.id:null,y.values)}}};
@@ -8,4 +8,4 @@ import{api as $,apiRequest as w}from"../api.js";import{placeTools as Oe,WITHHELD
8
8
  <span class="stx-main"><strong>{{path}}</strong><small>{{meta}}</small></span>
9
9
  <span class="stx-chip">{{expires}}</span>
10
10
  <button type="button" class="stx-kebab" aria-label="Actions for {{path}}" title="Actions">\u22EE</button>
11
- </div>`,B=["general","branding","email","cookies","cache"];async function Ne(c,l){const[r,y]=await Promise.all([H.get("/api/sidebar/menu").catch(()=>({items:[]})),H.get("/api/sidebar/registered-items").catch(()=>[])]),n=new Map([["/","Dashboard (built in)"]]),i=(p,u)=>{for(const o of p||[]){if(!o||o.hidden||o.restricted)continue;const a=typeof o.url=="string"?o.url:"";a.startsWith(Re)||(a.startsWith("#/")&&a.length>2&&!n.has(a.slice(1))&&n.set(a.slice(1),`${u?`${u} \u203A `:""}${o.text||a}`),i(o.items,o.url?u:o.text||u))}},k=(y||[]).filter(p=>!/^~\d+$/.test(String(p?.item?.text||"")));i(Oe(r?.items||[],k),""),n.has(l)||n.set(l,`${l} (not in the sidebar)`),c.replaceChildren();for(const[p,u]of n){const o=document.createElement("option");o.value=p,o.textContent=u,c.appendChild(o)}}let f=null,ge=!1;function Ve(){ge||!window.R?.use||(ge=!0,R.use((c,l,r)=>!(Q.test(l?.path||"")&&!Q.test(c?.path||""))||!f?.dirty()?r():E.confirm("You have unsaved settings. Leave anyway? They are kept as a draft for your next visit (not the SMTP password).").then(n=>{n?r():history.replaceState(null,"","#/settings")})),M.subscribe("router:afterChange",({to:c}={})=>{if(f&&!Q.test(c?.path||"")){const l=f;f=null,l.dispose()}}))}export const settingsView={templateUrl:"/admin/js/templates/settings.html",async onMount(c){if(Ve(),f){const e=f;f=null,e.dispose()}const l=[],r=e=>(l.push(e),e);let y=!1;const n=c.get(0).querySelector(".stx")||c.get(0),i=()=>!y&&n.isConnected,k=E.loader(c.get(0),{type:"dots"});let p;try{p=await $.settings.get()}catch(e){k.destroy(),E.toast(`Could not load the settings: ${e.message||e}`,{type:"error"});return}if(k.destroy(),!n.isConnected)return;const u=M.observable(p||{}),o=$e(p||{}),a={};for(const[e,t]of Object.entries(o))a[e]=M.observable(t);const j=()=>Object.fromEntries(Object.keys(a).map(e=>[e,a[e].value])),X=()=>Object.fromEntries(Object.keys(a).map(e=>[e,a[e].peek()])),v=M.observable(o),U=M.computed(()=>ve(v.value)),x=M.computed(()=>ve(j())!==U.value),C=M.observable(!1),T=M.observable(""),Z=M.observable(!1);$.plugins.policy().then(e=>{i()&&(Z.value=e?.signedOnly===!1)}).catch(()=>{});const q=M.observable(!1),ee=M.computed(()=>{const e=new Set(Ae(j(),v.value));return Object.fromEntries(Object.keys(qe).map(t=>[t,e.has(t)]))}),_=M.observable([]);r(M.effect(()=>{_.value=Ue(j(),u.value).map(e=>({...e,label:e.tone==="danger"?"Mail":"Check"}))}));const te=M.observable(""),L=M.observable(!1),O=M.observable(""),A=M.observable(""),m=M.observable(null),K=M.observable([]),F=M.observable(""),W=M.observable(!0),z=M.observable(""),se=M.observable([]);r(M.effect(()=>{const e=F.value.trim().toLowerCase(),t=Date.now();se.value=[...K.value].reverse().filter(s=>!e||String(s.key).toLowerCase().includes(e)||(s.tags||[]).some(d=>String(d).toLowerCase().includes(e))).map(s=>{const d=J(s.key);return{id:s.key,path:d.path,meta:[d.page?`as ${d.role}`:"not a page",(s.tags||[]).join(", ")].filter(Boolean).join(" \xB7 "),expires:He(s.expiresAt,t)}})}));const ye={...a,saving:C,dirty:x,tabs:ee,problems:_,testTo:te,testing:L,testResult:O,testTone:A,cacheQuery:F,cacheLoading:W,cacheError:z,cacheRows:se,errorText:T,problemsText:M.computed(()=>_.value.length?"yes":""),siteUrlError:M.computed(()=>he(a.siteUrl.value)),noSmtp:M.computed(()=>!String(a.smtpHost.value||"").trim()),mayAllowInsecureTLS:Z,dirtyEmail:M.computed(()=>ee.value.email),cacheOn:M.computed(()=>m.value?.enabled===!0),cacheState:M.computed(()=>{const e=m.value;return e?e.enabled?`On (${e.driver})`:"Off":"Status unknown"}),cacheSize:M.computed(()=>{const e=m.value;return e?.enabled&&e.size!==null&&e.size!==void 0?`${e.size}${e.maxItems?` of ${e.maxItems}`:""} entries`:""}),cacheHits:M.computed(()=>{const e=m.value?.hitRate;return e==null?"":`${Math.round(e*100)}% served from the cache`}),cacheToggleText:M.computed(()=>m.value?.enabled?"Turn off":"Turn on"),cacheEmpty:M.computed(()=>F.value.trim()?"Nothing matches.":m.value?.enabled?"The cache is empty - pages are cached as visitors open them.":"The cache is off.")};async function N(){if(C.peek())return;const e=X(),t=v.peek(),s=he(e.siteUrl);if(s){E.toast(`Site URL: ${s}`,{type:"error"});return}C.value=!0,T.value="";const d=String(e.title).trim()!==String(t.title).trim();try{await $.settings.save(je(e,u.peek(),{adminHomeReady:q.peek()}));const P=await $.settings.get().catch(()=>null);if(!i())return;P&&(u.value=P);const Le={...e,smtpPass:""};a.smtpPass.value="",v.value=Le;try{S.remove?S.remove(g):S.set(g,null)}catch{}document.dispatchEvent(new CustomEvent("dm:admin-home-changed")),(d||["adminBrandEnabled","adminBrandTitle","adminBrandLogo","adminBrandLogoDark","adminBrandIcon"].some(pe=>e[pe]!==t[pe]))&&document.dispatchEvent(new CustomEvent("dm:sidebar-rebuild")),fe(be),E.toast("Settings saved.",{type:"success"})}catch(P){T.value=P.message||"Could not save the settings.",E.toast("Settings not saved - see the message at the top.",{type:"error"})}finally{C.value=!1}}async function we(){await E.confirm("Throw away your unsaved settings?")&&(ae(v.peek()),T.value="")}function ae(e){for(const[t,s]of Object.entries(e))a[t]&&(a[t].value=s)}async function ke(){if(!L.peek()){L.value=!0,A.value="",O.value="Sending\u2026";try{const e=await w("/settings/test-email",{method:"POST",body:JSON.stringify({to:te.peek().trim()||void 0})});if(!i())return;O.value=e?.message||"Test email sent.",A.value="is-ok"}catch(e){if(!i())return;O.value=e.message||"Could not send the test email.",A.value="is-bad"}finally{L.value=!1}}}async function D(){W.value=!0;try{const[e,t]=await Promise.all([w("/cache/status").catch(()=>null),w("/cache/keys")]);if(!i())return;m.value=e,K.value=Array.isArray(t?.entries)?t.entries:[],z.value=""}catch(e){if(!i())return;z.value=`Could not read the cache: ${e.message||e}`}finally{W.value=!1}}async function Ee(){if(await E.confirm("Clear the whole response cache? The next visitor to each page renders it afresh.")){try{await w("/cache/clear",{method:"POST"}),E.toast("Cache cleared.",{type:"success"})}catch(e){E.toast(e.message||"Could not clear the cache.",{type:"error"})}i()&&await D()}}async function Se(){const e=m.peek()?.enabled===!0;if(!(e&&!await E.confirm("Turn the response cache off? Every visit will render its page afresh until it is turned back on. The choice is saved (config/cache.json)."))){try{m.value=await w("/cache/toggle",{method:"POST",body:JSON.stringify({enabled:!e})}),E.toast(e?"Cache turned off.":"Cache turned on.",{type:"success"}),fe(be)}catch(t){E.toast(t.message||"Could not change the cache.",{type:"error"})}i()&&await D()}}const ne=e=>K.peek().find(t=>t.key===e);function Me(e){const t=ne(e);if(!t)return[];const s=J(t.key);return[{header:s.path},{label:"Open the page",icon:"external-link",disabled:!s.page,action:()=>window.open(s.path,"_blank","noopener")},{label:"Copy key",icon:"copy",action:async()=>{try{await navigator.clipboard.writeText(t.key),E.toast("Key copied.",{type:"success"})}catch{E.toast("Could not copy - your browser blocked the clipboard.",{type:"warning"})}}},...s.page?[{label:"Copy address",icon:"link",action:async()=>{try{await navigator.clipboard.writeText(new URL(s.path,location.origin).href),E.toast("Address copied.",{type:"success"})}catch{E.toast("Could not copy - your browser blocked the clipboard.",{type:"warning"})}}}]:[]]}n.querySelector(".stx-problems").innerHTML=We;const b=n.querySelector(".stx-list");b.innerHTML=ze;const V=E.tabs(n.querySelector(".stx-tabs"),{tabSelector:".tab-item",panelSelector:".tab-panel"}),oe=new URLSearchParams(location.hash.split("?")[1]||"").get("tab");B.includes(oe)&&V.activate(B.indexOf(oe));const xe=M.applyBindings(ye,n,{methods:{save:N,discard:we,sendTest:ke,refreshCache:D,clearCache:Ee,toggleCache:Se,pickBrandImage:async e=>{const t=await _e({title:"Choose a branding image",current:a[e].peek()});t&&i()&&(a[e].value=t)},clearBrandImage:e=>{a[e].value=""},goTab:e=>{const t=B.indexOf(e);t>=0&&V.activate(t)}}});r(()=>xe.dispose());for(const e of n.querySelectorAll("[data-brand-icon]")){const t=e.dataset.brandIcon,s=Ke("Choose an icon",a[t].peek());s.input.id=`stx-${t}`,s.input.classList.add("form-input");const d=()=>{a[t].value=s.input.value};s.input.addEventListener("input",d),r(()=>s.input.removeEventListener("input",d)),r(M.effect(()=>{s.input.value=a[t].value})),e.appendChild(s.el)}r(Ie(n,{position:"bottom"}));const Ce=e=>{const t=e.target.closest("[data-go]");if(!t)return;const s=B.indexOf(t.dataset.go);s>=0&&V.activate(s)};n.querySelector(".stx-problems").addEventListener("click",Ce);const Y=n.querySelector("#stx-admin-home");Ne(Y,Be(a.adminHome.peek())).then(()=>{i()&&(Y.value=a.adminHome.peek(),q.value=!0)}).catch(()=>{});const Te=E.contextMenu(b,{cursor:"glyph",match:".stx-row",inherit:!1,density:"compact",items:e=>Me(e.dataset.id)});r(()=>Te?.destroy?.());const re=e=>{const t=ne(e.dataset.id),s=t&&J(t.key);s?.page?window.open(s.path,"_blank","noopener"):G(e)},ie=e=>{const t=e.target.closest(".stx-row");if(!t)return;const s=e.target.closest(".stx-kebab");if(s){G(s);return}re(t)},ce=e=>{const t=e.target.closest(".stx-row");t&&(e.key==="F10"&&e.shiftKey?(e.preventDefault(),G(t)):e.key==="Enter"&&e.target===t&&re(t))};b.addEventListener("click",ie),b.addEventListener("keydown",ce),r(()=>{b.removeEventListener("click",ie),b.removeEventListener("keydown",ce)}),me(c,{id:"settings-view-site",icon:"external-link",title:"View site",onClick:()=>window.open("/","_blank","noopener")}),me(c,{id:"settings-save",icon:"save",title:"Save (Ctrl+S)",onClick:()=>N()});const le=e=>{!(e.ctrlKey||e.metaKey)||e.key!=="s"||(e.preventDefault(),e.stopImmediatePropagation(),N())};document.addEventListener("keydown",le,!0),r(()=>document.removeEventListener("keydown",le,!0));const ue=()=>{if(x.peek())try{S.set(g,{form:De(X()),base:U.peek(),at:new Date().toISOString()})}catch{}},de=e=>{x.peek()&&(ue(),e.preventDefault(),e.returnValue="")};window.addEventListener("beforeunload",de),r(()=>window.removeEventListener("beforeunload",de)),f={dirty:()=>x.peek(),dispose(){y=!0,ue(),l.splice(0).reverse().forEach(e=>{try{e()}catch{}})}},I.scan(n),D();let h=null;try{h=S.get(g)}catch{}if(h?.form){try{S.remove?S.remove(g):S.set(g,null)}catch{}const e=h.base&&h.base!==U.peek(),t=h.at?` (${Fe(h.at)})`:"",s=e?`You left unsaved settings${t}, but the saved settings have changed since. Restore your version anyway?`:`You left unsaved settings${t}. Restore them?`;await E.confirm(s)&&i()&&(ae(Pe(v.peek(),h.form)),q.peek()&&(Y.value=a.adminHome.peek()))}}};
11
+ </div>`,B=["general","branding","email","cookies","cache"];async function Ne(c,l){const[r,y]=await Promise.all([H.get("/api/sidebar/menu").catch(()=>({items:[]})),H.get("/api/sidebar/registered-items").catch(()=>[])]),n=new Map([["/","Dashboard (built in)"]]),i=(p,u)=>{for(const o of p||[]){if(!o||o.hidden||o.restricted)continue;const a=typeof o.url=="string"?o.url:"";a.startsWith(Re)||(a.startsWith("#/")&&a.length>2&&!n.has(a.slice(1))&&n.set(a.slice(1),`${u?`${u} \u203A `:""}${o.text||a}`),i(o.items,o.url?u:o.text||u))}},k=(y||[]).filter(p=>!/^~\d+$/.test(String(p?.item?.text||"")));i(Oe(r?.items||[],k),""),n.has(l)||n.set(l,`${l} (not in the sidebar)`),c.replaceChildren();for(const[p,u]of n){const o=document.createElement("option");o.value=p,o.textContent=u,c.appendChild(o)}}let f=null,ge=!1;function Ve(){ge||!window.R?.use||(ge=!0,R.use((c,l,r)=>!(Q.test(l?.path||"")&&!Q.test(c?.path||""))||!f?.dirty()?r():E.confirm("You have unsaved settings. Leave anyway? They are kept as a draft for your next visit (not the SMTP password).").then(n=>{n?r():history.replaceState(null,"","#/settings")})),M.subscribe("router:afterChange",({to:c}={})=>{if(f&&!Q.test(c?.path||"")){const l=f;f=null,l.dispose()}}))}export const settingsView={templateUrl:"/admin/js/templates/settings.html",async onMount(c){if(Ve(),f){const e=f;f=null,e.dispose()}const l=[],r=e=>(l.push(e),e);let y=!1;const n=c.get(0).querySelector(".stx")||c.get(0),i=()=>!y&&n.isConnected,k=E.loader(c.get(0),{type:"dots"});let p;try{p=await $.settings.get()}catch(e){k.destroy(),E.toast(`Could not load the settings: ${e.message||e}`,{type:"error"});return}if(k.destroy(),!n.isConnected)return;const u=M.observable(p||{}),o=$e(p||{}),a={};for(const[e,t]of Object.entries(o))a[e]=M.observable(t);const j=()=>Object.fromEntries(Object.keys(a).map(e=>[e,a[e].value])),X=()=>Object.fromEntries(Object.keys(a).map(e=>[e,a[e].peek()])),v=M.observable(o),U=M.computed(()=>ve(v.value)),x=M.computed(()=>ve(j())!==U.value),C=M.observable(!1),T=M.observable(""),Z=M.observable(!1);$.plugins.policy().then(e=>{i()&&(Z.value=e?.signedOnly===!1)}).catch(()=>{});const q=M.observable(!1),ee=M.computed(()=>{const e=new Set(Ae(j(),v.value));return Object.fromEntries(Object.keys(qe).map(t=>[t,e.has(t)]))}),_=M.observable([]);r(M.effect(()=>{_.value=Ue(j(),u.value).map(e=>({...e,label:e.tone==="danger"?"Mail":"Check"}))}));const te=M.observable(""),L=M.observable(!1),O=M.observable(""),A=M.observable(""),m=M.observable(null),K=M.observable([]),F=M.observable(""),W=M.observable(!0),z=M.observable(""),se=M.observable([]);r(M.effect(()=>{const e=F.value.trim().toLowerCase(),t=Date.now();se.value=[...K.value].reverse().filter(s=>!e||String(s.key).toLowerCase().includes(e)||(s.tags||[]).some(d=>String(d).toLowerCase().includes(e))).map(s=>{const d=J(s.key);return{id:s.key,path:d.path,meta:[d.page?`as ${d.role}`:"not a page",(s.tags||[]).join(", ")].filter(Boolean).join(" \xB7 "),expires:He(s.expiresAt,t)}})}));const ye={...a,saving:C,dirty:x,tabs:ee,problems:_,testTo:te,testing:L,testResult:O,testTone:A,cacheQuery:F,cacheLoading:W,cacheError:z,cacheRows:se,errorText:T,problemsText:M.computed(()=>_.value.length?"yes":""),siteUrlError:M.computed(()=>he(a.siteUrl.value)),noSmtp:M.computed(()=>!String(a.smtpHost.value||"").trim()),mayAllowInsecureTLS:Z,dirtyEmail:M.computed(()=>ee.value.email),cacheOn:M.computed(()=>m.value?.enabled===!0),cacheState:M.computed(()=>{const e=m.value;return e?e.enabled?`On (${e.driver})`:"Off":"Status unknown"}),cacheSize:M.computed(()=>{const e=m.value;return e?.enabled&&e.size!==null&&e.size!==void 0?`${e.size}${e.maxItems?` of ${e.maxItems}`:""} entries`:""}),cacheHits:M.computed(()=>{const e=m.value?.hitRate;return e==null?"":`${Math.round(e*100)}% served from the cache`}),cacheToggleText:M.computed(()=>m.value?.enabled?"Turn off":"Turn on"),cacheEmpty:M.computed(()=>F.value.trim()?"Nothing matches.":m.value?.enabled?"The cache is empty - pages are cached as visitors open them.":"The cache is off.")};async function N(){if(C.peek())return;const e=X(),t=v.peek(),s=he(e.siteUrl);if(s){E.toast(`Site URL: ${s}`,{type:"error"});return}C.value=!0,T.value="";const d=String(e.title).trim()!==String(t.title).trim();try{await $.settings.save(je(e,u.peek(),{adminHomeReady:q.peek()})),window.dispatchEvent(new Event("admin-assistant:settings"));const P=await $.settings.get().catch(()=>null);if(!i())return;P&&(u.value=P);const Le={...e,smtpPass:""};a.smtpPass.value="",v.value=Le;try{S.remove?S.remove(g):S.set(g,null)}catch{}document.dispatchEvent(new CustomEvent("dm:admin-home-changed")),(d||["adminBrandEnabled","adminBrandTitle","adminBrandLogo","adminBrandLogoDark","adminBrandIcon"].some(pe=>e[pe]!==t[pe]))&&document.dispatchEvent(new CustomEvent("dm:sidebar-rebuild")),fe(be),E.toast("Settings saved.",{type:"success"})}catch(P){T.value=P.message||"Could not save the settings.",E.toast("Settings not saved - see the message at the top.",{type:"error"})}finally{C.value=!1}}async function we(){await E.confirm("Throw away your unsaved settings?")&&(ae(v.peek()),T.value="")}function ae(e){for(const[t,s]of Object.entries(e))a[t]&&(a[t].value=s)}async function ke(){if(!L.peek()){L.value=!0,A.value="",O.value="Sending\u2026";try{const e=await w("/settings/test-email",{method:"POST",body:JSON.stringify({to:te.peek().trim()||void 0})});if(!i())return;O.value=e?.message||"Test email sent.",A.value="is-ok"}catch(e){if(!i())return;O.value=e.message||"Could not send the test email.",A.value="is-bad"}finally{L.value=!1}}}async function D(){W.value=!0;try{const[e,t]=await Promise.all([w("/cache/status").catch(()=>null),w("/cache/keys")]);if(!i())return;m.value=e,K.value=Array.isArray(t?.entries)?t.entries:[],z.value=""}catch(e){if(!i())return;z.value=`Could not read the cache: ${e.message||e}`}finally{W.value=!1}}async function Ee(){if(await E.confirm("Clear the whole response cache? The next visitor to each page renders it afresh.")){try{await w("/cache/clear",{method:"POST"}),E.toast("Cache cleared.",{type:"success"})}catch(e){E.toast(e.message||"Could not clear the cache.",{type:"error"})}i()&&await D()}}async function Se(){const e=m.peek()?.enabled===!0;if(!(e&&!await E.confirm("Turn the response cache off? Every visit will render its page afresh until it is turned back on. The choice is saved (config/cache.json)."))){try{m.value=await w("/cache/toggle",{method:"POST",body:JSON.stringify({enabled:!e})}),E.toast(e?"Cache turned off.":"Cache turned on.",{type:"success"}),fe(be)}catch(t){E.toast(t.message||"Could not change the cache.",{type:"error"})}i()&&await D()}}const ne=e=>K.peek().find(t=>t.key===e);function Me(e){const t=ne(e);if(!t)return[];const s=J(t.key);return[{header:s.path},{label:"Open the page",icon:"external-link",disabled:!s.page,action:()=>window.open(s.path,"_blank","noopener")},{label:"Copy key",icon:"copy",action:async()=>{try{await navigator.clipboard.writeText(t.key),E.toast("Key copied.",{type:"success"})}catch{E.toast("Could not copy - your browser blocked the clipboard.",{type:"warning"})}}},...s.page?[{label:"Copy address",icon:"link",action:async()=>{try{await navigator.clipboard.writeText(new URL(s.path,location.origin).href),E.toast("Address copied.",{type:"success"})}catch{E.toast("Could not copy - your browser blocked the clipboard.",{type:"warning"})}}}]:[]]}n.querySelector(".stx-problems").innerHTML=We;const b=n.querySelector(".stx-list");b.innerHTML=ze;const V=E.tabs(n.querySelector(".stx-tabs"),{tabSelector:".tab-item",panelSelector:".tab-panel"}),oe=new URLSearchParams(location.hash.split("?")[1]||"").get("tab");B.includes(oe)&&V.activate(B.indexOf(oe));const xe=M.applyBindings(ye,n,{methods:{save:N,discard:we,sendTest:ke,refreshCache:D,clearCache:Ee,toggleCache:Se,pickBrandImage:async e=>{const t=await _e({title:"Choose a branding image",current:a[e].peek()});t&&i()&&(a[e].value=t)},clearBrandImage:e=>{a[e].value=""},goTab:e=>{const t=B.indexOf(e);t>=0&&V.activate(t)}}});r(()=>xe.dispose());for(const e of n.querySelectorAll("[data-brand-icon]")){const t=e.dataset.brandIcon,s=Ke("Choose an icon",a[t].peek());s.input.id=`stx-${t}`,s.input.classList.add("form-input");const d=()=>{a[t].value=s.input.value};s.input.addEventListener("input",d),r(()=>s.input.removeEventListener("input",d)),r(M.effect(()=>{s.input.value=a[t].value})),e.appendChild(s.el)}r(Ie(n,{position:"bottom"}));const Ce=e=>{const t=e.target.closest("[data-go]");if(!t)return;const s=B.indexOf(t.dataset.go);s>=0&&V.activate(s)};n.querySelector(".stx-problems").addEventListener("click",Ce);const Y=n.querySelector("#stx-admin-home");Ne(Y,Be(a.adminHome.peek())).then(()=>{i()&&(Y.value=a.adminHome.peek(),q.value=!0)}).catch(()=>{});const Te=E.contextMenu(b,{cursor:"glyph",match:".stx-row",inherit:!1,density:"compact",items:e=>Me(e.dataset.id)});r(()=>Te?.destroy?.());const re=e=>{const t=ne(e.dataset.id),s=t&&J(t.key);s?.page?window.open(s.path,"_blank","noopener"):G(e)},ie=e=>{const t=e.target.closest(".stx-row");if(!t)return;const s=e.target.closest(".stx-kebab");if(s){G(s);return}re(t)},ce=e=>{const t=e.target.closest(".stx-row");t&&(e.key==="F10"&&e.shiftKey?(e.preventDefault(),G(t)):e.key==="Enter"&&e.target===t&&re(t))};b.addEventListener("click",ie),b.addEventListener("keydown",ce),r(()=>{b.removeEventListener("click",ie),b.removeEventListener("keydown",ce)}),me(c,{id:"settings-view-site",icon:"external-link",title:"View site",onClick:()=>window.open("/","_blank","noopener")}),me(c,{id:"settings-save",icon:"save",title:"Save (Ctrl+S)",onClick:()=>N()});const le=e=>{!(e.ctrlKey||e.metaKey)||e.key!=="s"||(e.preventDefault(),e.stopImmediatePropagation(),N())};document.addEventListener("keydown",le,!0),r(()=>document.removeEventListener("keydown",le,!0));const ue=()=>{if(x.peek())try{S.set(g,{form:De(X()),base:U.peek(),at:new Date().toISOString()})}catch{}},de=e=>{x.peek()&&(ue(),e.preventDefault(),e.returnValue="")};window.addEventListener("beforeunload",de),r(()=>window.removeEventListener("beforeunload",de)),f={dirty:()=>x.peek(),dispose(){y=!0,ue(),l.splice(0).reverse().forEach(e=>{try{e()}catch{}})}},I.scan(n),D();let h=null;try{h=S.get(g)}catch{}if(h?.form){try{S.remove?S.remove(g):S.set(g,null)}catch{}const e=h.base&&h.base!==U.peek(),t=h.at?` (${Fe(h.at)})`:"",s=e?`You left unsaved settings${t}, but the saved settings have changed since. Restore your version anyway?`:`You left unsaved settings${t}. Restore them?`;await E.confirm(s)&&i()&&(ae(Pe(v.peek(),h.form)),q.peek()&&(Y.value=a.adminHome.peek()))}}};
@@ -1240,7 +1240,7 @@ The four Tools below were plugins until 0.67.0 and are now part of the CMS. They
1240
1240
  - Hand-over: with staff available (the Chats screen open and Available on - memory presence, 75s) the chat goes to `waiting` and staff are notified (source `core:chat`, admins); with nobody available the visitor leaves name and email (`message`) unless the launcher says never; `askDetails: always` asks before putting them through. A staff reply makes it `open` and the bot stays quiet. Hourly tidy-up closes quiet chats (bot 2h, waiting/open 24h) and deletes ended ones after `retentionDays` (90) - bot-only chats with no details after 7 days - with their messages and any orphan messages, one write per collection (adapters' `removeMany`). Chats in memory are an LRU of 2000; unknown tokens are remembered for a minute. A Launchers module that is missing refuses every chat.
1241
1241
  - Admin: **Content > Chats** (`#/launchers/chats`, `#/launchers/chats/:id`) - the inbox, waiting first, the live thread (3s poll), replies with per-chat drafts, end/delete/email in a context menu, Available switch, settings cog; sidebar badge `/api/chats/_count` (live while someone waits, red after 5 minutes). **Chats > Knowledge** (`#/launchers/knowledge`) - entries with an editor slideover (question, other ways of asking, keywords, Markdown answer, up to five buttons, on/off), Try the bot with scores, and the Unanswered list (Make an entry, add to the closest entry, dismiss). Visitor panel `public/js/launcher-chat.mjs` `mountChat(container, {launcherId, title, chat})` + `public/css/launcher-chat.css`, domma-reactive.
1242
1242
  - Permission `chats` (`read`, `reply`, `manage`) in the Tools group; Admin is granted it once. All of it is behind the Launchers switch.
1243
- - Della's AI answers (unreleased; Pro plan, hosted sites): when the matcher says `none`, `services/chat/ai.js` `aiAnswer()` asks the Manager (`MANAGER_URL` + `FLEET_TOKEN`, `POST /api/fleet/launcher-chat`; on dcm the in-process registry `Symbol.for('domma.launcher-chat')`) with the site's name, `assistantBrief()` (site.json `assistant.context`/`rules` from Site Settings > General > AI assistant, plus the launcher's `chat.aiContext`/`aiRules`), the enabled non-sample Knowledge (most used first, 16,000 characters), the last 10 visitor/bot messages and the question. A non-empty answer is stored as a bot message with `ai: true` (`misses` reset); empty or refused falls back to the usual "do not know". The question is still logged as unanswered. A 403 (no licence) backs off 10 minutes, a 429 (month used) 30 minutes, anything else 1 minute. Per launcher `chat.ai` (default on), `chat.aiUseSite` (default on; off = the launcher's own context only - the site's rules always apply), `chat.aiMaxPerChat` (20; `aiCount` on the session); the default bot name is now Della. `aiContext`/`aiRules` never reach the page (`publicLauncher`). `/api/chat/config` says `ai` so the panel can say Della is an AI assistant. Manager side: `plugins/site-manager/services/launcherChatRoutes.js` (fleet token, the `ai-site-builder` licence, 2,000 answers per site per month counting "do not know", 4 at once) and `tools/launcher-chat` (Claude Haiku 5.5, low effort; fixed cached system prompt, then the owner's context and rules as a second system block; the visitor's words only in the user message; `LAUNCHER_CHAT_ANTHROPIC_KEY` read by the job alone).
1243
+ - Della's AI answers (unreleased; Pro plan, hosted sites): when the matcher says `none`, `services/chat/ai.js` `aiAnswer()` asks the Manager (`MANAGER_URL` + `FLEET_TOKEN`, `POST /api/fleet/launcher-chat`; on dcm the in-process registry `Symbol.for('domma.launcher-chat')`) with the site's name, `assistantBrief()` (site.json `assistant.context`/`rules` from Site Settings > General > AI assistant, plus the launcher's `chat.aiContext`/`aiRules`), the enabled non-sample Knowledge (most used first, 16,000 characters), the last 10 visitor/bot messages and the question. A non-empty answer is stored as a bot message with `ai: true` (`misses` reset); empty or refused falls back to the usual "do not know". The question is still logged as unanswered. A 403 (no licence) backs off 10 minutes, a 429 (month used) 30 minutes, anything else 1 minute. Per launcher `chat.ai` (default on), `chat.aiUseSite` (default on; off = the launcher's own context only - the site's rules always apply), `chat.aiMaxPerChat` (20; `aiCount` on the session); the default bot name is now Della. A character's chat is called by the character's name, or by `chat.characterName` when set (admin: **Call her** under Use Della) - `characterChat()` in `public/js/characters.mjs` - so Della can be "Dash" on one launcher with her own artwork. `aiContext`/`aiRules` never reach the page (`publicLauncher`). `/api/chat/config` says `ai` so the panel can say Della is an AI assistant. Manager side: `plugins/site-manager/services/launcherChatRoutes.js` (fleet token, the `ai-site-builder` licence, 2,000 answers per site per month counting "do not know", 4 at once) and `tools/launcher-chat` (Claude Haiku 5.5, low effort; fixed cached system prompt, then the owner's context and rules as a second system block; the visitor's words only in the user message; `LAUNCHER_CHAT_ANTHROPIC_KEY` read by the job alone).
1244
1244
  - Saved chats (unreleased): preset `chat-saved` (in `CHAT_PRESET_SLUGS`, `chats.manage` through the generic API, kept out of site repos) - a copy of a chat with `note`, `outcome` (to look at / looking into it / done), visitor, page, dates, who saved it, `transcript` (plain text) and `messages`. `POST /api/chats/:id/save` (reply), `GET /api/chats/saved` and `/saved/:sid` (read), `PUT /saved/:sid` (reply; note, outcome), `DELETE /saved/:sid` (manage); at most 2,000 per site. Chats inbox: a **Saved** tab, the context-menu item **Save for a closer look…**, and an outcome/note bar on an open saved chat (`services/chat/saved.js`, `arrangeSaved()`).
1245
1245
  - Visitor panel look (unreleased): bot and staff avatars, runs of messages grouped (name on the first, avatar on the last), gradient visitor bubbles, soft chips for links and choices, a rounded composer with the send button inside, messages easing in (still for reduced motion), and in a launcher panel the bot's avatar (with a dot while someone answers) and the status under the title. Panel 400 x 600. Per-chat branding: `chat.accent` / `chat.accentText` (a theme token or hex, `launcherColour`) and `chat.avatar` (a site address only, `launcherAvatar()`), in the page's chat block and `/api/chat/config`; the panel sets `--chat-accent` / `--chat-accent-text` on itself (`launcherChatAccentCss()`: a hex accent with no text colour gets black or white by contrast, a token its `--dm-<token>-text`), and the bot's picture replaces its initial in the heading, the typing row and its messages.
1246
1246
  - Chat window and extras (unreleased): `chat.size` sm/md/lg/custom + `width`/`height` (`launcherChatBox()`; desktop only, clamped 300-720 x 380-900 and to the window), `chat.resizable` (a grip in the corner opposite the disc; size kept per launcher in the browser, `launcher-chat-size:<id>`, double-click resets), `chat.starters` (up to 4 buttons under the greeting; a tap within 1.7s of opening waits out the anti-bot window), `chat.personButton` below/header (an icon with a tooltip before the close button), greeting placeholders `{greeting}` `{timeofday}` `{day}` `{date}` `{time}` `{botname}` `{site}`, `chat.times` time/datetime/none on each message (`fillGreeting()`, the visitor's clock, text only), and `chat.keepDays` (0 = the site's `retentionDays`; the hourly tidy-up reads each launcher's).
@@ -0,0 +1,53 @@
1
+ # Admin assistant
2
+
3
+ Enable the core mechanism at **System > Site Settings > General > Admin assistant**.
4
+ It starts switched off. A settings editor can choose its display name, Della/Dot/Daisy
5
+ artwork (or none), additional context and rules. Global character visibility and reduced
6
+ motion preferences still apply. This is separate from public visitor chat.
7
+
8
+ Once enabled, signed-in users see **Ask Della** (or the chosen name) throughout their
9
+ admin screens. The panel answers questions and drafts plain text that the person can
10
+ copy into an editor. It has no action tools and cannot save, publish, send, inspect
11
+ records or change settings. Core help currently covers Pages, Theme and Site Settings;
12
+ other screens get general help until their plugin registers more specific guidance.
13
+
14
+ Questions, up to ten recent messages and permission-filtered help are sent to the site's
15
+ existing AI service. The current screen's records, page content, CVs, files and form
16
+ values are not attached. Conversations stay in browser memory, are cleared on sign-out
17
+ or a user change, and can be cleared in the panel. They are not saved as visitor chats.
18
+ The site's shared AI context and rules are combined with the admin-specific settings.
19
+
20
+ The Manager needs the admin-assistant AI mode update. It uses the existing hosted AI
21
+ entitlement and monthly allowance. A site with no configured AI service shows an
22
+ unavailable message. Older Managers are detected and asked to update; their visitor
23
+ answer mode is not silently used for admin assistance.
24
+
25
+ ## Plugin help and assistant identities
26
+
27
+ A plugin can register static guidance during startup through its supplied hooks:
28
+
29
+ ```js
30
+ hooks.registerAdminAssistant({
31
+ routes: ['/plugins/example'],
32
+ permission: 'example.read',
33
+ name: 'Your helper',
34
+ character: 'della',
35
+ context: 'Describe this tool and its documented operations here.'
36
+ });
37
+ ```
38
+
39
+ The CMS stamps the registration with the plugin's name. The registered permission and
40
+ the signed-in user's admin scope must both permit the current route before its guidance
41
+ or identity is used. A plugin cannot replace another plugin's registration. Context is
42
+ static text, capped at 8,000 characters; the hook does not accept record loaders or
43
+ action handlers. A custom name does not create a new artwork pack. Dash's Job Board
44
+ integration and pose pack are separate work.
45
+
46
+ Authenticated endpoints:
47
+
48
+ - `GET /api/admin-assistant/config?route=/theme` returns presentation and availability.
49
+ - `POST /api/admin-assistant/ask` accepts `question`, `route` and bounded `history`.
50
+
51
+ The server derives the assistant, context, rules and AI mode. Request fields cannot
52
+ replace them. Requests are rate limited; disabled assistants and inaccessible tools
53
+ are rejected before the AI service is called.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "domma-cms",
3
- "version": "1.52.0",
3
+ "version": "1.53.1",
4
4
  "description": "File-based CMS powered by Domma and Fastify. Run npx domma-cms my-site to create a new project.",
5
5
  "type": "module",
6
6
  "main": "server/server.js",
@@ -1 +1 @@
1
- export const CHARACTERS=Object.freeze({dot:Object.freeze({id:"dot",name:"Dot",artwork:"/public/images/characters/dot-poses.png"}),daisy:Object.freeze({id:"daisy",name:"Daisy",artwork:"/public/images/characters/daisy-poses.png"}),della:Object.freeze({id:"della",name:"Della",artwork:"/public/images/characters/della-poses.png"})});export function characterId(e){return typeof e=="string"&&Object.hasOwn(CHARACTERS,e)?e:""}export function normaliseCharacterSettings(e){const r=e&&typeof e=="object"&&!Array.isArray(e)?e:{};return{enabled:r.enabled!==!1,animated:r.animated!==!1,launchers:r.launchers!==!1,chats:r.chats!==!1,builders:r.builders!==!1,dot:r.dot!==!1,daisy:r.daisy!==!1}}export function builderCharacterState({working:e=!1,busy:r=!1,error:a="",status:t="",hasContent:n=!1}={}){return a||["waiting","failed","stopped"].includes(t)?"help":e||t==="building"?"working":r?"thinking":["ready","released"].includes(t)?"success":n||t==="review"?"ready":"greeting"}export function characterChat(e={},r){const a=characterId(e.character);return{...e,character:a,...a?{botName:CHARACTERS[a].name}:{},characterOptions:normaliseCharacterSettings(r)}}export function chatCharacterState({busy:e=!1,error:r="",ended:a=!1,status:t="none",askDetails:n=!1,replied:i=!1}={}){return r||n?"help":e?"thinking":a||t==="message"?"success":i?"ready":"greeting"}
1
+ export const CHARACTERS=Object.freeze({dot:Object.freeze({id:"dot",name:"Dot",artwork:"/public/images/characters/dot-poses.png"}),daisy:Object.freeze({id:"daisy",name:"Daisy",artwork:"/public/images/characters/daisy-poses.png"}),della:Object.freeze({id:"della",name:"Della",artwork:"/public/images/characters/della-poses.png"})});export function characterId(e){return typeof e=="string"&&Object.hasOwn(CHARACTERS,e)?e:""}export function normaliseCharacterSettings(e){const r=e&&typeof e=="object"&&!Array.isArray(e)?e:{};return{enabled:r.enabled!==!1,animated:r.animated!==!1,launchers:r.launchers!==!1,chats:r.chats!==!1,builders:r.builders!==!1,dot:r.dot!==!1,daisy:r.daisy!==!1}}export function builderCharacterState({working:e=!1,busy:r=!1,error:t="",status:a="",hasContent:n=!1}={}){return t||["waiting","failed","stopped"].includes(a)?"help":e||a==="building"?"working":r?"thinking":["ready","released"].includes(a)?"success":n||a==="review"?"ready":"greeting"}export function characterChat(e={},r){const t=characterId(e.character),a=typeof e.characterName=="string"?e.characterName.replace(/[\u0000-\u001f\u007f]/g," ").trim().slice(0,40):"";return{...e,character:t,...t?{botName:a||CHARACTERS[t].name}:{},characterOptions:normaliseCharacterSettings(r)}}export function chatCharacterState({busy:e=!1,error:r="",ended:t=!1,status:a="none",askDetails:n=!1,replied:i=!1}={}){return r||n?"help":e?"thinking":t||a==="message"?"success":i?"ready":"greeting"}
@@ -1,5 +1,5 @@
1
- import{cssClasses as M}from"./css-classes.mjs";import{characterId as b}from"./characters.mjs";export const LAUNCHER_POSITIONS=["TL","TC","TR","ML","MR","BL","BC","BR"],LAUNCHER_POSITION_LABEL={TL:"Top left",TC:"Top centre",TR:"Top right",ML:"Middle left",MR:"Middle right",BL:"Bottom left",BC:"Bottom centre",BR:"Bottom right"},LAUNCHER_TRIGGER_STYLES=["icon","icon-text"],LAUNCHER_TOOLTIP_MODES=["label","custom","off"],LAUNCHER_DEVICES=["all","desktop","phone"],LAUNCHER_AUDIENCES=["everyone","signed-in","signed-out"],LAUNCHER_PAGE_MODES=["all","only","except"],LAUNCHER_ACTIONS=["modal","slideover","chat"],LAUNCHER_MODAL_KINDS=["page","form","block"],LAUNCHER_SLIDEOVER_KINDS=["page","form","block"],LAUNCHER_MODAL_SIZES=["xs","sm","md","lg","xl","xxl","full","screen","custom"],LAUNCHER_MODAL_HEIGHTS=["auto","sm","md","lg","full","custom"],LAUNCHER_WIDTH_UNITS=["px","%"],LAUNCHER_HEIGHT_UNITS=["px","vh"],LAUNCHER_MODAL_WIDTH_CSS=Object.freeze({xs:"320px",sm:"400px",md:"600px",lg:"800px",xl:"1140px",xxl:"1400px",full:"90vw"}),LAUNCHER_MODAL_HEIGHT_CSS=Object.freeze({sm:"40vh",md:"60vh",lg:"80vh",full:"90vh"}),LAUNCHER_SLIDEOVER_WIDTHS=["sm","md","lg","xl"],LAUNCHER_SIDES=["left","right"],LAUNCHER_ASK_DETAILS=["offline","always","never"],LAUNCHER_TOKENS=["primary","secondary","success","danger","warning","info","surface","text","background"],LAUNCHER_LIMITS=Object.freeze({nameMax:60,labelMax:40,tooltipMax:120,titleMax:80,iconMax:40,idMax:40,sizeMin:32,sizeMax:96,offsetMax:500,pathsMax:50,pathMax:200,greetingMax:300,botNameMax:40,aiContextMax:4e3,aiRulesMax:2e3,avatarMax:300,chatWidth:[300,720],chatHeight:[380,900],startersMax:4,starterMax:80,aiMaxPerChat:[0,100],keepDays:[0,730],widthPx:[240,2400],widthPct:[20,100],heightPx:[160,2e3],heightVh:[20,100]}),LAUNCHER_DEFAULTS=Object.freeze({enabled:!0,showDisc:!0,name:"New launcher",label:"Open",tooltipMode:"label",tooltip:"",icon:"message-circle",triggerStyle:"icon",position:"BR",offsetX:32,offsetY:32,size:52,radius:26,devices:"all",phone:Object.freeze({override:!1,position:"BR",offsetX:16,offsetY:16,size:48}),colours:Object.freeze({background:"",text:""}),class:"",pages:Object.freeze({mode:"all",paths:Object.freeze([])}),audience:"everyone",action:Object.freeze({type:"modal",kind:"page",ref:"",title:"",size:"lg",side:"right",width:"md",customWidth:900,widthUnit:"px",height:"auto",customHeight:70,heightUnit:"vh"}),chat:Object.freeze({greeting:"Hi! How can we help?",botName:"Della",bot:!0,staff:!0,askDetails:"offline",ai:!0,aiUseSite:!0,aiContext:"",aiRules:"",accent:"",accentText:"",avatar:"",character:"",size:"md",width:400,height:600,resizable:!0,starters:Object.freeze([]),aiMaxPerChat:20,personButton:"below",keepDays:0,times:"time"})});const c=(e,t,i)=>t.includes(e)?e:i;function f(e,t,i,o){const r=typeof e=="number"?e:typeof e=="string"&&e.trim()?Number(e):NaN;return Number.isFinite(r)?Math.min(o,Math.max(i,Math.round(r))):Math.min(o,Math.max(i,t))}function l(e,t,i=""){return typeof e!="string"?i:e.replace(/[\u0000-\u001f\u007f]/g," ").trim().replace(/\s+/g," ").slice(0,t)||i}const d=e=>e&&typeof e=="object"&&!Array.isArray(e)?e:{};export const LAUNCHER_ID_RE=/^[a-z0-9][a-z0-9-]{0,39}$/;const y=/^[a-z0-9][a-z0-9-]{0,39}$/,R=/^\/[A-Za-z0-9._~\-/]*$/,C=/^[a-z0-9][a-z0-9_-]{0,99}$/i;export function launcherColour(e){if(typeof e!="string")return"";const t=e.trim().toLowerCase();return LAUNCHER_TOKENS.includes(t)||/^#(?:[0-9a-f]{3}|[0-9a-f]{4}|[0-9a-f]{6}|[0-9a-f]{8})$/.test(t)?t:""}export function launcherColourCss(e){const t=launcherColour(e);return t?LAUNCHER_TOKENS.includes(t)?`var(--dm-${t})`:t:""}export function normaliseLauncherPath(e){if(typeof e!="string")return"";let t=e.trim().split(/[?#]/)[0].replace(/\s+/g,"");return!t||(t.startsWith("/")||(t="/"+t),t=t.replace(/\/{2,}/g,"/"),t.length>1&&(t=t.replace(/\/+$/,"")),t.length>LAUNCHER_LIMITS.pathMax||!/^\/[A-Za-z0-9._~\-/*]*$/.test(t))?"":t}export function launcherPathMatches(e,t){const i=normaliseLauncherPath(e||"/")||"/",o=normaliseLauncherPath(t);return o?o.endsWith("/*")&&i===(o.slice(0,-2)||"/")?!0:new RegExp("^"+o.split("*").map(n=>n.replace(/[.+?^${}()|[\]\\]/g,"\\$&")).join(".*")+"$","i").test(i):!1}export function launcherShowsOn(e,t,i){if(!e||e.enabled===!1||e.audience==="signed-in"&&!i||e.audience==="signed-out"&&i)return!1;const o=e.pages.paths.some(r=>launcherPathMatches(t,r));return e.pages.mode==="only"?o:e.pages.mode==="except"?!o:!0}function E(e,t){const i=d(e);return{override:i.override===!0,position:c(i.position,LAUNCHER_POSITIONS,LAUNCHER_DEFAULTS.phone.position),offsetX:f(i.offsetX,LAUNCHER_DEFAULTS.phone.offsetX,0,LAUNCHER_LIMITS.offsetMax),offsetY:f(i.offsetY,LAUNCHER_DEFAULTS.phone.offsetY,0,LAUNCHER_LIMITS.offsetMax),size:f(i.size,Math.min(t,LAUNCHER_DEFAULTS.phone.size),LAUNCHER_LIMITS.sizeMin,LAUNCHER_LIMITS.sizeMax)}}function L(e){const t=d(e),i=c(t.type,LAUNCHER_ACTIONS,LAUNCHER_DEFAULTS.action.type),o=i==="modal"?LAUNCHER_MODAL_KINDS:LAUNCHER_SLIDEOVER_KINDS,r=i==="chat"?"page":c(t.kind,o,"page");let n=typeof t.ref=="string"?t.ref.trim():"";r==="page"?(n=n?normaliseLauncherPath(n):"",n.includes("*")&&(n="")):C.test(n)||(n=""),i==="chat"&&(n="");const a=LAUNCHER_DEFAULTS.action,h=c(t.widthUnit,LAUNCHER_WIDTH_UNITS,a.widthUnit),s=c(t.heightUnit,LAUNCHER_HEIGHT_UNITS,a.heightUnit);return{type:i,kind:r,ref:n,title:l(t.title,LAUNCHER_LIMITS.titleMax),size:c(t.size,LAUNCHER_MODAL_SIZES,a.size),side:c(t.side,LAUNCHER_SIDES,a.side),width:c(t.width,LAUNCHER_SLIDEOVER_WIDTHS,a.width),customWidth:f(t.customWidth,h==="%"?90:a.customWidth,...h==="%"?LAUNCHER_LIMITS.widthPct:LAUNCHER_LIMITS.widthPx),widthUnit:h,height:c(t.height,LAUNCHER_MODAL_HEIGHTS,a.height),customHeight:f(t.customHeight,s==="px"?600:a.customHeight,...s==="px"?LAUNCHER_LIMITS.heightPx:LAUNCHER_LIMITS.heightVh),heightUnit:s}}export function launcherModalBox(e){const t=e||LAUNCHER_DEFAULTS.action;if(t.size==="screen")return{width:"100vw",height:"100vh",screen:!0};const i=t.size==="custom"?t.widthUnit==="%"?`${t.customWidth}vw`:`${t.customWidth}px`:LAUNCHER_MODAL_WIDTH_CSS[t.size]||LAUNCHER_MODAL_WIDTH_CSS.lg,o=t.height==="custom"?`${t.customHeight}${t.heightUnit==="px"?"px":"vh"}`:LAUNCHER_MODAL_HEIGHT_CSS[t.height]||"";return{width:i,height:o,screen:!1}}export function normaliseLauncherChat(e){const t=d(e),i=LAUNCHER_DEFAULTS.chat;return{greeting:typeof t.greeting=="string"?t.greeting.replace(/\r\n?/g,`
2
- `).replace(/[\u0000-\u0009\u000b-\u001f\u007f]/g," ").trim().slice(0,LAUNCHER_LIMITS.greetingMax):i.greeting,botName:l(t.botName,LAUNCHER_LIMITS.botNameMax,i.botName),bot:t.bot!==!1,staff:t.staff!==!1,askDetails:c(t.askDetails,LAUNCHER_ASK_DETAILS,i.askDetails),ai:t.ai!==!1,aiUseSite:t.aiUseSite!==!1,aiContext:m(t.aiContext,LAUNCHER_LIMITS.aiContextMax),aiRules:m(t.aiRules,LAUNCHER_LIMITS.aiRulesMax),accent:launcherColour(t.accent),accentText:launcherColour(t.accentText),avatar:launcherAvatar(t.avatar),character:b(t.character),size:c(t.size,LAUNCHER_CHAT_SIZES,i.size),width:f(t.width,i.width,...LAUNCHER_LIMITS.chatWidth),height:f(t.height,i.height,...LAUNCHER_LIMITS.chatHeight),resizable:t.resizable!==!1,starters:(Array.isArray(t.starters)?t.starters:typeof t.starters=="string"?t.starters.split(`
1
+ import{cssClasses as M}from"./css-classes.mjs";import{characterId as b}from"./characters.mjs";export const LAUNCHER_POSITIONS=["TL","TC","TR","ML","MR","BL","BC","BR"],LAUNCHER_POSITION_LABEL={TL:"Top left",TC:"Top centre",TR:"Top right",ML:"Middle left",MR:"Middle right",BL:"Bottom left",BC:"Bottom centre",BR:"Bottom right"},LAUNCHER_TRIGGER_STYLES=["icon","icon-text"],LAUNCHER_TOOLTIP_MODES=["label","custom","off"],LAUNCHER_DEVICES=["all","desktop","phone"],LAUNCHER_AUDIENCES=["everyone","signed-in","signed-out"],LAUNCHER_PAGE_MODES=["all","only","except"],LAUNCHER_ACTIONS=["modal","slideover","chat"],LAUNCHER_MODAL_KINDS=["page","form","block"],LAUNCHER_SLIDEOVER_KINDS=["page","form","block"],LAUNCHER_MODAL_SIZES=["xs","sm","md","lg","xl","xxl","full","screen","custom"],LAUNCHER_MODAL_HEIGHTS=["auto","sm","md","lg","full","custom"],LAUNCHER_WIDTH_UNITS=["px","%"],LAUNCHER_HEIGHT_UNITS=["px","vh"],LAUNCHER_MODAL_WIDTH_CSS=Object.freeze({xs:"320px",sm:"400px",md:"600px",lg:"800px",xl:"1140px",xxl:"1400px",full:"90vw"}),LAUNCHER_MODAL_HEIGHT_CSS=Object.freeze({sm:"40vh",md:"60vh",lg:"80vh",full:"90vh"}),LAUNCHER_SLIDEOVER_WIDTHS=["sm","md","lg","xl"],LAUNCHER_SIDES=["left","right"],LAUNCHER_ASK_DETAILS=["offline","always","never"],LAUNCHER_TOKENS=["primary","secondary","success","danger","warning","info","surface","text","background"],LAUNCHER_LIMITS=Object.freeze({nameMax:60,labelMax:40,tooltipMax:120,titleMax:80,iconMax:40,idMax:40,sizeMin:32,sizeMax:96,offsetMax:500,pathsMax:50,pathMax:200,greetingMax:300,botNameMax:40,aiContextMax:4e3,aiRulesMax:2e3,avatarMax:300,chatWidth:[300,720],chatHeight:[380,900],startersMax:4,starterMax:80,aiMaxPerChat:[0,100],keepDays:[0,730],widthPx:[240,2400],widthPct:[20,100],heightPx:[160,2e3],heightVh:[20,100]}),LAUNCHER_DEFAULTS=Object.freeze({enabled:!0,showDisc:!0,name:"New launcher",label:"Open",tooltipMode:"label",tooltip:"",icon:"message-circle",triggerStyle:"icon",position:"BR",offsetX:32,offsetY:32,size:52,radius:26,devices:"all",phone:Object.freeze({override:!1,position:"BR",offsetX:16,offsetY:16,size:48}),colours:Object.freeze({background:"",text:""}),class:"",pages:Object.freeze({mode:"all",paths:Object.freeze([])}),audience:"everyone",action:Object.freeze({type:"modal",kind:"page",ref:"",title:"",size:"lg",side:"right",width:"md",customWidth:900,widthUnit:"px",height:"auto",customHeight:70,heightUnit:"vh"}),chat:Object.freeze({greeting:"Hi! How can we help?",botName:"Della",bot:!0,staff:!0,askDetails:"offline",ai:!0,aiUseSite:!0,aiContext:"",aiRules:"",accent:"",accentText:"",avatar:"",character:"",characterName:"",size:"md",width:400,height:600,resizable:!0,starters:Object.freeze([]),aiMaxPerChat:20,personButton:"below",keepDays:0,times:"time"})});const c=(e,t,i)=>t.includes(e)?e:i;function f(e,t,i,o){const r=typeof e=="number"?e:typeof e=="string"&&e.trim()?Number(e):NaN;return Number.isFinite(r)?Math.min(o,Math.max(i,Math.round(r))):Math.min(o,Math.max(i,t))}function l(e,t,i=""){return typeof e!="string"?i:e.replace(/[\u0000-\u001f\u007f]/g," ").trim().replace(/\s+/g," ").slice(0,t)||i}const d=e=>e&&typeof e=="object"&&!Array.isArray(e)?e:{};export const LAUNCHER_ID_RE=/^[a-z0-9][a-z0-9-]{0,39}$/;const y=/^[a-z0-9][a-z0-9-]{0,39}$/,R=/^\/[A-Za-z0-9._~\-/]*$/,C=/^[a-z0-9][a-z0-9_-]{0,99}$/i;export function launcherColour(e){if(typeof e!="string")return"";const t=e.trim().toLowerCase();return LAUNCHER_TOKENS.includes(t)||/^#(?:[0-9a-f]{3}|[0-9a-f]{4}|[0-9a-f]{6}|[0-9a-f]{8})$/.test(t)?t:""}export function launcherColourCss(e){const t=launcherColour(e);return t?LAUNCHER_TOKENS.includes(t)?`var(--dm-${t})`:t:""}export function normaliseLauncherPath(e){if(typeof e!="string")return"";let t=e.trim().split(/[?#]/)[0].replace(/\s+/g,"");return!t||(t.startsWith("/")||(t="/"+t),t=t.replace(/\/{2,}/g,"/"),t.length>1&&(t=t.replace(/\/+$/,"")),t.length>LAUNCHER_LIMITS.pathMax||!/^\/[A-Za-z0-9._~\-/*]*$/.test(t))?"":t}export function launcherPathMatches(e,t){const i=normaliseLauncherPath(e||"/")||"/",o=normaliseLauncherPath(t);return o?o.endsWith("/*")&&i===(o.slice(0,-2)||"/")?!0:new RegExp("^"+o.split("*").map(n=>n.replace(/[.+?^${}()|[\]\\]/g,"\\$&")).join(".*")+"$","i").test(i):!1}export function launcherShowsOn(e,t,i){if(!e||e.enabled===!1||e.audience==="signed-in"&&!i||e.audience==="signed-out"&&i)return!1;const o=e.pages.paths.some(r=>launcherPathMatches(t,r));return e.pages.mode==="only"?o:e.pages.mode==="except"?!o:!0}function E(e,t){const i=d(e);return{override:i.override===!0,position:c(i.position,LAUNCHER_POSITIONS,LAUNCHER_DEFAULTS.phone.position),offsetX:f(i.offsetX,LAUNCHER_DEFAULTS.phone.offsetX,0,LAUNCHER_LIMITS.offsetMax),offsetY:f(i.offsetY,LAUNCHER_DEFAULTS.phone.offsetY,0,LAUNCHER_LIMITS.offsetMax),size:f(i.size,Math.min(t,LAUNCHER_DEFAULTS.phone.size),LAUNCHER_LIMITS.sizeMin,LAUNCHER_LIMITS.sizeMax)}}function L(e){const t=d(e),i=c(t.type,LAUNCHER_ACTIONS,LAUNCHER_DEFAULTS.action.type),o=i==="modal"?LAUNCHER_MODAL_KINDS:LAUNCHER_SLIDEOVER_KINDS,r=i==="chat"?"page":c(t.kind,o,"page");let n=typeof t.ref=="string"?t.ref.trim():"";r==="page"?(n=n?normaliseLauncherPath(n):"",n.includes("*")&&(n="")):C.test(n)||(n=""),i==="chat"&&(n="");const a=LAUNCHER_DEFAULTS.action,h=c(t.widthUnit,LAUNCHER_WIDTH_UNITS,a.widthUnit),s=c(t.heightUnit,LAUNCHER_HEIGHT_UNITS,a.heightUnit);return{type:i,kind:r,ref:n,title:l(t.title,LAUNCHER_LIMITS.titleMax),size:c(t.size,LAUNCHER_MODAL_SIZES,a.size),side:c(t.side,LAUNCHER_SIDES,a.side),width:c(t.width,LAUNCHER_SLIDEOVER_WIDTHS,a.width),customWidth:f(t.customWidth,h==="%"?90:a.customWidth,...h==="%"?LAUNCHER_LIMITS.widthPct:LAUNCHER_LIMITS.widthPx),widthUnit:h,height:c(t.height,LAUNCHER_MODAL_HEIGHTS,a.height),customHeight:f(t.customHeight,s==="px"?600:a.customHeight,...s==="px"?LAUNCHER_LIMITS.heightPx:LAUNCHER_LIMITS.heightVh),heightUnit:s}}export function launcherModalBox(e){const t=e||LAUNCHER_DEFAULTS.action;if(t.size==="screen")return{width:"100vw",height:"100vh",screen:!0};const i=t.size==="custom"?t.widthUnit==="%"?`${t.customWidth}vw`:`${t.customWidth}px`:LAUNCHER_MODAL_WIDTH_CSS[t.size]||LAUNCHER_MODAL_WIDTH_CSS.lg,o=t.height==="custom"?`${t.customHeight}${t.heightUnit==="px"?"px":"vh"}`:LAUNCHER_MODAL_HEIGHT_CSS[t.height]||"";return{width:i,height:o,screen:!1}}export function normaliseLauncherChat(e){const t=d(e),i=LAUNCHER_DEFAULTS.chat;return{greeting:typeof t.greeting=="string"?t.greeting.replace(/\r\n?/g,`
2
+ `).replace(/[\u0000-\u0009\u000b-\u001f\u007f]/g," ").trim().slice(0,LAUNCHER_LIMITS.greetingMax):i.greeting,botName:l(t.botName,LAUNCHER_LIMITS.botNameMax,i.botName),bot:t.bot!==!1,staff:t.staff!==!1,askDetails:c(t.askDetails,LAUNCHER_ASK_DETAILS,i.askDetails),ai:t.ai!==!1,aiUseSite:t.aiUseSite!==!1,aiContext:m(t.aiContext,LAUNCHER_LIMITS.aiContextMax),aiRules:m(t.aiRules,LAUNCHER_LIMITS.aiRulesMax),accent:launcherColour(t.accent),accentText:launcherColour(t.accentText),avatar:launcherAvatar(t.avatar),character:b(t.character),characterName:l(t.characterName,LAUNCHER_LIMITS.botNameMax,""),size:c(t.size,LAUNCHER_CHAT_SIZES,i.size),width:f(t.width,i.width,...LAUNCHER_LIMITS.chatWidth),height:f(t.height,i.height,...LAUNCHER_LIMITS.chatHeight),resizable:t.resizable!==!1,starters:(Array.isArray(t.starters)?t.starters:typeof t.starters=="string"?t.starters.split(`
3
3
  `):[]).map(r=>l(r,LAUNCHER_LIMITS.starterMax)).filter(Boolean).slice(0,LAUNCHER_LIMITS.startersMax),aiMaxPerChat:f(t.aiMaxPerChat,i.aiMaxPerChat,...LAUNCHER_LIMITS.aiMaxPerChat),personButton:c(t.personButton,LAUNCHER_PERSON_BUTTON,i.personButton),keepDays:f(t.keepDays,i.keepDays,...LAUNCHER_LIMITS.keepDays),times:c(t.times,LAUNCHER_CHAT_TIMES,i.times)}}export const LAUNCHER_PERSON_BUTTON=["below","header"],LAUNCHER_CHAT_TIMES=["time","datetime","none"],GREETING_PLACEHOLDERS=["greeting","timeofday","day","date","time","botname","site"];export function fillGreeting(e,{now:t=new Date,botName:i="",site:o=""}={}){const r=t.getHours(),n=r<12?"morning":r<18?"afternoon":"evening",a={greeting:`Good ${n}`,timeofday:n,day:t.toLocaleDateString("en-GB",{weekday:"long"}),date:t.toLocaleDateString("en-GB",{day:"numeric",month:"long"}),time:t.toLocaleTimeString("en-GB",{hour:"2-digit",minute:"2-digit"}),botname:i,site:o};return String(e??"").replace(/\{\s*([a-z]+)\s*\}/gi,(h,s)=>{const u=a[s.toLowerCase()];return u===void 0?h:u})}export const LAUNCHER_CHAT_SIZES=["sm","md","lg","custom"];const x={sm:[340,500],md:[400,600],lg:[480,720]};export function launcherChatBox(e={}){if(e.size==="custom")return{width:f(e.width,400,...LAUNCHER_LIMITS.chatWidth),height:f(e.height,600,...LAUNCHER_LIMITS.chatHeight)};const[t,i]=x[e.size]||x.md;return{width:t,height:i}}export function launcherAvatar(e){if(typeof e!="string")return"";const t=e.trim();return!t||t.length>LAUNCHER_LIMITS.avatarMax||t.startsWith("//")?"":/^\/[A-Za-z0-9._~\-/%]+$/.test(t)?t:""}export function launcherChatAccentCss(e={}){const t=launcherColourCss(e.accent);if(!t)return{accent:"",accentText:""};let i=launcherColourCss(e.accentText);if(!i){const o=launcherColour(e.accent);if(o.startsWith("#")){const r=o.length<=5?o.slice(1,4).split("").map(s=>s+s).join(""):o.slice(1,7),[n,a,h]=[0,2,4].map(s=>parseInt(r.slice(s,s+2),16)/255).map(s=>s<=.03928?s/12.92:((s+.055)/1.055)**2.4);i=.2126*n+.7152*a+.0722*h>.179?"#111111":"#ffffff"}else i=o==="primary"?"var(--dm-primary-text, #fff)":`var(--dm-${o}-text, #fff)`}return{accent:t,accentText:i}}function m(e,t){return typeof e=="string"?e.replace(/\r\n?/g,`
4
4
  `).replace(/[\u0000-\u0009\u000b-\u001f\u007f]/g," ").replace(/\n{3,}/g,`
5
5
 
@@ -1,4 +1,4 @@
1
- import{LAUNCHER_LIMITS as C,launcherChatBox as mt,launcherModalBox as pt,launcherSpot as ft,launcherStack as vt}from"/public/js/launcher-settings.mjs?v=20261110-builder-characters";const V=i=>`launcher-chat-size:${i}`,bt=i=>{try{const c=globalThis.S?.get?.(V(i));return c&&Number(c.width)&&Number(c.height)?c:null}catch{return null}},Z=(i,c)=>{try{globalThis.S?.set?.(V(i),c)}catch{}};import{mountCharacter as gt}from"./character-view.mjs?v=20261110-builder-characters";const J="(max-width: 640px)",Q=[".site-search-floating-trigger","#back-to-top-btn","#go-to-bottom-btn",".dm-theme-switcher:not(.dm-ts-inline)","nav.dm-breadcrumbs",".dm-motion-fab"].join(","),tt={sm:"360px",md:"480px",lg:"640px",xl:"860px"},yt=i=>String(i??"").replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;"),et=()=>document.documentElement.classList.contains("dm-reduced-motion")||matchMedia("(prefers-reduced-motion: reduce)").matches,wt=`
1
+ import{LAUNCHER_LIMITS as C,launcherChatBox as mt,launcherModalBox as pt,launcherSpot as ft,launcherStack as vt}from"/public/js/launcher-settings.mjs?v=20261110-character-name";const V=i=>`launcher-chat-size:${i}`,bt=i=>{try{const c=globalThis.S?.get?.(V(i));return c&&Number(c.width)&&Number(c.height)?c:null}catch{return null}},Z=(i,c)=>{try{globalThis.S?.set?.(V(i),c)}catch{}};import{mountCharacter as gt}from"./character-view.mjs?v=20261110-builder-characters";const J="(max-width: 640px)",Q=[".site-search-floating-trigger","#back-to-top-btn","#go-to-bottom-btn",".dm-theme-switcher:not(.dm-ts-inline)","nav.dm-breadcrumbs",".dm-motion-fab"].join(","),tt={sm:"360px",md:"480px",lg:"640px",xl:"860px"},yt=i=>String(i??"").replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;"),et=()=>document.documentElement.classList.contains("dm-reduced-motion")||matchMedia("(prefers-reduced-motion: reduce)").matches,wt=`
2
2
  <button type="button" class="dm-launcher" data-id="{{id}}" data-bind-class="cls" data-bind-style="style.value"
3
3
  data-bind-aria-expanded="expanded.value" data-bind-hidden="hidden.value" aria-haspopup="dialog" aria-label="{{label}}">
4
4
  <span class="dm-launcher-icon" data-icon="{{icon}}" aria-hidden="true"></span>
@@ -0,0 +1,43 @@
1
+ /** Authenticated help and drafts, separate from visitor chat and with no write tools. */
2
+ import {authenticate as defaultAuthenticate} from '../../middleware/auth.js';
3
+ import {getConfig} from '../../config.js';
4
+ import {siteAssistant} from '../../services/assistant.js';
5
+ import {adminAssistantConfig, adminAssistantContext, requestAdminAnswer} from '../../services/adminAssistant.js';
6
+
7
+ export async function adminAssistantRoutes(fastify, {authenticate = defaultAuthenticate, contextFor = adminAssistantContext, settings = adminAssistantConfig, answer = requestAdminAnswer} = {}) {
8
+ const guard = {preHandler: [authenticate]};
9
+ fastify.get('/admin-assistant/config', guard, async request => {
10
+ const cfg = settings();
11
+ if (!cfg.enabled) return {enabled: false};
12
+ const help = contextFor(request.user, request.query?.route || '/');
13
+ if (help.error) return {enabled: false};
14
+ return {enabled: true, available: cfg.available, name: help.name || cfg.name,
15
+ character: cfg.charactersEnabled === false ? '' : help.character || cfg.character, animated: cfg.animated};
16
+ });
17
+ fastify.post('/admin-assistant/ask', {...guard, bodyLimit: 20 * 1024, config: {rateLimit: {max: 12, timeWindow: '1 minute'}}}, async (request, reply) => {
18
+ const cfg = settings();
19
+ if (!cfg.enabled) return reply.code(403).send({error: 'The admin assistant is switched off.'});
20
+ const body = request.body || {};
21
+ if (typeof body.question !== 'string' || !body.question.trim() || body.question.length > 1000) return reply.code(400).send({error: 'Ask a question of up to 1000 characters.'});
22
+ if (body.history !== undefined && (!Array.isArray(body.history) || body.history.length > 10 || body.history.some(m => !['visitor', 'bot'].includes(m?.from) || typeof m.text !== 'string' || m.text.length > 1000))) {
23
+ return reply.code(400).send({error: 'Invalid conversation history.'});
24
+ }
25
+ const help = contextFor(request.user, body.route || '/');
26
+ if (help.error) return reply.code(help.status).send({error: help.error});
27
+ const site = getConfig('site') || {};
28
+ const shared = siteAssistant();
29
+ try {
30
+ const result = await answer({audience: 'admin', botName: help.name || cfg.name,
31
+ site: {name: String(site.title || '').slice(0, 200)}, context: [shared.context, cfg.context].filter(Boolean).join('\n\n'),
32
+ rules: [shared.rules, cfg.rules].filter(Boolean).join('\n'), knowledge: (help.context.match(/[\s\S]{1,4000}/g) || []).map((a, i) => ({q: `Admin tool guidance ${i + 1}`, a})),
33
+ history: body.history || [], question: body.question.trim()});
34
+ if (result.status !== 200) return reply.code([403, 429, 503].includes(result.status) ? result.status : 503)
35
+ .send({error: result.status === 429 ? 'The site AI allowance is currently unavailable. Please try again later.' : 'AI answers are not available for this site right now.'});
36
+ if (result.body?.audience !== 'admin') return reply.code(503).send({error: 'The Manager needs the admin assistant update before it can answer here.'});
37
+ return {answer: typeof result.body.answer === 'string' && result.body.answer.trim()
38
+ ? result.body.answer.slice(0, 6000) : 'I do not have enough information to answer that. Try asking about the current tool or provide the facts for a draft.'};
39
+ } catch {
40
+ return reply.code(503).send({error: 'The assistant could not answer just now. Please try again.'});
41
+ }
42
+ });
43
+ }
@@ -24,6 +24,7 @@ import {cssClassProblems} from '../../../public/js/css-classes.mjs';
24
24
  import {motionFooterMirror, normaliseMotionSettings} from '../../services/motionSettings.js';
25
25
  import {invalidateMeasurementId, measurementIdOf, normaliseMeasurementId} from '../../services/googleAnalytics.js';
26
26
  import {assistantProblem, normaliseAssistant} from '../../services/assistant.js';
27
+ import {adminAssistantProblem, normaliseAdminAssistant} from '../../services/adminAssistant.js';
27
28
  import {normaliseCharacterSettings} from '../../../public/js/characters.mjs';
28
29
 
29
30
  const __dirname = path.dirname(fileURLToPath(import.meta.url));
@@ -150,7 +151,7 @@ export async function settingsRoutes(fastify) {
150
151
  // The "Reduce motion" control (Site Settings > Reduce motion) - services/motionSettings.js.
151
152
  'motion',
152
153
  // What every AI answer knows about the site and the rules it keeps (services/assistant.js).
153
- 'assistant', 'characters'
154
+ 'assistant', 'characters', 'adminAssistant'
154
155
  ]);
155
156
  const unknownKeys = Object.keys(data).filter(k => !ALLOWED_KEYS.has(k));
156
157
  if (unknownKeys.length > 0) {
@@ -193,6 +194,10 @@ export async function settingsRoutes(fastify) {
193
194
  if ('characters' in data && (!data.characters || typeof data.characters !== 'object' || Array.isArray(data.characters))) {
194
195
  return reply.status(400).send({error: 'Builders and Bots: send an object.'});
195
196
  }
197
+ if ('adminAssistant' in data) {
198
+ const problem = adminAssistantProblem(data.adminAssistant);
199
+ if (problem) return reply.status(400).send({error: `Admin assistant: ${problem}`});
200
+ }
196
201
  if ('assistant' in data) {
197
202
  const a = data.assistant;
198
203
  if (!a || typeof a !== 'object' || Array.isArray(a)) return reply.status(400).send({error: 'AI assistant: send {context, rules}.'});
@@ -223,6 +228,7 @@ export async function settingsRoutes(fastify) {
223
228
  // The Reduce motion control: stored whitelisted, with the footer keys it used to live
224
229
  // under kept in step for older readers. A client that still writes only those footer
225
230
  // keys (fleet tooling) moves the block with them, so its change is not overruled.
231
+ if ('adminAssistant' in data) merged.adminAssistant = normaliseAdminAssistant(merged.adminAssistant);
226
232
  if ('characters' in data) merged.characters = normaliseCharacterSettings(merged.characters);
227
233
  if ('motion' in data) {
228
234
  if (data.motion !== null && (typeof data.motion !== 'object' || Array.isArray(data.motion))) {
package/server/server.js CHANGED
@@ -556,6 +556,7 @@ const { formsRoutes } = await import('./routes/api/forms.js');
556
556
  const { viewsRoutes } = await import('./routes/api/views.js');
557
557
  const { actionsRoutes } = await import('./routes/api/actions.js');
558
558
  const {blocksRoutes} = await import('./routes/api/blocks.js');
559
+ const {adminAssistantRoutes} = await import('./routes/api/admin-assistant.js');
559
560
  const {listTagsRoutes} = await import('./routes/api/list-tags.js');
560
561
  const {componentsRoutes} = await import('./routes/api/components.js');
561
562
  const {versionsRoutes} = await import('./routes/api/versions.js');
@@ -595,6 +596,7 @@ await app.register(formsRoutes, { prefix: '/api' });
595
596
  await app.register(viewsRoutes, { prefix: '/api' });
596
597
  await app.register(actionsRoutes, { prefix: '/api' });
597
598
  await app.register(blocksRoutes, {prefix: '/api'});
599
+ await app.register(adminAssistantRoutes, {prefix: '/api'});
598
600
  await app.register(listTagsRoutes, {prefix: '/api'});
599
601
  await app.register(componentsRoutes, {prefix: '/api'});
600
602
  await app.register(versionsRoutes, {prefix: '/api'});
@@ -0,0 +1,73 @@
1
+ /** Core admin assistant: opt-in settings, permission-filtered help and AI transport. */
2
+ import {getConfig} from '../config.js';
3
+ import {adminAccessFor} from './adminAccess.js';
4
+ import {covers} from './pluginScope.js';
5
+ import {characterId, normaliseCharacterSettings} from '../../public/js/characters.mjs';
6
+
7
+ const providers = new Map();
8
+ const text = (v, max) => typeof v === 'string' ? v.trim().slice(0, max) : '';
9
+ export function normaliseAdminAssistant(value = {}) {
10
+ return {enabled: value?.enabled === true, name: text(value?.name, 40) || 'Della',
11
+ character: characterId(value?.character), context: text(value?.context, 4000), rules: text(value?.rules, 2000)};
12
+ }
13
+ export function adminAssistantProblem(value) {
14
+ if (!value || typeof value !== 'object' || Array.isArray(value)) return 'Send an admin assistant object.';
15
+ if (value.enabled !== undefined && typeof value.enabled !== 'boolean') return 'enabled must be true or false.';
16
+ for (const [key, max] of [['name', 40], ['context', 4000], ['rules', 2000]]) {
17
+ if (value[key] !== undefined && (typeof value[key] !== 'string' || value[key].length > max)) return `${key} must be text of at most ${max} characters.`;
18
+ }
19
+ if (value.character !== undefined && value.character !== '' && !characterId(value.character)) return 'Choose a known character or no character.';
20
+ return '';
21
+ }
22
+
23
+ /** Plugins supply static help, never records. The loader binds registration to its owner. */
24
+ export function registerAdminAssistant(owner, def, allowedRoutes) {
25
+ if (!def || !Array.isArray(def.routes) || !def.routes.length || !def.permission || !text(def.context, 8000)) {
26
+ throw new Error('Admin assistant help needs routes, a permission and context.');
27
+ }
28
+ if (!def.routes.every(r => typeof r === 'string' && /^\/[a-z0-9/_-]*$/i.test(r))) throw new Error('Invalid assistant route.');
29
+ if (allowedRoutes && !def.routes.every(route => allowedRoutes.some(prefix => covers(prefix, route)))) throw new Error('Assistant routes must belong to the registering plugin.');
30
+ providers.set(owner, {routes: [...def.routes], permission: String(def.permission), context: text(def.context, 8000), name: text(def.name, 40), character: characterId(def.character)});
31
+ return () => providers.delete(owner);
32
+ }
33
+
34
+ const CORE_HELP = [
35
+ {routes: ['/pages', '/page'], permission: 'pages.read', context: 'Pages are edited under Content > Pages. Open a page, edit its title and Markdown content, and use Preview to review it. Use the editor Save command to save it. Its status determines whether it is published. This assistant can draft text but cannot save or publish it.'},
36
+ {routes: ['/theme'], permission: 'theme.read', context: 'Content > Theme controls the public and admin themes, typography, scheduled day/night themes, the public theme switcher and scoped element overrides. Make changes in the Theme tool and use Save. Site and admin themes are independent.'},
37
+ {routes: ['/settings'], permission: 'settings.read', context: 'Site Settings controls the site identity, branding, footer, email settings and assistant configuration. Changes are saved using the Save command. Only people with the settings update permission can change these options.'}
38
+ ];
39
+ const GENERAL = 'You are inside Domma CMS admin. The navigation shows tools this account can use. You provide explanations and draft plain text for the person to copy into an editor. You cannot inspect records or carry out actions. For an undocumented operation, say you do not know. Never suggest bypassing permissions.';
40
+
41
+ export function adminAssistantContext(user, route = '/', access = adminAccessFor(user)) {
42
+ const path = typeof route === 'string' ? route.split('?')[0].slice(0, 200) : '/';
43
+ if (!/^\/[a-z0-9/_-]*$/i.test(path)) return {error: 'Invalid admin screen.', status: 400};
44
+ const scope = access.adminScope;
45
+ const always = ['/my-profile', '/my-preferences'];
46
+ if (scope && ![...(scope.allow || []), ...always].some(prefix => covers(prefix, path))) return {error: 'That screen is outside your admin access.', status: 403};
47
+ const matching = [...CORE_HELP, ...providers.values()].filter(p => p.routes.some(prefix => covers(prefix, path)));
48
+ const holds = permission => access.permissions.includes(permission) || access.permissions.includes(permission.replace(/\.read$/, ''));
49
+ const allowed = matching.filter(p => holds(p.permission));
50
+ if (matching.length && !allowed.length) return {error: 'You do not have permission for that tool.', status: 403};
51
+ const persona = allowed.find(p => p.name);
52
+ return {context: [GENERAL, ...allowed.map(p => p.context)].join('\n\n'),
53
+ ...(persona ? {name: persona.name, character: persona.character} : {})};
54
+ }
55
+
56
+ export function adminAssistantConfig() {
57
+ const site = getConfig('site') || {};
58
+ const settings = normaliseAdminAssistant(site.adminAssistant);
59
+ const characters = normaliseCharacterSettings(site.characters);
60
+ return {...settings, character: characters.enabled ? settings.character : '', charactersEnabled: characters.enabled, animated: characters.animated,
61
+ available: Boolean(globalThis[Symbol.for('domma.launcher-chat')] || process.env.MANAGER_URL && process.env.FLEET_TOKEN)};
62
+ }
63
+
64
+ export async function requestAdminAnswer(input, {env = process.env, fetchFn = fetch} = {}) {
65
+ const local = globalThis[Symbol.for('domma.launcher-chat')];
66
+ if (local) return local.answer(input);
67
+ if (!env.MANAGER_URL || !env.FLEET_TOKEN) return {status: 503, body: {error: 'AI answers are not configured on this site.'}};
68
+ const response = await fetchFn(`${env.MANAGER_URL.replace(/\/+$/, '')}/api/fleet/launcher-chat`, {
69
+ method: 'POST', headers: {authorization: `Bearer ${env.FLEET_TOKEN}`, 'content-type': 'application/json'},
70
+ body: JSON.stringify(input), signal: AbortSignal.timeout(30_000)
71
+ });
72
+ return {status: response.status, body: await response.json()};
73
+ }
@@ -97,6 +97,7 @@ export function normaliseLauncherChat(raw) {
97
97
  accentText: launcherColour(r.accentText),
98
98
  avatar: launcherAvatar(r.avatar),
99
99
  character: storedChat(r).character,
100
+ characterName: clip(r.characterName, BOT_NAME_MAX, ''),
100
101
  aiMaxPerChat: Number.isFinite(Number(r.aiMaxPerChat)) && String(r.aiMaxPerChat ?? '').trim() !== ''
101
102
  ? Math.min(100, Math.max(0, Math.round(Number(r.aiMaxPerChat)))) : LAUNCHER_CHAT_DEFAULTS.aiMaxPerChat,
102
103
  starters: storedChat(r).starters,
@@ -26,7 +26,7 @@ import {
26
26
  export const LAUNCHERS_CACHE_TAG = 'site';
27
27
 
28
28
  /** Bumped by hand when launchers.mjs or launchers.css changes - the updater replaces public/ wholesale. */
29
- export const LAUNCHERS_ASSET_V = '20261110-builder-characters';
29
+ export const LAUNCHERS_ASSET_V = '20261110-character-name';
30
30
 
31
31
  /** @returns {object[]} the stored launchers, normalised, in order; none when the file is missing or broken */
32
32
  export function getLaunchers() {
@@ -36,6 +36,7 @@ import {
36
36
  } from './hooks.js';
37
37
  import {registerPluginResource, unregisterPluginResourcesByPlugin} from './permissionRegistry.js';
38
38
  import {registerThemeProvider} from './themeSettings.js';
39
+ import {registerAdminAssistant} from './adminAssistant.js';
39
40
  import {classifyEntitlement, mayLoad} from './pluginEntitlement.js';
40
41
  import {notifierFor} from './notify.js';
41
42
  import {disableInstantCalls, enableInstantCalls, grantInstantCallsOnce} from './instantCalls.js';
@@ -45,7 +46,7 @@ import {disableDashboardPro, enableDashboardPro, registerWidget, unregisterWidge
45
46
  import {createCollection, getCollection, updateCollection} from './collections.js';
46
47
  import * as defaultRolesService from './roles.js';
47
48
  import {getAdminScope, normaliseAdminScope} from './roles.js';
48
- import {pluginAuthGuards} from './pluginScope.js';
49
+ import {pluginAuthGuards, pluginAdminPaths} from './pluginScope.js';
49
50
  import {getEffectiveRoles} from './userRoles.js';
50
51
  import {isDcmStaff} from './staffAccess.js';
51
52
  import * as defaultUsersService from './users.js';
@@ -554,6 +555,7 @@ export async function registerPlugins(fastify) {
554
555
  // Custom themes the plugin offers (the Theme Roller) - bound to the
555
556
  // plugin, so one plugin cannot replace another's. See themeSettings.js.
556
557
  registerThemes: (provider) => registerThemeProvider(manifest.name, provider),
558
+ registerAdminAssistant: (definition) => registerAdminAssistant(manifest.name, definition, pluginAdminPaths(manifest)),
557
559
  // Calendar sources and related items (0.79) - stamped with the plugin's name.
558
560
  registerCalendarSource: (source) => registerCalendarSource({...source, owner: manifest.name}),
559
561
  getCalendarSources,