domma-cms 1.54.0 → 1.55.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 +4 -0
- package/admin/js/lib/launchers-arrange.js +2 -2
- package/admin/js/templates/docs/usage-chat.html +5 -0
- package/admin/js/views/launchers.js +22 -20
- package/package.json +1 -1
- package/public/js/launcher-chat.mjs +1 -1
- package/public/js/launcher-settings.mjs +4 -4
- package/public/js/launchers.mjs +2 -2
- package/server/services/chat/ai.js +2 -2
- package/server/services/chat/conversation.js +5 -3
- package/server/services/chat/settings.js +2 -0
- package/server/services/launchers.js +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,9 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## [1.55.0] - 2026-11-11
|
|
4
|
+
|
|
5
|
+
- Chat launchers have an **Answer from the Knowledge** switch (`chat.useKnowledge`, default on). Off: that chat skips the site's Knowledge (no answers or choices from it, not given to the AI, nothing logged as Unanswered) and only the AI answers, from the launcher's own context. For a chat about something else, such as admin help (the jobs site's admin Dash).
|
|
6
|
+
|
|
3
7
|
## [1.54.0] - 2026-11-11
|
|
4
8
|
|
|
5
9
|
- Add Dash's own six-pose character pack for Job Board assistants, with ready, greeting, working, thinking, success and help poses. Dash can be selected in admin assistant settings and chat launchers. Editing a launcher preserves its selected character and custom branding.
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import{LAUNCHER_DEFAULTS as b,LAUNCHER_LIMITS as r,LAUNCHER_POSITION_LABEL as u,launcherColourCss as l,launcherReady as x,launcherSpot as y,launcherAvatar as f,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){if(e.place==="admin")return`the admin only${e.devices==="desktop"?", desktop only":e.devices==="phone"?", phones only":""}`;const t=e.pages.paths.length,n=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":"",o=e.devices==="desktop"?", desktop only":e.devices==="phone"?", phones only":"";return`${n}${a}${o}${e.place==="both"?", and the admin":""}`}export function launcherProblem(e){return x(e)?e.place!=="admin"&&e.pages.mode==="only"&&!e.pages.paths.length?"Shows on no pages":"":"Choose what it opens"}export function launcherRow(e){const t=launcherProblem(e),n=e.triggerStyle==="icon-text",a=l(e.colours.background)||"var(--dm-primary)",o=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:n,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":o,"border-radius":n?"999px":`${Math.round(e.radius/e.size*100)}%`}}}export function arrangeLaunchers(e,{filter:t="all",query:n=""}={}){const a=String(n||"").trim().toLowerCase();return e.filter(o=>t==="on"?o.enabled:t==="off"?!o.enabled:!0).filter(o=>!a||[o.name,o.label,o.action.ref,o.action.title].some(i=>String(i||"").toLowerCase().includes(a)))}export function countLaunchers(e){const t=e.filter(n=>n.enabled).length;return{all:e.length,on:t,off:e.length-t}}export function moveItem(e,t,n){const a=[...e];if(t<0||t>=a.length||n<0||n>=a.length||t===n)return a;const[o]=a.splice(t,1);return a.splice(n,0,o),a}export function blankLauncher(e=[]){const t=new Set(e.map(a=>a.name));let n="New launcher";for(let a=2;t.has(n);a++)n=`New launcher ${a}`;return p({name:n})}export function duplicateLauncher(e,t=[]){const n=new Set(t.map(o=>o.name));let a=`${e.name} (copy)`.slice(0,r.nameMax);for(let o=2;n.has(a);o++)a=`${e.name} (copy ${o})`.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,place:t.place,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,character:t.chat.character||"",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 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,place:e.place,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.character||"",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(`
|
|
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,character:t.chat.character||"",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,useKnowledge:t.chat.useKnowledge,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,place:e.place,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.character||"",characterName:String(e.characterName||"").trim(),greeting:e.greeting,botName:e.botName,bot:e.bot,staff:e.staff,askDetails:e.askDetails,ai:e.ai,useKnowledge:e.useKnowledge,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={},n={};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."):n.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),o=a.filter(i=>!g(i));o.length?t.paths=`Not an address: ${o.slice(0,3).join(", ")}`:a.length>r.pathsMax?t.paths=`At most ${r.pathsMax} rules.`:e.pagesMode==="only"&&!a.length&&(n.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
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()&&!f(e.avatar)&&(t.avatar="Choose a picture from Media (an address on this site)."),{errors:t,warnings:n}}export function previewSpot(e,{vw:t=320,vh:n=200,scale:a=.5,phone:o=!1}={}){const i=o&&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=y(i?e.phonePosition:e.position,{w:c,h:s,vw:t,vh:n,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(n-s,h.top)),size:s,w:c}}export{b as LAUNCHER_DEFAULTS,u as LAUNCHER_POSITION_LABEL};
|
|
@@ -63,6 +63,11 @@
|
|
|
63
63
|
<p>Switch an entry off (right-click it) to stop the bot using it without losing it. The <strong>answered N
|
|
64
64
|
times</strong> count shows which entries earn their keep.</p>
|
|
65
65
|
|
|
66
|
+
<p><strong>Answer from the Knowledge</strong> (on by default, in the launcher's chat settings) can be switched off for one
|
|
67
|
+
launcher. That chat then ignores the Knowledge: no answers or "Did you mean" choices from it, the AI does not see it,
|
|
68
|
+
and its questions are not added to Unanswered. Only the AI answers, from that launcher's own boxes. Use it for a chat
|
|
69
|
+
about something else, such as a help chat in the admin.</p>
|
|
70
|
+
|
|
66
71
|
<h3>Answering visitors: Chats</h3>
|
|
67
72
|
<p><strong>Content > Chats</strong> is the inbox. Its sidebar badge counts the chats that need you: a visitor
|
|
68
73
|
<strong>Waiting</strong> for a person (a live dot; red after five minutes), a <strong>Message left</strong> when
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{apiRequest as V,api as
|
|
1
|
+
import{apiRequest as V,api as we}from"../api.js";import{CHARACTERS as Ve}from"../../../public/js/characters.mjs";import{addBannerAction as ye}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 Je}from"../lib/tool-kit.js";import{rowPlaceKeeper as Qe}from"../lib/menu-drag.js";import{FILTERS as Ze,LAUNCHER_POSITION_LABEL as Te,arrangeLaunchers as ea,blankLauncher as aa,checkLauncherForm as ta,countLaunchers as la,duplicateLauncher as na,formFromLauncher as sa,launcherFromForm as oa,launcherRow as ia,moveItem as da,previewSpot as ra}from"../lib/launchers-arrange.js";import{LAUNCHER_LIMITS as o,LAUNCHER_TOKENS as G,launcherChatAccentCss as ca,launcherColourCss as $e,launcherHref as J}from"../../../public/js/launcher-settings.mjs";const Me=/^#\/launchers\/?(\?.*)?$/,Ee="#/launchers",Q="launchers.filter",U="launchers.draft",ha=`
|
|
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>
|
|
@@ -16,12 +16,12 @@ import{apiRequest as V,api as ye}from"../api.js";import{CHARACTERS as Ve}from"..
|
|
|
16
16
|
<div class="lnx-grid2">
|
|
17
17
|
<div class="lnx-field">
|
|
18
18
|
<label class="form-label" for="lnx-f-name">Name <span data-help="Only you see this - it names the launcher in this list."></span></label>
|
|
19
|
-
<input id="lnx-f-name" class="form-input" maxlength="${
|
|
19
|
+
<input id="lnx-f-name" class="form-input" maxlength="${o.nameMax}" data-model="name.value">
|
|
20
20
|
<small class="lnx-err" data-bind-hidden="!err.value.name" data-bind-text="err.value.name"></small>
|
|
21
21
|
</div>
|
|
22
22
|
<div class="lnx-field">
|
|
23
23
|
<label class="form-label" for="lnx-f-label">Label <span data-help="What the disc says: read out to screen readers, and written on the pill when the style is Pill."></span></label>
|
|
24
|
-
<input id="lnx-f-label" class="form-input" maxlength="${
|
|
24
|
+
<input id="lnx-f-label" class="form-input" maxlength="${o.labelMax}" data-model="label.value">
|
|
25
25
|
<small class="lnx-err" data-bind-hidden="!err.value.label" data-bind-text="err.value.label"></small>
|
|
26
26
|
</div>
|
|
27
27
|
<div class="lnx-field">
|
|
@@ -30,12 +30,12 @@ import{apiRequest as V,api as ye}from"../api.js";import{CHARACTERS as Ve}from"..
|
|
|
30
30
|
</div>
|
|
31
31
|
<div class="lnx-field" data-bind-hidden="tooltipMode.value !== 'custom'">
|
|
32
32
|
<label class="form-label" for="lnx-f-tip">Tooltip words</label>
|
|
33
|
-
<input id="lnx-f-tip" class="form-input" maxlength="${
|
|
33
|
+
<input id="lnx-f-tip" class="form-input" maxlength="${o.tooltipMax}" placeholder="e.g. Questions? Ask us here" data-model="tooltip.value">
|
|
34
34
|
</div>
|
|
35
35
|
<div class="lnx-field">
|
|
36
36
|
<label class="form-label" for="lnx-f-icon">Icon <span data-help="A Domma icon name - press the grid button to browse them."></span></label>
|
|
37
37
|
<div class="lnx-inline">
|
|
38
|
-
<input id="lnx-f-icon" class="form-input" maxlength="${
|
|
38
|
+
<input id="lnx-f-icon" class="form-input" maxlength="${o.iconMax}" data-model="icon.value">
|
|
39
39
|
<button type="button" class="lnx-icon-btn lnx-pick-icon" title="Browse icons"><span data-icon="grid" data-icon-size="14"></span></button>
|
|
40
40
|
</div>
|
|
41
41
|
</div>
|
|
@@ -105,7 +105,7 @@ import{apiRequest as V,api as ye}from"../api.js";import{CHARACTERS as Ve}from"..
|
|
|
105
105
|
<div class="lnx-grid2">
|
|
106
106
|
<div class="lnx-field">
|
|
107
107
|
<label class="form-label" for="lnx-f-title">Title <span data-help="The heading of the modal, slideover or chat. Empty uses the label."></span></label>
|
|
108
|
-
<input id="lnx-f-title" class="form-input" maxlength="${
|
|
108
|
+
<input id="lnx-f-title" class="form-input" maxlength="${o.titleMax}" data-model="title.value">
|
|
109
109
|
</div>
|
|
110
110
|
<div class="lnx-field" data-bind-hidden="actionType.value !== 'modal'">
|
|
111
111
|
<label class="form-label" for="lnx-f-size">Modal width <span data-help="Never wider than the window: a phone always gets nearly its full width. Full screen fills the whole window, height too."></span></label>
|
|
@@ -114,7 +114,7 @@ import{apiRequest as V,api as ye}from"../api.js";import{CHARACTERS as Ve}from"..
|
|
|
114
114
|
<div class="lnx-field" data-bind-hidden="actionType.value !== 'modal' || modalSize.value !== 'custom'">
|
|
115
115
|
<label class="form-label" for="lnx-f-cw">Custom width</label>
|
|
116
116
|
<div class="lnx-unit"><input id="lnx-f-cw" type="number" class="form-input" data-model="customWidth.value"
|
|
117
|
-
data-bind-min="widthUnit.value === '%' ? ${
|
|
117
|
+
data-bind-min="widthUnit.value === '%' ? ${o.widthPct[0]} : ${o.widthPx[0]}" data-bind-max="widthUnit.value === '%' ? ${o.widthPct[1]} : ${o.widthPx[1]}">
|
|
118
118
|
<select class="form-input" data-model="widthUnit.value" aria-label="Width unit">${h(c.widthUnit)}</select></div>
|
|
119
119
|
</div>
|
|
120
120
|
<div class="lnx-field" data-bind-hidden="actionType.value !== 'modal' || modalSize.value === 'screen'">
|
|
@@ -124,7 +124,7 @@ import{apiRequest as V,api as ye}from"../api.js";import{CHARACTERS as Ve}from"..
|
|
|
124
124
|
<div class="lnx-field" data-bind-hidden="actionType.value !== 'modal' || modalSize.value === 'screen' || modalHeight.value !== 'custom'">
|
|
125
125
|
<label class="form-label" for="lnx-f-ch">Custom height</label>
|
|
126
126
|
<div class="lnx-unit"><input id="lnx-f-ch" type="number" class="form-input" data-model="customHeight.value"
|
|
127
|
-
data-bind-min="heightUnit.value === 'px' ? ${
|
|
127
|
+
data-bind-min="heightUnit.value === 'px' ? ${o.heightPx[0]} : ${o.heightVh[0]}" data-bind-max="heightUnit.value === 'px' ? ${o.heightPx[1]} : ${o.heightVh[1]}">
|
|
128
128
|
<select class="form-input" data-model="heightUnit.value" aria-label="Height unit">${h(c.heightUnit)}</select></div>
|
|
129
129
|
</div>
|
|
130
130
|
<div class="lnx-field" data-bind-hidden="actionType.value !== 'slideover'">
|
|
@@ -143,14 +143,14 @@ import{apiRequest as V,api as ye}from"../api.js";import{CHARACTERS as Ve}from"..
|
|
|
143
143
|
<small>Use the character's name, portrait and animated poses. Site Settings controls visibility and motion. Your custom name and picture are kept when no character is selected.</small>
|
|
144
144
|
<div data-bind-hidden="!character.value">
|
|
145
145
|
<label class="form-label" for="lnx-f-charname">Display name <span data-help-title="Display name" data-help="Leave empty to use the character's own name. An optional name changes the chat name, while keeping the selected artwork."></span></label>
|
|
146
|
-
<input id="lnx-f-charname" class="form-input" maxlength="${
|
|
146
|
+
<input id="lnx-f-charname" class="form-input" maxlength="${o.botNameMax}" placeholder="Character's own name" data-model="characterName.value">
|
|
147
147
|
</div>
|
|
148
148
|
<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>
|
|
149
|
-
<textarea id="lnx-f-greeting" class="form-input" rows="2" maxlength="${
|
|
149
|
+
<textarea id="lnx-f-greeting" class="form-input" rows="2" maxlength="${o.greetingMax}" data-model="greeting.value"></textarea>
|
|
150
150
|
</div>
|
|
151
151
|
<div class="lnx-field">
|
|
152
152
|
<label class="form-label" for="lnx-f-botname">Bot's name <span data-help="Shown on the bot's answers."></span></label>
|
|
153
|
-
<input id="lnx-f-botname" data-bind-disabled="!!character.value" class="form-input" maxlength="${
|
|
153
|
+
<input id="lnx-f-botname" data-bind-disabled="!!character.value" class="form-input" maxlength="${o.botNameMax}" data-model="botName.value">
|
|
154
154
|
</div>
|
|
155
155
|
<div class="lnx-field">
|
|
156
156
|
<label class="form-label" for="lnx-f-accent">Chat colour <span data-help="This chat's own colour: its heading, the visitor's messages and the send button. Theme uses the site's primary colour, so each chat can carry its own branding."></span></label>
|
|
@@ -168,8 +168,8 @@ import{apiRequest as V,api as ye}from"../api.js";import{CHARACTERS as Ve}from"..
|
|
|
168
168
|
<label class="form-label" for="lnx-f-chatsize">Chat window size <span data-help="How big the chat window opens on a computer, in pixels. It never grows past the visitor's window, and on a phone the chat always fills the screen."></span></label>
|
|
169
169
|
<select id="lnx-f-chatsize" class="form-input" data-model="chatSize.value">${h(c.chatSize)}</select>
|
|
170
170
|
<div class="lnx-grid2" data-bind-hidden="chatSize.value !== 'custom'">
|
|
171
|
-
<input type="number" class="form-input" aria-label="Chat window width in pixels" min="${
|
|
172
|
-
<input type="number" class="form-input" aria-label="Chat window height in pixels" min="${
|
|
171
|
+
<input type="number" class="form-input" aria-label="Chat window width in pixels" min="${o.chatWidth[0]}" max="${o.chatWidth[1]}" data-model="chatWidth.value">
|
|
172
|
+
<input type="number" class="form-input" aria-label="Chat window height in pixels" min="${o.chatHeight[0]}" max="${o.chatHeight[1]}" data-model="chatHeight.value">
|
|
173
173
|
</div>
|
|
174
174
|
<small class="lnx-err" data-bind-hidden="!err.value.chatWidth && !err.value.chatHeight" data-bind-text="err.value.chatWidth || err.value.chatHeight"></small>
|
|
175
175
|
</div>
|
|
@@ -189,9 +189,9 @@ import{apiRequest as V,api as ye}from"../api.js";import{CHARACTERS as Ve}from"..
|
|
|
189
189
|
<small class="lnx-err" data-bind-hidden="!err.value.keepDays" data-bind-text="err.value.keepDays"></small>
|
|
190
190
|
</div>
|
|
191
191
|
<label class="lnx-check"><input type="checkbox" class="form-switch" data-model="chatResizable.value"> Visitors can resize the chat
|
|
192
|
-
<span data-help="A grip in the corner away from the disc lets visitors drag the window bigger or smaller (between ${
|
|
192
|
+
<span data-help="A grip in the corner away from the disc lets visitors drag the window bigger or smaller (between ${o.chatWidth[0]} x ${o.chatHeight[0]} and ${o.chatWidth[1]} x ${o.chatHeight[1]}). Their size is remembered in their browser; a double-click on the grip puts yours back."></span></label>
|
|
193
193
|
<div class="lnx-field" style="grid-column: 1 / -1">
|
|
194
|
-
<label class="form-label" for="lnx-f-starters">Questions to start with <span data-help="Up to ${
|
|
194
|
+
<label class="form-label" for="lnx-f-starters">Questions to start with <span data-help="Up to ${o.startersMax}, one per line: buttons under the greeting that ask the question for the visitor. They go once the chat starts."></span></label>
|
|
195
195
|
<textarea id="lnx-f-starters" class="form-input" rows="3" data-model="starters.value" placeholder="How much does it cost? Can you move my WordPress site?"></textarea>
|
|
196
196
|
<small class="lnx-err" data-bind-hidden="!err.value.starters" data-bind-text="err.value.starters"></small>
|
|
197
197
|
</div>
|
|
@@ -212,6 +212,8 @@ import{apiRequest as V,api as ye}from"../api.js";import{CHARACTERS as Ve}from"..
|
|
|
212
212
|
<span data-help="The bot answers from your Knowledge entries. It offers choices when it is not sure, and hands over to your team when it has no answer."></span></label>
|
|
213
213
|
<label class="lnx-check"><input type="checkbox" class="form-switch" data-model="staff.value"> Your team can answer
|
|
214
214
|
<span data-help="Conversations reach the Chats inbox so your team can reply live. Off: the bot only, and a visitor can still leave their details."></span></label>
|
|
215
|
+
<label class="lnx-check" data-bind-hidden="!bot.value"><input type="checkbox" class="form-switch" data-model="useKnowledge.value"> Answer from the Knowledge
|
|
216
|
+
<span data-help-title="Answer from the Knowledge" data-help="On: the bot answers from your Knowledge entries (Chats > Knowledge) first, and the AI sees them too. Off: this chat ignores the Knowledge and only the AI answers, from the boxes below - for a chat about something else, such as help in the admin."></span></label>
|
|
215
217
|
<label class="lnx-check" data-bind-hidden="!bot.value"><input type="checkbox" class="form-switch" data-model="ai.value"> AI answers what the Knowledge does not
|
|
216
218
|
<span data-help-title="AI answers" data-help="When no Knowledge entry fits, the bot asks Claude, which answers only from your Knowledge, Site Settings > AI assistant and the box below, and says it does not know rather than guess. Comes with the Pro plan on hosted sites; elsewhere the bot answers from the Knowledge alone."></span></label>
|
|
217
219
|
<label class="lnx-check" style="grid-column: 1 / -1" data-bind-hidden="!bot.value || !ai.value"><input type="checkbox" class="form-switch" data-model="aiUseSite.value"> Use the site's About the business
|
|
@@ -219,7 +221,7 @@ import{apiRequest as V,api as ye}from"../api.js";import{CHARACTERS as Ve}from"..
|
|
|
219
221
|
<div class="lnx-field" style="grid-column: 1 / -1" data-bind-hidden="!bot.value || !ai.value">
|
|
220
222
|
<label class="form-label" for="lnx-f-aicontext">What the AI should know for this launcher
|
|
221
223
|
<span data-help="Added to Site Settings > AI assistant > About the business (or used on its own when the site's settings are off), for chats from this launcher only - say, the products on the pages it shows on. Sent to Claude with each question, so leave out anything private."></span></label>
|
|
222
|
-
<textarea id="lnx-f-aicontext" class="form-input" rows="3" maxlength="${
|
|
224
|
+
<textarea id="lnx-f-aicontext" class="form-input" rows="3" maxlength="${o.aiContextMax}" data-model="aiContext.value"
|
|
223
225
|
placeholder="On the shop pages: we post to the UK only, orders before 2pm go the same day."></textarea>
|
|
224
226
|
</div>
|
|
225
227
|
<div class="lnx-field" data-bind-hidden="!bot.value || !ai.value">
|
|
@@ -229,7 +231,7 @@ import{apiRequest as V,api as ye}from"../api.js";import{CHARACTERS as Ve}from"..
|
|
|
229
231
|
<div class="lnx-field" style="grid-column: 1 / -1" data-bind-hidden="!bot.value || !ai.value">
|
|
230
232
|
<label class="form-label" for="lnx-f-airules">Rules for this launcher
|
|
231
233
|
<span data-help="One per line: what answers from this launcher must never do or say. They add to the rules in Site Settings > AI assistant; they cannot lift one."></span></label>
|
|
232
|
-
<textarea id="lnx-f-airules" class="form-input" rows="2" maxlength="${
|
|
234
|
+
<textarea id="lnx-f-airules" class="form-input" rows="2" maxlength="${o.aiRulesMax}" data-model="aiRules.value"
|
|
233
235
|
placeholder="Only talk about orders and delivery. Never promise a delivery date."></textarea>
|
|
234
236
|
</div>
|
|
235
237
|
</div>
|
|
@@ -253,7 +255,7 @@ import{apiRequest as V,api as ye}from"../api.js";import{CHARACTERS as Ve}from"..
|
|
|
253
255
|
<div class="lnx-field"><label class="form-label">From the top or bottom <span data-help="How far in from the top or bottom edge, in pixels. For a middle spot it nudges the disc down."></span></label>
|
|
254
256
|
<div class="lnx-range"><input type="range" min="0" max="300" data-model="offsetY.value" aria-label="From the top or bottom"><output data-bind-text="offsetY.value"></output></div></div>
|
|
255
257
|
<div class="lnx-field"><label class="form-label">Size <span data-help="The disc's width and height. 44px or more is easy to tap."></span></label>
|
|
256
|
-
<div class="lnx-range"><input type="range" min="${
|
|
258
|
+
<div class="lnx-range"><input type="range" min="${o.sizeMin}" max="${o.sizeMax}" data-model="size.value" aria-label="Size"><output data-bind-text="size.value"></output></div></div>
|
|
257
259
|
<div class="lnx-field" data-bind-hidden="triggerStyle.value === 'icon-text'"><label class="form-label">Roundness <span data-help="0 is a square; half the size is a circle."></span></label>
|
|
258
260
|
<div class="lnx-range"><input type="range" min="0" data-bind-max="maxRadius.value" data-model="radius.value" aria-label="Roundness"><output data-bind-text="radius.value"></output></div></div>
|
|
259
261
|
<div class="lnx-field">
|
|
@@ -274,7 +276,7 @@ import{apiRequest as V,api as ye}from"../api.js";import{CHARACTERS as Ve}from"..
|
|
|
274
276
|
<div class="lnx-field"><label class="form-label">From the top or bottom</label>
|
|
275
277
|
<div class="lnx-range"><input type="range" min="0" max="200" data-model="phoneOffsetY.value" aria-label="From the top or bottom on phones"><output data-bind-text="phoneOffsetY.value"></output></div></div>
|
|
276
278
|
<div class="lnx-field"><label class="form-label">Size</label>
|
|
277
|
-
<div class="lnx-range"><input type="range" min="${
|
|
279
|
+
<div class="lnx-range"><input type="range" min="${o.sizeMin}" max="${o.sizeMax}" data-model="phoneSize.value" aria-label="Size on phones"><output data-bind-text="phoneSize.value"></output></div></div>
|
|
278
280
|
</div>
|
|
279
281
|
</div>
|
|
280
282
|
</div>
|
|
@@ -310,4 +312,4 @@ import{apiRequest as V,api as ye}from"../api.js";import{CHARACTERS as Ve}from"..
|
|
|
310
312
|
<button type="button" class="btn btn-sm btn-primary" data-on-click="save" data-bind-disabled="cannot.value">
|
|
311
313
|
<span data-icon="check" data-icon-size="13"></span> <span data-bind-text="saveText"></span></button>
|
|
312
314
|
</div>
|
|
313
|
-
</div>`,Z=s=>String(s??"").replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""");function ma(s){const p=document.createElement("template");return p.innerHTML=s.trim(),p.content.firstElementChild}const T=s=>s?G.includes(s)?s:"custom":"",x=Je(Me),ee={list:()=>V("/launchers/items",{method:"GET"}),save:s=>V("/launchers/items",{method:"PUT",body:JSON.stringify({launchers:s})}),patch:(s,p)=>V(`/launchers/items/${encodeURIComponent(s)}`,{method:"PATCH",body:JSON.stringify(p)})};export const launchersView={templateUrl:"/admin/js/templates/launchers.html",async onMount(s){x.reset();const p=s.get(0).querySelector(".lnx")||s.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=Ze.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=ea(u.value,{filter:$.value,query:W.value}).map(oa)}));const Oe=M.computed(()=>la(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=na(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 j=new Set;function De(a,t,l){const m=a.close.bind(a);let o=!1,b=!1;return a.close=async d=>{if(!o&&d!==!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=sa(l||aa(u.peek()));t&&!Object.hasOwn(t,"character")&&typeof t.useDella=="boolean"&&(t={...t,character:t.useDella?"della":""});const 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.useDella,delete b.ref,delete b.background,delete b.text,delete b.accent,delete b.accentText;const d=Object.fromEntries(Object.entries(b).map(([e,r])=>[e,M.observable(r)])),N=()=>Object.fromEntries(Object.keys(d).map(e=>[e,d[e].peek()])),re=e=>JSON.stringify(Object.fromEntries(Object.entries(e).map(([r,n])=>[r,typeof n=="boolean"?n:String(n??"")]))),Be=re(b),de=()=>re(N())!==Be||!!t,ce=e=>{const r=e.actionType==="chat"?"page":e.kind;return{...e,kind:r,ref:r==="form"?e.refForm:r==="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(d).map(e=>[e,d[e].value]))),Y=M.computed(()=>ta(H())),R=M.observable(!1),he=(e,r)=>{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)},r?{vw:120,vh:220,scale:.5,phone:!0}:{vw:320,vh:200,scale:.5}),f=e.triggerStyle==="icon-text"&&!r;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={...d,saving:R,err:M.computed(()=>Y.value.errors),warn:M.computed(()=>Y.value.warnings),cannot:M.computed(()=>R.value||Object.keys(Y.value.errors).length>0),maxRadius:M.computed(()=>Math.floor(Number(d.size.value)/2)),previewStyle:M.computed(()=>he(H(),!1)),phonePreviewStyle:M.computed(()=>he(H(),!0)),botInitial:M.computed(()=>(String(d.botName.value||"").trim()[0]||"?").toUpperCase()),avatarPreview:M.computed(()=>{const e=ca(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(d.size.value)/2);Number(d.radius.peek())>e&&(d.radius.value=e)}),ue=(e,r,n)=>{let f=e.peek();return M.effect(()=>{const C=e.value;C!==f&&(f=C,r.value=n(C))})},Ke=ue(d.widthUnit,d.customWidth,e=>e==="%"?90:900),qe=ue(d.heightUnit,d.customHeight,e=>e==="px"?600:70),k=E.slideover({title:m?"New launcher":`Edit ${Z(l.name)}`,size:"lg",position:"right"}),v=ma(ua),me=await Ne().catch(()=>({forms:[],blocks:[]})),fe=(e,r,n)=>{const f=document.createElement("option");f.value="",f.textContent=r.length?"Choose\u2026":"None yet",e.appendChild(f);const C=n&&!r.some(D=>D.value===n)?[...r,{value:n,text:`${n} (missing)`}]:r;for(const D of C){const X=document.createElement("option");X.value=D.value,X.textContent=D.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=ia(ce(N()),l?.id||""),r=u.peek(),n=m?[...r,e]:r.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 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 r=e.target.closest(".lnx-corners button[data-pos]");if(r){const n=r.closest(".lnx-corners-phone")?"phonePosition":"position";d[n].value=r.dataset.pos;return}if(e.target.closest(".lnx-pick-icon")){const{openIconPicker:n}=await import("../lib/card-builder.js");n(f=>{d.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:d.avatar.peek()});f&&(d.avatar.value=String(f).replace(/^https?:\/\/[^/]+/i,""));return}if(e.target.closest(".lnx-clear-avatar")){d.avatar.value="";return}if(e.target.closest(".lnx-pick-page")){const{openPagePicker:n}=await import("../lib/page-picker.js");n(f=>{d.refPage.value=f})}};v.addEventListener("click",xe);const Xe=M.effect(()=>{const e=d.icon.value;v.querySelectorAll(".lnx-preview-disc").forEach(r=>{const n=document.createElement("span");n.setAttribute("data-icon",e||"message-circle"),n.className="lnx-preview-icon",r.querySelector(".lnx-preview-icon")?.replaceWith(n),I.scan(r)})}),ge={id:l?.id??null,dirty:de,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=De(k,de,"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=ha;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=>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=Qe(),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=ra(u.peek(),m,o);u.value=b,P(b)}});x.add(()=>t.destroy())}we(s,{id:"launchers-new",icon:"plus",title:"New launcher",onClick:()=>z()}),we(s,{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)}}};
|
|
315
|
+
</div>`,Z=s=>String(s??"").replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""");function ma(s){const p=document.createElement("template");return p.innerHTML=s.trim(),p.content.firstElementChild}const T=s=>s?G.includes(s)?s:"custom":"",x=Je(Me),ee={list:()=>V("/launchers/items",{method:"GET"}),save:s=>V("/launchers/items",{method:"PUT",body:JSON.stringify({launchers:s})}),patch:(s,p)=>V(`/launchers/items/${encodeURIComponent(s)}`,{method:"PATCH",body:JSON.stringify(p)})};export const launchersView={templateUrl:"/admin/js/templates/launchers.html",async onMount(s){x.reset();const p=s.get(0).querySelector(".lnx")||s.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=Ze.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=ea(u.value,{filter:$.value,query:W.value}).map(ia)}));const Oe=M.computed(()=>la(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([we.forms.list().catch(()=>[]),we.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 Ie(a){const t=u.peek(),l=t.findIndex(i=>i.id===a.id),m=na(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 Pe(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:()=>Ie(t)},{type:"divider"},{label:"Delete\u2026",icon:"trash",danger:!0,action:()=>Pe(t)}]:[]}let y=null;const j=new Set;function De(a,t,l){const m=a.close.bind(a);let i=!1,b=!1;return a.close=async r=>{if(!i&&r!==!0&&t()){if(b)return;b=!0;const N=await E.confirm(l);if(b=!1,!N)return}return i=!0,m()},()=>{i=!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(y){E.toast("Finish the launcher you have open first.",{type:"info"});return}const m=!l,i=sa(l||aa(u.peek()));t&&!Object.hasOwn(t,"character")&&typeof t.useDella=="boolean"&&(t={...t,character:t.useDella?"della":""});const b={...i,refPage:i.kind==="page"?i.ref:"",refForm:i.kind==="form"?i.ref:"",refBlock:i.kind==="block"?i.ref:"",bgChoice:T(i.background),bgHex:T(i.background)==="custom"?i.background:"",fgChoice:T(i.text),fgHex:T(i.text)==="custom"?i.text:"",accentChoice:T(i.accent),accentHex:T(i.accent)==="custom"?i.accent:"",accentTextChoice:T(i.accentText),accentTextHex:T(i.accentText)==="custom"?i.accentText:"",...t||{}};delete b.useDella,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(()=>ta(H())),R=M.observable(!1),he=(e,d)=>{const n=ra({...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(()=>Y.value.errors),warn:M.computed(()=>Y.value.warnings),cannot:M.computed(()=>R.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=ca(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=ma(ua),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(D=>D.value===n)?[...d,{value:n,text:`${n} (missing)`}]:d;for(const D of C){const X=document.createElement("option");X.value=D.value,X.textContent=D.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=oa(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 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};y=ge,j.add(k),Ge(k,()=>{Ye.dispose(),je(),We?.(),Ke?.(),qe?.(),Xe?.(),v.removeEventListener("click",xe),j.delete(k),y===ge&&(y=null)}),be=De(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=ha;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=>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)},oe=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",oe),x.add(()=>{g.removeEventListener("click",ne),g.removeEventListener("change",se),g.removeEventListener("keydown",oe)}),typeof E.sortable=="function"){const a=Qe(),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:i})=>{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=da(u.peek(),m,i);u.value=b,P(b)}});x.add(()=>t.destroy())}ye(s,{id:"launchers-new",icon:"plus",title:"New launcher",onClick:()=>z()}),ye(s,{id:"launchers-chats",icon:"message-square",title:"Chats - the conversations from chat launchers",onClick:()=>{location.hash="#/launchers/chats"}});const ie=a=>{y?.dirty()&&(a.preventDefault(),a.returnValue="")};if(window.addEventListener("beforeunload",ie),x.add(()=>window.removeEventListener("beforeunload",ie)),x.add(()=>{if(y?.dirty())try{S.set(U,{id:y.id,values:y.values(),at:new Date().toISOString()})}catch{}[...j].forEach(a=>{try{a.close(!0)}catch{}})}),I.scan(p),await Le(),!A())return;let w=null;try{w=S.get(U)}catch{}if(w?.values){try{S.remove?S.remove(U):S.set(U,null)}catch{}const a=w.id&&O(w.id)?`your changes to "${Z(O(w.id).name)}"`:"the new launcher you started";await E.confirm(`You left ${a} unsaved. Pick up where you left off?`)&&A()&&z(w.id&&O(w.id)?w.id:null,w.values)}}};
|
package/package.json
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{fillGreeting as Ce,launcherChatAccentCss as Ae}from"/public/js/launcher-settings.mjs?v=20261111-
|
|
1
|
+
import{fillGreeting as Ce,launcherChatAccentCss as Ae}from"/public/js/launcher-settings.mjs?v=20261111-knowledge-switch";import{CHARACTERS as Ne,characterId as ae,normaliseCharacterSettings as G,chatCharacterState as $e}from"./characters.mjs?v=20261111-dash-character";import{mountCharacter as we}from"./character-view.mjs?v=20261111-dash-character";const De={waiting:3e3,open:3e3,bot:9e3,message:2e4},Be=6e3,He="/public/css/launcher-chat.css?v=20261111-dash-character",se=()=>document.documentElement.classList.contains("dm-reduced-motion")||!!window.matchMedia?.("(prefers-reduced-motion: reduce)").matches;function Oe(){if(document.querySelector("link[data-dm-chat-css]"))return;const t=document.createElement("link");t.rel="stylesheet",t.href=He,t.dataset.dmChatCss="",document.head.appendChild(t)}const ne={get:t=>{try{return globalThis.S?.get?.(t)??null}catch{return null}},set:(t,d)=>{try{globalThis.S?.set?.(t,d)}catch{}},remove:t=>{try{globalThis.S?.remove?globalThis.S.remove(t):globalThis.S?.set?.(t,null)}catch{}}};async function Y(t,d,o,n){const f=n?{"X-Chat-Token":n}:{};let i;try{i=t==="GET"?await H.get(d,{headers:f}):await H.post(d,o,{headers:f})}catch(l){const w=l?.data||l?.response?.data;throw new Error(w?.error||"The chat could not be reached. Check your connection and try again.")}if(i&&i.error)throw new Error(i.error);return i}const Me=(t,d="time")=>{if(d==="none")return"";const o=t?new Date(t):null;if(!o||Number.isNaN(o.getTime()))return"";const n=o.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"});return d!=="datetime"?n:`${new Date().toDateString()===o.toDateString()?"Today":o.toLocaleDateString([],{day:"numeric",month:"short"})}, ${n}`},re=t=>(String(t||"").trim().match(/[\p{L}\p{N}]/u)?.[0]||"?").toUpperCase();function Pe(t,d=!1,o="",n="time"){const f=Array.isArray(t.suggestions)&&t.suggestions.length?[...t.suggestions.map(l=>({key:`${t.n}-${l.i}`,n:t.n,i:l.i,label:l.label})),{key:`${t.n}-none`,n:t.n,i:-1,label:"None of these"}]:[],i=t.from==="visitor"?"You":t.name||(t.from==="system"?"":"The team");return{key:`m${t.n}`,n:t.n,from:t.from,fresh:d,cls:M.observable(`dm-chat-msg dm-chat-msg--${t.from}`),name:i,initial:re(i),avatar:t.from==="bot"?o:"",text:typeof t.text=="string"?t.text:"",html:typeof t.html=="string"?t.html:"",links:(Array.isArray(t.links)?t.links:[]).map(l=>{const w=/^https?:/i.test(l.url);return{url:l.url,label:l.label,target:w?"_blank":"_self",rel:w?"noopener noreferrer":""}}),choices:f,starters:[],time:Me(t.at,n)}}function _e(t){const d=o=>o?`${o.from}|${o.name}`:"";return t.forEach((o,n)=>{const f=l=>l&&l.from!=="system"&&d(l)===d(o),i=[`dm-chat-msg dm-chat-msg--${o.from}`];o.from!=="system"&&f(t[n-1])&&i.push("is-cont"),o.from!=="system"&&f(t[n+1])&&i.push("has-next"),o.fresh&&i.push("is-new"),o.cls.value=i.join(" ")}),t}const qe=`
|
|
2
2
|
<div class="dm-chat" data-bind-class="rootClass.value">
|
|
3
3
|
<div class="dm-chat-character" hidden>
|
|
4
4
|
<span class="dm-chat-character-stage"></span>
|
|
@@ -1,6 +1,6 @@
|
|
|
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_PLACES=["site","admin","both"],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",place:"site",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,o)=>t.includes(e)?e:o;function f(e,t,o,i){const r=typeof e=="number"?e:typeof e=="string"&&e.trim()?Number(e):NaN;return Number.isFinite(r)?Math.min(i,Math.max(o,Math.round(r))):Math.min(i,Math.max(o,t))}function l(e,t,o=""){return typeof e!="string"?o:e.replace(/[\u0000-\u001f\u007f]/g," ").trim().replace(/\s+/g," ").slice(0,t)||o}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 o=normaliseLauncherPath(e||"/")||"/",i=normaliseLauncherPath(t);return i?i.endsWith("/*")&&o===(i.slice(0,-2)||"/")?!0:new RegExp("^"+i.split("*").map(n=>n.replace(/[.+?^${}()|[\]\\]/g,"\\$&")).join(".*")+"$","i").test(o):!1}export function launcherShowsOn(e,t,o){if(!e||e.enabled===!1||!launcherOnSite(e)||e.audience==="signed-in"&&!o||e.audience==="signed-out"&&o)return!1;const i=e.pages.paths.some(r=>launcherPathMatches(t,r));return e.pages.mode==="only"?i:e.pages.mode==="except"?!i:!0}export function launcherOnSite(e){return!!e&&e.place!=="admin"}export function launcherInAdmin(e){return!!e&&(e.place==="admin"||e.place==="both")}function E(e,t){const o=d(e);return{override:o.override===!0,position:c(o.position,LAUNCHER_POSITIONS,LAUNCHER_DEFAULTS.phone.position),offsetX:f(o.offsetX,LAUNCHER_DEFAULTS.phone.offsetX,0,LAUNCHER_LIMITS.offsetMax),offsetY:f(o.offsetY,LAUNCHER_DEFAULTS.phone.offsetY,0,LAUNCHER_LIMITS.offsetMax),size:f(o.size,Math.min(t,LAUNCHER_DEFAULTS.phone.size),LAUNCHER_LIMITS.sizeMin,LAUNCHER_LIMITS.sizeMax)}}function A(e){const t=d(e),o=c(t.type,LAUNCHER_ACTIONS,LAUNCHER_DEFAULTS.action.type),i=o==="modal"?LAUNCHER_MODAL_KINDS:LAUNCHER_SLIDEOVER_KINDS,r=o==="chat"?"page":c(t.kind,i,"page");let n=typeof t.ref=="string"?t.ref.trim():"";r==="page"?(n=n?normaliseLauncherPath(n):"",n.includes("*")&&(n="")):C.test(n)||(n=""),o==="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:o,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 o=t.size==="custom"?t.widthUnit==="%"?`${t.customWidth}vw`:`${t.customWidth}px`:LAUNCHER_MODAL_WIDTH_CSS[t.size]||LAUNCHER_MODAL_WIDTH_CSS.lg,i=t.height==="custom"?`${t.customHeight}${t.heightUnit==="px"?"px":"vh"}`:LAUNCHER_MODAL_HEIGHT_CSS[t.height]||"";return{width:o,height:i,screen:!1}}export function normaliseLauncherChat(e){const t=d(e),o=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):o.greeting,botName:l(t.botName,LAUNCHER_LIMITS.botNameMax,o.botName),bot:t.bot!==!1,staff:t.staff!==!1,askDetails:c(t.askDetails,LAUNCHER_ASK_DETAILS,o.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,o.size),width:f(t.width,o.width,...LAUNCHER_LIMITS.chatWidth),height:f(t.height,o.height,...LAUNCHER_LIMITS.chatHeight),resizable:t.resizable!==!1,starters:(Array.isArray(t.starters)?t.starters:typeof t.starters=="string"?t.starters.split(`
|
|
3
|
-
`):[]).map(r=>l(r,LAUNCHER_LIMITS.starterMax)).filter(Boolean).slice(0,LAUNCHER_LIMITS.startersMax),aiMaxPerChat:f(t.aiMaxPerChat,o.aiMaxPerChat,...LAUNCHER_LIMITS.aiMaxPerChat),personButton:c(t.personButton,LAUNCHER_PERSON_BUTTON,o.personButton),keepDays:f(t.keepDays,o.keepDays,...LAUNCHER_LIMITS.keepDays),times:c(t.times,LAUNCHER_CHAT_TIMES,o.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:o="",site:i=""}={}){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:o,site:i};return String(e??"").replace(/\{\s*([a-z]+)\s*\}/gi,(h,s)=>{const
|
|
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_PLACES=["site","admin","both"],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",place:"site",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,useKnowledge:!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,o)=>t.includes(e)?e:o;function f(e,t,o,i){const r=typeof e=="number"?e:typeof e=="string"&&e.trim()?Number(e):NaN;return Number.isFinite(r)?Math.min(i,Math.max(o,Math.round(r))):Math.min(i,Math.max(o,t))}function l(e,t,o=""){return typeof e!="string"?o:e.replace(/[\u0000-\u001f\u007f]/g," ").trim().replace(/\s+/g," ").slice(0,t)||o}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 o=normaliseLauncherPath(e||"/")||"/",i=normaliseLauncherPath(t);return i?i.endsWith("/*")&&o===(i.slice(0,-2)||"/")?!0:new RegExp("^"+i.split("*").map(n=>n.replace(/[.+?^${}()|[\]\\]/g,"\\$&")).join(".*")+"$","i").test(o):!1}export function launcherShowsOn(e,t,o){if(!e||e.enabled===!1||!launcherOnSite(e)||e.audience==="signed-in"&&!o||e.audience==="signed-out"&&o)return!1;const i=e.pages.paths.some(r=>launcherPathMatches(t,r));return e.pages.mode==="only"?i:e.pages.mode==="except"?!i:!0}export function launcherOnSite(e){return!!e&&e.place!=="admin"}export function launcherInAdmin(e){return!!e&&(e.place==="admin"||e.place==="both")}function E(e,t){const o=d(e);return{override:o.override===!0,position:c(o.position,LAUNCHER_POSITIONS,LAUNCHER_DEFAULTS.phone.position),offsetX:f(o.offsetX,LAUNCHER_DEFAULTS.phone.offsetX,0,LAUNCHER_LIMITS.offsetMax),offsetY:f(o.offsetY,LAUNCHER_DEFAULTS.phone.offsetY,0,LAUNCHER_LIMITS.offsetMax),size:f(o.size,Math.min(t,LAUNCHER_DEFAULTS.phone.size),LAUNCHER_LIMITS.sizeMin,LAUNCHER_LIMITS.sizeMax)}}function A(e){const t=d(e),o=c(t.type,LAUNCHER_ACTIONS,LAUNCHER_DEFAULTS.action.type),i=o==="modal"?LAUNCHER_MODAL_KINDS:LAUNCHER_SLIDEOVER_KINDS,r=o==="chat"?"page":c(t.kind,i,"page");let n=typeof t.ref=="string"?t.ref.trim():"";r==="page"?(n=n?normaliseLauncherPath(n):"",n.includes("*")&&(n="")):C.test(n)||(n=""),o==="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:o,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 o=t.size==="custom"?t.widthUnit==="%"?`${t.customWidth}vw`:`${t.customWidth}px`:LAUNCHER_MODAL_WIDTH_CSS[t.size]||LAUNCHER_MODAL_WIDTH_CSS.lg,i=t.height==="custom"?`${t.customHeight}${t.heightUnit==="px"?"px":"vh"}`:LAUNCHER_MODAL_HEIGHT_CSS[t.height]||"";return{width:o,height:i,screen:!1}}export function normaliseLauncherChat(e){const t=d(e),o=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):o.greeting,botName:l(t.botName,LAUNCHER_LIMITS.botNameMax,o.botName),bot:t.bot!==!1,staff:t.staff!==!1,askDetails:c(t.askDetails,LAUNCHER_ASK_DETAILS,o.askDetails),ai:t.ai!==!1,useKnowledge:t.useKnowledge!==!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,o.size),width:f(t.width,o.width,...LAUNCHER_LIMITS.chatWidth),height:f(t.height,o.height,...LAUNCHER_LIMITS.chatHeight),resizable:t.resizable!==!1,starters:(Array.isArray(t.starters)?t.starters:typeof t.starters=="string"?t.starters.split(`
|
|
3
|
+
`):[]).map(r=>l(r,LAUNCHER_LIMITS.starterMax)).filter(Boolean).slice(0,LAUNCHER_LIMITS.startersMax),aiMaxPerChat:f(t.aiMaxPerChat,o.aiMaxPerChat,...LAUNCHER_LIMITS.aiMaxPerChat),personButton:c(t.personButton,LAUNCHER_PERSON_BUTTON,o.personButton),keepDays:f(t.keepDays,o.keepDays,...LAUNCHER_LIMITS.keepDays),times:c(t.times,LAUNCHER_CHAT_TIMES,o.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:o="",site:i=""}={}){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:o,site:i};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,o]=x[e.size]||x.md;return{width:t,height:o}}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 o=launcherColourCss(e.accentText);if(!o){const i=launcherColour(e.accent);if(i.startsWith("#")){const r=i.length<=5?i.slice(1,4).split("").map(s=>s+s).join(""):i.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);o=.2126*n+.7152*a+.0722*h>.179?"#111111":"#ffffff"}else o=i==="primary"?"var(--dm-primary-text, #fff)":`var(--dm-${i}-text, #fff)`}return{accent:t,accentText:o}}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
|
|
|
6
|
-
`).trim().slice(0,t):""}export function normaliseLauncher(e){const t=d(e),o=LAUNCHER_DEFAULTS,i=f(t.size,o.size,LAUNCHER_LIMITS.sizeMin,LAUNCHER_LIMITS.sizeMax),r=Math.floor(i/2),n=d(t.pages),a=(Array.isArray(n.paths)?n.paths:typeof n.paths=="string"?n.paths.split(/[\n,]+/):[]).map(normaliseLauncherPath).filter(Boolean).filter((s,p
|
|
6
|
+
`).trim().slice(0,t):""}export function normaliseLauncher(e){const t=d(e),o=LAUNCHER_DEFAULTS,i=f(t.size,o.size,LAUNCHER_LIMITS.sizeMin,LAUNCHER_LIMITS.sizeMax),r=Math.floor(i/2),n=d(t.pages),a=(Array.isArray(n.paths)?n.paths:typeof n.paths=="string"?n.paths.split(/[\n,]+/):[]).map(normaliseLauncherPath).filter(Boolean).filter((s,u,p)=>p.indexOf(s)===u).slice(0,LAUNCHER_LIMITS.pathsMax),h=d(t.colours);return{id:typeof t.id=="string"&&LAUNCHER_ID_RE.test(t.id)?t.id:"",enabled:t.enabled!==!1,showDisc:t.showDisc!==!1,name:l(t.name,LAUNCHER_LIMITS.nameMax,o.name),label:l(t.label,LAUNCHER_LIMITS.labelMax,o.label),tooltipMode:c(t.tooltipMode,LAUNCHER_TOOLTIP_MODES,o.tooltipMode),tooltip:l(t.tooltip,LAUNCHER_LIMITS.tooltipMax,""),icon:typeof t.icon=="string"&&y.test(t.icon.trim())?t.icon.trim():o.icon,triggerStyle:c(t.triggerStyle,LAUNCHER_TRIGGER_STYLES,o.triggerStyle),position:c(t.position,LAUNCHER_POSITIONS,o.position),offsetX:f(t.offsetX,o.offsetX,0,LAUNCHER_LIMITS.offsetMax),offsetY:f(t.offsetY,o.offsetY,0,LAUNCHER_LIMITS.offsetMax),size:i,radius:Math.min(r,f(t.radius,o.radius,0,r)),devices:c(t.devices,LAUNCHER_DEVICES,o.devices),phone:E(t.phone,i),colours:{background:launcherColour(h.background),text:launcherColour(h.text)},class:M(typeof t.class=="string"?t.class:"").join(" "),pages:{mode:c(n.mode,LAUNCHER_PAGE_MODES,o.pages.mode),paths:a},audience:c(t.audience,LAUNCHER_AUDIENCES,o.audience),place:c(t.place,LAUNCHER_PLACES,o.place),action:A(t.action),chat:normaliseLauncherChat(t.chat)}}export function launcherTooltip(e){return!e||e.tooltipMode==="off"?"":e.tooltipMode==="custom"?e.tooltip||e.label:e.triggerStyle==="icon-text"?"":e.label}export function launcherHref(e){return`#launcher-${e}`}export function newLauncherId(e=new Set,t=Math.random){for(let o=0;o<1e3;o++){const i="l-"+Math.floor(t()*2176782336).toString(36).padStart(6,"0");if(!e.has(i))return i}return"l-"+Date.now().toString(36)}export function normaliseLaunchers(e,t=Math.random){const o=Array.isArray(e)?e:Array.isArray(e?.launchers)?e.launchers:[],i=new Set;return o.filter(r=>r&&typeof r=="object"&&!Array.isArray(r)).map(r=>{const n=normaliseLauncher(r);return(!n.id||i.has(n.id))&&(n.id=newLauncherId(i,t)),i.add(n.id),n})}export function launcherReady(e){return e?e.action.type==="chat"?!0:!!e.action.ref:!1}export function publicLauncher(e){const t={id:e.id,disc:e.showDisc,label:e.label,tooltip:launcherTooltip(e),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:e.phone,colours:{background:launcherColourCss(e.colours.background),text:launcherColourCss(e.colours.text)},class:e.class,action:{type:e.action.type,title:e.action.title||e.label,size:e.action.size,side:e.action.side,width:e.action.width,customWidth:e.action.customWidth,widthUnit:e.action.widthUnit,height:e.action.height,customHeight:e.action.customHeight,heightUnit:e.action.heightUnit}};if(e.action.type==="chat"){const{aiContext:o,aiRules:i,aiUseSite:r,aiMaxPerChat:n,keepDays:a,useKnowledge:h,...s}=e.chat;t.chat=s}return t}export function launcherSpot(e,{w:t,h:o,vw:i,vh:r,offsetX:n,offsetY:a}){const h=e[1]==="L"?"L":e[1]==="R"?"R":"C",s=e[0],u=h==="L"?n:h==="R"?i-t-n:Math.round((i-t)/2+n),p=s==="T"?a:s==="B"?r-o-a:Math.round((r-o)/2+a);return{left:u,top:p}}const g=12,L=(e,t)=>e.left<t.right+g&&t.left<e.right+g&&e.top<t.bottom+g&&t.top<e.bottom+g;export function launcherStack(e,t,{w:o,h:i},r){const n=e[0]==="B";let a=t.top;for(let h=0;h<=r.length;h++){const s={left:t.left,top:a,right:t.left+o,bottom:a+i},u=r.find(p=>p&&p.right>p.left&&p.bottom>p.top&&L(s,p));if(!u)break;a=Math.round(n?u.top-g-i:u.bottom+g)}return{left:t.left,top:a}}
|
package/public/js/launchers.mjs
CHANGED
|
@@ -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=20261111-
|
|
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=20261111-knowledge-switch";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=20261111-dash-character";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",".admin-assistant-trigger"].join(","),tt={sm:"360px",md:"480px",lg:"640px",xl:"860px"},yt=i=>String(i??"").replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,"""),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>
|
|
@@ -9,4 +9,4 @@ import{LAUNCHER_LIMITS as C,launcherChatBox as mt,launcherModalBox as pt,launche
|
|
|
9
9
|
<button type="button" class="dm-launcher-chat-close" data-on-click="close" aria-label="Close"><span data-icon="x" aria-hidden="true"></span></button>
|
|
10
10
|
</div>
|
|
11
11
|
<div class="dm-launcher-chat-body"></div>
|
|
12
|
-
<p class="dm-launcher-note" data-bind-hidden="!note.value" data-bind-text="note.value"></p>`;function Mt(i){const c=i.getBoundingClientRect();return getComputedStyle(i).opacity!=="0"||i.offsetParent!==null?c:{top:Math.min(c.top,i.offsetTop),left:Math.min(c.left,i.offsetLeft),right:Math.max(c.right,i.offsetLeft+i.offsetWidth),bottom:Math.max(c.bottom,i.offsetTop+i.offsetHeight)}}function nt(i){window.Domma?.icons?.scan&&window.Domma.icons.scan(i)}function ot(i,{fill:c}){const r=document.createElement("iframe");if(r.className="dm-launcher-frame"+(c?" is-fill":""),r.title=i.action.title,r.src=`/_launcher/${encodeURIComponent(i.id)}`,r.setAttribute("loading","eager"),!c){let u=null;r.addEventListener("load",()=>{const H=r.contentDocument;if(!H?.body)return;const S=H.querySelector(".site-content")||H.body,R=()=>{r.style.height=`${Math.ceil(S.getBoundingClientRect().height)}px`};R(),u?.disconnect(),u=new ResizeObserver(R),u.observe(S)})}return r}export function mountLaunchers(i){if(!Array.isArray(i)||!i.length||document.querySelector(".dm-launchers"))return null;const c=M.observable(matchMedia(J).matches),r=document.createElement("div");r.className="dm-launchers";const u=i.map(t=>{const n=o=>o&&t.phone?.override?{...t,...t.phone}:t,e=t.triggerStyle==="icon-text",a=o=>{const v=n(o),x={"--launcher-size":`${v.size}px`,"--launcher-radius":`${e?999:Math.min(t.radius,Math.floor(v.size/2))}px`,"--launcher-glyph":`${Math.round(v.size*20/52)}px`};return t.colours.background&&(x["--launcher-bg"]=t.colours.background),t.colours.text&&(x["--launcher-fg"]=t.colours.text),x},d=M.observable(-9999),m=M.observable(-9999);return{id:t.id,label:t.label,icon:t.icon,pill:e,launcher:t,look:n,left:d,top:m,cls:["dm-launcher--"+t.action.type,e?"dm-launcher--pill":"",t.class].filter(Boolean).join(" "),style:M.computed(()=>({...a(c.value),left:`${d.value}px`,top:`${m.value}px`})),expanded:M.observable("false"),hidden:M.computed(()=>t.disc===!1||t.devices==="desktop"&&c.value||t.devices==="phone"&&!c.value)}});r.innerHTML='<div class="dm-launchers-list" data-each="rows.value key=id"></div>',r.firstElementChild.innerHTML=wt;const H=M.applyBindings({rows:M.observable(u)},r);document.body.appendChild(r),nt(r);const S=t=>r.querySelector(`.dm-launcher[data-id="${CSS.escape(t)}"]`),R=[];for(const t of u){const n=t.launcher.chat;if(!n?.bot||!n.character||n.characterOptions?.enabled===!1||n.characterOptions?.launchers===!1)continue;const e=S(t.id);if(!e)continue;e.classList.add("dm-character-disc");const a=e.querySelector(".dm-launcher-label"),d=gt(e,{id:n.character,portrait:!0,animated:!1});a&&e.appendChild(a),R.push(d)}const at={TL:"right",ML:"right",BL:"right",TR:"left",MR:"left",BR:"left",TC:"bottom",BC:"top"},B=new Map;for(const t of u){const n=t.launcher.tooltip,e=S(t.id);if(!(!n||!e||typeof E.tooltip!="function"))try{B.set(t.id,E.tooltip(e,{content:n,position:at[t.launcher.position]||"top",trigger:"hover focus",className:"dm-launcher-tip"}))}catch{}}function D(){const t=document.documentElement.clientWidth,n=window.innerHeight,e=[...document.querySelectorAll(Q)].filter(a=>!r.contains(a)&&getComputedStyle(a).position==="fixed"&&getComputedStyle(a).display!=="none").map(Mt);for(const a of u){const d=S(a.id);if(!d||d.hidden)continue;const m=a.look(c.peek()),o=d.offsetWidth,v=d.offsetHeight,x=ft(m.position,{w:o,h:v,vw:t,vh:n,offsetX:m.offsetX,offsetY:m.offsetY}),T=vt(m.position,x,{w:o,h:v},e),z=Math.max(0,Math.min(t-o,T.left)),_=Math.max(0,Math.min(n-v,T.top));a.left.value=z,a.top.value=_,e.push({left:z,top:_,right:z+o,bottom:_+v})}}let q=0;const A=()=>{cancelAnimationFrame(q),q=requestAnimationFrame(D)},K=new MutationObserver(t=>{t.some(n=>[...n.addedNodes].some(e=>e.nodeType===1&&e.matches?.(Q)))&&A()});K.observe(document.body,{childList:!0});const P=matchMedia(J),U=()=>{c.value=P.matches,A()};P.addEventListener?.("change",U),window.addEventListener("resize",A),window.addEventListener("load",A,{once:!0}),D();let g=null;const it=M.effect(()=>{const t=u.some(n=>n.expanded.value==="true"&&(n.launcher.action.type!=="chat"||c.value));document.documentElement.classList.toggle("dm-launcher-covering",t)});function Y(){const t=g;g=null,t&&(t.row.expanded.value="false",t.close())}function ct(t){const n=t.launcher,e=pt(n.action),a=E.modal({title:n.action.title,size:e.width,content:ot(n,{fill:!!e.height}),className:"dm-launcher-modal",bodyClass:"dm-launcher-modal-body",buttons:[],animation:et()?!1:"fade",onClosed:()=>{g?.row===t&&(g=null,t.expanded.value="false"),setTimeout(()=>{try{a.destroy()}catch{}},0)}});return a.element?.classList.add("dm-launcher-modal",`dm-launcher-modal--${n.action.size}`),a.element?.style.setProperty("--launcher-modal-w",e.width),e.height&&(a.element?.classList.add("dm-launcher-modal--fixed"),a.element?.style.setProperty("--launcher-modal-h",e.height)),a.open(),()=>{try{a.close()}catch{}}}function st(t){const n=t.launcher,e=E.slideover({title:yt(n.action.title),position:n.action.side,size:c.peek()?"full":tt[n.action.width]||tt.md,content:ot(n,{fill:!0}),bodyClass:"dm-launcher-so-body",animation:!et(),onClosed:()=>{g?.row===t&&(g=null,t.expanded.value="false"),setTimeout(()=>{try{e.destroy?.()}catch{}e.element?.remove()},0)}});return e.element?.classList.add("dm-launcher-so"),e.open(),()=>{try{e.close()}catch{}}}function rt(t,n){const e=t.launcher,a=S(t.id),d=a&&!a.hidden?a:null,m=d||(n?.isConnected?n:null),o=document.createElement("div");o.className="dm-launcher-chat",o.setAttribute("role","dialog"),o.setAttribute("aria-label",e.action.title),o.innerHTML=xt;const v=M.observable("");let x=null,T=!1;const z=()=>{if(!T){T=!0;try{x?.destroy?.()}catch{}_.dispose?.(),o.remove(),document.removeEventListener("keydown",G),window.removeEventListener("resize",O),g?.row===t&&(g=null,t.expanded.value="false"),(m?.isConnected?m:null)?.focus()}},_=M.applyBindings({title:e.action.title,note:v,close:z},o),G=l=>{l.key!=="Escape"||l.defaultPrevented||!o.contains(document.activeElement)||(l.preventDefault(),z())},O=()=>{if(c.peek()){o.classList.add("is-full"),o.removeAttribute("style");return}o.classList.remove("is-full");const l=document.documentElement.clientWidth,s=window.innerHeight,N=e.chat?.resizable!==!1&&bt(e.id)||mt(e.chat||{}),y=Math.min(Math.max(C.chatWidth[0],Number(N.width)),C.chatWidth[1],l-24),w=Math.min(Math.max(C.chatHeight[0],Number(N.height)),C.chatHeight[1],s-24),p=L=>Math.max(12,Math.min(l-y-12,L)),h=L=>Math.max(12,Math.min(s-w-12,L));let b,k;if(!d){b=p(e.position[1]==="L"?24:l-y-24),k=h(s-w-24),Object.assign(o.style,{left:`${b}px`,top:`${k}px`,width:`${y}px`,height:`${w}px`});return}const f=d.getBoundingClientRect(),$=f.left+f.width/2>l/2;e.position[0]==="M"?(b=p($?f.left-y-12:f.right+12),k=h(f.top+f.height/2-w/2)):(b=p($?f.right-y:f.left),k=e.position[0]==="T"?h(f.bottom+12):h(f.top-w-12)),Object.assign(o.style,{left:`${b}px`,top:`${k}px`,width:`${y}px`,height:`${w}px`})};if(document.body.appendChild(o),O(),e.chat?.resizable!==!1){const l=document.createElement("div");l.className="dm-launcher-chat-grip",l.setAttribute("role","separator"),l.setAttribute("aria-label","Resize the chat"),l.title="Drag to resize",o.appendChild(l);let s=null;const N=p=>{if(!s)return;const h=document.documentElement.clientWidth,b=window.innerHeight,k=(p.clientX-s.x)*(s.fromLeft?-1:1),f=(p.clientY-s.y)*(s.fromTop?-1:1),$=Math.round(Math.min(Math.max(C.chatWidth[0],s.w+k),C.chatWidth[1],h-24)),L=Math.round(Math.min(Math.max(C.chatHeight[0],s.h+f),C.chatHeight[1],b-24)),ht=s.fromLeft?s.right-$:s.left,ut=s.fromTop?s.bottom-L:s.top;Object.assign(o.style,{width:`${$}px`,height:`${L}px`,left:`${Math.max(12,Math.min(h-$-12,ht))}px`,top:`${Math.max(12,Math.min(b-L-12,ut))}px`}),s.size={width:$,height:L}},y=()=>{s&&(s.size&&Z(e.id,s.size),s=null,o.classList.remove("is-resizing"),window.removeEventListener("pointermove",N),window.removeEventListener("pointerup",y))},w=()=>{const[p,h]=String(e.position||"BR");l.dataset.corner=`${p==="T"?"b":"t"}${h==="L"?"r":"l"}`};w(),l.addEventListener("pointerdown",p=>{if(c.peek())return;p.preventDefault();const h=o.getBoundingClientRect(),b=l.dataset.corner;s={x:p.clientX,y:p.clientY,w:h.width,h:h.height,left:h.left,top:h.top,right:h.right,bottom:h.bottom,fromLeft:b[1]==="l",fromTop:b[0]==="t"},o.classList.add("is-resizing"),window.addEventListener("pointermove",N),window.addEventListener("pointerup",y)}),l.addEventListener("dblclick",()=>{Z(e.id,null),O(),w()})}nt(o),document.addEventListener("keydown",G),window.addEventListener("resize",O);const dt=o.querySelector(".dm-launcher-chat-body");return import("/public/js/launcher-chat.mjs?v=20261111-dash-character").then(l=>{if(!T){if(typeof l.mountChat!="function")throw new Error("no mountChat");x=l.mountChat(dt,{launcherId:e.id,title:e.action.title,chat:e.chat||{}})}}).catch(()=>{T||(v.value="Chat is unavailable right now. Please try again later.")}),o.querySelector(".dm-launcher-chat-close")?.focus(),z}function I(t,n=null){const e=u.find(o=>o.id===t);if(!e)return;const a=g?.row===e;if(Y(),a)return;e.expanded.value="true";try{B.get(e.id)?.close()}catch{}const d=e.launcher.action.type,m=d==="chat"?rt(e,n):d==="slideover"?st(e):ct(e);g={row:e,close:m}}const j=t=>{const n=t.target.closest(".dm-launcher");n&&I(n.dataset.id)};r.addEventListener("click",j);const F=/^#launcher-([a-z0-9][a-z0-9-]{0,39})$/,lt=t=>{const n=t.closest("[data-launcher]");if(n)return{el:n,id:n.dataset.launcher};const e=t.closest("a[href]"),a=e&&F.exec(e.getAttribute("href")||"");return a?{el:e,id:a[1]}:null},X=t=>{if(t.button>0||t.metaKey||t.ctrlKey||t.shiftKey||t.altKey||r.contains(t.target))return;const n=t.target instanceof Element?lt(t.target):null;!n||!u.some(e=>e.id===n.id)||(t.preventDefault(),I(n.id,n.el))};document.addEventListener("click",X);const W=F.exec(location.hash);return W&&u.some(t=>t.id===W[1])&&(history.replaceState(history.state,"",location.pathname+location.search),setTimeout(()=>I(W[1]),0)),{place:D,launch:I,destroy(){Y(),it?.(),document.documentElement.classList.remove("dm-launcher-covering"),R.forEach(t=>t.destroy());for(const t of B.values())try{t.destroy()}catch{}B.clear(),cancelAnimationFrame(q),K.disconnect(),P.removeEventListener?.("change",U),window.removeEventListener("resize",A),window.removeEventListener("load",A),r.removeEventListener("click",j),document.removeEventListener("click",X),H?.dispose?.(),r.remove()}}}typeof window<"u"&&Array.isArray(window.__CMS_LAUNCHERS__)&&window.M&&window.E&&(window.DommaLaunchers=mountLaunchers(window.__CMS_LAUNCHERS__));
|
|
12
|
+
<p class="dm-launcher-note" data-bind-hidden="!note.value" data-bind-text="note.value"></p>`;function Mt(i){const c=i.getBoundingClientRect();return getComputedStyle(i).opacity!=="0"||i.offsetParent!==null?c:{top:Math.min(c.top,i.offsetTop),left:Math.min(c.left,i.offsetLeft),right:Math.max(c.right,i.offsetLeft+i.offsetWidth),bottom:Math.max(c.bottom,i.offsetTop+i.offsetHeight)}}function nt(i){window.Domma?.icons?.scan&&window.Domma.icons.scan(i)}function ot(i,{fill:c}){const r=document.createElement("iframe");if(r.className="dm-launcher-frame"+(c?" is-fill":""),r.title=i.action.title,r.src=`/_launcher/${encodeURIComponent(i.id)}`,r.setAttribute("loading","eager"),!c){let u=null;r.addEventListener("load",()=>{const H=r.contentDocument;if(!H?.body)return;const S=H.querySelector(".site-content")||H.body,R=()=>{r.style.height=`${Math.ceil(S.getBoundingClientRect().height)}px`};R(),u?.disconnect(),u=new ResizeObserver(R),u.observe(S)})}return r}export function mountLaunchers(i){if(!Array.isArray(i)||!i.length||document.querySelector(".dm-launchers"))return null;const c=M.observable(matchMedia(J).matches),r=document.createElement("div");r.className="dm-launchers";const u=i.map(t=>{const n=o=>o&&t.phone?.override?{...t,...t.phone}:t,e=t.triggerStyle==="icon-text",a=o=>{const v=n(o),x={"--launcher-size":`${v.size}px`,"--launcher-radius":`${e?999:Math.min(t.radius,Math.floor(v.size/2))}px`,"--launcher-glyph":`${Math.round(v.size*20/52)}px`};return t.colours.background&&(x["--launcher-bg"]=t.colours.background),t.colours.text&&(x["--launcher-fg"]=t.colours.text),x},d=M.observable(-9999),m=M.observable(-9999);return{id:t.id,label:t.label,icon:t.icon,pill:e,launcher:t,look:n,left:d,top:m,cls:["dm-launcher--"+t.action.type,e?"dm-launcher--pill":"",t.class].filter(Boolean).join(" "),style:M.computed(()=>({...a(c.value),left:`${d.value}px`,top:`${m.value}px`})),expanded:M.observable("false"),hidden:M.computed(()=>t.disc===!1||t.devices==="desktop"&&c.value||t.devices==="phone"&&!c.value)}});r.innerHTML='<div class="dm-launchers-list" data-each="rows.value key=id"></div>',r.firstElementChild.innerHTML=wt;const H=M.applyBindings({rows:M.observable(u)},r);document.body.appendChild(r),nt(r);const S=t=>r.querySelector(`.dm-launcher[data-id="${CSS.escape(t)}"]`),R=[];for(const t of u){const n=t.launcher.chat;if(!n?.bot||!n.character||n.characterOptions?.enabled===!1||n.characterOptions?.launchers===!1)continue;const e=S(t.id);if(!e)continue;e.classList.add("dm-character-disc");const a=e.querySelector(".dm-launcher-label"),d=gt(e,{id:n.character,portrait:!0,animated:!1});a&&e.appendChild(a),R.push(d)}const at={TL:"right",ML:"right",BL:"right",TR:"left",MR:"left",BR:"left",TC:"bottom",BC:"top"},B=new Map;for(const t of u){const n=t.launcher.tooltip,e=S(t.id);if(!(!n||!e||typeof E.tooltip!="function"))try{B.set(t.id,E.tooltip(e,{content:n,position:at[t.launcher.position]||"top",trigger:"hover focus",className:"dm-launcher-tip"}))}catch{}}function D(){const t=document.documentElement.clientWidth,n=window.innerHeight,e=[...document.querySelectorAll(Q)].filter(a=>!r.contains(a)&&getComputedStyle(a).position==="fixed"&&getComputedStyle(a).display!=="none").map(Mt);for(const a of u){const d=S(a.id);if(!d||d.hidden)continue;const m=a.look(c.peek()),o=d.offsetWidth,v=d.offsetHeight,x=ft(m.position,{w:o,h:v,vw:t,vh:n,offsetX:m.offsetX,offsetY:m.offsetY}),T=vt(m.position,x,{w:o,h:v},e),z=Math.max(0,Math.min(t-o,T.left)),_=Math.max(0,Math.min(n-v,T.top));a.left.value=z,a.top.value=_,e.push({left:z,top:_,right:z+o,bottom:_+v})}}let q=0;const A=()=>{cancelAnimationFrame(q),q=requestAnimationFrame(D)},K=new MutationObserver(t=>{t.some(n=>[...n.addedNodes].some(e=>e.nodeType===1&&e.matches?.(Q)))&&A()});K.observe(document.body,{childList:!0});const P=matchMedia(J),U=()=>{c.value=P.matches,A()};P.addEventListener?.("change",U),window.addEventListener("resize",A),window.addEventListener("load",A,{once:!0}),D();let g=null;const it=M.effect(()=>{const t=u.some(n=>n.expanded.value==="true"&&(n.launcher.action.type!=="chat"||c.value));document.documentElement.classList.toggle("dm-launcher-covering",t)});function Y(){const t=g;g=null,t&&(t.row.expanded.value="false",t.close())}function ct(t){const n=t.launcher,e=pt(n.action),a=E.modal({title:n.action.title,size:e.width,content:ot(n,{fill:!!e.height}),className:"dm-launcher-modal",bodyClass:"dm-launcher-modal-body",buttons:[],animation:et()?!1:"fade",onClosed:()=>{g?.row===t&&(g=null,t.expanded.value="false"),setTimeout(()=>{try{a.destroy()}catch{}},0)}});return a.element?.classList.add("dm-launcher-modal",`dm-launcher-modal--${n.action.size}`),a.element?.style.setProperty("--launcher-modal-w",e.width),e.height&&(a.element?.classList.add("dm-launcher-modal--fixed"),a.element?.style.setProperty("--launcher-modal-h",e.height)),a.open(),()=>{try{a.close()}catch{}}}function st(t){const n=t.launcher,e=E.slideover({title:yt(n.action.title),position:n.action.side,size:c.peek()?"full":tt[n.action.width]||tt.md,content:ot(n,{fill:!0}),bodyClass:"dm-launcher-so-body",animation:!et(),onClosed:()=>{g?.row===t&&(g=null,t.expanded.value="false"),setTimeout(()=>{try{e.destroy?.()}catch{}e.element?.remove()},0)}});return e.element?.classList.add("dm-launcher-so"),e.open(),()=>{try{e.close()}catch{}}}function rt(t,n){const e=t.launcher,a=S(t.id),d=a&&!a.hidden?a:null,m=d||(n?.isConnected?n:null),o=document.createElement("div");o.className="dm-launcher-chat",o.setAttribute("role","dialog"),o.setAttribute("aria-label",e.action.title),o.innerHTML=xt;const v=M.observable("");let x=null,T=!1;const z=()=>{if(!T){T=!0;try{x?.destroy?.()}catch{}_.dispose?.(),o.remove(),document.removeEventListener("keydown",G),window.removeEventListener("resize",O),g?.row===t&&(g=null,t.expanded.value="false"),(m?.isConnected?m:null)?.focus()}},_=M.applyBindings({title:e.action.title,note:v,close:z},o),G=l=>{l.key!=="Escape"||l.defaultPrevented||!o.contains(document.activeElement)||(l.preventDefault(),z())},O=()=>{if(c.peek()){o.classList.add("is-full"),o.removeAttribute("style");return}o.classList.remove("is-full");const l=document.documentElement.clientWidth,s=window.innerHeight,N=e.chat?.resizable!==!1&&bt(e.id)||mt(e.chat||{}),y=Math.min(Math.max(C.chatWidth[0],Number(N.width)),C.chatWidth[1],l-24),w=Math.min(Math.max(C.chatHeight[0],Number(N.height)),C.chatHeight[1],s-24),p=L=>Math.max(12,Math.min(l-y-12,L)),h=L=>Math.max(12,Math.min(s-w-12,L));let b,k;if(!d){b=p(e.position[1]==="L"?24:l-y-24),k=h(s-w-24),Object.assign(o.style,{left:`${b}px`,top:`${k}px`,width:`${y}px`,height:`${w}px`});return}const f=d.getBoundingClientRect(),$=f.left+f.width/2>l/2;e.position[0]==="M"?(b=p($?f.left-y-12:f.right+12),k=h(f.top+f.height/2-w/2)):(b=p($?f.right-y:f.left),k=e.position[0]==="T"?h(f.bottom+12):h(f.top-w-12)),Object.assign(o.style,{left:`${b}px`,top:`${k}px`,width:`${y}px`,height:`${w}px`})};if(document.body.appendChild(o),O(),e.chat?.resizable!==!1){const l=document.createElement("div");l.className="dm-launcher-chat-grip",l.setAttribute("role","separator"),l.setAttribute("aria-label","Resize the chat"),l.title="Drag to resize",o.appendChild(l);let s=null;const N=p=>{if(!s)return;const h=document.documentElement.clientWidth,b=window.innerHeight,k=(p.clientX-s.x)*(s.fromLeft?-1:1),f=(p.clientY-s.y)*(s.fromTop?-1:1),$=Math.round(Math.min(Math.max(C.chatWidth[0],s.w+k),C.chatWidth[1],h-24)),L=Math.round(Math.min(Math.max(C.chatHeight[0],s.h+f),C.chatHeight[1],b-24)),ht=s.fromLeft?s.right-$:s.left,ut=s.fromTop?s.bottom-L:s.top;Object.assign(o.style,{width:`${$}px`,height:`${L}px`,left:`${Math.max(12,Math.min(h-$-12,ht))}px`,top:`${Math.max(12,Math.min(b-L-12,ut))}px`}),s.size={width:$,height:L}},y=()=>{s&&(s.size&&Z(e.id,s.size),s=null,o.classList.remove("is-resizing"),window.removeEventListener("pointermove",N),window.removeEventListener("pointerup",y))},w=()=>{const[p,h]=String(e.position||"BR");l.dataset.corner=`${p==="T"?"b":"t"}${h==="L"?"r":"l"}`};w(),l.addEventListener("pointerdown",p=>{if(c.peek())return;p.preventDefault();const h=o.getBoundingClientRect(),b=l.dataset.corner;s={x:p.clientX,y:p.clientY,w:h.width,h:h.height,left:h.left,top:h.top,right:h.right,bottom:h.bottom,fromLeft:b[1]==="l",fromTop:b[0]==="t"},o.classList.add("is-resizing"),window.addEventListener("pointermove",N),window.addEventListener("pointerup",y)}),l.addEventListener("dblclick",()=>{Z(e.id,null),O(),w()})}nt(o),document.addEventListener("keydown",G),window.addEventListener("resize",O);const dt=o.querySelector(".dm-launcher-chat-body");return import("/public/js/launcher-chat.mjs?v=20261111-knowledge-switch").then(l=>{if(!T){if(typeof l.mountChat!="function")throw new Error("no mountChat");x=l.mountChat(dt,{launcherId:e.id,title:e.action.title,chat:e.chat||{}})}}).catch(()=>{T||(v.value="Chat is unavailable right now. Please try again later.")}),o.querySelector(".dm-launcher-chat-close")?.focus(),z}function I(t,n=null){const e=u.find(o=>o.id===t);if(!e)return;const a=g?.row===e;if(Y(),a)return;e.expanded.value="true";try{B.get(e.id)?.close()}catch{}const d=e.launcher.action.type,m=d==="chat"?rt(e,n):d==="slideover"?st(e):ct(e);g={row:e,close:m}}const j=t=>{const n=t.target.closest(".dm-launcher");n&&I(n.dataset.id)};r.addEventListener("click",j);const F=/^#launcher-([a-z0-9][a-z0-9-]{0,39})$/,lt=t=>{const n=t.closest("[data-launcher]");if(n)return{el:n,id:n.dataset.launcher};const e=t.closest("a[href]"),a=e&&F.exec(e.getAttribute("href")||"");return a?{el:e,id:a[1]}:null},X=t=>{if(t.button>0||t.metaKey||t.ctrlKey||t.shiftKey||t.altKey||r.contains(t.target))return;const n=t.target instanceof Element?lt(t.target):null;!n||!u.some(e=>e.id===n.id)||(t.preventDefault(),I(n.id,n.el))};document.addEventListener("click",X);const W=F.exec(location.hash);return W&&u.some(t=>t.id===W[1])&&(history.replaceState(history.state,"",location.pathname+location.search),setTimeout(()=>I(W[1]),0)),{place:D,launch:I,destroy(){Y(),it?.(),document.documentElement.classList.remove("dm-launcher-covering"),R.forEach(t=>t.destroy());for(const t of B.values())try{t.destroy()}catch{}B.clear(),cancelAnimationFrame(q),K.disconnect(),P.removeEventListener?.("change",U),window.removeEventListener("resize",A),window.removeEventListener("load",A),r.removeEventListener("click",j),document.removeEventListener("click",X),H?.dispose?.(),r.remove()}}}typeof window<"u"&&Array.isArray(window.__CMS_LAUNCHERS__)&&window.M&&window.E&&(window.DommaLaunchers=mountLaunchers(window.__CMS_LAUNCHERS__));
|
|
@@ -78,14 +78,14 @@ async function ask(payload, {env, fetchFn}) {
|
|
|
78
78
|
*
|
|
79
79
|
* @param {string} id - the chat
|
|
80
80
|
* @param {string} question - what the visitor just wrote
|
|
81
|
-
* @param {{botName: string, aiContext?: string, aiRules?: string}} chat - the launcher's chat block
|
|
81
|
+
* @param {{botName: string, aiContext?: string, aiRules?: string, useKnowledge?: boolean}} chat - the launcher's chat block
|
|
82
82
|
* @returns {Promise<string>} the answer, or '' (no answer: carry on without)
|
|
83
83
|
*/
|
|
84
84
|
export async function aiAnswer(id, question, chat, {env = process.env, fetchFn = fetch, log = console} = {}) {
|
|
85
85
|
if (!aiAvailable(env)) return '';
|
|
86
86
|
try {
|
|
87
87
|
const brief = assistantBrief(chat);
|
|
88
|
-
const {byId} = await knowledgeIndex();
|
|
88
|
+
const {byId} = chat.useKnowledge === false ? {byId: new Map()} : await knowledgeIndex();
|
|
89
89
|
const count = (await messagesAfter(id, 0)).slice(-(HISTORY_MESSAGES + 1));
|
|
90
90
|
const payload = {
|
|
91
91
|
botName: chat.botName,
|
|
@@ -174,7 +174,8 @@ async function aiTurn(id, text, chat, session) {
|
|
|
174
174
|
|
|
175
175
|
/** The bot's reply to a visitor's words, written to the chat. Inside withChat. */
|
|
176
176
|
async function botReply(id, text, chat, settings) {
|
|
177
|
-
|
|
177
|
+
// A launcher that does not use the Knowledge still hears "a person", hello and thanks; the rest goes to the AI.
|
|
178
|
+
const {index, byId} = chat.useKnowledge === false ? {index: null, byId: new Map()} : await knowledgeIndex();
|
|
178
179
|
const r = match(index, text, {confidence: settings.confidence});
|
|
179
180
|
const session = await getSession(id, {fresh: true});
|
|
180
181
|
if (r.kind === 'handover') return handoverNow(id, chat);
|
|
@@ -191,8 +192,9 @@ async function botReply(id, text, chat, settings) {
|
|
|
191
192
|
return addMessage(id, {from: 'bot', text: SAY.suggest,
|
|
192
193
|
suggestions: r.suggestions.map(s => ({id: s.id, label: s.question}))});
|
|
193
194
|
}
|
|
194
|
-
// Still logged when the AI answers: it is a gap in the Knowledge worth filling either way
|
|
195
|
-
|
|
195
|
+
// Still logged when the AI answers: it is a gap in the Knowledge worth filling either way
|
|
196
|
+
// (not for a launcher that does not use the Knowledge: its questions are no gap in it).
|
|
197
|
+
if (chat.useKnowledge !== false) await logUnanswered(text, r.best?.question || '');
|
|
196
198
|
const said = await aiTurn(id, text, chat, session);
|
|
197
199
|
if (said) return said;
|
|
198
200
|
const misses = int(session?.data.misses) + 1;
|
|
@@ -38,6 +38,7 @@ export const LAUNCHER_CHAT_DEFAULTS = Object.freeze({
|
|
|
38
38
|
staff: true,
|
|
39
39
|
askDetails: 'offline',
|
|
40
40
|
ai: true,
|
|
41
|
+
useKnowledge: true,
|
|
41
42
|
aiUseSite: true,
|
|
42
43
|
aiContext: '',
|
|
43
44
|
aiRules: '',
|
|
@@ -90,6 +91,7 @@ export function normaliseLauncherChat(raw) {
|
|
|
90
91
|
staff: flag(r.staff, true),
|
|
91
92
|
askDetails: ASK_DETAILS.includes(r.askDetails) ? r.askDetails : LAUNCHER_CHAT_DEFAULTS.askDetails,
|
|
92
93
|
ai: flag(r.ai, true),
|
|
94
|
+
useKnowledge: flag(r.useKnowledge, true),
|
|
93
95
|
aiUseSite: flag(r.aiUseSite, true),
|
|
94
96
|
aiContext: block(r.aiContext, AI_CONTEXT_MAX),
|
|
95
97
|
aiRules: block(r.aiRules, AI_RULES_MAX),
|
|
@@ -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 = '20261111-
|
|
29
|
+
export const LAUNCHERS_ASSET_V = '20261111-knowledge-switch';
|
|
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() {
|