domma-cms 1.49.2 → 1.50.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +7 -0
- package/admin/js/lib/chats-arrange.js +2 -2
- package/admin/js/lib/launchers-arrange.js +5 -2
- package/admin/js/lib/site-settings-arrange.js +2 -2
- package/admin/js/templates/chats.html +26 -2
- package/admin/js/templates/docs/usage-chat.html +51 -5
- package/admin/js/templates/launchers.html +4 -0
- package/admin/js/templates/settings.html +18 -0
- package/admin/js/views/chats.js +5 -5
- package/admin/js/views/launchers.js +105 -33
- package/docs/DommaFeatures.md +4 -0
- package/package.json +1 -1
- package/public/css/launcher-chat.css +1 -1
- package/public/css/launchers.css +1 -1
- package/public/js/launcher-chat.mjs +16 -10
- package/public/js/launcher-settings.mjs +6 -2
- package/public/js/launchers.mjs +3 -3
- package/server/routes/api/chat.js +4 -2
- package/server/routes/api/chats.js +37 -0
- package/server/routes/api/settings.js +11 -1
- package/server/services/assistant.js +67 -0
- package/server/services/chat/ai.js +109 -0
- package/server/services/chat/conversation.js +37 -2
- package/server/services/chat/saved.js +117 -0
- package/server/services/chat/settings.js +30 -4
- package/server/services/chat/store.js +1 -1
- package/server/services/collectionAccess.js +2 -1
- package/server/services/launchers.js +1 -1
- package/server/services/presetCollections.js +24 -2
- package/server/services/siteGitignore.js +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,12 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## [1.50.0] - 2026-11-10
|
|
4
|
+
|
|
5
|
+
- **Della, the chat bot, can answer with AI what the Knowledge does not** (Pro plan, hosted sites). Claude answers only from the Knowledge, Site Settings > General > AI assistant (About the business, Rules) and each chat launcher's own context and rules, and says it does not know rather than guess. Switch it off per launcher. The bot's default name is now Della. `services/chat/ai.js`, `services/assistant.js`.
|
|
6
|
+
- **Save a chat for a closer look.** Chats > right-click > Save for a closer look keeps a copy (the Saved Chats collection) with a note and an outcome, under a new Saved tab in the inbox. It outlives the chat's own tidy-up.
|
|
7
|
+
- **More per-chat settings in Launchers:** the chat window size and whether visitors can resize it, up to four questions to start with, Talk to a person as an icon in the heading, a cap on AI answers per chat, and how long its chats are kept (the site's time by default). The greeting takes `{greeting}`, `{timeofday}`, `{day}`, `{date}`, `{time}`, `{botname}` and `{site}`, and each chat chooses whether messages show the time, the date and time, or nothing. A launcher may leave out the site's AI context but never its Rules.
|
|
8
|
+
- **The visitor chat has a new look**: avatars, grouped messages, a heading with the bot's status, a rounded composer. Each chat launcher can carry its own branding: the bot's name, a **chat colour** (and the text on it) and a **bot's picture** from Media.
|
|
9
|
+
|
|
3
10
|
## [1.49.2] - 2026-11-09
|
|
4
11
|
|
|
5
12
|
- **The menu marks the right item when several point at one page with different queries.** A navbar or footer with "Find a job" (`/jobs`), "Contract roles" (`/jobs?type=contract`) and "Remote roles" (`/jobs?remote=remote`) used to show all three as the current page on `/jobs`. Now an item counts only when its own query is in the address, and the most specific one wins: `/jobs` marks "Find a job", `/jobs?type=contract` marks "Contract roles". A lone item with a query of its own (`/about?ref=nav`) is still current on `/about`. `currentItems()` in `public/js/menu-decor.mjs` does this for the navbar, the footer and `[menu]`.
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
export const STATUS=Object.freeze({bot:{label:"With the bot",tone:"muted"},waiting:{label:"Waiting",tone:"danger"},open:{label:"Chatting",tone:"ok"},message:{label:"Message left",tone:"warn"},closed:{label:"Ended",tone:"muted"}});const l={waiting:0,message:1,open:2,bot:3,closed:4};export function mayDo(e=[],r
|
|
2
|
-
`).filter(Boolean).length,meta:
|
|
1
|
+
export const STATUS=Object.freeze({bot:{label:"With the bot",tone:"muted"},waiting:{label:"Waiting",tone:"danger"},open:{label:"Chatting",tone:"ok"},message:{label:"Message left",tone:"warn"},closed:{label:"Ended",tone:"muted"}});const l={waiting:0,message:1,open:2,bot:3,closed:4};export function mayDo(e=[],a,r){return e.includes(a)||e.includes(`${a}.${r}`)}export function shortSpan(e){const a=Math.max(0,Math.round(Number(e)/1e3)||0);if(a<60)return`${a}s`;const r=Math.round(a/60);if(r<60)return`${r} min`;const i=Math.round(r/60);return i<48?`${i} h`:`${Math.round(i/24)} d`}export function arrangeChats(e,{query:a="",now:r=Date.now()}={}){const i=String(a||"").trim().toLowerCase();return(Array.isArray(e)?e:[]).filter(t=>!i||[t.name,t.email,t.page,t.summary].some(n=>String(n||"").toLowerCase().includes(i))).slice().sort((t,n)=>{const s=l[t.status]??9,u=l[n.status]??9;return s!==u?s-u:t.status==="waiting"?Date.parse(t.waitingSince||0)-Date.parse(n.waitingSince||0):Date.parse(n.lastAt||0)-Date.parse(t.lastAt||0)}).map(t=>{const n=STATUS[t.status]||{label:t.status,tone:"muted"},s=t.waitingSince?Math.max(0,r-Date.parse(t.waitingSince)):0,u=t.status==="waiting"&&s>=5*6e4;return{id:t.id,who:t.name||"Visitor",email:t.email||"",line:t.summary||(t.count?"(no question yet)":"Just opened"),chip:n.label,chipClass:`chat-chip chat-chip--${u?"danger":n.tone}`,meta:t.status==="waiting"?`waiting ${shortSpan(s)}`:t.page||"",unread:Number(t.unread)||0,unreadText:Number(t.unread)?String(t.unread):"",status:t.status}})}export const OUTCOME=Object.freeze({"to look at":{label:"To look at",tone:"warn"},"looking into it":{label:"Looking into it",tone:"ok"},done:{label:"Done",tone:"muted"}});export function arrangeSaved(e,{query:a=""}={}){const r=String(a||"").trim().toLowerCase(),i={"to look at":0,"looking into it":1,done:2};return(Array.isArray(e)?e:[]).filter(o=>!r||[o.title,o.note,o.name,o.email,o.page].some(t=>String(t||"").toLowerCase().includes(r))).slice().sort((o,t)=>(i[o.outcome]??9)-(i[t.outcome]??9)||Date.parse(t.savedAt||0)-Date.parse(o.savedAt||0)).map(o=>{const t=OUTCOME[o.outcome]||OUTCOME["to look at"],n=o.savedAt?new Date(o.savedAt).toLocaleDateString([],{day:"numeric",month:"short"}):"";return{id:o.id,who:o.name||"Visitor",email:o.email||"",line:o.note||o.title||"",chip:t.label,chipClass:`chat-chip chat-chip--${t.tone}`,meta:[n&&`saved ${n}`,o.savedBy&&`by ${o.savedBy}`].filter(Boolean).join(" "),unread:0,unreadText:"",status:"saved"}})}export function threadRow(e){const a=e.from==="visitor"?"Visitor":e.from==="bot"?"Bot":e.from==="staff"?e.name||"Staff":"",r=e.ai?"Answered by AI (nothing in the Knowledge fitted)":e.answer?`Answered from: ${e.answer}`:Array.isArray(e.suggestions)&&e.suggestions.length?`Offered: ${e.suggestions.join(" \xB7 ")}`:"";return{key:`m${e.n}`,n:e.n,cls:`chat-msg chat-msg--${e.from}`,who:a,text:e.text||"",note:r,time:e.at?new Date(e.at).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}):""}}export function arrangeKnowledge(e,{query:a="",sort:r="question"}={}){const i=String(a||"").trim().toLowerCase(),o=(Array.isArray(e)?e:[]).filter(n=>!i||[n.question,n.alternatives,n.keywords,n.answer].some(s=>String(s||"").toLowerCase().includes(i))),t={question:(n,s)=>n.question.localeCompare(s.question),hits:(n,s)=>s.hits-n.hits||n.question.localeCompare(s.question),recent:(n,s)=>Date.parse(s.updatedAt||0)-Date.parse(n.updatedAt||0)}[r]||((n,s)=>n.question.localeCompare(s.question));return o.slice().sort(t).map(n=>({id:n.id,question:n.question,preview:String(n.answer||"").replace(/[*_`#>\[\]()]/g,"").replace(/\s+/g," ").trim().slice(0,140),ways:String(n.alternatives||"").split(`
|
|
2
|
+
`).filter(Boolean).length,meta:n.hits?`answered ${n.hits} time${n.hits===1?"":"s"}`:"not used yet",off:!n.enabled,sample:!!n.sample}))}export function linksToRows(e){return(Array.isArray(e)?e:[]).map((a,r)=>({key:`l${r}-${Date.now()}`,label:a.label||"",url:a.url||""}))}export function rowsToLinks(e){return(Array.isArray(e)?e:[]).map(a=>({label:String(a.label??"").trim(),url:String(a.url??"").trim()})).filter(a=>a.url)}export function describeTest(e){if(!e)return"";switch(e.kind){case"answer":return`Answers with "${e.answer.question}" (score ${Math.round(e.answer.score*100)}%).`;case"suggest":return`Not sure - offers: ${e.suggestions.map(a=>`"${a.question}" (${Math.round(a.score*100)}%)`).join(", ")}.`;case"handover":return"Hands over to a person (the visitor asked for one).";case"greeting":return"Says hello back.";case"thanks":return"Says you are welcome.";default:return e.ranked?.length?`No answer - the closest was "${e.ranked[0].question}" at ${Math.round(e.ranked[0].score*100)}%. It goes on the Unanswered list.`:"No answer - nothing came close. It goes on the Unanswered list."}}
|
|
@@ -1,2 +1,5 @@
|
|
|
1
|
-
import{LAUNCHER_DEFAULTS as
|
|
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,greeting:t.chat.greeting,botName:t.chat.botName,bot:t.chat.bot,staff:t.chat.staff,askDetails:t.chat.askDetails
|
|
1
|
+
import{LAUNCHER_DEFAULTS as b,LAUNCHER_LIMITS as r,LAUNCHER_POSITION_LABEL as u,launcherColourCss as l,launcherReady as x,launcherSpot as f,launcherAvatar as y,normaliseLauncher as p,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=l(e.colours.background)||"var(--dm-primary)",n=l(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 p({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 p({...structuredClone(e),id:"",name:a,enabled:!1})}export function formFromLauncher(e){const t=p(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,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 p({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:{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
|
+
`),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&&!l(s)&&(t[i]="A theme colour, or a hex colour such as #3366ff.")}if(e.actionType==="chat"){const i=String(e.starters||"").split(`
|
|
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"],branding:["brandEnabled","brandText","brandLogo","brandIcon","brandUrl","adminBrandEnabled","adminBrandTitle","adminBrandLogo","adminBrandLogoDark","adminBrandIcon"],favicon:["favicon"],footer:["footerCopyright","footerLayout","footerBlurb","footerBlocks","footerClass","footerSocialClass","footerLook","footerCtaText","footerCtaHighlight","footerCtaUrl","footerCtaSub","footerWatermark","footerStatus","footerFacts","footerTagline","footerEmail","footerAddress","footerGradFrom","footerGradTo","socialTwitter","socialFacebook","socialInstagram","socialLinkedin","socialGithub","socialYoutube"],email:["smtpHost","smtpPort","smtpUser","smtpPass","smtpSecure","smtpInsecureTLS","smtpFromAddress","smtpFromName"],pageNavigation:["bttEnabled","bttSmooth","bttLabel","bttThreshold","bttPosition","bttOffset","bttBottomOffset","gtbEnabled","gtbSmooth","gtbLabel","gtbThreshold","gtbPosition","gtbOffset","gtbBottomOffset"],cookies:["ccEnabled","ccMessage","ccAcceptAll","ccRejectAll","ccCustomize","ccSavePrefs","ccPrivacyText","ccPrivacyUrl","ccCookieText","ccCookieUrl","ccPosition","ccLayout","ccTheme","ccShowFunctional","ccShowAnalytics","ccShowMarketing","ccVersion","ccSettingsLink","ccSettingsLinkText"],breadcrumbs:["bcEnabled","bcHomeLabel","bcPosition","bcOffsetX","bcOffsetY"],motion:["mtEnabled","mtLabel","mtDefault","mtControl","mtPlacement","mtTriggerStyle","mtPosition","mtOffsetX","mtOffsetY","mtIconSize","mtIconRadius","mtClass"]},SECRET_FIELDS=["smtpPass"],BREADCRUMB_POSITIONS=["TL","TR","BL","BR"],MOTION_PLACEMENTS=["footer","floating","navbar"],MOTION_LABEL="Reduce motion";const d=["system","off","on"],c=(t,r,n,o)=>{const a=Number.parseInt(t,10);return Number.isFinite(a)?Math.min(o,Math.max(n,a)):r};export function motionFromSettings(t={}){const r=t.motion&&typeof t.motion=="object"?t.motion:{},n=t.footer||{},o=m=>r[m]!==void 0&&r[m]!==null,a=o("default")?r.default:n.motionDefault,i=o("control")?r.control:n.motionControl,l=c(r.iconSize,52,32,96);return{mtEnabled:(o("enabled")?r.enabled:n.showMotionToggle)!==!1,mtLabel:typeof r.label=="string"&&r.label.trim()?r.label.trim():MOTION_LABEL,mtDefault:d.includes(a)?a:"system",mtControl:i==="checkbox"?"checkbox":"switch",mtPlacement:MOTION_PLACEMENTS.includes(r.placement)?r.placement:"footer",mtTriggerStyle:r.triggerStyle==="icon-text"?"icon-text":"icon",mtPosition:BREADCRUMB_POSITIONS.includes(r.position)?r.position:"BL",mtOffsetX:e(c(r.offsetX,32,0,500)),mtOffsetY:e(c(r.offsetY,32,0,500)),mtIconSize:e(l),mtIconRadius:e(c(r.iconRadius,26,0,Math.floor(l/2))),mtClass:e(r.class)}}export function motionFromForm(t){const r=c(t.mtIconSize,52,32,96);return{enabled:t.mtEnabled===!0,default:d.includes(t.mtDefault)?t.mtDefault:"system",placement:MOTION_PLACEMENTS.includes(t.mtPlacement)?t.mtPlacement:"footer",control:t.mtControl==="checkbox"?"checkbox":"switch",triggerStyle:t.mtTriggerStyle==="icon-text"?"icon-text":"icon",label:e(t.mtLabel).trim().replace(/\s+/g," ").slice(0,40)||MOTION_LABEL,position:BREADCRUMB_POSITIONS.includes(t.mtPosition)?t.mtPosition:"BL",offsetX:c(t.mtOffsetX,32,0,500),offsetY:c(t.mtOffsetY,32,0,500),iconSize:r,iconRadius:c(t.mtIconRadius,26,0,Math.floor(r/2)),class:e(t.mtClass).trim()}}export function footerBlockNames(t){return[...new Set(String(t??"").split(/[\s,]+/).map(r=>r.trim().toLowerCase()).filter(Boolean))]}export function gaIdError(t){const r=e(t).trim();return!r||/^G-[A-Z0-9]{4,20}$/i.test(r)?"":"A measurement ID looks like G-XXXXXXXXXX (Google Analytics > Admin > Data streams)."}export const FOOTER_LAYOUTS=["auto","columns","row"],FOOTER_LOOKS=["","showcase"],FOOTER_FACTS_MAX=4;const p=/^(\/|#|https?:\/\/|mailto:)/,g=/^#[0-9a-f]{6}$/i;export function footerShowcaseErrors(t){const r=[],n=e(t.footerCtaUrl).trim();n&&!p.test(n)&&r.push("The footer call to action link must start with /, #, https:// or mailto: (Footer tool).");for(const[o,a]of[["from",t.footerGradFrom],["to",t.footerGradTo]]){const i=e(a).trim();i&&!g.test(i)&&r.push(`The footer gradient "${o}" colour must look like #f26b3a (Footer tool).`)}return r}const e=(t,r="")=>t==null?r:String(t),s=(t,r)=>{const n=Number.parseInt(t,10);return Number.isFinite(n)?n:r};export function homeValue(t){return/^\/[A-Za-z0-9\-_/]*$/.test(t||"")&&String(t).replace(/\/+$/,"")||"/"}export function formFromSettings(t={}){const r=t.backToTop||{},n=t.goToBottom||{},o=t.cookieConsent||{},a=t.breadcrumbs||{};return{title:e(t.title),tagline:e(t.tagline),siteUrl:e(t.baseUrl),adminHome:homeValue(t.adminHome),spacerSize:e(t.layoutOptions?.spacerSize??40),bodyClass:e(t.bodyClass),brandEnabled:t.brand?.enabled!==!1,brandText:e(t.brand?.text),brandLogo:e(t.brand?.logo),brandIcon:e(t.brand?.icon),brandUrl:e(t.brand?.url,"/"),favicon:e(t.favicon),adminBrandEnabled:t.adminBrand?.enabled!==!1,adminBrandTitle:e(t.adminBrand?.title),adminBrandLogo:e(t.adminBrand?.logo),adminBrandLogoDark:e(t.adminBrand?.logoDark),adminBrandIcon:e(t.adminBrand?.icon),footerCopyright:e(t.footer?.copyright),footerLayout:FOOTER_LAYOUTS.includes(t.footer?.layout)?t.footer.layout:"auto",footerBlurb:e(t.footer?.blurb),footerBlocks:Array.isArray(t.footer?.blocks)?t.footer.blocks.filter(i=>typeof i=="string").join(", "):"",footerClass:e(t.footer?.class),footerSocialClass:e(t.footer?.socialClass),footerLook:FOOTER_LOOKS.includes(t.footer?.look)?t.footer.look:"",footerCtaText:e(t.footer?.cta?.text),footerCtaHighlight:e(t.footer?.cta?.highlight),footerCtaUrl:e(t.footer?.cta?.url),footerCtaSub:e(t.footer?.cta?.sub),footerWatermark:e(t.footer?.watermark),footerStatus:e(t.footer?.status),footerFacts:Array.isArray(t.footer?.facts)?t.footer.facts.filter(i=>typeof i=="string").join(`
|
|
2
|
-
`):"",footerTagline:e(t.footer?.tagline),footerEmail:e(t.footer?.email),footerAddress:e(t.footer?.address),footerGradFrom:e(t.footer?.gradient?.from),footerGradTo:e(t.footer?.gradient?.to),socialTwitter:e(t.social?.twitter),socialFacebook:e(t.social?.facebook),socialInstagram:e(t.social?.instagram),socialLinkedin:e(t.social?.linkedin),socialGithub:e(t.social?.github),socialYoutube:e(t.social?.youtube),smtpHost:e(t.smtp?.host),smtpPort:e(t.smtp?.port||587),smtpUser:e(t.smtp?.user),smtpPass:"",smtpSecure:t.smtp?.secure===!0,smtpInsecureTLS:t.smtp?.allowInsecureTLS===!0,smtpFromAddress:e(t.smtp?.fromAddress),smtpFromName:e(t.smtp?.fromName),bttEnabled:r.enabled!==!1,bttSmooth:r.smooth!==!1,bttLabel:e(r.label),bttThreshold:e(r.scrollThreshold??300),bttPosition:e(r.position,"bottom-right"),bttOffset:e(r.offset??32),bttBottomOffset:e(r.bottomOffset??r.offset??32),gtbEnabled:n.enabled===!0,gtbSmooth:n.smooth!==!1,gtbLabel:e(n.label),gtbThreshold:e(n.scrollThreshold??300),gtbPosition:e(n.position,"bottom-right"),gtbOffset:e(n.offset??32),gtbBottomOffset:e(n.bottomOffset??n.offset??32),ccEnabled:o.enabled!==!1,ccMessage:e(o.message),ccAcceptAll:e(o.acceptAllText,"Accept All"),ccRejectAll:e(o.rejectAllText,"Reject All"),ccCustomize:e(o.customizeText,"Customize"),ccSavePrefs:e(o.savePreferencesText,"Save Preferences"),ccPrivacyText:e(o.privacyPolicyText,"Privacy Policy"),ccPrivacyUrl:e(o.privacyPolicyUrl),ccCookieText:e(o.cookiePolicyText,"Cookie Policy"),ccCookieUrl:e(o.cookiePolicyUrl),ccPosition:e(o.position,"bottom"),ccLayout:e(o.layout,"bar"),ccTheme:e(o.theme,"dark"),ccShowFunctional:o.showFunctional!==!1,ccShowAnalytics:o.showAnalytics!==!1,ccShowMarketing:o.showMarketing!==!1,ccVersion:e(o.consentVersion,"1.0"),ccSettingsLink:o.showSettingsLink!==!1,ccSettingsLinkText:e(o.settingsLinkText,"Cookie settings"),bcEnabled:a.enabled===!0,bcHomeLabel:e(a.homeLabel,"Home"),bcPosition:BREADCRUMB_POSITIONS.includes(a.position)?a.position:"TL",bcOffsetX:e(a.offsetX??8),bcOffsetY:e(a.offsetY??8),...motionFromSettings(t)}}export function payloadFromForm(t,r={},{adminHomeReady:n=!0}={}){const o=i=>e(i).trim(),a=motionFromForm(t);return{title:o(t.title),tagline:o(t.tagline),baseUrl:o(t.siteUrl).replace(/\/+$/,""),...n&&{adminHome:o(t.adminHome)||"/"},layoutOptions:{spacerSize:s(t.spacerSize,40)||40},bodyClass:o(t.bodyClass),brand:{...r.brand,enabled:t.brandEnabled!==!1,text:o(t.brandText),logo:o(t.brandLogo),icon:o(t.brandIcon),url:o(t.brandUrl)||"/"},favicon:o(t.favicon),adminBrand:{...r.adminBrand,enabled:t.adminBrandEnabled!==!1,title:o(t.adminBrandTitle),logo:o(t.adminBrandLogo),logoDark:o(t.adminBrandLogoDark),icon:o(t.adminBrandIcon)},footer:{copyright:o(t.footerCopyright),layout:FOOTER_LAYOUTS.includes(t.footerLayout)?t.footerLayout:"auto",blurb:o(t.footerBlurb),blocks:footerBlockNames(t.footerBlocks),links:r.footer?.links||[],showMotionToggle:a.enabled,motionDefault:a.default,motionControl:a.control,class:o(t.footerClass),socialClass:o(t.footerSocialClass),look:FOOTER_LOOKS.includes(t.footerLook)?t.footerLook:"",cta:{text:o(t.footerCtaText),highlight:o(t.footerCtaHighlight),url:o(t.footerCtaUrl),sub:o(t.footerCtaSub)},watermark:o(t.footerWatermark),status:o(t.footerStatus),facts:String(t.footerFacts??"").split(`
|
|
1
|
+
export const TAB_FIELDS={general:["title","tagline","siteUrl","adminHome","spacerSize","bodyClass","aiContext","aiRules"],branding:["brandEnabled","brandText","brandLogo","brandIcon","brandUrl","adminBrandEnabled","adminBrandTitle","adminBrandLogo","adminBrandLogoDark","adminBrandIcon"],favicon:["favicon"],footer:["footerCopyright","footerLayout","footerBlurb","footerBlocks","footerClass","footerSocialClass","footerLook","footerCtaText","footerCtaHighlight","footerCtaUrl","footerCtaSub","footerWatermark","footerStatus","footerFacts","footerTagline","footerEmail","footerAddress","footerGradFrom","footerGradTo","socialTwitter","socialFacebook","socialInstagram","socialLinkedin","socialGithub","socialYoutube"],email:["smtpHost","smtpPort","smtpUser","smtpPass","smtpSecure","smtpInsecureTLS","smtpFromAddress","smtpFromName"],pageNavigation:["bttEnabled","bttSmooth","bttLabel","bttThreshold","bttPosition","bttOffset","bttBottomOffset","gtbEnabled","gtbSmooth","gtbLabel","gtbThreshold","gtbPosition","gtbOffset","gtbBottomOffset"],cookies:["ccEnabled","ccMessage","ccAcceptAll","ccRejectAll","ccCustomize","ccSavePrefs","ccPrivacyText","ccPrivacyUrl","ccCookieText","ccCookieUrl","ccPosition","ccLayout","ccTheme","ccShowFunctional","ccShowAnalytics","ccShowMarketing","ccVersion","ccSettingsLink","ccSettingsLinkText"],breadcrumbs:["bcEnabled","bcHomeLabel","bcPosition","bcOffsetX","bcOffsetY"],motion:["mtEnabled","mtLabel","mtDefault","mtControl","mtPlacement","mtTriggerStyle","mtPosition","mtOffsetX","mtOffsetY","mtIconSize","mtIconRadius","mtClass"]},SECRET_FIELDS=["smtpPass"],BREADCRUMB_POSITIONS=["TL","TR","BL","BR"],MOTION_PLACEMENTS=["footer","floating","navbar"],MOTION_LABEL="Reduce motion";const d=["system","off","on"],c=(t,r,n,o)=>{const a=Number.parseInt(t,10);return Number.isFinite(a)?Math.min(o,Math.max(n,a)):r};export function motionFromSettings(t={}){const r=t.motion&&typeof t.motion=="object"?t.motion:{},n=t.footer||{},o=m=>r[m]!==void 0&&r[m]!==null,a=o("default")?r.default:n.motionDefault,i=o("control")?r.control:n.motionControl,l=c(r.iconSize,52,32,96);return{mtEnabled:(o("enabled")?r.enabled:n.showMotionToggle)!==!1,mtLabel:typeof r.label=="string"&&r.label.trim()?r.label.trim():MOTION_LABEL,mtDefault:d.includes(a)?a:"system",mtControl:i==="checkbox"?"checkbox":"switch",mtPlacement:MOTION_PLACEMENTS.includes(r.placement)?r.placement:"footer",mtTriggerStyle:r.triggerStyle==="icon-text"?"icon-text":"icon",mtPosition:BREADCRUMB_POSITIONS.includes(r.position)?r.position:"BL",mtOffsetX:e(c(r.offsetX,32,0,500)),mtOffsetY:e(c(r.offsetY,32,0,500)),mtIconSize:e(l),mtIconRadius:e(c(r.iconRadius,26,0,Math.floor(l/2))),mtClass:e(r.class)}}export function motionFromForm(t){const r=c(t.mtIconSize,52,32,96);return{enabled:t.mtEnabled===!0,default:d.includes(t.mtDefault)?t.mtDefault:"system",placement:MOTION_PLACEMENTS.includes(t.mtPlacement)?t.mtPlacement:"footer",control:t.mtControl==="checkbox"?"checkbox":"switch",triggerStyle:t.mtTriggerStyle==="icon-text"?"icon-text":"icon",label:e(t.mtLabel).trim().replace(/\s+/g," ").slice(0,40)||MOTION_LABEL,position:BREADCRUMB_POSITIONS.includes(t.mtPosition)?t.mtPosition:"BL",offsetX:c(t.mtOffsetX,32,0,500),offsetY:c(t.mtOffsetY,32,0,500),iconSize:r,iconRadius:c(t.mtIconRadius,26,0,Math.floor(r/2)),class:e(t.mtClass).trim()}}export function footerBlockNames(t){return[...new Set(String(t??"").split(/[\s,]+/).map(r=>r.trim().toLowerCase()).filter(Boolean))]}export function gaIdError(t){const r=e(t).trim();return!r||/^G-[A-Z0-9]{4,20}$/i.test(r)?"":"A measurement ID looks like G-XXXXXXXXXX (Google Analytics > Admin > Data streams)."}export const FOOTER_LAYOUTS=["auto","columns","row"],FOOTER_LOOKS=["","showcase"],FOOTER_FACTS_MAX=4;const p=/^(\/|#|https?:\/\/|mailto:)/,g=/^#[0-9a-f]{6}$/i;export function footerShowcaseErrors(t){const r=[],n=e(t.footerCtaUrl).trim();n&&!p.test(n)&&r.push("The footer call to action link must start with /, #, https:// or mailto: (Footer tool).");for(const[o,a]of[["from",t.footerGradFrom],["to",t.footerGradTo]]){const i=e(a).trim();i&&!g.test(i)&&r.push(`The footer gradient "${o}" colour must look like #f26b3a (Footer tool).`)}return r}const e=(t,r="")=>t==null?r:String(t),s=(t,r)=>{const n=Number.parseInt(t,10);return Number.isFinite(n)?n:r};export function homeValue(t){return/^\/[A-Za-z0-9\-_/]*$/.test(t||"")&&String(t).replace(/\/+$/,"")||"/"}export function formFromSettings(t={}){const r=t.backToTop||{},n=t.goToBottom||{},o=t.cookieConsent||{},a=t.breadcrumbs||{};return{title:e(t.title),tagline:e(t.tagline),siteUrl:e(t.baseUrl),adminHome:homeValue(t.adminHome),spacerSize:e(t.layoutOptions?.spacerSize??40),bodyClass:e(t.bodyClass),aiContext:e(t.assistant?.context),aiRules:e(t.assistant?.rules),brandEnabled:t.brand?.enabled!==!1,brandText:e(t.brand?.text),brandLogo:e(t.brand?.logo),brandIcon:e(t.brand?.icon),brandUrl:e(t.brand?.url,"/"),favicon:e(t.favicon),adminBrandEnabled:t.adminBrand?.enabled!==!1,adminBrandTitle:e(t.adminBrand?.title),adminBrandLogo:e(t.adminBrand?.logo),adminBrandLogoDark:e(t.adminBrand?.logoDark),adminBrandIcon:e(t.adminBrand?.icon),footerCopyright:e(t.footer?.copyright),footerLayout:FOOTER_LAYOUTS.includes(t.footer?.layout)?t.footer.layout:"auto",footerBlurb:e(t.footer?.blurb),footerBlocks:Array.isArray(t.footer?.blocks)?t.footer.blocks.filter(i=>typeof i=="string").join(", "):"",footerClass:e(t.footer?.class),footerSocialClass:e(t.footer?.socialClass),footerLook:FOOTER_LOOKS.includes(t.footer?.look)?t.footer.look:"",footerCtaText:e(t.footer?.cta?.text),footerCtaHighlight:e(t.footer?.cta?.highlight),footerCtaUrl:e(t.footer?.cta?.url),footerCtaSub:e(t.footer?.cta?.sub),footerWatermark:e(t.footer?.watermark),footerStatus:e(t.footer?.status),footerFacts:Array.isArray(t.footer?.facts)?t.footer.facts.filter(i=>typeof i=="string").join(`
|
|
2
|
+
`):"",footerTagline:e(t.footer?.tagline),footerEmail:e(t.footer?.email),footerAddress:e(t.footer?.address),footerGradFrom:e(t.footer?.gradient?.from),footerGradTo:e(t.footer?.gradient?.to),socialTwitter:e(t.social?.twitter),socialFacebook:e(t.social?.facebook),socialInstagram:e(t.social?.instagram),socialLinkedin:e(t.social?.linkedin),socialGithub:e(t.social?.github),socialYoutube:e(t.social?.youtube),smtpHost:e(t.smtp?.host),smtpPort:e(t.smtp?.port||587),smtpUser:e(t.smtp?.user),smtpPass:"",smtpSecure:t.smtp?.secure===!0,smtpInsecureTLS:t.smtp?.allowInsecureTLS===!0,smtpFromAddress:e(t.smtp?.fromAddress),smtpFromName:e(t.smtp?.fromName),bttEnabled:r.enabled!==!1,bttSmooth:r.smooth!==!1,bttLabel:e(r.label),bttThreshold:e(r.scrollThreshold??300),bttPosition:e(r.position,"bottom-right"),bttOffset:e(r.offset??32),bttBottomOffset:e(r.bottomOffset??r.offset??32),gtbEnabled:n.enabled===!0,gtbSmooth:n.smooth!==!1,gtbLabel:e(n.label),gtbThreshold:e(n.scrollThreshold??300),gtbPosition:e(n.position,"bottom-right"),gtbOffset:e(n.offset??32),gtbBottomOffset:e(n.bottomOffset??n.offset??32),ccEnabled:o.enabled!==!1,ccMessage:e(o.message),ccAcceptAll:e(o.acceptAllText,"Accept All"),ccRejectAll:e(o.rejectAllText,"Reject All"),ccCustomize:e(o.customizeText,"Customize"),ccSavePrefs:e(o.savePreferencesText,"Save Preferences"),ccPrivacyText:e(o.privacyPolicyText,"Privacy Policy"),ccPrivacyUrl:e(o.privacyPolicyUrl),ccCookieText:e(o.cookiePolicyText,"Cookie Policy"),ccCookieUrl:e(o.cookiePolicyUrl),ccPosition:e(o.position,"bottom"),ccLayout:e(o.layout,"bar"),ccTheme:e(o.theme,"dark"),ccShowFunctional:o.showFunctional!==!1,ccShowAnalytics:o.showAnalytics!==!1,ccShowMarketing:o.showMarketing!==!1,ccVersion:e(o.consentVersion,"1.0"),ccSettingsLink:o.showSettingsLink!==!1,ccSettingsLinkText:e(o.settingsLinkText,"Cookie settings"),bcEnabled:a.enabled===!0,bcHomeLabel:e(a.homeLabel,"Home"),bcPosition:BREADCRUMB_POSITIONS.includes(a.position)?a.position:"TL",bcOffsetX:e(a.offsetX??8),bcOffsetY:e(a.offsetY??8),...motionFromSettings(t)}}export function payloadFromForm(t,r={},{adminHomeReady:n=!0}={}){const o=i=>e(i).trim(),a=motionFromForm(t);return{title:o(t.title),tagline:o(t.tagline),baseUrl:o(t.siteUrl).replace(/\/+$/,""),...n&&{adminHome:o(t.adminHome)||"/"},layoutOptions:{spacerSize:s(t.spacerSize,40)||40},bodyClass:o(t.bodyClass),assistant:{context:o(t.aiContext),rules:o(t.aiRules)},brand:{...r.brand,enabled:t.brandEnabled!==!1,text:o(t.brandText),logo:o(t.brandLogo),icon:o(t.brandIcon),url:o(t.brandUrl)||"/"},favicon:o(t.favicon),adminBrand:{...r.adminBrand,enabled:t.adminBrandEnabled!==!1,title:o(t.adminBrandTitle),logo:o(t.adminBrandLogo),logoDark:o(t.adminBrandLogoDark),icon:o(t.adminBrandIcon)},footer:{copyright:o(t.footerCopyright),layout:FOOTER_LAYOUTS.includes(t.footerLayout)?t.footerLayout:"auto",blurb:o(t.footerBlurb),blocks:footerBlockNames(t.footerBlocks),links:r.footer?.links||[],showMotionToggle:a.enabled,motionDefault:a.default,motionControl:a.control,class:o(t.footerClass),socialClass:o(t.footerSocialClass),look:FOOTER_LOOKS.includes(t.footerLook)?t.footerLook:"",cta:{text:o(t.footerCtaText),highlight:o(t.footerCtaHighlight),url:o(t.footerCtaUrl),sub:o(t.footerCtaSub)},watermark:o(t.footerWatermark),status:o(t.footerStatus),facts:String(t.footerFacts??"").split(`
|
|
3
3
|
`).map(i=>i.trim()).filter(Boolean).slice(0,FOOTER_FACTS_MAX),tagline:o(t.footerTagline),email:o(t.footerEmail),address:o(t.footerAddress),gradient:{from:o(t.footerGradFrom),to:o(t.footerGradTo)}},social:{twitter:o(t.socialTwitter),facebook:o(t.socialFacebook),instagram:o(t.socialInstagram),linkedin:o(t.socialLinkedin),github:o(t.socialGithub),youtube:o(t.socialYoutube)},smtp:{host:o(t.smtpHost),port:s(t.smtpPort,587)||587,user:o(t.smtpUser),pass:e(t.smtpPass),secure:t.smtpSecure===!0,allowInsecureTLS:t.smtpInsecureTLS===!0,fromAddress:o(t.smtpFromAddress),fromName:o(t.smtpFromName)},backToTop:{enabled:t.bttEnabled===!0,scrollThreshold:s(t.bttThreshold,300),position:e(t.bttPosition)||"bottom-right",offset:s(t.bttOffset,32),bottomOffset:s(t.bttBottomOffset,32),label:o(t.bttLabel),smooth:t.bttSmooth===!0},goToBottom:{enabled:t.gtbEnabled===!0,scrollThreshold:s(t.gtbThreshold,300),position:e(t.gtbPosition)||"bottom-right",offset:s(t.gtbOffset,32),bottomOffset:s(t.gtbBottomOffset,32),label:o(t.gtbLabel),smooth:t.gtbSmooth===!0},cookieConsent:{enabled:t.ccEnabled===!0,message:o(t.ccMessage),acceptAllText:o(t.ccAcceptAll),rejectAllText:o(t.ccRejectAll),customizeText:o(t.ccCustomize),savePreferencesText:o(t.ccSavePrefs),privacyPolicyText:o(t.ccPrivacyText),privacyPolicyUrl:o(t.ccPrivacyUrl),cookiePolicyText:o(t.ccCookieText),cookiePolicyUrl:o(t.ccCookieUrl),position:e(t.ccPosition)||"bottom",layout:e(t.ccLayout)||"bar",theme:e(t.ccTheme)||"dark",showFunctional:t.ccShowFunctional===!0,showAnalytics:t.ccShowAnalytics===!0,showMarketing:t.ccShowMarketing===!0,consentVersion:o(t.ccVersion)||"1.0",showSettingsLink:t.ccSettingsLink===!0,settingsLinkText:o(t.ccSettingsLinkText)||"Cookie settings"},breadcrumbs:{enabled:t.bcEnabled===!0,homeLabel:o(t.bcHomeLabel)||"Home",position:BREADCRUMB_POSITIONS.includes(t.bcPosition)?t.bcPosition:"TL",offsetX:s(t.bcOffsetX,8),offsetY:s(t.bcOffsetY,8)},motion:a}}export function siteUrlError(t){const r=e(t).trim().replace(/\/+$/,"");return r?/^https?:\/\//i.test(r)?/^https?:\/\/([a-z0-9.\-]+|\[[0-9a-f:.]+\])(:\d{1,5})?$/i.test(r)?"":"Just the address, like https://example.com - no page path after it.":"Start with https:// (or http://).":""}const b=t=>typeof t=="boolean"?t:e(t);export function snapshot(t){return JSON.stringify(Object.keys(t).sort().map(r=>[r,b(t[r])]))}export function changedTabs(t,r){const n=[];for(const[o,a]of Object.entries(TAB_FIELDS))a.some(i=>b(t[i])!==b(r[i]))&&n.push(o);return n}export function draftOf(t){return Object.fromEntries(Object.entries(t).filter(([r])=>!SECRET_FIELDS.includes(r)))}const h={footerMotionToggle:"mtEnabled",footerMotionDefault:"mtDefault",footerMotionControl:"mtControl"};export function formFromDraft(t,r={}){const n={...r};for(const[a,i]of Object.entries(h))a in n&&!(i in n)&&(n[i]=n[a]),delete n[a];const o={...t};for(const[a,i]of Object.entries(n))a in o&&!SECRET_FIELDS.includes(a)&&(o[a]=i);return o}export function settingsProblems(t,r={}){const n=[];return e(t.smtpHost).trim()?e(t.smtpFromAddress).trim()||n.push({tone:"warn",tab:"email",text:"No From address - mail has no sender and many servers refuse it."}):n.push({tone:"danger",tab:"email",text:"No SMTP host - mail goes to a throwaway test inbox and reaches no one (password resets, form notifications)."}),(t.ccEnabled===!0||e(r.googleAnalytics?.measurementId).trim())&&!e(t.ccPrivacyUrl).trim()&&n.push({tone:"warn",tab:"cookies",text:"The cookie banner is on but links to no privacy policy."}),n}export function describeCacheKey(t){const r=/^page:(.*?):m\d+:role([^:]*):/.exec(String(t||""));return r?{path:r[1]||"/",role:r[2]||"anon",page:!0}:{path:String(t||""),role:"",page:!1}}export function expiresIn(t,r=Date.now()){if(t==null)return"no expiry";const n=t-r;return n<=0?"expired":n<6e4?`${Math.round(n/1e3)}s`:n<36e5?`${Math.round(n/6e4)}m`:`${Math.round(n/36e5)}h`}export function footerForm(t={}){const r=formFromSettings(t);return Object.fromEntries(TAB_FIELDS.footer.map(n=>[n,r[n]]))}export function footerPayload(t){const{footer:r,social:n}=payloadFromForm(t);return delete r.links,delete r.showMotionToggle,delete r.motionDefault,delete r.motionControl,{footer:r,social:n}}export function siteSettingsForm(t={}){return Object.fromEntries(Object.entries(formFromSettings(t)).filter(([r])=>!TAB_FIELDS.footer.includes(r)&&!u.includes(r)))}export function siteSettingsPayload(...t){const{footer:r,social:n,favicon:o,backToTop:a,goToBottom:i,breadcrumbs:l,motion:m,...f}=payloadFromForm(...t);return f}export const APPEARANCE_TABS=["favicon","pageNavigation","breadcrumbs","motion","search"];const u=APPEARANCE_TABS.flatMap(t=>TAB_FIELDS[t]||[]);export function appearanceForm(t={}){const r=formFromSettings(t);return Object.fromEntries(u.map(n=>[n,r[n]]))}export function appearancePayload(t){const{favicon:r,backToTop:n,goToBottom:o,breadcrumbs:a,motion:i}=payloadFromForm(t);return{favicon:r,backToTop:n,goToBottom:o,breadcrumbs:a,motion:i}}
|
|
@@ -16,10 +16,12 @@
|
|
|
16
16
|
data-bind-aria-pressed="view.value === 'active'" data-on-click="showActive">Active</button>
|
|
17
17
|
<button type="button" class="btn btn-sm btn-ghost" data-bind-class="view.value === 'closed' && 'is-active'"
|
|
18
18
|
data-bind-aria-pressed="view.value === 'closed'" data-on-click="showClosed">Ended</button>
|
|
19
|
+
<button type="button" class="btn btn-sm btn-ghost" data-bind-class="view.value === 'saved' && 'is-active'"
|
|
20
|
+
data-bind-aria-pressed="view.value === 'saved'" data-on-click="showSaved">Saved</button>
|
|
19
21
|
</div>
|
|
20
22
|
<span class="chats-count" data-bind-text="countText.value"></span>
|
|
21
23
|
<span data-help-title="The inbox"
|
|
22
|
-
data-help="Visitors chat from a chat launcher on your site. The bot answers first from the Knowledge; a chat comes to you when the visitor asks for a person (Waiting), when nobody was available and they left their details (Message left), or when you reply to one yourself. Waiting chats are at the top, the longest wait first. Right-click a chat (or its ⋮) for everything you can do with it."></span>
|
|
24
|
+
data-help="Visitors chat from a chat launcher on your site. The bot answers first from the Knowledge; a chat comes to you when the visitor asks for a person (Waiting), when nobody was available and they left their details (Message left), or when you reply to one yourself. Waiting chats are at the top, the longest wait first. Right-click a chat (or its ⋮) for everything you can do with it - including Save for a closer look, which keeps a copy under Saved (and in the Saved Chats collection) after the chat itself is gone."></span>
|
|
23
25
|
|
|
24
26
|
<div class="chats-bar-end">
|
|
25
27
|
<label class="chats-avail" data-bind-hidden="!canReply">
|
|
@@ -61,11 +63,27 @@
|
|
|
61
63
|
</div>
|
|
62
64
|
<button type="button" class="btn btn-sm btn-ghost chats-head-kebab" aria-label="Chat actions" title="Actions">⋮</button>
|
|
63
65
|
</header>
|
|
66
|
+
<div class="chats-saved-bar" data-bind-hidden="!savedOpen.value">
|
|
67
|
+
<label class="chats-saved-field">
|
|
68
|
+
<span>Outcome</span>
|
|
69
|
+
<select class="form-input" data-model="savedOutcome.value" data-bind-disabled="!canReply">
|
|
70
|
+
<option value="to look at">To look at</option>
|
|
71
|
+
<option value="looking into it">Looking into it</option>
|
|
72
|
+
<option value="done">Done</option>
|
|
73
|
+
</select>
|
|
74
|
+
</label>
|
|
75
|
+
<label class="chats-saved-field chats-saved-note">
|
|
76
|
+
<span>Why it was saved, and what came of it</span>
|
|
77
|
+
<textarea class="form-input" rows="2" maxlength="2000" data-model="savedNote.value" data-bind-disabled="!canReply"></textarea>
|
|
78
|
+
</label>
|
|
79
|
+
<button type="button" class="btn btn-sm btn-primary" data-on-click="saveSavedNote" data-bind-hidden="!canReply"
|
|
80
|
+
data-bind-disabled="!savedDirty.value">Save</button>
|
|
81
|
+
</div>
|
|
64
82
|
<div class="chats-messages" role="log" aria-live="polite" tabindex="0">
|
|
65
83
|
<!-- Message template inserted by chats.js (MESSAGE). -->
|
|
66
84
|
<div class="chats-msgs" data-each="thread.value key=key"></div>
|
|
67
85
|
</div>
|
|
68
|
-
<form class="chats-reply" data-on-submit="sendReply" data-bind-hidden="!canReply">
|
|
86
|
+
<form class="chats-reply" data-on-submit="sendReply" data-bind-hidden="!canReply || savedOpen.value">
|
|
69
87
|
<textarea class="form-input" rows="2" maxlength="1000" aria-label="Your reply"
|
|
70
88
|
data-bind-placeholder="replyHint.value" data-model="reply.value"
|
|
71
89
|
data-bind-disabled="!canWrite.value"></textarea>
|
|
@@ -134,6 +152,12 @@
|
|
|
134
152
|
.chat-msg--system { align-self: center; align-items: center; max-width: 95%; }
|
|
135
153
|
.chat-msg--system .chat-msg-text { background: none; border: 0; font-size: var(--dm-text-sm); color: var(--dm-text-muted); padding: 0; text-align: center; }
|
|
136
154
|
.chat-msg--system .chat-msg-who { display: none; }
|
|
155
|
+
.chats-saved-bar { display: flex; flex-wrap: wrap; align-items: flex-end; gap: .5rem .75rem; padding: .6rem .75rem; border-bottom: 1px solid var(--dm-border);
|
|
156
|
+
background: color-mix(in srgb, var(--dm-warning) 6%, transparent); }
|
|
157
|
+
.chats-saved-field { display: flex; flex-direction: column; gap: .2rem; margin: 0; font-size: var(--dm-text-xs); color: var(--dm-text-muted); }
|
|
158
|
+
.chats-saved-field select { height: 2rem; padding-top: 0; padding-bottom: 0; }
|
|
159
|
+
.chats-saved-note { flex: 1 1 260px; }
|
|
160
|
+
.chats-saved-note textarea { resize: vertical; min-height: 2.25rem; }
|
|
137
161
|
.chats-reply { display: flex; gap: .5rem; align-items: flex-end; padding: .6rem .75rem; border-top: 1px solid var(--dm-border); }
|
|
138
162
|
.chats-reply textarea { flex: 1; resize: vertical; min-height: 2.5rem; }
|
|
139
163
|
|
|
@@ -10,15 +10,29 @@
|
|
|
10
10
|
<p>A <strong>chat launcher</strong> puts a chat on your site: visitors tap the disc and talk to you in a small panel.
|
|
11
11
|
A <strong>bot</strong> answers first, straight away, from what you have taught it in the <strong>Knowledge</strong>.
|
|
12
12
|
When it cannot help, or the visitor asks for a person, the chat comes to you in <strong>Content > Chats</strong>.
|
|
13
|
-
When nobody is available, the visitor leaves their name and email instead, so nobody is left waiting.
|
|
14
|
-
|
|
13
|
+
When nobody is available, the visitor leaves their name and email instead, so nobody is left waiting. The bot is
|
|
14
|
+
called <strong>Della</strong> to begin with (rename her per launcher). With the Pro plan on a hosted site, Della
|
|
15
|
+
can also answer, with AI, the questions your Knowledge does not cover - see <a href="#della-ai">AI answers</a>.</p>
|
|
15
16
|
|
|
16
17
|
<h3>Setting it up</h3>
|
|
17
18
|
<ol>
|
|
18
19
|
<li>In <strong>Launchers</strong>, add a launcher and choose the <strong>Chat</strong> action. Its chat settings
|
|
19
20
|
are the greeting, the bot's name, whether the bot answers (off: every message goes to a person), whether
|
|
20
21
|
visitors can ask for a person, and when to ask for a name and email: <strong>when nobody is available</strong>
|
|
21
|
-
(the usual), <strong>always</strong> before putting them through, or <strong>never</strong
|
|
22
|
+
(the usual), <strong>always</strong> before putting them through, or <strong>never</strong>. Each chat has
|
|
23
|
+
its own branding too: the bot's name, a <strong>chat colour</strong> (its heading, the visitor's messages and
|
|
24
|
+
the send button; the text on it is picked to read well unless you choose one) and a <strong>bot's
|
|
25
|
+
picture</strong> from Media in place of the first letter of its name.</li>
|
|
26
|
+
<li>Also per chat: the <strong>chat window size</strong> (small, medium, large or your own pixels - a phone is
|
|
27
|
+
always full screen) and whether <strong>visitors can resize</strong> it (a grip in the corner away from the
|
|
28
|
+
disc; their size is remembered in their browser, double-click the grip to put yours back); up to four
|
|
29
|
+
<strong>questions to start with</strong>, shown as buttons under the greeting; where <strong>Talk to a
|
|
30
|
+
person</strong> goes - under the conversation, or as an icon in the chat's heading with its name as a tooltip;
|
|
31
|
+
how long its ended chats are kept, if not the site's time; and what each message shows of when it was sent -
|
|
32
|
+
the time, the date and time, or nothing.</li>
|
|
33
|
+
<li>The greeting can greet by the visitor's clock: <code>{greeting}</code> (Good morning / afternoon / evening),
|
|
34
|
+
<code>{timeofday}</code> (morning / afternoon / evening), <code>{day}</code>, <code>{date}</code>,
|
|
35
|
+
<code>{time}</code>, <code>{botname}</code> and <code>{site}</code> - for example <em>{greeting}! I'm {botname} - how can I help this {timeofday}?</em></li>
|
|
22
36
|
<li>Open <strong>Chats > Knowledge</strong> and replace the four example entries (marked
|
|
23
37
|
<strong>Example</strong>) with your own - or use <strong>Remove the examples</strong>.</li>
|
|
24
38
|
<li>Ask a few questions in <strong>Try the bot</strong> the way a visitor would, and add phrasings until it
|
|
@@ -68,6 +82,36 @@
|
|
|
68
82
|
how long ended chats are kept (90 days to begin with), and how many new chats the whole site takes in an hour
|
|
69
83
|
(300 to begin with; each visitor can start at most 6 an hour and send 120 messages).</p>
|
|
70
84
|
|
|
85
|
+
<h3 id="della-ai">AI answers (Pro plan, hosted sites)</h3>
|
|
86
|
+
<p>When nothing in the Knowledge fits a question, Della asks Claude (Anthropic's AI). Claude answers only from what
|
|
87
|
+
you have given it and says it does not know rather than guess - then the chat goes on as before ("Sorry, I do not
|
|
88
|
+
know" and the offer of a person). What Claude is given with each question:</p>
|
|
89
|
+
<ul>
|
|
90
|
+
<li>your enabled Knowledge entries;</li>
|
|
91
|
+
<li><strong>Site Settings > General > AI assistant</strong>: <strong>About the business</strong> (plain facts in
|
|
92
|
+
your words - what you do, where, hours, how you like to sound) and <strong>Rules</strong> (one per line: what an
|
|
93
|
+
answer must never do or say, such as "Never quote a price");</li>
|
|
94
|
+
<li>the launcher's own <strong>What the AI should know</strong> and <strong>Rules</strong> (Launchers, the chat
|
|
95
|
+
settings) - added on top of the site's, for that launcher only. A launcher's rules add to the site's; they
|
|
96
|
+
cannot lift one. Switch off <strong>Use the site's AI assistant settings</strong> for a chat about something
|
|
97
|
+
else entirely (one event, one product): then only the launcher's own context is used. The site's Rules apply to every
|
|
98
|
+
AI answer either way - nothing a launcher or a visitor does can lift them. Each chat also caps its AI answers
|
|
99
|
+
(<strong>AI answers per chat</strong>, 20 to begin with); past it the bot answers from the Knowledge alone;</li>
|
|
100
|
+
<li>the last few messages of the chat, and the question.</li>
|
|
101
|
+
</ul>
|
|
102
|
+
<p>Switch it off per launcher with <strong>AI answers what the Knowledge does not</strong>. Questions the AI answered
|
|
103
|
+
still go on the Unanswered list, so you can turn the common ones into Knowledge; in the inbox an AI answer is
|
|
104
|
+
marked "Answered by AI". Visitors see a line under the chat saying Della is an AI assistant. What you write in the
|
|
105
|
+
context and rules is sent to Claude with each question, so leave out anything private. Each site has 2,000 AI
|
|
106
|
+
answers a month; past that the bot answers from the Knowledge alone until the next month.</p>
|
|
107
|
+
|
|
108
|
+
<h3>Saving a chat for a closer look</h3>
|
|
109
|
+
<p>Right-click a chat (or its ⋮) and choose <strong>Save for a closer look</strong>, with a note on why. A copy of the
|
|
110
|
+
whole conversation goes under <strong>Saved</strong> in the inbox (and in the <strong>Saved Chats</strong>
|
|
111
|
+
collection), and stays after the chat itself is tidied up or deleted. Open one to read it, move its
|
|
112
|
+
<strong>Outcome</strong> along (To look at, Looking into it, Done) and keep notes on what came of it. Anyone who can
|
|
113
|
+
answer chats can save one; deleting a saved copy needs Manage.</p>
|
|
114
|
+
|
|
71
115
|
<h3>What visitors see</h3>
|
|
72
116
|
<p>The greeting, then the conversation. Their chat carries on across pages and reloads in the same browser for a
|
|
73
117
|
day (two weeks after they leave a message). They can tap <strong>Talk to a person</strong> (or
|
|
@@ -76,14 +120,16 @@
|
|
|
76
120
|
|
|
77
121
|
<h3>Tidy-up and privacy</h3>
|
|
78
122
|
<ul>
|
|
123
|
+
<li>Every conversation is saved. How long ended ones are kept is the site's default (the settings cog, 90 days to
|
|
124
|
+
begin with); a chat launcher can keep its own for a different time.</li>
|
|
79
125
|
<li>Every hour: chats with the bot quiet for two hours end; waiting and open chats quiet for a day end; ended
|
|
80
126
|
chats older than the keep setting are deleted with their messages - chats that only ever talked to the bot and left
|
|
81
127
|
no details go after a week. A message left for the team is kept until
|
|
82
128
|
someone ends it.</li>
|
|
83
129
|
<li>A visitor's chat is theirs by a random key kept in their browser; the site stores only a fingerprint of it.
|
|
84
130
|
Messages are plain text, up to 1,000 characters.</li>
|
|
85
|
-
<li>Chats, messages, Knowledge
|
|
86
|
-
otherwise.</li>
|
|
131
|
+
<li>Chats, messages, Knowledge, the Unanswered list and saved chats are kept in MongoDB where your site has it, in
|
|
132
|
+
files otherwise. Saved chats are never tidied away: delete them when you have finished with them.</li>
|
|
87
133
|
</ul>
|
|
88
134
|
|
|
89
135
|
<h3>Who can do what</h3>
|
|
@@ -77,6 +77,10 @@
|
|
|
77
77
|
.lnx-icon-btn:hover { color: var(--dm-primary); border-color: var(--dm-primary); }
|
|
78
78
|
.lnx-err { color: var(--dm-danger); font-size: var(--dm-text-xs); }
|
|
79
79
|
.lnx-warn { color: var(--dm-text-muted); font-size: var(--dm-text-xs); }
|
|
80
|
+
.lnx-avatar-row { display: flex; align-items: center; gap: .5rem; flex-wrap: wrap; }
|
|
81
|
+
.lnx-avatar-preview { width: 40px; height: 40px; border-radius: 50%; display: inline-flex; align-items: center; justify-content: center;
|
|
82
|
+
font-weight: 700; overflow: hidden; flex: 0 0 auto; }
|
|
83
|
+
.lnx-avatar-preview img { width: 100%; height: 100%; object-fit: cover; }
|
|
80
84
|
.lnx-check { display: flex; align-items: center; gap: .45rem; font-size: var(--dm-text-sm); }
|
|
81
85
|
.lnx-range { display: flex; align-items: center; gap: .5rem; }
|
|
82
86
|
.lnx-unit { display: flex; gap: .5rem; }
|
|
@@ -71,6 +71,24 @@
|
|
|
71
71
|
</div>
|
|
72
72
|
</div>
|
|
73
73
|
</div>
|
|
74
|
+
<div class="stx-card dm-settings-section">
|
|
75
|
+
<div class="stx-card-title dm-section--info dm-settings-section-title"><span data-icon="message-circle" data-icon-size="16" aria-hidden="true"></span>AI assistant
|
|
76
|
+
<span data-help-title="AI assistant" data-help="What the site's AI answers know and the rules they keep - today that is Della, the chat bot in a chat launcher, when she answers a question your Knowledge does not cover. Each chat launcher can add its own on top in Launchers. What you write here is sent to Claude (Anthropic) with each question, so leave out anything private."></span></div>
|
|
77
|
+
<div class="stx-grid">
|
|
78
|
+
<div class="stx-wide">
|
|
79
|
+
<label class="form-label" for="stx-ai-context">About the business
|
|
80
|
+
<span data-help="Plain facts in your own words: what you do, where, your hours and prices if you want them given, how you like to sound. The AI answers only from this and the chat Knowledge, and says it does not know rather than guess."></span></label>
|
|
81
|
+
<textarea id="stx-ai-context" class="form-input" rows="5" maxlength="4000"
|
|
82
|
+
placeholder="We are a family plumbing firm in Leeds, open 8am to 6pm on weekdays. We fit and service boilers..." data-model="aiContext.value"></textarea>
|
|
83
|
+
</div>
|
|
84
|
+
<div class="stx-wide">
|
|
85
|
+
<label class="form-label" for="stx-ai-rules">Rules
|
|
86
|
+
<span data-help="One per line: what an answer must never do or say. For example: Never quote a price. Do not give medical advice. Do not discuss other companies. A launcher's own rules add to these; they cannot lift one."></span></label>
|
|
87
|
+
<textarea id="stx-ai-rules" class="form-input" rows="3" maxlength="2000"
|
|
88
|
+
placeholder="Never quote a price - offer a free quote instead." data-model="aiRules.value"></textarea>
|
|
89
|
+
</div>
|
|
90
|
+
</div>
|
|
91
|
+
</div>
|
|
74
92
|
<div class="stx-card stx-moved dm-settings-section">
|
|
75
93
|
<span data-icon="droplet"></span>
|
|
76
94
|
<div class="stx-moved-text">
|
package/admin/js/views/chats.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{apiRequest as
|
|
1
|
+
import{apiRequest as De}from"../api.js";import{addBannerAction as Re}from"../lib/plugin-chrome.js";import{helpPopovers as ce}from"../lib/help-popover.js";import{onceClosed as Ae,openMenuAt as ie,sidebarCount as V,viewLifetime as He}from"../lib/tool-kit.js";import{arrangeChats as Le,arrangeSaved as Oe,mayDo as de,OUTCOME as ue,STATUS as Ie,threadRow as he}from"../lib/chats-arrange.js";const Pe=/^#\/launchers\/chats\b/,pe=5e3,me=3e3,Ue=3e4,ve="chats.drafts",i=(h,l="GET",$)=>De(h,{method:l,...$!==void 0?{body:JSON.stringify($)}:{}});function qe(h){const l=document.createElement("template");return l.innerHTML=h.trim(),l.content.firstElementChild}const Be=()=>{try{const h=S.get(ve);return h&&typeof h=="object"?h:{}}catch{return{}}},fe=h=>{try{S.set(ve,h)}catch{}},Ke=`
|
|
2
2
|
<div class="chat-row" data-id="{{id}}" tabindex="0" role="button" data-bind-class="$root.openId.value === id && 'is-open'">
|
|
3
3
|
<span class="chat-row-who">{{who}}</span>
|
|
4
4
|
<span data-bind-class="chipClass">{{chip}}</span>
|
|
@@ -6,12 +6,12 @@ import{apiRequest as be}from"../api.js";import{addBannerAction as ge}from"../lib
|
|
|
6
6
|
<span class="chat-row-meta">{{meta}}</span>
|
|
7
7
|
<span class="chat-row-unread" aria-label="unread">{{unreadText}}</span>
|
|
8
8
|
<button type="button" class="chat-row-kebab" aria-label="Chat actions" title="Actions">\u22EE</button>
|
|
9
|
-
</div>`,
|
|
9
|
+
</div>`,je=`
|
|
10
10
|
<div data-bind-class="cls">
|
|
11
11
|
<span class="chat-msg-who">{{who}} \xB7 {{time}}</span>
|
|
12
12
|
<div class="chat-msg-text">{{text}}</div>
|
|
13
13
|
<span class="chat-msg-note">{{note}}</span>
|
|
14
|
-
</div>`,l=ke(Ce);export const chatsView={templateUrl:"/admin/js/templates/chats.html",async onMount(c){l.reset();const n=c.get(0);let g=!1;l.add(()=>{g=!0});const r=()=>!g&&n.isConnected,z=await h("/auth/permissions").then(e=>e.permissions||[]).catch(()=>[]);if(!r())return;const v=ne(z,"chats","reply"),G=ne(z,"chats","manage"),d=M.observable([]),K=M.observable(""),w=M.observable("active"),p=M.observable(!0),k=M.observable(""),s=M.observable(location.hash.match(/^#\/launchers\/chats\/([A-Za-z0-9_-]+)/)?.[1]||""),i=M.observable(null),T=M.observable([]),m=M.observable(""),H=M.observable(!1),C=M.observable(!1),V=M.observable([]),W=M.observable({installed:!0,count:1});let x=0,J=!1;const U=M.observable([]);l.add(M.effect(()=>{U.value=Me(d.value,{query:K.value})}));const ie={query:K,view:w,loading:p,loadError:k,rows:U,openId:s,thread:T,reply:m,available:C,canReply:v,isEmpty:M.computed(()=>!p.value&&!k.value&&U.value.length===0),emptyText:M.computed(()=>K.value.trim()?"No chats match.":w.value==="active"?"No chats right now. They appear here as visitors start them.":"No ended chats."),countText:M.computed(()=>{if(p.value)return"";const e=d.value.filter(a=>a.status==="waiting").length,t=d.value.length;return`${t} chat${t===1?"":"s"}${e?` \xB7 ${e} waiting`:""}`}),availText:M.computed(()=>{const e=V.value;return C.value?e.length>1?`Available (${e.length} of you)`:"Available for chats":e.length?`Not available \xB7 ${e.length} other${e.length===1?"":"s"} available`:"Not available"}),noLauncherNote:M.computed(()=>{const e=W.value;return e.installed&&!e.count?"No chat launcher is switched on yet, so visitors cannot start a chat. Add a launcher with the Chat action in Launchers.":""}),head:M.computed(()=>{const e=i.value;if(!e)return{who:"",chip:"",chipClass:"chat-chip",email:"",mailto:"",meta:""};const t=Ee[e.status]||{label:e.status,tone:"muted"},a=e.startedAt?`started ${D(e.startedAt).fromNow()}`:"";return{who:e.name||"Visitor",chip:t.label,chipClass:`chat-chip chat-chip--${t.tone}`,email:e.email,mailto:e.email?`mailto:${e.email}`:"",meta:[e.page?`on ${e.page}`:"",a].filter(Boolean).join(" \xB7 ")}}),canWrite:M.computed(()=>v&&!!i.value&&i.value.status!=="closed"),canSend:M.computed(()=>v&&!H.value&&m.value.trim().length>0&&!!i.value&&i.value.status!=="closed"),replyHint:M.computed(()=>i.value?.status==="closed"?"This chat has ended.":i.value?.status==="message"?"Reply here (they see it if they come back) - or email them.":"Type a reply\u2026 (Ctrl+Enter sends)")};let y=Ne();l.add(M.effect(()=>{const e=s.peek(),t=m.value;e&&(t?y[e]=t:delete y[e],ce(y))}));const Y=e=>{m.peek().trim()&&(e.preventDefault(),e.returnValue="")};window.addEventListener("beforeunload",Y),l.add(()=>window.removeEventListener("beforeunload",Y)),n.querySelector(".chats-list").innerHTML=De,n.querySelector(".chats-msgs").innerHTML=He;const j=n.querySelector(".chats-list"),N=n.querySelector(".chats-messages"),de=ae(n,{position:"bottom"});l.add(de);let $=0,L=0,Z=0;l.add(()=>{clearTimeout($),clearTimeout(L),clearInterval(Z)});async function f(){clearTimeout($);try{const e=await h(`/chats?view=${w.peek()}`);if(!r())return;d.value=e.items||[],V.value=e.available||[],W.value=e.launchers||{installed:!0,count:1},k.value=""}catch{if(!r())return;p.peek()&&(k.value="Could not load the chats.")}finally{r()&&(p.value=!1,$=setTimeout(Q(f),oe))}}const Q=e=>()=>{if(document.hidden){$=setTimeout(Q(e),oe);return}e()};async function R(e=!1){clearTimeout(L);const t=s.peek();if(t){e&&(x=0,T.value=[]);try{const a=await h(`/chats/${encodeURIComponent(t)}?after=${x}`);if(!r()||s.peek()!==t)return;i.value=a.chat;const o=(a.messages||[]).filter(u=>u.n>x);if(o.length){const u=N.scrollHeight-N.scrollTop-N.clientHeight<80;x=Math.max(x,...o.map(_=>_.n)),T.value=[...T.peek(),...o.map(Te)],(e||u)&&requestAnimationFrame(()=>{N.scrollTop=N.scrollHeight}),O("#/launchers/chats")}d.value=d.peek().map(u=>u.id===t?{...u,...a.chat}:u)}catch(a){if(!r()||s.peek()!==t)return;if(/not found/i.test(a?.message||"")){E.toast("That chat no longer exists",{type:"warning"}),P();return}}r()&&s.peek()===t&&(L=setTimeout(()=>R(),document.hidden?le*4:le))}}function A(e){!e||s.peek()===e||(s.value=e,i.value=d.peek().find(t=>t.id===e)||null,m.value=y[e]||"",history.replaceState(null,"",`#/launchers/chats/${e}`),R(!0))}function P(){clearTimeout(L),s.value="",i.value=null,T.value=[],m.value="",history.replaceState(null,"","#/launchers/chats")}async function X(){const e=s.peek(),t=m.peek().trim();if(!(!e||!t||H.peek())){H.value=!0;try{if(await h(`/chats/${encodeURIComponent(e)}/reply`,"POST",{text:t}),!r())return;m.value="",await R(),f(),O("#/launchers/chats")}catch(a){E.toast(a?.message||"The reply was not sent",{type:"error"})}finally{r()&&(H.value=!1)}}}async function ue(e){try{await h(`/chats/${encodeURIComponent(e)}/close`,"POST",{}),E.toast("Chat ended",{type:"success"}),s.peek()===e&&R(),f(),O("#/launchers/chats")}catch(t){E.toast(t?.message||"Could not end the chat",{type:"error"})}}async function he(e){if(!(!await E.confirm("Delete this chat and all its messages? This cannot be undone.")||!r()))try{await h(`/chats/${encodeURIComponent(e)}`,"DELETE"),delete y[e],ce(y),s.peek()===e&&P(),d.value=d.peek().filter(a=>a.id!==e),O("#/launchers/chats"),E.toast("Chat deleted",{type:"success"})}catch(a){E.toast(a?.message||"Could not delete the chat",{type:"error"})}}async function q(e=!1){if(v)try{const t=await h("/chats/presence","POST",e?{leaving:!0}:{available:C.peek()});!e&&r()&&typeof t?.online=="number"&&f()}catch{}}v&&(C.value=!0,q(),Z=setInterval(()=>q(),xe),l.add(M.effect(()=>{if(C.value,!J){J=!0;return}q()})),l.add(()=>q(!0)));const pe=M.applyBindings(ie,n,{methods:{retry:()=>{p.value=!0,k.value="",f()},showActive:()=>{w.value="active",p.value=!0,f()},showClosed:()=>{w.value="closed",p.value=!0,f()},sendReply:()=>(X(),!1),back:()=>P()}});l.add(()=>pe.dispose()),n.querySelector(".chats-reply textarea")?.addEventListener("keydown",e=>{(e.ctrlKey||e.metaKey)&&e.key==="Enter"&&(e.preventDefault(),X())});const ee=e=>{const t=d.peek().find(a=>a.id===e)||(i.peek()?.id===e?i.peek():null);return t?[{label:"Open",icon:"message-circle",action:()=>A(e)},...t.email?[{label:"Email the visitor",icon:"mail",action:()=>{location.href=`mailto:${t.email}`}},{label:"Copy email address",icon:"copy",action:()=>navigator.clipboard?.writeText(t.email).then(()=>E.toast("Copied",{type:"success"})).catch(()=>{})}]:[],...t.page?[{label:"Open the page they were on",icon:"external-link",action:()=>window.open(t.page,"_blank","noopener")}]:[],...v&&t.status!=="closed"?[{type:"divider"},{label:"End chat",icon:"x-circle",action:()=>ue(e)}]:[],...G?[{type:"divider"},{label:"Delete",icon:"trash",danger:!0,action:()=>he(e)}]:[]]:[]},me=E.contextMenu(j,{cursor:"glyph",match:".chat-row",inherit:!1,density:"compact",items:e=>ee(e.dataset.id)});l.add(()=>me?.destroy?.());const F=n.querySelector(".chats-head-kebab"),fe=E.contextMenu(F,{cursor:"glyph",inherit:!1,density:"compact",items:()=>ee(s.peek())});l.add(()=>fe?.destroy?.()),F.addEventListener("click",()=>se(F)),j.addEventListener("click",e=>{const t=e.target.closest(".chat-row");if(t){if(e.target.closest(".chat-row-kebab")){se(t);return}A(t.dataset.id)}}),j.addEventListener("keydown",e=>{const t=e.target.closest?.(".chat-row");t&&(e.key==="Enter"||e.key===" ")&&e.target===t&&(e.preventDefault(),A(t.dataset.id))});let b=null;async function ve(){if(b)return;let e;try{e=(await h("/chats/settings")).settings}catch{E.toast("Could not read the chat settings",{type:"error"});return}if(!r()||b)return;const t=E.slideover({title:"Chat settings",size:"sm",position:"right"});b=t;const a=Se(`
|
|
14
|
+
</div>`,r=He(Pe);export const chatsView={templateUrl:"/admin/js/templates/chats.html",async onMount(h){r.reset();const l=h.get(0);let $=!1;r.add(()=>{$=!0});const n=()=>!$&&l.isConnected,Z=await i("/auth/permissions").then(e=>e.permissions||[]).catch(()=>[]);if(!n())return;const b=de(Z,"chats","reply"),z=de(Z,"chats","manage"),m=M.observable([]),O=M.observable(""),d=M.observable("active"),y=M.observable(!0),g=M.observable(""),o=M.observable(location.hash.match(/^#\/launchers\/chats\/([A-Za-z0-9_-]+)/)?.[1]||""),u=M.observable(null),k=M.observable([]),v=M.observable(""),P=M.observable(!1),R=M.observable(!1),Q=M.observable([]),X=M.observable({installed:!0,count:1}),f=M.observable([]),p=M.observable(null),U=M.observable(""),q=M.observable("to look at");let A=0,ee=!1;const G=M.observable([]);r.add(M.effect(()=>{G.value=d.value==="saved"?Oe(f.value,{query:O.value}):Le(m.value,{query:O.value})}));const ye={query:O,view:d,loading:y,loadError:g,rows:G,openId:o,thread:k,reply:v,available:R,canReply:b,savedOpen:p,savedNote:U,savedOutcome:q,savedDirty:M.computed(()=>!!p.value&&(U.value!==(p.value.note||"")||q.value!==p.value.outcome)),isEmpty:M.computed(()=>!y.value&&!g.value&&G.value.length===0),emptyText:M.computed(()=>O.value.trim()?"No chats match.":d.value==="active"?"No chats right now. They appear here as visitors start them.":d.value==="saved"?"No saved chats. Right-click a chat and choose Save for a closer look to keep a copy here.":"No ended chats."),countText:M.computed(()=>{if(y.value)return"";if(d.value==="saved"){const a=f.value.length,s=f.value.filter(c=>c.outcome!=="done").length;return`${a} saved${s?` \xB7 ${s} to finish`:""}`}const e=m.value.filter(a=>a.status==="waiting").length,t=m.value.length;return`${t} chat${t===1?"":"s"}${e?` \xB7 ${e} waiting`:""}`}),availText:M.computed(()=>{const e=Q.value;return R.value?e.length>1?`Available (${e.length} of you)`:"Available for chats":e.length?`Not available \xB7 ${e.length} other${e.length===1?"":"s"} available`:"Not available"}),noLauncherNote:M.computed(()=>{const e=X.value;return e.installed&&!e.count?"No chat launcher is switched on yet, so visitors cannot start a chat. Add a launcher with the Chat action in Launchers.":""}),head:M.computed(()=>{const e=p.value;if(e){const c=ue[e.outcome]||ue["to look at"],L=e.savedAt?`saved ${D(e.savedAt).fromNow()}${e.savedBy?` by ${e.savedBy}`:""}`:"";return{who:e.name||"Visitor",chip:c.label,chipClass:`chat-chip chat-chip--${c.tone}`,email:e.email,mailto:e.email?`mailto:${e.email}`:"",meta:[e.page?`on ${e.page}`:"",L].filter(Boolean).join(" \xB7 ")}}const t=u.value;if(!t)return{who:"",chip:"",chipClass:"chat-chip",email:"",mailto:"",meta:""};const a=Ie[t.status]||{label:t.status,tone:"muted"},s=t.startedAt?`started ${D(t.startedAt).fromNow()}`:"";return{who:t.name||"Visitor",chip:a.label,chipClass:`chat-chip chat-chip--${a.tone}`,email:t.email,mailto:t.email?`mailto:${t.email}`:"",meta:[t.page?`on ${t.page}`:"",s].filter(Boolean).join(" \xB7 ")}}),canWrite:M.computed(()=>b&&!!u.value&&u.value.status!=="closed"),canSend:M.computed(()=>b&&!P.value&&v.value.trim().length>0&&!!u.value&&u.value.status!=="closed"),replyHint:M.computed(()=>u.value?.status==="closed"?"This chat has ended.":u.value?.status==="message"?"Reply here (they see it if they come back) - or email them.":"Type a reply\u2026 (Ctrl+Enter sends)")};let T=Be();r.add(M.effect(()=>{const e=o.peek(),t=v.value;e&&(t?T[e]=t:delete T[e],fe(T))}));const te=e=>{v.peek().trim()&&(e.preventDefault(),e.returnValue="")};window.addEventListener("beforeunload",te),r.add(()=>window.removeEventListener("beforeunload",te)),l.querySelector(".chats-list").innerHTML=Ke,l.querySelector(".chats-msgs").innerHTML=je;const W=l.querySelector(".chats-list"),x=l.querySelector(".chats-messages"),be=ce(l,{position:"bottom"});r.add(be);let B=0,H=0,ae=0;r.add(()=>{clearTimeout(B),clearTimeout(H),clearInterval(ae)});async function w(){if(clearTimeout(B),d.peek()==="saved")return ge();try{const e=await i(`/chats?view=${d.peek()}`);if(!n())return;m.value=e.items||[],Q.value=e.available||[],X.value=e.launchers||{installed:!0,count:1},g.value=""}catch{if(!n())return;y.peek()&&(g.value="Could not load the chats.")}finally{n()&&(y.value=!1,B=setTimeout(se(w),pe))}}async function ge(){try{const e=await i("/chats/saved");if(!n()||d.peek()!=="saved")return;f.value=e.items||[],g.value=""}catch{n()&&(g.value="Could not load the saved chats.")}finally{n()&&(y.value=!1)}}async function ne(e){if(!(!e||p.peek()?.id===e)){clearTimeout(H),u.value=null,v.value="",o.value=e,k.value=[];try{const{item:t}=await i(`/chats/saved/${encodeURIComponent(e)}`);if(!n()||o.peek()!==e)return;p.value=t,U.value=t.note||"",q.value=t.outcome,k.value=(t.messages||[]).map(he),requestAnimationFrame(()=>{x.scrollTop=0})}catch(t){if(!n())return;E.toast(t?.message||"Could not open the saved chat",{type:"error"}),C()}}}async function ke(){const e=p.peek();if(e)try{const{item:t}=await i(`/chats/saved/${encodeURIComponent(e.id)}`,"PUT",{note:U.peek(),outcome:q.peek()});if(!n())return;p.value={...e,...t},f.value=f.peek().map(a=>a.id===t.id?t:a),E.toast("Saved",{type:"success"})}catch(t){E.toast(t?.message||"Could not save",{type:"error"})}}async function we(e){const t=await E.prompt("Save a copy of this chat for a closer look. Why are you saving it? (optional)");if(!(t==null||!n()))try{if(await i(`/chats/${encodeURIComponent(e)}/save`,"POST",{note:String(t)}),!n())return;E.toast("Saved - find it under Saved",{type:"success"})}catch(a){E.toast(a?.message||"Could not save the chat",{type:"error"})}}async function Ee(e){if(!(!await E.confirm("Delete this saved copy? The chat itself is not affected. This cannot be undone.")||!n()))try{await i(`/chats/saved/${encodeURIComponent(e)}`,"DELETE"),o.peek()===e&&C(),f.value=f.peek().filter(a=>a.id!==e),E.toast("Saved copy deleted",{type:"success"})}catch(a){E.toast(a?.message||"Could not delete it",{type:"error"})}}const se=e=>()=>{if(document.hidden){B=setTimeout(se(e),pe);return}e()};async function K(e=!1){clearTimeout(H);const t=o.peek();if(t){e&&(A=0,k.value=[]);try{const a=await i(`/chats/${encodeURIComponent(t)}?after=${A}`);if(!n()||o.peek()!==t)return;u.value=a.chat;const s=(a.messages||[]).filter(c=>c.n>A);if(s.length){const c=x.scrollHeight-x.scrollTop-x.clientHeight<80;A=Math.max(A,...s.map(L=>L.n)),k.value=[...k.peek(),...s.map(he)],(e||c)&&requestAnimationFrame(()=>{x.scrollTop=x.scrollHeight}),V("#/launchers/chats")}m.value=m.peek().map(c=>c.id===t?{...c,...a.chat}:c)}catch(a){if(!n()||o.peek()!==t)return;if(/not found/i.test(a?.message||"")){E.toast("That chat no longer exists",{type:"warning"}),C();return}}n()&&o.peek()===t&&(H=setTimeout(()=>K(),document.hidden?me*4:me))}}function j(e){if(d.peek()==="saved"){ne(e);return}!e||o.peek()===e||(o.value=e,u.value=m.peek().find(t=>t.id===e)||null,v.value=T[e]||"",history.replaceState(null,"",`#/launchers/chats/${e}`),K(!0))}function C(){clearTimeout(H),o.value="",u.value=null,p.value=null,k.value=[],v.value="",history.replaceState(null,"","#/launchers/chats")}async function oe(){const e=o.peek(),t=v.peek().trim();if(!(!e||!t||P.peek())){P.value=!0;try{if(await i(`/chats/${encodeURIComponent(e)}/reply`,"POST",{text:t}),!n())return;v.value="",await K(),w(),V("#/launchers/chats")}catch(a){E.toast(a?.message||"The reply was not sent",{type:"error"})}finally{n()&&(P.value=!1)}}}async function Me(e){try{await i(`/chats/${encodeURIComponent(e)}/close`,"POST",{}),E.toast("Chat ended",{type:"success"}),o.peek()===e&&K(),w(),V("#/launchers/chats")}catch(t){E.toast(t?.message||"Could not end the chat",{type:"error"})}}async function Ce(e){if(!(!await E.confirm("Delete this chat and all its messages? This cannot be undone.")||!n()))try{await i(`/chats/${encodeURIComponent(e)}`,"DELETE"),delete T[e],fe(T),o.peek()===e&&C(),m.value=m.peek().filter(a=>a.id!==e),V("#/launchers/chats"),E.toast("Chat deleted",{type:"success"})}catch(a){E.toast(a?.message||"Could not delete the chat",{type:"error"})}}async function F(e=!1){if(b)try{const t=await i("/chats/presence","POST",e?{leaving:!0}:{available:R.peek()});!e&&n()&&typeof t?.online=="number"&&w()}catch{}}b&&(R.value=!0,F(),ae=setInterval(()=>F(),Ue),r.add(M.effect(()=>{if(R.value,!ee){ee=!0;return}F()})),r.add(()=>F(!0)));function J(e){if(d.peek()===e)return;const t=d.peek()==="saved"||e==="saved";d.value=e,t&&o.peek()&&C(),y.value=!0,w()}const Te=M.applyBindings(ye,l,{methods:{retry:()=>{y.value=!0,g.value="",w()},showActive:()=>{J("active")},showClosed:()=>{J("closed")},showSaved:()=>{J("saved")},saveSavedNote:()=>ke(),sendReply:()=>(oe(),!1),back:()=>C()}});r.add(()=>Te.dispose()),l.querySelector(".chats-reply textarea")?.addEventListener("keydown",e=>{(e.ctrlKey||e.metaKey)&&e.key==="Enter"&&(e.preventDefault(),oe())});const le=e=>{if(d.peek()==="saved"){const a=f.peek().find(s=>s.id===e)||(p.peek()?.id===e?p.peek():null);return a?[{label:"Open",icon:"message-circle",action:()=>ne(e)},...a.email?[{label:"Email the visitor",icon:"mail",action:()=>{location.href=`mailto:${a.email}`}}]:[],...a.page?[{label:"Open the page they were on",icon:"external-link",action:()=>window.open(a.page,"_blank","noopener")}]:[],...z?[{type:"divider"},{label:"Delete saved copy",icon:"trash",danger:!0,action:()=>Ee(e)}]:[]]:[]}const t=m.peek().find(a=>a.id===e)||(u.peek()?.id===e?u.peek():null);return t?[{label:"Open",icon:"message-circle",action:()=>j(e)},...t.email?[{label:"Email the visitor",icon:"mail",action:()=>{location.href=`mailto:${t.email}`}},{label:"Copy email address",icon:"copy",action:()=>navigator.clipboard?.writeText(t.email).then(()=>E.toast("Copied",{type:"success"})).catch(()=>{})}]:[],...t.page?[{label:"Open the page they were on",icon:"external-link",action:()=>window.open(t.page,"_blank","noopener")}]:[],...b?[{type:"divider"},{label:"Save for a closer look\u2026",icon:"bookmark",action:()=>we(e)}]:[],...b&&t.status!=="closed"?[{type:"divider"},{label:"End chat",icon:"x-circle",action:()=>Me(e)}]:[],...z?[{type:"divider"},{label:"Delete",icon:"trash",danger:!0,action:()=>Ce(e)}]:[]]:[]},Se=E.contextMenu(W,{cursor:"glyph",match:".chat-row",inherit:!1,density:"compact",items:e=>le(e.dataset.id)});r.add(()=>Se?.destroy?.());const Y=l.querySelector(".chats-head-kebab"),xe=E.contextMenu(Y,{cursor:"glyph",inherit:!1,density:"compact",items:()=>le(o.peek())});r.add(()=>xe?.destroy?.()),Y.addEventListener("click",()=>ie(Y)),W.addEventListener("click",e=>{const t=e.target.closest(".chat-row");if(t){if(e.target.closest(".chat-row-kebab")){ie(t);return}j(t.dataset.id)}}),W.addEventListener("keydown",e=>{const t=e.target.closest?.(".chat-row");t&&(e.key==="Enter"||e.key===" ")&&e.target===t&&(e.preventDefault(),j(t.dataset.id))});let N=null;async function Ne(){if(N)return;let e;try{e=(await i("/chats/settings")).settings}catch{E.toast("Could not read the chat settings",{type:"error"});return}if(!n()||N)return;const t=E.slideover({title:"Chat settings",size:"sm",position:"right"});N=t;const a=qe(`
|
|
15
15
|
<div class="chats-settings" style="display:flex;flex-direction:column;gap:1rem;padding:.25rem">
|
|
16
16
|
<div>
|
|
17
17
|
<label class="form-label" for="chat-set-conf">How sure the bot must be
|
|
@@ -35,7 +35,7 @@ import{apiRequest as be}from"../api.js";import{addBannerAction as ge}from"../lib
|
|
|
35
35
|
</div>
|
|
36
36
|
<div>
|
|
37
37
|
<label class="form-label" for="chat-set-keep">Keep ended chats for (days)
|
|
38
|
-
<span data-help="
|
|
38
|
+
<span data-help="The site's default: ended chats and their messages are deleted after this many days (7 to 730). A chat launcher can keep its own for a different time (Launchers > the chat settings). Messages left for the team are kept until someone ends them; Save for a closer look keeps a copy for good."></span>
|
|
39
39
|
</label>
|
|
40
40
|
<input id="chat-set-keep" type="number" min="7" max="730" class="form-input" data-model="retentionDays.value" data-bind-disabled="!canManage">
|
|
41
41
|
</div>
|
|
@@ -50,4 +50,4 @@ import{apiRequest as be}from"../api.js";import{addBannerAction as ge}from"../lib
|
|
|
50
50
|
<button type="button" class="btn btn-sm btn-ghost" data-on-click="cancel">Cancel</button>
|
|
51
51
|
<button type="button" class="btn btn-sm btn-primary" data-on-click="save" data-bind-hidden="!canManage" data-bind-disabled="!dirty.value">Save</button>
|
|
52
52
|
</div>
|
|
53
|
-
</div>`),
|
|
53
|
+
</div>`),s={canManage:z,confidence:M.observable(e.confidence),staffName:M.observable(e.staffName),retentionDays:M.observable(String(e.retentionDays)),maxNewChatsPerHour:M.observable(String(e.maxNewChatsPerHour))};s.dirty=M.computed(()=>s.confidence.value!==e.confidence||s.staffName.value!==e.staffName||Number(s.retentionDays.value)!==e.retentionDays||Number(s.maxNewChatsPerHour.value)!==e.maxNewChatsPerHour),t.element.appendChild(a);const c=ce(a),L=M.applyBindings(s,a,{methods:{cancel:()=>t.close(),save:async()=>{try{e=(await i("/chats/settings","PUT",{confidence:s.confidence.peek(),staffName:s.staffName.peek(),retentionDays:Number(s.retentionDays.peek()),maxNewChatsPerHour:Number(s.maxNewChatsPerHour.peek())})).settings,E.toast("Chat settings saved",{type:"success"}),t.close()}catch(_){E.toast(_?.message||"Could not save",{type:"error"})}}}});Ae(t,()=>{L.dispose(),c(),N===t&&(N=null)});const $e=t.close;t.close=async(..._)=>s.dirty.peek()&&!r.leaving&&!await E.confirm("Discard your changes to the chat settings?")?!1:$e(..._),t.open()}r.add(()=>N?.close()),Re(h,{id:"chats-settings",icon:"settings",title:"Chat settings",onClick:Ne});const re=e=>{e.ctrlKey||e.metaKey||e.altKey||e.target.closest?.("input, textarea, select, [contenteditable], .dm-slideover")||(e.key==="/"&&(e.preventDefault(),l.querySelector(".chats-search input")?.focus()),e.key==="Escape"&&o.peek()&&C())};if(document.addEventListener("keydown",re),r.add(()=>document.removeEventListener("keydown",re)),I.scan(l),await w(),n()&&o.peek()){const e=o.peek();o.value="",j(e)}}};
|