domma-cms 1.58.0 → 1.60.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.
@@ -1,16 +1,16 @@
1
- import{apiRequest as ce}from"../api.js";import{helpPopovers as W}from"../lib/help-popover.js";import{onceClosed as de,openMenuAt as H,viewLifetime as ue}from"../lib/tool-kit.js";import{arrangeKnowledge as pe,describeTest as F,linksToRows as ke,mayDo as be,rowsToLinks as Y}from"../lib/chats-arrange.js";const he=/^#\/launchers\/knowledge\b/,c=(f,l="GET",g)=>ce(f,{method:l,...g!==void 0?{body:JSON.stringify(g)}:{}});function ve(f){const l=document.createElement("template");return l.innerHTML=f.trim(),l.content.firstElementChild}const me=`
1
+ import{apiRequest as ue}from"../api.js";import{helpPopovers as Y}from"../lib/help-popover.js";import{onceClosed as pe,openMenuAt as z,viewLifetime as be}from"../lib/tool-kit.js";import{arrangeKnowledge as ke,describeTest as X,linksToRows as he,mayDo as me,rowsToLinks as Z}from"../lib/chats-arrange.js";import{chatsBaseFor as ve,mountAiAssistTabs as ye}from"../lib/ai-assist.js";const fe=/^#\/(launchers|ai-assist)\/knowledge\b/,c=(w,l="GET",g)=>ue(w,{method:l,...g!==void 0?{body:JSON.stringify(g)}:{}});function we(w){const l=document.createElement("template");return l.innerHTML=w.trim(),l.content.firstElementChild}const ge=`
2
2
  <article class="ck-card" data-id="{{id}}" tabindex="0" data-bind-class="off && 'is-off'">
3
3
  <h3 class="ck-q">{{question}}</h3>
4
4
  <p class="ck-a">{{preview}}</p>
5
5
  <div class="ck-meta"><span>{{meta}}</span><span>{{waysText}}</span>
6
6
  <span class="ck-chip ck-chip--warn" data-bind-hidden="!sample">Example</span><span class="ck-chip" data-bind-hidden="!off">Off</span></div>
7
7
  <button type="button" class="ck-kebab" aria-label="Entry actions" title="Actions">\u22EE</button>
8
- </article>`,ye=`
8
+ </article>`,Ee=`
9
9
  <article class="ck-card ck-uq" data-id="{{id}}" tabindex="0">
10
10
  <h3 class="ck-q">{{text}}</h3>
11
11
  <div class="ck-meta"><span>{{asked}}</span><span>{{bestText}}</span></div>
12
12
  <button type="button" class="ck-kebab" aria-label="Question actions" title="Actions">\u22EE</button>
13
- </article>`,k=ue(he);export const chatKnowledgeView={templateUrl:"/admin/js/templates/chat-knowledge.html",async onMount(f){k.reset();const l=f.get(0);let g=!1;k.add(()=>{g=!0});const v=()=>!g&&l.isConnected,X=await c("/auth/permissions").then(t=>t.permissions||[]).catch(()=>[]);if(!v())return;const p=be(X,"chats","manage"),i=M.observable([]),b=M.observable([]),q=M.observable(/[?&]tab=unanswered/.test(location.hash)?"unanswered":"knowledge"),x=M.observable(""),z=M.observable("question"),T=M.observable(!0),S=M.observable(""),$=M.observable(""),L=M.observable(""),O=M.observable([]);k.add(M.effect(()=>{O.value=pe(i.value,{query:x.value,sort:z.value}).map(t=>({...t,waysText:t.ways?`${t.ways} other way${t.ways===1?"":"s"} of asking`:""}))}));const U=M.observable([]);k.add(M.effect(()=>{const t=x.value.trim().toLowerCase();U.value=b.value.filter(e=>!t||e.text.toLowerCase().includes(t)).map(e=>({id:e.id,text:e.text,asked:`asked ${e.count} time${e.count===1?"":"s"}${e.lastAt?`, last ${D(e.lastAt).fromNow()}`:""}`,bestText:e.best?`closest: ${e.best}`:"nothing close"}))}));const Z={tab:q,query:x,sort:z,loading:T,loadError:S,tryText:$,tryOut:L,entries:O,questions:U,canManage:p,knowledgeCount:M.computed(()=>String(i.value.length)),unansweredCount:M.computed(()=>String(b.value.length)),sampleNote:M.computed(()=>{const t=i.value.filter(e=>e.sample).length;return t?`${t} example entr${t===1?"y was":"ies were"} added to show how this works. Change them, or remove them.`:""}),emptyText:M.computed(()=>T.value||S.value?"":q.value==="knowledge"?O.value.length?"":x.value.trim()?"No entries match.":"The bot knows nothing yet. Add an entry, or turn an unanswered question into one.":U.value.length?"":x.value.trim()?"No questions match.":"Nothing unanswered. Questions the bot cannot answer appear here.")};l.querySelector(".ck-items").innerHTML=me,l.querySelector(".ck-qs").innerHTML=ye;const _=W(l,{position:"bottom"});k.add(_);async function A(){try{const[t,e]=await Promise.all([c("/chats/knowledge"),c("/chats/unanswered")]);if(!v())return;i.value=t.items||[],b.value=e.items||[],S.value=""}catch{v()&&(S.value="Could not load the Knowledge.")}finally{v()&&(T.value=!1)}}async function ee(t,e){try{const a=await c(`/chats/knowledge/${encodeURIComponent(t)}`,"PUT",{enabled:e});i.value=i.peek().map(o=>o.id===t?a:o),E.toast(e?"Entry switched on":"Entry switched off - the bot will not use it",{type:"success"})}catch(a){E.toast(a?.message||"Could not change the entry",{type:"error"})}}async function te(t){if(await E.confirm("Delete this entry? The bot stops using it at once."))try{await c(`/chats/knowledge/${encodeURIComponent(t)}`,"DELETE"),i.value=i.peek().filter(e=>e.id!==t),E.toast("Entry deleted",{type:"success"})}catch(e){E.toast(e?.message||"Could not delete the entry",{type:"error"})}}async function K(t,e=!1){try{e?await c(`/chats/unanswered/${encodeURIComponent(t)}`,"DELETE"):await c(`/chats/unanswered/${encodeURIComponent(t)}/done`,"POST",{done:!0}),b.value=b.peek().filter(a=>a.id!==t)}catch(a){E.toast(a?.message||"Could not change the list",{type:"error"})}}let m=null;function y(t,{fromUnanswered:e=null,question:a=""}={}){if(!p)return;if(m){m.so.close();return}const o=!t,d=E.slideover({title:o?"New Knowledge entry":"Edit entry",size:"md",position:"right"});m={so:d};const r=ve(`
13
+ </article>`,b=be(fe);export const chatKnowledgeView={templateUrl:"/admin/js/templates/chat-knowledge.html",async onMount(w){b.reset();const l=w.get(0);let g=!1;b.add(()=>{g=!0});const m=()=>!g&&l.isConnected,_=await c("/auth/permissions").then(t=>t.permissions||[]).catch(()=>[]);if(!m())return;const p=me(_,"chats","manage"),i=M.observable([]),k=M.observable([]),q=M.observable(/[?&]tab=unanswered/.test(location.hash)?"unanswered":"knowledge"),x=M.observable(""),Q=M.observable("question"),T=M.observable(!0),S=M.observable(""),$=M.observable(""),L=M.observable(""),A=M.observable([]);b.add(M.effect(()=>{A.value=ke(i.value,{query:x.value,sort:Q.value}).map(t=>({...t,waysText:t.ways?`${t.ways} other way${t.ways===1?"":"s"} of asking`:""}))}));const O=M.observable([]);b.add(M.effect(()=>{const t=x.value.trim().toLowerCase();O.value=k.value.filter(e=>!t||e.text.toLowerCase().includes(t)).map(e=>({id:e.id,text:e.text,asked:`asked ${e.count} time${e.count===1?"":"s"}${e.lastAt?`, last ${D(e.lastAt).fromNow()}`:""}`,bestText:e.best?`closest: ${e.best}`:"nothing close"}))}));const ee={tab:q,query:x,sort:Q,loading:T,loadError:S,tryText:$,tryOut:L,entries:A,questions:O,canManage:p,knowledgeCount:M.computed(()=>String(i.value.length)),unansweredCount:M.computed(()=>String(k.value.length)),sampleNote:M.computed(()=>{const t=i.value.filter(e=>e.sample).length;return t?`${t} example entr${t===1?"y was":"ies were"} added to show how this works. Change them, or remove them.`:""}),emptyText:M.computed(()=>T.value||S.value?"":q.value==="knowledge"?A.value.length?"":x.value.trim()?"No entries match.":"The bot knows nothing yet. Add an entry, or turn an unanswered question into one.":O.value.length?"":x.value.trim()?"No questions match.":"Nothing unanswered. Questions the bot cannot answer appear here.")},V=ve(location.hash);ye(l,"knowledge");const U=l.querySelector('a[href="#/launchers/chats"]');U&&(V==="#/ai-assist"?U.remove():U.setAttribute("href",`${V}/chats`)),l.querySelector(".ck-items").innerHTML=ge,l.querySelector(".ck-qs").innerHTML=Ee;const te=Y(l,{position:"bottom"});b.add(te);async function K(){try{const[t,e]=await Promise.all([c("/chats/knowledge"),c("/chats/unanswered")]);if(!m())return;i.value=t.items||[],k.value=e.items||[],S.value=""}catch{m()&&(S.value="Could not load the Knowledge.")}finally{m()&&(T.value=!1)}}async function ae(t,e){try{const a=await c(`/chats/knowledge/${encodeURIComponent(t)}`,"PUT",{enabled:e});i.value=i.peek().map(o=>o.id===t?a:o),E.toast(e?"Entry switched on":"Entry switched off - the bot will not use it",{type:"success"})}catch(a){E.toast(a?.message||"Could not change the entry",{type:"error"})}}async function se(t){if(await E.confirm("Delete this entry? The bot stops using it at once."))try{await c(`/chats/knowledge/${encodeURIComponent(t)}`,"DELETE"),i.value=i.peek().filter(e=>e.id!==t),E.toast("Entry deleted",{type:"success"})}catch(e){E.toast(e?.message||"Could not delete the entry",{type:"error"})}}async function N(t,e=!1){try{e?await c(`/chats/unanswered/${encodeURIComponent(t)}`,"DELETE"):await c(`/chats/unanswered/${encodeURIComponent(t)}/done`,"POST",{done:!0}),k.value=k.peek().filter(a=>a.id!==t)}catch(a){E.toast(a?.message||"Could not change the list",{type:"error"})}}let v=null;function y(t,{fromUnanswered:e=null,question:a=""}={}){if(!p)return;if(v){v.so.close();return}const o=!t,d=E.slideover({title:o?"New Knowledge entry":"Edit entry",size:"md",position:"right"});v={so:d};const r=we(`
14
14
  <div class="ck-panel">
15
15
  <div>
16
16
  <label class="form-label" for="ck-ed-q">Question</label>
@@ -53,8 +53,8 @@ import{apiRequest as ce}from"../api.js";import{helpPopovers as W}from"../lib/hel
53
53
  <button type="button" class="btn btn-sm btn-primary" data-on-click="save" data-bind-disabled="saving.value">
54
54
  <span data-icon="save" data-icon-size="13"></span> Save</button>
55
55
  </div>
56
- </div>`),u={question:t?.question||a||"",alternatives:t?.alternatives||"",keywords:t?.keywords||"",answer:t?.answer||"",enabled:t?t.enabled:!0,links:JSON.stringify(t?.links||[])},n={question:M.observable(u.question),alternatives:M.observable(u.alternatives),keywords:M.observable(u.keywords),answer:M.observable(u.answer),enabled:M.observable(u.enabled),links:M.observable(ke(t?.links)),saving:M.observable(!1),tested:M.observable("")},J=()=>n.question.peek()!==u.question||n.alternatives.peek()!==u.alternatives||n.keywords.peek()!==u.keywords||n.answer.peek()!==u.answer||n.enabled.peek()!==u.enabled||JSON.stringify(Y(C()))!==u.links;r.querySelector(".ck-links").innerHTML=`<div class="ck-link-row" data-key="{{key}}">
56
+ </div>`),u={question:t?.question||a||"",alternatives:t?.alternatives||"",keywords:t?.keywords||"",answer:t?.answer||"",enabled:t?t.enabled:!0,links:JSON.stringify(t?.links||[])},s={question:M.observable(u.question),alternatives:M.observable(u.alternatives),keywords:M.observable(u.keywords),answer:M.observable(u.answer),enabled:M.observable(u.enabled),links:M.observable(he(t?.links)),saving:M.observable(!1),tested:M.observable("")},F=()=>s.question.peek()!==u.question||s.alternatives.peek()!==u.alternatives||s.keywords.peek()!==u.keywords||s.answer.peek()!==u.answer||s.enabled.peek()!==u.enabled||JSON.stringify(Z(C()))!==u.links;r.querySelector(".ck-links").innerHTML=`<div class="ck-link-row" data-key="{{key}}">
57
57
  <input type="text" class="form-input ck-link-label" placeholder="Label" maxlength="60" value="{{label}}" aria-label="Button label">
58
58
  <input type="text" class="form-input ck-link-url" placeholder="/contact or https://\u2026" maxlength="500" value="{{url}}" aria-label="Button link">
59
- <button type="button" class="btn btn-xs btn-ghost ck-link-x" aria-label="Remove this button" style="opacity:.6"><span data-icon="x" data-icon-size="12"></span></button></div>`;const C=()=>[...r.querySelectorAll(".ck-link-row")].map(s=>({key:s.dataset.key,label:s.querySelector(".ck-link-label").value,url:s.querySelector(".ck-link-url").value})),j=async()=>{if(n.saving.peek())return;n.saving.value=!0;const s={question:n.question.peek(),alternatives:n.alternatives.peek(),keywords:n.keywords.peek(),answer:n.answer.peek(),enabled:n.enabled.peek(),links:Y(C()),...e&&{fromUnanswered:e}};try{const h=o?await c("/chats/knowledge","POST",s):await c(`/chats/knowledge/${encodeURIComponent(t.id)}`,"PUT",s);if(!v())return;i.value=o?[...i.peek(),h]:i.peek().map(w=>w.id===h.id?h:w),e&&(b.value=b.peek().filter(w=>w.id!==e)),E.toast(o?"Entry added - the bot uses it now":"Entry saved",{type:"success"}),B=!0,d.close()}catch(h){E.toast(h?.message||"Could not save the entry",{type:"error"})}finally{n.saving.value=!1}};let B=!1;d.element.appendChild(r);const oe=M.applyBindings(n,r,{methods:{save:j,cancel:()=>d.close(),addLink:()=>{n.links.value=[...C(),{key:`l${Date.now()}`,label:"",url:""}],I.scan(r)},test:async()=>{try{const s=await c("/chats/knowledge/test","POST",{text:n.question.peek()});n.tested.value=`Asked "${n.question.peek()}": ${F(s)}${o||n.answer.peek()!==u.answer?" (Unsaved changes are not in the test yet.)":""}`}catch{n.tested.value="Could not ask the bot."}}}});r.addEventListener("click",s=>{const h=s.target.closest(".ck-link-x");if(!h)return;const w=h.closest(".ck-link-row").dataset.key;n.links.value=C().filter(re=>re.key!==w)}),r.addEventListener("keydown",s=>{(s.ctrlKey||s.metaKey)&&s.key==="Enter"&&(s.preventDefault(),j())});const le=W(r);de(d,()=>{oe.dispose(),le(),window.removeEventListener("beforeunload",G),m?.so===d&&(m=null)});const ie=d.close;d.close=async(...s)=>!B&&!k.leaving&&J()&&!await E.confirm("Discard the changes to this entry?")?!1:ie(...s);const G=s=>{!B&&J()&&(s.preventDefault(),s.returnValue="")};window.addEventListener("beforeunload",G),I.scan(r),d.open(),setTimeout(()=>r.querySelector(n.question.peek()?"#ck-ed-ans":"#ck-ed-q")?.focus(),60)}k.add(()=>m?.so.close());function N(t=$.peek()){const e=String(t||"").trim();e&&($.value=e,c("/chats/knowledge/test","POST",{text:e}).then(a=>{v()&&(L.value=`"${e}": ${F(a)}`)}).catch(()=>{v()&&(L.value="Could not ask the bot.")}),l.querySelector(".ck-try")?.scrollIntoView({block:"nearest"}))}const ae=M.applyBindings(Z,l,{methods:{retry:()=>{T.value=!0,A()},showKnowledge:()=>{q.value="knowledge"},showUnanswered:()=>{q.value="unanswered"},create:()=>y(null),tryIt:()=>(N(),!1),removeExamples:async()=>{if(await E.confirm("Remove the example entries? Entries you have edited are kept."))try{const t=await c("/chats/knowledge/remove-examples","POST",{});E.toast(`${t.removed} example${t.removed===1?"":"s"} removed`,{type:"success"}),A()}catch(t){E.toast(t?.message||"Could not remove them",{type:"error"})}}}});k.add(()=>ae.dispose());const Q=t=>i.peek().find(e=>e.id===t),R=l.querySelector(".ck-list"),P=l.querySelector(".ck-unanswered"),ne=E.contextMenu(R,{cursor:"glyph",match:".ck-card",inherit:!1,density:"compact",items:t=>{const e=Q(t.dataset.id);return e?[{label:p?"Edit":"View",icon:"edit",action:()=>y(e),disabled:!p},{label:"Try its question",icon:"message-circle",action:()=>N(e.question)},...p?[{label:e.enabled?"Switch off":"Switch on",icon:e.enabled?"eye-off":"eye",action:()=>ee(e.id,!e.enabled)},{type:"divider"},{label:"Delete",icon:"trash",danger:!0,action:()=>te(e.id)}]:[]]:[]}});k.add(()=>ne?.destroy?.());const se=E.contextMenu(P,{cursor:"glyph",match:".ck-card",inherit:!1,density:"compact",items:t=>{const e=b.peek().find(o=>o.id===t.dataset.id);if(!e)return[];const a=e.best?i.peek().find(o=>o.question===e.best):null;return[{label:"Make an entry",icon:"plus",disabled:!p,action:()=>y(null,{question:e.text,fromUnanswered:e.id})},...a?[{label:`Add to "${a.question.slice(0,40)}"`,icon:"corner-down-right",disabled:!p,action:async()=>{try{const o=[a.alternatives,e.text].filter(Boolean).join(`
60
- `),d=await c(`/chats/knowledge/${encodeURIComponent(a.id)}`,"PUT",{alternatives:o});i.value=i.peek().map(r=>r.id===d.id?d:r),await K(e.id),E.toast("Added as another way of asking",{type:"success"})}catch(o){E.toast(o?.message||"Could not add it",{type:"error"})}}}]:[],{label:"Try it",icon:"message-circle",action:()=>N(e.text)},{type:"divider"},{label:"Dismiss",icon:"check",disabled:!p,action:()=>K(e.id)},{label:"Delete",icon:"trash",danger:!0,disabled:!p,action:()=>K(e.id,!0)}]}});k.add(()=>se?.destroy?.()),R.addEventListener("click",t=>{const e=t.target.closest(".ck-card");if(e){if(t.target.closest(".ck-kebab")){H(e);return}y(Q(e.dataset.id))}}),P.addEventListener("click",t=>{const e=t.target.closest(".ck-card");if(!e)return;if(t.target.closest(".ck-kebab")){H(e);return}const a=b.peek().find(o=>o.id===e.dataset.id);a&&p?y(null,{question:a.text,fromUnanswered:a.id}):a&&H(e)});for(const t of[R,P])t.addEventListener("keydown",e=>{const a=e.target.closest?.(".ck-card");a&&e.key==="Enter"&&e.target===a&&a.click()});const V=t=>{t.ctrlKey||t.metaKey||t.altKey||t.target.closest?.("input, textarea, select, [contenteditable], .dm-slideover")||(t.key==="/"?(t.preventDefault(),l.querySelector(".ck-search input")?.focus()):(t.key==="n"||t.key==="N")&&p&&(t.preventDefault(),y(null)))};document.addEventListener("keydown",V),k.add(()=>document.removeEventListener("keydown",V)),I.scan(l),await A()}};
59
+ <button type="button" class="btn btn-xs btn-ghost ck-link-x" aria-label="Remove this button" style="opacity:.6"><span data-icon="x" data-icon-size="12"></span></button></div>`;const C=()=>[...r.querySelectorAll(".ck-link-row")].map(n=>({key:n.dataset.key,label:n.querySelector(".ck-link-label").value,url:n.querySelector(".ck-link-url").value})),G=async()=>{if(s.saving.peek())return;s.saving.value=!0;const n={question:s.question.peek(),alternatives:s.alternatives.peek(),keywords:s.keywords.peek(),answer:s.answer.peek(),enabled:s.enabled.peek(),links:Z(C()),...e&&{fromUnanswered:e}};try{const h=o?await c("/chats/knowledge","POST",n):await c(`/chats/knowledge/${encodeURIComponent(t.id)}`,"PUT",n);if(!m())return;i.value=o?[...i.peek(),h]:i.peek().map(f=>f.id===h.id?h:f),e&&(k.value=k.peek().filter(f=>f.id!==e)),E.toast(o?"Entry added - the bot uses it now":"Entry saved",{type:"success"}),H=!0,d.close()}catch(h){E.toast(h?.message||"Could not save the entry",{type:"error"})}finally{s.saving.value=!1}};let H=!1;d.element.appendChild(r);const ie=M.applyBindings(s,r,{methods:{save:G,cancel:()=>d.close(),addLink:()=>{s.links.value=[...C(),{key:`l${Date.now()}`,label:"",url:""}],I.scan(r)},test:async()=>{try{const n=await c("/chats/knowledge/test","POST",{text:s.question.peek()});s.tested.value=`Asked "${s.question.peek()}": ${X(n)}${o||s.answer.peek()!==u.answer?" (Unsaved changes are not in the test yet.)":""}`}catch{s.tested.value="Could not ask the bot."}}}});r.addEventListener("click",n=>{const h=n.target.closest(".ck-link-x");if(!h)return;const f=h.closest(".ck-link-row").dataset.key;s.links.value=C().filter(de=>de.key!==f)}),r.addEventListener("keydown",n=>{(n.ctrlKey||n.metaKey)&&n.key==="Enter"&&(n.preventDefault(),G())});const re=Y(r);pe(d,()=>{ie.dispose(),re(),window.removeEventListener("beforeunload",W),v?.so===d&&(v=null)});const ce=d.close;d.close=async(...n)=>!H&&!b.leaving&&F()&&!await E.confirm("Discard the changes to this entry?")?!1:ce(...n);const W=n=>{!H&&F()&&(n.preventDefault(),n.returnValue="")};window.addEventListener("beforeunload",W),I.scan(r),d.open(),setTimeout(()=>r.querySelector(s.question.peek()?"#ck-ed-ans":"#ck-ed-q")?.focus(),60)}b.add(()=>v?.so.close());function R(t=$.peek()){const e=String(t||"").trim();e&&($.value=e,c("/chats/knowledge/test","POST",{text:e}).then(a=>{m()&&(L.value=`"${e}": ${X(a)}`)}).catch(()=>{m()&&(L.value="Could not ask the bot.")}),l.querySelector(".ck-try")?.scrollIntoView({block:"nearest"}))}const ne=M.applyBindings(ee,l,{methods:{retry:()=>{T.value=!0,K()},showKnowledge:()=>{q.value="knowledge"},showUnanswered:()=>{q.value="unanswered"},create:()=>y(null),tryIt:()=>(R(),!1),removeExamples:async()=>{if(await E.confirm("Remove the example entries? Entries you have edited are kept."))try{const t=await c("/chats/knowledge/remove-examples","POST",{});E.toast(`${t.removed} example${t.removed===1?"":"s"} removed`,{type:"success"}),K()}catch(t){E.toast(t?.message||"Could not remove them",{type:"error"})}}}});b.add(()=>ne.dispose());const J=t=>i.peek().find(e=>e.id===t),P=l.querySelector(".ck-list"),B=l.querySelector(".ck-unanswered"),oe=E.contextMenu(P,{cursor:"glyph",match:".ck-card",inherit:!1,density:"compact",items:t=>{const e=J(t.dataset.id);return e?[{label:p?"Edit":"View",icon:"edit",action:()=>y(e),disabled:!p},{label:"Try its question",icon:"message-circle",action:()=>R(e.question)},...p?[{label:e.enabled?"Switch off":"Switch on",icon:e.enabled?"eye-off":"eye",action:()=>ae(e.id,!e.enabled)},{type:"divider"},{label:"Delete",icon:"trash",danger:!0,action:()=>se(e.id)}]:[]]:[]}});b.add(()=>oe?.destroy?.());const le=E.contextMenu(B,{cursor:"glyph",match:".ck-card",inherit:!1,density:"compact",items:t=>{const e=k.peek().find(o=>o.id===t.dataset.id);if(!e)return[];const a=e.best?i.peek().find(o=>o.question===e.best):null;return[{label:"Make an entry",icon:"plus",disabled:!p,action:()=>y(null,{question:e.text,fromUnanswered:e.id})},...a?[{label:`Add to "${a.question.slice(0,40)}"`,icon:"corner-down-right",disabled:!p,action:async()=>{try{const o=[a.alternatives,e.text].filter(Boolean).join(`
60
+ `),d=await c(`/chats/knowledge/${encodeURIComponent(a.id)}`,"PUT",{alternatives:o});i.value=i.peek().map(r=>r.id===d.id?d:r),await N(e.id),E.toast("Added as another way of asking",{type:"success"})}catch(o){E.toast(o?.message||"Could not add it",{type:"error"})}}}]:[],{label:"Try it",icon:"message-circle",action:()=>R(e.text)},{type:"divider"},{label:"Dismiss",icon:"check",disabled:!p,action:()=>N(e.id)},{label:"Delete",icon:"trash",danger:!0,disabled:!p,action:()=>N(e.id,!0)}]}});b.add(()=>le?.destroy?.()),P.addEventListener("click",t=>{const e=t.target.closest(".ck-card");if(e){if(t.target.closest(".ck-kebab")){z(e);return}y(J(e.dataset.id))}}),B.addEventListener("click",t=>{const e=t.target.closest(".ck-card");if(!e)return;if(t.target.closest(".ck-kebab")){z(e);return}const a=k.peek().find(o=>o.id===e.dataset.id);a&&p?y(null,{question:a.text,fromUnanswered:a.id}):a&&z(e)});for(const t of[P,B])t.addEventListener("keydown",e=>{const a=e.target.closest?.(".ck-card");a&&e.key==="Enter"&&e.target===a&&a.click()});const j=t=>{t.ctrlKey||t.metaKey||t.altKey||t.target.closest?.("input, textarea, select, [contenteditable], .dm-slideover")||(t.key==="/"?(t.preventDefault(),l.querySelector(".ck-search input")?.focus()):(t.key==="n"||t.key==="N")&&p&&(t.preventDefault(),y(null)))};document.addEventListener("keydown",j),b.add(()=>document.removeEventListener("keydown",j)),I.scan(l),await K()}};
@@ -1,4 +1,4 @@
1
- import{apiRequest as De}from"../api.js";import{addBannerAction as Re}from"../lib/plugin-chrome.js";import{helpPopovers as ce}from"../lib/help-popover.js";import{onceClosed as Ae,openMenuAt as ie,sidebarCount as V,viewLifetime as He}from"../lib/tool-kit.js";import{arrangeChats as Le,arrangeSaved as Oe,mayDo as de,OUTCOME as ue,STATUS as Ie,threadRow as he}from"../lib/chats-arrange.js";const Pe=/^#\/launchers\/chats\b/,pe=5e3,me=3e3,Ue=3e4,ve="chats.drafts",i=(h,l="GET",$)=>De(h,{method:l,...$!==void 0?{body:JSON.stringify($)}:{}});function qe(h){const l=document.createElement("template");return l.innerHTML=h.trim(),l.content.firstElementChild}const Be=()=>{try{const h=S.get(ve);return h&&typeof h=="object"?h:{}}catch{return{}}},fe=h=>{try{S.set(ve,h)}catch{}},Ke=`
1
+ import{apiRequest as De}from"../api.js";import{addBannerAction as Ae}from"../lib/plugin-chrome.js";import{helpPopovers as ce}from"../lib/help-popover.js";import{onceClosed as Re,openMenuAt as de,sidebarCount as _,viewLifetime as Le}from"../lib/tool-kit.js";import{arrangeChats as He,arrangeSaved as Oe,mayDo as ue,OUTCOME as he,STATUS as qe,threadRow as pe}from"../lib/chats-arrange.js";import{chatsBaseFor as Be,mountAiAssistTabs as Pe}from"../lib/ai-assist.js";import{onPresence as Ue,setAvailable as Ie}from"../lib/chat-presence.js";const Ke=/^#\/(launchers|ai-assist)\/chats\b/,me=5e3,ve=3e3,fe="chats.drafts",u=(h,l="GET",A)=>De(h,{method:l,...A!==void 0?{body:JSON.stringify(A)}:{}});function Fe(h){const l=document.createElement("template");return l.innerHTML=h.trim(),l.content.firstElementChild}const je=()=>{try{const h=S.get(fe);return h&&typeof h=="object"?h:{}}catch{return{}}},ye=h=>{try{S.set(fe,h)}catch{}},Ve=`
2
2
  <div class="chat-row" data-id="{{id}}" tabindex="0" role="button" data-bind-class="$root.openId.value === id && 'is-open'">
3
3
  <span class="chat-row-who">{{who}}</span>
4
4
  <span data-bind-class="chipClass">{{chip}}</span>
@@ -6,12 +6,12 @@ import{apiRequest as De}from"../api.js";import{addBannerAction as Re}from"../lib
6
6
  <span class="chat-row-meta">{{meta}}</span>
7
7
  <span class="chat-row-unread" aria-label="unread">{{unreadText}}</span>
8
8
  <button type="button" class="chat-row-kebab" aria-label="Chat actions" title="Actions">\u22EE</button>
9
- </div>`,je=`
9
+ </div>`,_e=`
10
10
  <div data-bind-class="cls">
11
11
  <span class="chat-msg-who">{{who}} \xB7 {{time}}</span>
12
12
  <div class="chat-msg-text">{{text}}</div>
13
13
  <span class="chat-msg-note">{{note}}</span>
14
- </div>`,r=He(Pe);export const chatsView={templateUrl:"/admin/js/templates/chats.html",async onMount(h){r.reset();const l=h.get(0);let $=!1;r.add(()=>{$=!0});const n=()=>!$&&l.isConnected,Z=await i("/auth/permissions").then(e=>e.permissions||[]).catch(()=>[]);if(!n())return;const b=de(Z,"chats","reply"),z=de(Z,"chats","manage"),m=M.observable([]),O=M.observable(""),d=M.observable("active"),y=M.observable(!0),g=M.observable(""),o=M.observable(location.hash.match(/^#\/launchers\/chats\/([A-Za-z0-9_-]+)/)?.[1]||""),u=M.observable(null),k=M.observable([]),v=M.observable(""),P=M.observable(!1),R=M.observable(!1),Q=M.observable([]),X=M.observable({installed:!0,count:1}),f=M.observable([]),p=M.observable(null),U=M.observable(""),q=M.observable("to look at");let A=0,ee=!1;const G=M.observable([]);r.add(M.effect(()=>{G.value=d.value==="saved"?Oe(f.value,{query:O.value}):Le(m.value,{query:O.value})}));const ye={query:O,view:d,loading:y,loadError:g,rows:G,openId:o,thread:k,reply:v,available:R,canReply:b,savedOpen:p,savedNote:U,savedOutcome:q,savedDirty:M.computed(()=>!!p.value&&(U.value!==(p.value.note||"")||q.value!==p.value.outcome)),isEmpty:M.computed(()=>!y.value&&!g.value&&G.value.length===0),emptyText:M.computed(()=>O.value.trim()?"No chats match.":d.value==="active"?"No chats right now. They appear here as visitors start them.":d.value==="saved"?"No saved chats. Right-click a chat and choose Save for a closer look to keep a copy here.":"No ended chats."),countText:M.computed(()=>{if(y.value)return"";if(d.value==="saved"){const a=f.value.length,s=f.value.filter(c=>c.outcome!=="done").length;return`${a} saved${s?` \xB7 ${s} to finish`:""}`}const e=m.value.filter(a=>a.status==="waiting").length,t=m.value.length;return`${t} chat${t===1?"":"s"}${e?` \xB7 ${e} waiting`:""}`}),availText:M.computed(()=>{const e=Q.value;return R.value?e.length>1?`Available (${e.length} of you)`:"Available for chats":e.length?`Not available \xB7 ${e.length} other${e.length===1?"":"s"} available`:"Not available"}),noLauncherNote:M.computed(()=>{const e=X.value;return e.installed&&!e.count?"No chat launcher is switched on yet, so visitors cannot start a chat. Add a launcher with the Chat action in Launchers.":""}),head:M.computed(()=>{const e=p.value;if(e){const c=ue[e.outcome]||ue["to look at"],L=e.savedAt?`saved ${D(e.savedAt).fromNow()}${e.savedBy?` by ${e.savedBy}`:""}`:"";return{who:e.name||"Visitor",chip:c.label,chipClass:`chat-chip chat-chip--${c.tone}`,email:e.email,mailto:e.email?`mailto:${e.email}`:"",meta:[e.page?`on ${e.page}`:"",L].filter(Boolean).join(" \xB7 ")}}const t=u.value;if(!t)return{who:"",chip:"",chipClass:"chat-chip",email:"",mailto:"",meta:""};const a=Ie[t.status]||{label:t.status,tone:"muted"},s=t.startedAt?`started ${D(t.startedAt).fromNow()}`:"";return{who:t.name||"Visitor",chip:a.label,chipClass:`chat-chip chat-chip--${a.tone}`,email:t.email,mailto:t.email?`mailto:${t.email}`:"",meta:[t.page?`on ${t.page}`:"",s].filter(Boolean).join(" \xB7 ")}}),canWrite:M.computed(()=>b&&!!u.value&&u.value.status!=="closed"),canSend:M.computed(()=>b&&!P.value&&v.value.trim().length>0&&!!u.value&&u.value.status!=="closed"),replyHint:M.computed(()=>u.value?.status==="closed"?"This chat has ended.":u.value?.status==="message"?"Reply here (they see it if they come back) - or email them.":"Type a reply\u2026 (Ctrl+Enter sends)")};let T=Be();r.add(M.effect(()=>{const e=o.peek(),t=v.value;e&&(t?T[e]=t:delete T[e],fe(T))}));const te=e=>{v.peek().trim()&&(e.preventDefault(),e.returnValue="")};window.addEventListener("beforeunload",te),r.add(()=>window.removeEventListener("beforeunload",te)),l.querySelector(".chats-list").innerHTML=Ke,l.querySelector(".chats-msgs").innerHTML=je;const W=l.querySelector(".chats-list"),x=l.querySelector(".chats-messages"),be=ce(l,{position:"bottom"});r.add(be);let B=0,H=0,ae=0;r.add(()=>{clearTimeout(B),clearTimeout(H),clearInterval(ae)});async function w(){if(clearTimeout(B),d.peek()==="saved")return ge();try{const e=await i(`/chats?view=${d.peek()}`);if(!n())return;m.value=e.items||[],Q.value=e.available||[],X.value=e.launchers||{installed:!0,count:1},g.value=""}catch{if(!n())return;y.peek()&&(g.value="Could not load the chats.")}finally{n()&&(y.value=!1,B=setTimeout(se(w),pe))}}async function ge(){try{const e=await i("/chats/saved");if(!n()||d.peek()!=="saved")return;f.value=e.items||[],g.value=""}catch{n()&&(g.value="Could not load the saved chats.")}finally{n()&&(y.value=!1)}}async function ne(e){if(!(!e||p.peek()?.id===e)){clearTimeout(H),u.value=null,v.value="",o.value=e,k.value=[];try{const{item:t}=await i(`/chats/saved/${encodeURIComponent(e)}`);if(!n()||o.peek()!==e)return;p.value=t,U.value=t.note||"",q.value=t.outcome,k.value=(t.messages||[]).map(he),requestAnimationFrame(()=>{x.scrollTop=0})}catch(t){if(!n())return;E.toast(t?.message||"Could not open the saved chat",{type:"error"}),C()}}}async function ke(){const e=p.peek();if(e)try{const{item:t}=await i(`/chats/saved/${encodeURIComponent(e.id)}`,"PUT",{note:U.peek(),outcome:q.peek()});if(!n())return;p.value={...e,...t},f.value=f.peek().map(a=>a.id===t.id?t:a),E.toast("Saved",{type:"success"})}catch(t){E.toast(t?.message||"Could not save",{type:"error"})}}async function we(e){const t=await E.prompt("Save a copy of this chat for a closer look. Why are you saving it? (optional)");if(!(t==null||!n()))try{if(await i(`/chats/${encodeURIComponent(e)}/save`,"POST",{note:String(t)}),!n())return;E.toast("Saved - find it under Saved",{type:"success"})}catch(a){E.toast(a?.message||"Could not save the chat",{type:"error"})}}async function Ee(e){if(!(!await E.confirm("Delete this saved copy? The chat itself is not affected. This cannot be undone.")||!n()))try{await i(`/chats/saved/${encodeURIComponent(e)}`,"DELETE"),o.peek()===e&&C(),f.value=f.peek().filter(a=>a.id!==e),E.toast("Saved copy deleted",{type:"success"})}catch(a){E.toast(a?.message||"Could not delete it",{type:"error"})}}const se=e=>()=>{if(document.hidden){B=setTimeout(se(e),pe);return}e()};async function K(e=!1){clearTimeout(H);const t=o.peek();if(t){e&&(A=0,k.value=[]);try{const a=await i(`/chats/${encodeURIComponent(t)}?after=${A}`);if(!n()||o.peek()!==t)return;u.value=a.chat;const s=(a.messages||[]).filter(c=>c.n>A);if(s.length){const c=x.scrollHeight-x.scrollTop-x.clientHeight<80;A=Math.max(A,...s.map(L=>L.n)),k.value=[...k.peek(),...s.map(he)],(e||c)&&requestAnimationFrame(()=>{x.scrollTop=x.scrollHeight}),V("#/launchers/chats")}m.value=m.peek().map(c=>c.id===t?{...c,...a.chat}:c)}catch(a){if(!n()||o.peek()!==t)return;if(/not found/i.test(a?.message||"")){E.toast("That chat no longer exists",{type:"warning"}),C();return}}n()&&o.peek()===t&&(H=setTimeout(()=>K(),document.hidden?me*4:me))}}function j(e){if(d.peek()==="saved"){ne(e);return}!e||o.peek()===e||(o.value=e,u.value=m.peek().find(t=>t.id===e)||null,v.value=T[e]||"",history.replaceState(null,"",`#/launchers/chats/${e}`),K(!0))}function C(){clearTimeout(H),o.value="",u.value=null,p.value=null,k.value=[],v.value="",history.replaceState(null,"","#/launchers/chats")}async function oe(){const e=o.peek(),t=v.peek().trim();if(!(!e||!t||P.peek())){P.value=!0;try{if(await i(`/chats/${encodeURIComponent(e)}/reply`,"POST",{text:t}),!n())return;v.value="",await K(),w(),V("#/launchers/chats")}catch(a){E.toast(a?.message||"The reply was not sent",{type:"error"})}finally{n()&&(P.value=!1)}}}async function Me(e){try{await i(`/chats/${encodeURIComponent(e)}/close`,"POST",{}),E.toast("Chat ended",{type:"success"}),o.peek()===e&&K(),w(),V("#/launchers/chats")}catch(t){E.toast(t?.message||"Could not end the chat",{type:"error"})}}async function Ce(e){if(!(!await E.confirm("Delete this chat and all its messages? This cannot be undone.")||!n()))try{await i(`/chats/${encodeURIComponent(e)}`,"DELETE"),delete T[e],fe(T),o.peek()===e&&C(),m.value=m.peek().filter(a=>a.id!==e),V("#/launchers/chats"),E.toast("Chat deleted",{type:"success"})}catch(a){E.toast(a?.message||"Could not delete the chat",{type:"error"})}}async function F(e=!1){if(b)try{const t=await i("/chats/presence","POST",e?{leaving:!0}:{available:R.peek()});!e&&n()&&typeof t?.online=="number"&&w()}catch{}}b&&(R.value=!0,F(),ae=setInterval(()=>F(),Ue),r.add(M.effect(()=>{if(R.value,!ee){ee=!0;return}F()})),r.add(()=>F(!0)));function J(e){if(d.peek()===e)return;const t=d.peek()==="saved"||e==="saved";d.value=e,t&&o.peek()&&C(),y.value=!0,w()}const Te=M.applyBindings(ye,l,{methods:{retry:()=>{y.value=!0,g.value="",w()},showActive:()=>{J("active")},showClosed:()=>{J("closed")},showSaved:()=>{J("saved")},saveSavedNote:()=>ke(),sendReply:()=>(oe(),!1),back:()=>C()}});r.add(()=>Te.dispose()),l.querySelector(".chats-reply textarea")?.addEventListener("keydown",e=>{(e.ctrlKey||e.metaKey)&&e.key==="Enter"&&(e.preventDefault(),oe())});const le=e=>{if(d.peek()==="saved"){const a=f.peek().find(s=>s.id===e)||(p.peek()?.id===e?p.peek():null);return a?[{label:"Open",icon:"message-circle",action:()=>ne(e)},...a.email?[{label:"Email the visitor",icon:"mail",action:()=>{location.href=`mailto:${a.email}`}}]:[],...a.page?[{label:"Open the page they were on",icon:"external-link",action:()=>window.open(a.page,"_blank","noopener")}]:[],...z?[{type:"divider"},{label:"Delete saved copy",icon:"trash",danger:!0,action:()=>Ee(e)}]:[]]:[]}const t=m.peek().find(a=>a.id===e)||(u.peek()?.id===e?u.peek():null);return t?[{label:"Open",icon:"message-circle",action:()=>j(e)},...t.email?[{label:"Email the visitor",icon:"mail",action:()=>{location.href=`mailto:${t.email}`}},{label:"Copy email address",icon:"copy",action:()=>navigator.clipboard?.writeText(t.email).then(()=>E.toast("Copied",{type:"success"})).catch(()=>{})}]:[],...t.page?[{label:"Open the page they were on",icon:"external-link",action:()=>window.open(t.page,"_blank","noopener")}]:[],...b?[{type:"divider"},{label:"Save for a closer look\u2026",icon:"bookmark",action:()=>we(e)}]:[],...b&&t.status!=="closed"?[{type:"divider"},{label:"End chat",icon:"x-circle",action:()=>Me(e)}]:[],...z?[{type:"divider"},{label:"Delete",icon:"trash",danger:!0,action:()=>Ce(e)}]:[]]:[]},Se=E.contextMenu(W,{cursor:"glyph",match:".chat-row",inherit:!1,density:"compact",items:e=>le(e.dataset.id)});r.add(()=>Se?.destroy?.());const Y=l.querySelector(".chats-head-kebab"),xe=E.contextMenu(Y,{cursor:"glyph",inherit:!1,density:"compact",items:()=>le(o.peek())});r.add(()=>xe?.destroy?.()),Y.addEventListener("click",()=>ie(Y)),W.addEventListener("click",e=>{const t=e.target.closest(".chat-row");if(t){if(e.target.closest(".chat-row-kebab")){ie(t);return}j(t.dataset.id)}}),W.addEventListener("keydown",e=>{const t=e.target.closest?.(".chat-row");t&&(e.key==="Enter"||e.key===" ")&&e.target===t&&(e.preventDefault(),j(t.dataset.id))});let N=null;async function Ne(){if(N)return;let e;try{e=(await i("/chats/settings")).settings}catch{E.toast("Could not read the chat settings",{type:"error"});return}if(!n()||N)return;const t=E.slideover({title:"Chat settings",size:"sm",position:"right"});N=t;const a=qe(`
14
+ </div>`,r=Le(Ke);export const chatsView={templateUrl:"/admin/js/templates/chats.html",async onMount(h){r.reset();const l=h.get(0);let A=!1;r.add(()=>{A=!0});const s=()=>!A&&l.isConnected,z=Be(location.hash),b=`${z}/chats`,X=await u("/auth/permissions").then(e=>e.permissions||[]).catch(()=>[]);if(!s())return;const T=ue(X,"chats","reply"),G=ue(X,"chats","manage"),m=M.observable([]),q=M.observable(""),c=M.observable("active"),y=M.observable(!0),g=M.observable(""),o=M.observable(location.hash.match(/^#\/(?:launchers|ai-assist)\/chats\/([A-Za-z0-9_-]+)/)?.[1]||""),d=M.observable(null),k=M.observable([]),v=M.observable(""),B=M.observable(!1),R=M.observable(!1),ee=M.observable([]),te=M.observable({installed:!0,count:1}),f=M.observable([]),p=M.observable(null),P=M.observable(""),U=M.observable("to look at");let L=0;const W=M.observable([]);r.add(M.effect(()=>{W.value=c.value==="saved"?Oe(f.value,{query:q.value}):He(m.value,{query:q.value})}));const be={query:q,view:c,loading:y,loadError:g,rows:W,openId:o,thread:k,reply:v,available:R,canReply:T,savedOpen:p,savedNote:P,savedOutcome:U,savedDirty:M.computed(()=>!!p.value&&(P.value!==(p.value.note||"")||U.value!==p.value.outcome)),isEmpty:M.computed(()=>!y.value&&!g.value&&W.value.length===0),emptyText:M.computed(()=>q.value.trim()?"No chats match.":c.value==="active"?"No chats right now. They appear here as visitors start them.":c.value==="saved"?"No saved chats. Right-click a chat and choose Save for a closer look to keep a copy here.":"No ended chats."),countText:M.computed(()=>{if(y.value)return"";if(c.value==="saved"){const a=f.value.length,n=f.value.filter(i=>i.outcome!=="done").length;return`${a} saved${n?` \xB7 ${n} to finish`:""}`}const e=m.value.filter(a=>a.status==="waiting").length,t=m.value.length;return`${t} chat${t===1?"":"s"}${e?` \xB7 ${e} waiting`:""}`}),availText:M.computed(()=>{const e=ee.value;return R.value?e.length>1?`Available (${e.length} of you)`:"Available for chats":e.length?`Not available \xB7 ${e.length} other${e.length===1?"":"s"} available`:"Not available"}),noLauncherNote:M.computed(()=>{const e=te.value;return e.installed&&!e.count?"No chat launcher is switched on yet, so visitors cannot start a chat. Add a launcher with the Chat action in Launchers.":""}),head:M.computed(()=>{const e=p.value;if(e){const i=he[e.outcome]||he["to look at"],O=e.savedAt?`saved ${D(e.savedAt).fromNow()}${e.savedBy?` by ${e.savedBy}`:""}`:"";return{who:e.name||"Visitor",chip:i.label,chipClass:`chat-chip chat-chip--${i.tone}`,email:e.email,mailto:e.email?`mailto:${e.email}`:"",meta:[e.page?`on ${e.page}`:"",O].filter(Boolean).join(" \xB7 ")}}const t=d.value;if(!t)return{who:"",chip:"",chipClass:"chat-chip",email:"",mailto:"",meta:""};const a=qe[t.status]||{label:t.status,tone:"muted"},n=t.startedAt?`started ${D(t.startedAt).fromNow()}`:"";return{who:t.name||"Visitor",chip:a.label,chipClass:`chat-chip chat-chip--${a.tone}`,email:t.email,mailto:t.email?`mailto:${t.email}`:"",meta:[t.page?`on ${t.page}`:"",n].filter(Boolean).join(" \xB7 ")}}),canWrite:M.computed(()=>T&&!!d.value&&d.value.status!=="closed"),canSend:M.computed(()=>T&&!B.value&&v.value.trim().length>0&&!!d.value&&d.value.status!=="closed"),replyHint:M.computed(()=>d.value?.status==="closed"?"This chat has ended.":d.value?.status==="message"?"Reply here (they see it if they come back) - or email them.":"Type a reply\u2026 (Ctrl+Enter sends)")};let x=je();r.add(M.effect(()=>{const e=o.peek(),t=v.value;e&&(t?x[e]=t:delete x[e],ye(x))}));const ae=e=>{v.peek().trim()&&(e.preventDefault(),e.returnValue="")};window.addEventListener("beforeunload",ae),r.add(()=>window.removeEventListener("beforeunload",ae)),l.querySelector(".chats-list").innerHTML=Ve,l.querySelector(".chats-msgs").innerHTML=_e;const J=l.querySelector(".chats-list"),$=l.querySelector(".chats-messages"),ge=ce(l,{position:"bottom"});r.add(ge);let K=0,H=0;r.add(()=>{clearTimeout(K),clearTimeout(H)});async function w(){if(clearTimeout(K),c.peek()==="saved")return ke();try{const e=await u(`/chats?view=${c.peek()}`);if(!s())return;m.value=e.items||[],ee.value=e.available||[],te.value=e.launchers||{installed:!0,count:1},g.value=""}catch{if(!s())return;y.peek()&&(g.value="Could not load the chats.")}finally{s()&&(y.value=!1,K=setTimeout(ne(w),me))}}async function ke(){try{const e=await u("/chats/saved");if(!s()||c.peek()!=="saved")return;f.value=e.items||[],g.value=""}catch{s()&&(g.value="Could not load the saved chats.")}finally{s()&&(y.value=!1)}}async function se(e){if(!(!e||p.peek()?.id===e)){clearTimeout(H),d.value=null,v.value="",o.value=e,k.value=[];try{const{item:t}=await u(`/chats/saved/${encodeURIComponent(e)}`);if(!s()||o.peek()!==e)return;p.value=t,P.value=t.note||"",U.value=t.outcome,k.value=(t.messages||[]).map(pe),requestAnimationFrame(()=>{$.scrollTop=0})}catch(t){if(!s())return;E.toast(t?.message||"Could not open the saved chat",{type:"error"}),C()}}}async function we(){const e=p.peek();if(e)try{const{item:t}=await u(`/chats/saved/${encodeURIComponent(e.id)}`,"PUT",{note:P.peek(),outcome:U.peek()});if(!s())return;p.value={...e,...t},f.value=f.peek().map(a=>a.id===t.id?t:a),E.toast("Saved",{type:"success"})}catch(t){E.toast(t?.message||"Could not save",{type:"error"})}}async function Ee(e){const t=await E.prompt("Save a copy of this chat for a closer look. Why are you saving it? (optional)");if(!(t==null||!s()))try{if(await u(`/chats/${encodeURIComponent(e)}/save`,"POST",{note:String(t)}),!s())return;E.toast("Saved - find it under Saved",{type:"success"})}catch(a){E.toast(a?.message||"Could not save the chat",{type:"error"})}}async function Me(e){if(!(!await E.confirm("Delete this saved copy? The chat itself is not affected. This cannot be undone.")||!s()))try{await u(`/chats/saved/${encodeURIComponent(e)}`,"DELETE"),o.peek()===e&&C(),f.value=f.peek().filter(a=>a.id!==e),E.toast("Saved copy deleted",{type:"success"})}catch(a){E.toast(a?.message||"Could not delete it",{type:"error"})}}const ne=e=>()=>{if(document.hidden){K=setTimeout(ne(e),me);return}e()};async function F(e=!1){clearTimeout(H);const t=o.peek();if(t){e&&(L=0,k.value=[]);try{const a=await u(`/chats/${encodeURIComponent(t)}?after=${L}`);if(!s()||o.peek()!==t)return;d.value=a.chat;const n=(a.messages||[]).filter(i=>i.n>L);if(n.length){const i=$.scrollHeight-$.scrollTop-$.clientHeight<80;L=Math.max(L,...n.map(O=>O.n)),k.value=[...k.peek(),...n.map(pe)],(e||i)&&requestAnimationFrame(()=>{$.scrollTop=$.scrollHeight}),_(b)}m.value=m.peek().map(i=>i.id===t?{...i,...a.chat}:i)}catch(a){if(!s()||o.peek()!==t)return;if(/not found/i.test(a?.message||"")){E.toast("That chat no longer exists",{type:"warning"}),C();return}}s()&&o.peek()===t&&(H=setTimeout(()=>F(),document.hidden?ve*4:ve))}}function j(e){if(c.peek()==="saved"){se(e);return}!e||o.peek()===e||(o.value=e,d.value=m.peek().find(t=>t.id===e)||null,v.value=x[e]||"",history.replaceState(null,"",`${b}/${e}`),F(!0))}function C(){clearTimeout(H),o.value="",d.value=null,p.value=null,k.value=[],v.value="",history.replaceState(null,"",b)}async function oe(){const e=o.peek(),t=v.peek().trim();if(!(!e||!t||B.peek())){B.value=!0;try{if(await u(`/chats/${encodeURIComponent(e)}/reply`,"POST",{text:t}),!s())return;v.value="",await F(),w(),_(b)}catch(a){E.toast(a?.message||"The reply was not sent",{type:"error"})}finally{s()&&(B.value=!1)}}}async function Ce(e){try{await u(`/chats/${encodeURIComponent(e)}/close`,"POST",{}),E.toast("Chat ended",{type:"success"}),o.peek()===e&&F(),w(),_(b)}catch(t){E.toast(t?.message||"Could not end the chat",{type:"error"})}}async function Te(e){if(!(!await E.confirm("Delete this chat and all its messages? This cannot be undone.")||!s()))try{await u(`/chats/${encodeURIComponent(e)}`,"DELETE"),delete x[e],ye(x),o.peek()===e&&C(),m.value=m.peek().filter(a=>a.id!==e),_(b),E.toast("Chat deleted",{type:"success"})}catch(a){E.toast(a?.message||"Could not delete the chat",{type:"error"})}}if(T){let e=!1;r.add(Ue(({available:t})=>{R.peek()!==t&&(e=!0,R.value=t,e=!1,s()&&setTimeout(()=>{s()&&w()},400))})),r.add(M.effect(()=>{const t=R.value;e||Ie(t)}))}function Y(e){if(c.peek()===e)return;const t=c.peek()==="saved"||e==="saved";c.value=e,t&&o.peek()&&C(),y.value=!0,w()}const Se=M.applyBindings(be,l,{methods:{retry:()=>{y.value=!0,g.value="",w()},showActive:()=>{Y("active")},showClosed:()=>{Y("closed")},showSaved:()=>{Y("saved")},saveSavedNote:()=>we(),sendReply:()=>(oe(),!1),back:()=>C()}});r.add(()=>Se.dispose()),l.querySelector(".chats-reply textarea")?.addEventListener("keydown",e=>{(e.ctrlKey||e.metaKey)&&e.key==="Enter"&&(e.preventDefault(),oe())});const le=e=>{if(c.peek()==="saved"){const a=f.peek().find(n=>n.id===e)||(p.peek()?.id===e?p.peek():null);return a?[{label:"Open",icon:"message-circle",action:()=>se(e)},...a.email?[{label:"Email the visitor",icon:"mail",action:()=>{location.href=`mailto:${a.email}`}}]:[],...a.page?[{label:"Open the page they were on",icon:"external-link",action:()=>window.open(a.page,"_blank","noopener")}]:[],...G?[{type:"divider"},{label:"Delete saved copy",icon:"trash",danger:!0,action:()=>Me(e)}]:[]]:[]}const t=m.peek().find(a=>a.id===e)||(d.peek()?.id===e?d.peek():null);return t?[{label:"Open",icon:"message-circle",action:()=>j(e)},...t.email?[{label:"Email the visitor",icon:"mail",action:()=>{location.href=`mailto:${t.email}`}},{label:"Copy email address",icon:"copy",action:()=>navigator.clipboard?.writeText(t.email).then(()=>E.toast("Copied",{type:"success"})).catch(()=>{})}]:[],...t.page?[{label:"Open the page they were on",icon:"external-link",action:()=>window.open(t.page,"_blank","noopener")}]:[],...T?[{type:"divider"},{label:"Save for a closer look\u2026",icon:"bookmark",action:()=>Ee(e)}]:[],...T&&t.status!=="closed"?[{type:"divider"},{label:"End chat",icon:"x-circle",action:()=>Ce(e)}]:[],...G?[{type:"divider"},{label:"Delete",icon:"trash",danger:!0,action:()=>Te(e)}]:[]]:[]},xe=E.contextMenu(J,{cursor:"glyph",match:".chat-row",inherit:!1,density:"compact",items:e=>le(e.dataset.id)});r.add(()=>xe?.destroy?.());const Z=l.querySelector(".chats-head-kebab"),$e=E.contextMenu(Z,{cursor:"glyph",inherit:!1,density:"compact",items:()=>le(o.peek())});r.add(()=>$e?.destroy?.()),Z.addEventListener("click",()=>de(Z)),J.addEventListener("click",e=>{const t=e.target.closest(".chat-row");if(t){if(e.target.closest(".chat-row-kebab")){de(t);return}j(t.dataset.id)}}),J.addEventListener("keydown",e=>{const t=e.target.closest?.(".chat-row");t&&(e.key==="Enter"||e.key===" ")&&e.target===t&&(e.preventDefault(),j(t.dataset.id))});let N=null;async function re(){if(N)return;let e;try{e=(await u("/chats/settings")).settings}catch{E.toast("Could not read the chat settings",{type:"error"});return}if(!s()||N)return;const t=E.slideover({title:"Chat settings",size:"sm",position:"right"});N=t;const a=Fe(`
15
15
  <div class="chats-settings" style="display:flex;flex-direction:column;gap:1rem;padding:.25rem">
16
16
  <div>
17
17
  <label class="form-label" for="chat-set-conf">How sure the bot must be
@@ -50,4 +50,4 @@ import{apiRequest as De}from"../api.js";import{addBannerAction as Re}from"../lib
50
50
  <button type="button" class="btn btn-sm btn-ghost" data-on-click="cancel">Cancel</button>
51
51
  <button type="button" class="btn btn-sm btn-primary" data-on-click="save" data-bind-hidden="!canManage" data-bind-disabled="!dirty.value">Save</button>
52
52
  </div>
53
- </div>`),s={canManage:z,confidence:M.observable(e.confidence),staffName:M.observable(e.staffName),retentionDays:M.observable(String(e.retentionDays)),maxNewChatsPerHour:M.observable(String(e.maxNewChatsPerHour))};s.dirty=M.computed(()=>s.confidence.value!==e.confidence||s.staffName.value!==e.staffName||Number(s.retentionDays.value)!==e.retentionDays||Number(s.maxNewChatsPerHour.value)!==e.maxNewChatsPerHour),t.element.appendChild(a);const c=ce(a),L=M.applyBindings(s,a,{methods:{cancel:()=>t.close(),save:async()=>{try{e=(await i("/chats/settings","PUT",{confidence:s.confidence.peek(),staffName:s.staffName.peek(),retentionDays:Number(s.retentionDays.peek()),maxNewChatsPerHour:Number(s.maxNewChatsPerHour.peek())})).settings,E.toast("Chat settings saved",{type:"success"}),t.close()}catch(_){E.toast(_?.message||"Could not save",{type:"error"})}}}});Ae(t,()=>{L.dispose(),c(),N===t&&(N=null)});const $e=t.close;t.close=async(..._)=>s.dirty.peek()&&!r.leaving&&!await E.confirm("Discard your changes to the chat settings?")?!1:$e(..._),t.open()}r.add(()=>N?.close()),Re(h,{id:"chats-settings",icon:"settings",title:"Chat settings",onClick:Ne});const re=e=>{e.ctrlKey||e.metaKey||e.altKey||e.target.closest?.("input, textarea, select, [contenteditable], .dm-slideover")||(e.key==="/"&&(e.preventDefault(),l.querySelector(".chats-search input")?.focus()),e.key==="Escape"&&o.peek()&&C())};if(document.addEventListener("keydown",re),r.add(()=>document.removeEventListener("keydown",re)),I.scan(l),await w(),n()&&o.peek()){const e=o.peek();o.value="",j(e)}}};
53
+ </div>`),n={canManage:G,confidence:M.observable(e.confidence),staffName:M.observable(e.staffName),retentionDays:M.observable(String(e.retentionDays)),maxNewChatsPerHour:M.observable(String(e.maxNewChatsPerHour))};n.dirty=M.computed(()=>n.confidence.value!==e.confidence||n.staffName.value!==e.staffName||Number(n.retentionDays.value)!==e.retentionDays||Number(n.maxNewChatsPerHour.value)!==e.maxNewChatsPerHour),t.element.appendChild(a);const i=ce(a),O=M.applyBindings(n,a,{methods:{cancel:()=>t.close(),save:async()=>{try{e=(await u("/chats/settings","PUT",{confidence:n.confidence.peek(),staffName:n.staffName.peek(),retentionDays:Number(n.retentionDays.peek()),maxNewChatsPerHour:Number(n.maxNewChatsPerHour.peek())})).settings,E.toast("Chat settings saved",{type:"success"}),t.close()}catch(V){E.toast(V?.message||"Could not save",{type:"error"})}}}});Re(t,()=>{O.dispose(),i(),N===t&&(N=null)});const Ne=t.close;t.close=async(...V)=>n.dirty.peek()&&!r.leaving&&!await E.confirm("Discard your changes to the chat settings?")?!1:Ne(...V),t.open()}r.add(()=>N?.close()),Ae(h,{id:"chats-settings",icon:"settings",title:"Chat settings",onClick:re});const ie=e=>{e.ctrlKey||e.metaKey||e.altKey||e.target.closest?.("input, textarea, select, [contenteditable], .dm-slideover")||(e.key==="/"&&(e.preventDefault(),l.querySelector(".chats-search input")?.focus()),e.key==="Escape"&&o.peek()&&C())};document.addEventListener("keydown",ie),r.add(()=>document.removeEventListener("keydown",ie)),Pe(l,"chats");const Q=l.querySelector('a[href="#/launchers/knowledge"]');if(Q&&(z==="#/ai-assist"?Q.remove():Q.setAttribute("href",`${z}/knowledge`)),I.scan(l),await w(),s()&&o.peek()){const e=o.peek();o.value="",j(e)}s()&&/[?&]settings=1\b/.test(location.hash)&&(history.replaceState(null,"",b),re())}};
@@ -1 +1 @@
1
- const i={templateUrl:"",async onMount(){location.hash="#/menus"}};export const viewLoaders={projects:()=>import("./projects.js").then(e=>e.projectsView),projectDetail:()=>import("./project-detail.js").then(e=>e.projectDetailView),projectSettings:()=>import("./project-settings.js").then(e=>e.projectSettingsView),apiTokens:()=>import("./api-tokens.js").then(e=>e.apiTokensView),apiEndpoints:()=>import("./api-endpoints.js").then(e=>e.apiEndpointsView),apiEndpointEditor:()=>import("./api-endpoint-editor.js").then(e=>e.apiEndpointEditorView),dashboard:()=>import("./dashboard.js").then(e=>e.dashboardView),dashboards:()=>import("./dashboards.js").then(e=>e.dashboardsView),pages:()=>import("./pages.js").then(e=>e.pagesView),pageEditor:()=>import("./page-editor.js").then(e=>e.pageEditorView),appearance:()=>import("./appearance.js").then(e=>e.appearanceView),footer:()=>import("./footer.js").then(e=>e.footerView),settings:()=>import("./settings.js").then(e=>e.settingsView),theme:()=>import("./theme.js").then(e=>e.themeView),layouts:()=>import("./layouts.js").then(e=>e.layoutsView),media:()=>import("./media.js").then(e=>e.mediaView),login:()=>import("./login.js").then(e=>e.loginView),users:()=>import("./users.js").then(e=>e.usersView),userEditor:()=>import("./user-editor.js").then(e=>e.userEditorView),plugins:()=>import("./plugins.js").then(e=>e.pluginsView),pluginCode:()=>import("./plugin-code.js").then(e=>e.pluginCodeView),documentation:()=>import("./documentation.js").then(e=>e.documentationView),tutorials:()=>import("./tutorials.js").then(e=>e.tutorialsView),apiReference:()=>import("./api-reference.js").then(e=>e.apiReferenceView),collections:()=>import("./collections.js").then(e=>e.collectionsView),collectionEditor:()=>import("./collection-editor.js").then(e=>e.collectionEditorView),collectionEntries:()=>import("./collection-entries.js").then(e=>e.collectionEntriesView),forms:()=>import("./forms.js").then(e=>e.formsView),formEditor:()=>import("./form-editor.js").then(e=>e.formEditorView),formSubmissions:()=>import("./form-submissions.js").then(e=>e.formSubmissionsView),viewsList:()=>import("./views-list.js").then(e=>e.viewsListView),viewEditor:()=>import("./view-editor.js").then(e=>e.viewEditorView),viewPreview:()=>import("./view-preview.js").then(e=>e.viewPreviewView),actionsList:()=>import("./actions-list.js").then(e=>e.actionsListView),actionEditor:()=>import("./action-editor.js").then(e=>e.actionEditorView),proDocs:()=>import("./pro-docs.js").then(e=>e.proDocsView),blocks:()=>import("./blocks.js").then(e=>e.blocksView),components:()=>import("./components.js").then(e=>e.componentsView),myProfile:()=>import("./my-profile.js").then(e=>e.myProfileView),roles:()=>import("./roles.js").then(e=>e.rolesView),roleEditor:()=>import("./role-editor.js").then(e=>e.roleEditorView),effects:()=>import("./effects.js").then(e=>e.effectsView),search:()=>import("./search.js").then(e=>e.searchView),contentApi:()=>import("./content-api.js").then(e=>e.contentApiView),notes:()=>import("./notes.js").then(e=>e.notesView),chats:()=>import("./chats.js").then(e=>e.chatsView),chatKnowledge:()=>import("./chat-knowledge.js").then(e=>e.chatKnowledgeView),todo:()=>import("./todo.js").then(e=>e.todoView),calculator:()=>import("../lib/calculator.js").then(e=>e.calculatorView),analytics:()=>import("./analytics.js").then(e=>e.analyticsView),seo:()=>import("./seo.js").then(e=>e.seoView),wordpressImport:()=>import("./wordpress-import.js").then(e=>e.wordpressImportView),contacts:()=>import("./contacts.js").then(e=>e.contactsView),callNew:()=>import("./call-new.js").then(e=>e.callNewView),notifications:()=>import("./notifications.js").then(e=>e.notificationsView),menus:()=>import("./menus.js").then(e=>e.menusView),contextMenus:()=>import("./context-menus.js").then(e=>e.contextMenusView),launchers:()=>import("./launchers.js").then(e=>e.launchersView),contextMenuEditor:()=>import("./context-menu-editor.js").then(e=>e.contextMenuEditorView),menuEditor:()=>import("./menu-editor.js").then(e=>e.menuEditorView),menuLocations:()=>import("./menu-locations.js").then(e=>e.menuLocationsView),menusRedirect:async()=>i,pluginGuides:()=>import("./plugin-guides.js").then(e=>e.pluginGuidesView),pluginGuide:()=>import("./plugin-guides.js").then(e=>e.pluginGuideView)};for(const e of["tutorialCrud","tutorialPlugin","tutorialEditor","tutorialForms","componentsReference","componentsHowto","componentsWalkthrough","componentsRules","usagePages","usageMedia","usageNavigation","usageDconfig","usageShortcodes","usageSiteSettings","usagePlugins","usageUsersRoles","usageViews","usageActions","usageCtaShortcode","usageEditions","usageCollections","usageBlocks","usageTools","usageDashboard","usageSearchEngines","usageLaunchers","usageChat","apiRefAuthentication","apiRefPages","apiRefSettings","apiRefLayouts","apiRefNavigation","apiRefMedia","apiRefUsers","apiRefPlugins","apiRefCollections","apiRefViews","apiRefActions","apiRefForms","apiRefScaffold","apiRefExternal","apiRefContent","apiRefBuilder"])viewLoaders[e]=()=>import("./doc-pages.js").then(t=>t.docViews[e]);
1
+ const i={templateUrl:"",async onMount(){location.hash="#/menus"}};export const viewLoaders={projects:()=>import("./projects.js").then(e=>e.projectsView),projectDetail:()=>import("./project-detail.js").then(e=>e.projectDetailView),projectSettings:()=>import("./project-settings.js").then(e=>e.projectSettingsView),apiTokens:()=>import("./api-tokens.js").then(e=>e.apiTokensView),apiEndpoints:()=>import("./api-endpoints.js").then(e=>e.apiEndpointsView),apiEndpointEditor:()=>import("./api-endpoint-editor.js").then(e=>e.apiEndpointEditorView),dashboard:()=>import("./dashboard.js").then(e=>e.dashboardView),dashboards:()=>import("./dashboards.js").then(e=>e.dashboardsView),pages:()=>import("./pages.js").then(e=>e.pagesView),pageEditor:()=>import("./page-editor.js").then(e=>e.pageEditorView),appearance:()=>import("./appearance.js").then(e=>e.appearanceView),footer:()=>import("./footer.js").then(e=>e.footerView),settings:()=>import("./settings.js").then(e=>e.settingsView),theme:()=>import("./theme.js").then(e=>e.themeView),layouts:()=>import("./layouts.js").then(e=>e.layoutsView),media:()=>import("./media.js").then(e=>e.mediaView),login:()=>import("./login.js").then(e=>e.loginView),users:()=>import("./users.js").then(e=>e.usersView),userEditor:()=>import("./user-editor.js").then(e=>e.userEditorView),plugins:()=>import("./plugins.js").then(e=>e.pluginsView),pluginCode:()=>import("./plugin-code.js").then(e=>e.pluginCodeView),documentation:()=>import("./documentation.js").then(e=>e.documentationView),tutorials:()=>import("./tutorials.js").then(e=>e.tutorialsView),apiReference:()=>import("./api-reference.js").then(e=>e.apiReferenceView),collections:()=>import("./collections.js").then(e=>e.collectionsView),collectionEditor:()=>import("./collection-editor.js").then(e=>e.collectionEditorView),collectionEntries:()=>import("./collection-entries.js").then(e=>e.collectionEntriesView),forms:()=>import("./forms.js").then(e=>e.formsView),formEditor:()=>import("./form-editor.js").then(e=>e.formEditorView),formSubmissions:()=>import("./form-submissions.js").then(e=>e.formSubmissionsView),viewsList:()=>import("./views-list.js").then(e=>e.viewsListView),viewEditor:()=>import("./view-editor.js").then(e=>e.viewEditorView),viewPreview:()=>import("./view-preview.js").then(e=>e.viewPreviewView),actionsList:()=>import("./actions-list.js").then(e=>e.actionsListView),actionEditor:()=>import("./action-editor.js").then(e=>e.actionEditorView),proDocs:()=>import("./pro-docs.js").then(e=>e.proDocsView),blocks:()=>import("./blocks.js").then(e=>e.blocksView),components:()=>import("./components.js").then(e=>e.componentsView),myProfile:()=>import("./my-profile.js").then(e=>e.myProfileView),roles:()=>import("./roles.js").then(e=>e.rolesView),roleEditor:()=>import("./role-editor.js").then(e=>e.roleEditorView),effects:()=>import("./effects.js").then(e=>e.effectsView),search:()=>import("./search.js").then(e=>e.searchView),contentApi:()=>import("./content-api.js").then(e=>e.contentApiView),notes:()=>import("./notes.js").then(e=>e.notesView),chats:()=>import("./chats.js").then(e=>e.chatsView),chatKnowledge:()=>import("./chat-knowledge.js").then(e=>e.chatKnowledgeView),aiAssistChats:()=>import("./chats.js").then(e=>e.chatsView),aiAssistKnowledge:()=>import("./chat-knowledge.js").then(e=>e.chatKnowledgeView),aiAssistSettings:()=>import("./ai-assist-settings.js").then(e=>e.aiAssistSettingsView),todo:()=>import("./todo.js").then(e=>e.todoView),calculator:()=>import("../lib/calculator.js").then(e=>e.calculatorView),analytics:()=>import("./analytics.js").then(e=>e.analyticsView),seo:()=>import("./seo.js").then(e=>e.seoView),wordpressImport:()=>import("./wordpress-import.js").then(e=>e.wordpressImportView),contacts:()=>import("./contacts.js").then(e=>e.contactsView),callNew:()=>import("./call-new.js").then(e=>e.callNewView),notifications:()=>import("./notifications.js").then(e=>e.notificationsView),menus:()=>import("./menus.js").then(e=>e.menusView),contextMenus:()=>import("./context-menus.js").then(e=>e.contextMenusView),launchers:()=>import("./launchers.js").then(e=>e.launchersView),contextMenuEditor:()=>import("./context-menu-editor.js").then(e=>e.contextMenuEditorView),menuEditor:()=>import("./menu-editor.js").then(e=>e.menuEditorView),menuLocations:()=>import("./menu-locations.js").then(e=>e.menuLocationsView),menusRedirect:async()=>i,pluginGuides:()=>import("./plugin-guides.js").then(e=>e.pluginGuidesView),pluginGuide:()=>import("./plugin-guides.js").then(e=>e.pluginGuideView)};for(const e of["tutorialCrud","tutorialPlugin","tutorialEditor","tutorialForms","componentsReference","componentsHowto","componentsWalkthrough","componentsRules","usagePages","usageMedia","usageNavigation","usageDconfig","usageShortcodes","usageSiteSettings","usagePlugins","usageUsersRoles","usageViews","usageActions","usageCtaShortcode","usageEditions","usageCollections","usageBlocks","usageTools","usageDashboard","usageSearchEngines","usageLaunchers","usageChat","apiRefAuthentication","apiRefPages","apiRefSettings","apiRefLayouts","apiRefNavigation","apiRefMedia","apiRefUsers","apiRefPlugins","apiRefCollections","apiRefViews","apiRefActions","apiRefForms","apiRefScaffold","apiRefExternal","apiRefContent","apiRefBuilder"])viewLoaders[e]=()=>import("./doc-pages.js").then(t=>t.docViews[e]);
@@ -1,4 +1,4 @@
1
- import{api as k,apiRequest as f}from"../api.js";import{addBannerAction as B}from"../lib/plugin-chrome.js";import{SHAPES as $e,whileLoading as Pe}from"../lib/loading.js";import{helpPopovers as oe}from"../lib/help-popover.js";import{onceClosed as Ie,openMenuAt as ie,sidebarCount as Oe,viewLifetime as qe}from"../lib/tool-kit.js";import{DEFAULT_SETTINGS as re,FILTERS as A,arrangeNotifications as Ue,filterCounts as _e,normaliseSettings as Be,notificationRow as ce,sourceRow as Fe}from"../lib/notifications-arrange.js";import{desktopPermission as le,notificationSettings as de,primeSeen as We,requestDesktopPermission as He,showTestNotification as je}from"../lib/desktop-notify.js";const ue=/^#\/system\/notifications\/?(\?.*)?$/,Ge="#/system/notifications",F="notifications.filter",Ke=`
1
+ import{api as k,apiRequest as f}from"../api.js";import{addBannerAction as B}from"../lib/plugin-chrome.js";import{SHAPES as $e,whileLoading as Ie}from"../lib/loading.js";import{helpPopovers as oe}from"../lib/help-popover.js";import{onceClosed as Pe,openMenuAt as ie,sidebarCount as Oe,viewLifetime as qe}from"../lib/tool-kit.js";import{DEFAULT_SETTINGS as re,FILTERS as L,arrangeNotifications as Ue,filterCounts as _e,normaliseSettings as Be,notificationRow as le,sourceRow as We}from"../lib/notifications-arrange.js";import{desktopPermission as ce,notificationSettings as de,primeSeen as Fe,requestDesktopPermission as He,showTestNotification as je}from"../lib/desktop-notify.js";const pe=/^#\/system\/notifications\/?(\?.*)?$/,Ge="#/system/notifications",W="notifications.filter",Ke=`
2
2
  <div class="ntx-row" data-id="{{id}}" tabindex="0" data-bind-class="rowCls" data-bind-aria-expanded="open ? 'true' : 'false'">
3
3
  <span class="ntx-dot" aria-hidden="true"></span>
4
4
  <span class="ntx-main">
@@ -29,9 +29,9 @@ import{api as k,apiRequest as f}from"../api.js";import{addBannerAction as B}from
29
29
  <button type="button" class="btn btn-sm btn-ghost ntx-src-run" data-bind-hidden="!every">Run now</button>
30
30
  </div>
31
31
  <small class="ntx-src-err" data-bind-hidden="!lastError">{{lastError}}</small>
32
- </div>`,R={granted:"Allowed in this browser.",default:"Your browser will ask for permission when you turn this on.",denied:"Blocked in this browser. Allow notifications for this site in the browser's site settings (the icon by the address), then turn this on.",unsupported:"This browser cannot show desktop notifications here - they need a current browser and an https address."};function Je(r){const c=document.createElement("template");return c.innerHTML=r.trim(),c.content.firstElementChild}const d=qe(ue);async function b(){Oe(Ge);try{const{count:r}=await k.system.notifications.unreadCount(),c=$("#topbar-bell-badge");r>0?c.text(r>99?"99+":String(r)).removeAttr("hidden"):c.attr("hidden","").text("")}catch{}}export const notificationsView={templateUrl:"/admin/js/templates/notifications.html",async onMount(r){d.reset();const c=r.get(0).querySelector(".ntx")||r.get(0),y=()=>ue.test(location.hash)&&c.isConnected,i=M.observable([]),T=M.observable(!0),N=M.observable("");let W="all";try{W=A.includes(S.get(F))?S.get(F):"all"}catch{}const C=()=>new URLSearchParams(location.hash.split("?")[1]||"").get("type"),m=M.observable(A.includes(C())?C():W),H=()=>{y()&&A.includes(C())&&(m.value=C())},j=e=>{y()&&A.includes(e.detail?.type)&&(m.value=e.detail.type)};document.addEventListener("dm:notifications-filter",j),d.add(()=>document.removeEventListener("dm:notifications-filter",j)),window.addEventListener("hashchange",H),d.add(()=>window.removeEventListener("hashchange",H));const G=()=>{y()&&x({markRead:!1})};document.addEventListener("dm:notifications-changed",G),d.add(()=>document.removeEventListener("dm:notifications-changed",G));const K=M.observable(""),L=M.observable("");d.add(M.effect(()=>{const e=m.value;try{S.set(F,e)}catch{}}));const Y=M.computed(()=>_e(i.value));d.add(M.effect(()=>{const e=Y.value;!T.value&&m.peek()==="new"&&!e.new&&(m.value="all")}));const z=M.observable([]);d.add(M.effect(()=>{const e=Date.now(),t=L.value;z.value=Ue(i.value,{filter:m.value,query:K.value}).map(n=>ce(n,{now:e,expanded:t}))}));const pe=M.computed(()=>i.value.length?"No notifications match.":"No notifications - you're all caught up."),u=M.observable(de.read());d.add(M.effect(()=>de.write(u.value)));const D=(e,t)=>{u.value=Be({...u.peek(),[e]:t})},J=e=>i.peek().find(t=>String(t.id)===String(e)),me=(e,t)=>{i.value=i.peek().map(n=>String(n.id)===String(e)?t(n):n)},V=e=>{i.value=i.peek().filter(t=>String(t.id)!==String(e))};async function x({markRead:e=!0}={}){try{const t=i.peek().length?null:c.querySelector(".dm-loading-slot"),n=await Pe(t,k.system.notifications.list(),$e.iconRows);if(!y())return;const p=Array.isArray(n)?n:[];if(i.value=p.map(l=>({...l,isNew:!!l.unread})),N.value="",e&&p.some(l=>l.unread)){if(await f("/system/notifications/read-all",{method:"POST"}).catch(()=>{}),!y())return;i.value=i.peek().map(l=>({...l,unread:!1})),b()}}catch(t){N.value=`Could not load notifications: ${t.message||t}`}finally{T.value=!1}}async function X(e,t){try{t?await k.system.notifications.markRead(e.id):await f(`/system/notifications/${encodeURIComponent(e.id)}/unread`,{method:"POST"}),me(e.id,n=>({...n,unread:!t})),b()}catch(n){E.toast(`Not changed: ${n.message||n}`,{type:"error"})}}async function Q(e){try{await k.system.notifications.dismiss(e.id),V(e.id),b()}catch(t){E.toast(`Could not dismiss it: ${t.message||t}`,{type:"error"})}}async function he(e){if(await E.confirm(`Delete "${Ye(e.data?.title||"this notification")}" for everyone? Dismissing hides it for you only.`))try{await k.system.notifications.remove(e.id),V(e.id),E.toast("Notification deleted.",{type:"success"}),b()}catch(t){E.toast(/403|forbidden|permission/i.test(String(t.message||t))?"Deleting needs the Notifications delete permission - Dismiss hides it for you.":`Could not delete it: ${t.message||t}`,{type:"error"})}}async function fe(){const e=i.peek().length;if(!e){E.toast("Nothing to dismiss.",{type:"info"});return}if(await E.confirm(`Dismiss all ${e} notification${e===1?"":"s"}? They are hidden for you only.`))try{await f("/system/notifications/dismiss-all",{method:"POST"}),i.value=[],b()}catch(t){E.toast(`Could not dismiss them: ${t.message||t}`,{type:"error"})}}async function be(e){const t=e.data||{},n=[t.title,t.body,t.link].filter(Boolean).join(`
32
+ </div>`,R={granted:"Allowed in this browser.",default:"Your browser will ask for permission when you turn this on.",denied:"Blocked in this browser. Allow notifications for this site in the browser's site settings (the icon by the address), then turn this on.",unsupported:"This browser cannot show desktop notifications here - they need a current browser and an https address."};function Je(r){const l=document.createElement("template");return l.innerHTML=r.trim(),l.content.firstElementChild}const d=qe(pe);async function b(){Oe(Ge);try{const{count:r}=await k.system.notifications.unreadCount(),l=$("#topbar-bell-badge");r>0?l.text(r>99?"99+":String(r)).removeAttr("hidden"):l.attr("hidden","").text("")}catch{}}export const notificationsView={templateUrl:"/admin/js/templates/notifications.html",async onMount(r){d.reset();const l=r.get(0).querySelector(".ntx")||r.get(0),y=()=>pe.test(location.hash)&&l.isConnected,i=M.observable([]),T=M.observable(!0),N=M.observable("");let F="all";try{F=L.includes(S.get(W))?S.get(W):"all"}catch{}const C=()=>new URLSearchParams(location.hash.split("?")[1]||"").get("type"),h=M.observable(L.includes(C())?C():F),H=()=>{y()&&L.includes(C())&&(h.value=C())},j=e=>{y()&&L.includes(e.detail?.type)&&(h.value=e.detail.type)};document.addEventListener("dm:notifications-filter",j),d.add(()=>document.removeEventListener("dm:notifications-filter",j)),window.addEventListener("hashchange",H),d.add(()=>window.removeEventListener("hashchange",H));const G=()=>{y()&&x({markRead:!1})};document.addEventListener("dm:notifications-changed",G),d.add(()=>document.removeEventListener("dm:notifications-changed",G));const K=M.observable(""),A=M.observable("");d.add(M.effect(()=>{const e=h.value;try{S.set(W,e)}catch{}}));const Y=M.computed(()=>_e(i.value));d.add(M.effect(()=>{const e=Y.value;!T.value&&h.peek()==="new"&&!e.new&&(h.value="all")}));const z=M.observable([]);d.add(M.effect(()=>{const e=Date.now(),t=A.value;z.value=Ue(i.value,{filter:h.value,query:K.value}).map(n=>le(n,{now:e,expanded:t}))}));const ue=M.computed(()=>i.value.length?"No notifications match.":"No notifications - you're all caught up."),p=M.observable(de.read());d.add(M.effect(()=>de.write(p.value)));const D=(e,t)=>{p.value=Be({...p.peek(),[e]:t})},J=e=>i.peek().find(t=>String(t.id)===String(e)),he=(e,t)=>{i.value=i.peek().map(n=>String(n.id)===String(e)?t(n):n)},V=e=>{i.value=i.peek().filter(t=>String(t.id)!==String(e))};async function x({markRead:e=!0}={}){try{const t=i.peek().length?null:l.querySelector(".dm-loading-slot"),n=await Ie(t,k.system.notifications.list(),$e.iconRows);if(!y())return;const u=Array.isArray(n)?n:[];if(i.value=u.map(c=>({...c,isNew:!!c.unread})),N.value="",e&&u.some(c=>c.unread)){if(await f("/system/notifications/read-all",{method:"POST"}).catch(()=>{}),!y())return;i.value=i.peek().map(c=>({...c,unread:!1})),b()}}catch(t){N.value=`Could not load notifications: ${t.message||t}`}finally{T.value=!1}}async function X(e,t){try{t?await k.system.notifications.markRead(e.id):await f(`/system/notifications/${encodeURIComponent(e.id)}/unread`,{method:"POST"}),he(e.id,n=>({...n,unread:!t})),b()}catch(n){E.toast(`Not changed: ${n.message||n}`,{type:"error"})}}async function Q(e){try{await k.system.notifications.dismiss(e.id),V(e.id),b()}catch(t){E.toast(`Could not dismiss it: ${t.message||t}`,{type:"error"})}}async function me(e){if(await E.confirm(`Delete "${Ye(e.data?.title||"this notification")}" for everyone? Dismissing hides it for you only.`))try{await k.system.notifications.remove(e.id),V(e.id),E.toast("Notification deleted.",{type:"success"}),b()}catch(t){E.toast(/403|forbidden|permission/i.test(String(t.message||t))?"Deleting needs the Notifications delete permission - Dismiss hides it for you.":`Could not delete it: ${t.message||t}`,{type:"error"})}}async function fe(){const e=i.peek().length;if(!e){E.toast("Nothing to dismiss.",{type:"info"});return}if(await E.confirm(`Dismiss all ${e} notification${e===1?"":"s"}? They are hidden for you only.`))try{await f("/system/notifications/dismiss-all",{method:"POST"}),i.value=[],b()}catch(t){E.toast(`Could not dismiss them: ${t.message||t}`,{type:"error"})}}async function be(e){const t=e.data||{},n=[t.title,t.body,t.link].filter(Boolean).join(`
33
33
 
34
- `);try{await navigator.clipboard.writeText(n),E.toast("Copied.",{type:"success"})}catch{E.toast("Copying is blocked here - select the text instead.",{type:"warning"})}}const P=e=>{L.value=L.peek()===String(e)?"":String(e)};function ye(e){const t=J(e);if(!t)return[];const n=ce(t);return[{header:n.title},{label:n.open||L.peek()===n.id?"Close":"Read it",icon:"eye",action:()=>P(e)},...n.link?[n.linkTarget==="_self"?{label:"Go there",icon:"arrow-right",action:()=>{location.hash=n.link}}:{label:"Open link",icon:"external-link",action:()=>window.open(n.link,"_blank","noopener")}]:[],{label:"Copy text",icon:"copy",action:()=>be(t)},t.unread?{label:"Mark as read",icon:"check",action:()=>X(t,!0)}:{label:"Mark as unread",icon:"mail",action:()=>X(t,!1)},{type:"divider"},{label:"Dismiss",icon:"x",action:()=>Q(t)},{label:"Delete for everyone\u2026",icon:"trash",danger:!0,action:()=>he(t)}]}const v=c.querySelector(".ntx-list");v.innerHTML=Ke;const g=e=>()=>{m.value=e},ve=M.applyBindings({items:i,loading:T,loadError:N,filter:m,query:K,rows:z,counts:Y,emptyText:pe},c,{methods:{showAll:g("all"),showNew:g("new"),showCritical:g("critical"),showWarning:g("warning"),showInfo:g("info"),showSuccess:g("success")}});d.add(()=>ve.dispose()),d.add(oe(c,{position:"bottom"}));const ge=E.contextMenu(v,{cursor:"glyph",match:".ntx-row",inherit:!1,density:"compact",items:e=>ye(e.dataset.id)});d.add(()=>ge?.destroy?.());const Z=e=>{const t=e.target.closest(".ntx-row");if(!t)return;const n=e.target.closest(".ntx-kebab");if(n){ie(n);return}e.target.closest("a")||P(t.dataset.id)},ee=e=>{const t=e.target.closest(".ntx-row");if(t){if(e.key==="F10"&&e.shiftKey)e.preventDefault(),ie(t);else if(e.key==="Enter"&&e.target===t)P(t.dataset.id);else if(e.key==="Delete"&&e.target===t){const n=J(t.dataset.id);n&&Q(n)}}};v.addEventListener("click",Z),v.addEventListener("keydown",ee),d.add(()=>{v.removeEventListener("click",Z),v.removeEventListener("keydown",ee)});async function we(){try{const{added:e}=await f("/system/notifications/samples",{method:"POST"});await x({markRead:!1}),b(),E.toast(`${e} sample notifications added.${u.peek().desktop?" They pop up on the desktop within a minute.":""}`,{type:"success"})}catch(e){E.toast(/403|forbidden|permission/i.test(String(e.message||e))?"Adding samples needs the Notifications delete permission.":`Could not add samples: ${e.message||e}`,{type:"error"})}}function ke(){const e=E.slideover({title:"Notifications settings",size:"md",position:"right"}),t=Je(`
34
+ `);try{await navigator.clipboard.writeText(n),E.toast("Copied.",{type:"success"})}catch{E.toast("Copying is blocked here - select the text instead.",{type:"warning"})}}const P=e=>{A.value=A.peek()===String(e)?"":String(e)};function ye(e){const t=J(e);if(!t)return[];const n=le(t);return[{header:n.title},{label:n.open||A.peek()===n.id?"Close":"Read it",icon:"eye",action:()=>P(e)},...n.link?[n.linkTarget==="_self"?{label:"Go there",icon:"arrow-right",action:()=>{location.hash=n.link}}:{label:"Open link",icon:"external-link",action:()=>window.open(n.link,"_blank","noopener")}]:[],{label:"Copy text",icon:"copy",action:()=>be(t)},t.unread?{label:"Mark as read",icon:"check",action:()=>X(t,!0)}:{label:"Mark as unread",icon:"mail",action:()=>X(t,!1)},{type:"divider"},{label:"Dismiss",icon:"x",action:()=>Q(t)},{label:"Delete for everyone\u2026",icon:"trash",danger:!0,action:()=>me(t)}]}const v=l.querySelector(".ntx-list");v.innerHTML=Ke;const g=e=>()=>{h.value=e},ve=M.applyBindings({items:i,loading:T,loadError:N,filter:h,query:K,rows:z,counts:Y,emptyText:ue},l,{methods:{showAll:g("all"),showNew:g("new"),showCritical:g("critical"),showWarning:g("warning"),showInfo:g("info"),showSuccess:g("success")}});d.add(()=>ve.dispose()),d.add(oe(l,{position:"bottom"}));const ge=E.contextMenu(v,{cursor:"glyph",match:".ntx-row",inherit:!1,density:"compact",items:e=>ye(e.dataset.id)});d.add(()=>ge?.destroy?.());const Z=e=>{const t=e.target.closest(".ntx-row");if(!t)return;const n=e.target.closest(".ntx-kebab");if(n){ie(n);return}e.target.closest("a")||P(t.dataset.id)},ee=e=>{const t=e.target.closest(".ntx-row");if(t){if(e.key==="F10"&&e.shiftKey)e.preventDefault(),ie(t);else if(e.key==="Enter"&&e.target===t)P(t.dataset.id);else if(e.key==="Delete"&&e.target===t){const n=J(t.dataset.id);n&&Q(n)}}};v.addEventListener("click",Z),v.addEventListener("keydown",ee),d.add(()=>{v.removeEventListener("click",Z),v.removeEventListener("keydown",ee)});async function we(){try{const{added:e}=await f("/system/notifications/samples",{method:"POST"});await x({markRead:!1}),b(),E.toast(`${e} sample notifications added.${p.peek().desktop?" They pop up on the desktop within a minute.":""}`,{type:"success"})}catch(e){E.toast(/403|forbidden|permission/i.test(String(e.message||e))?"Adding samples needs the Notifications delete permission.":`Could not add samples: ${e.message||e}`,{type:"error"})}}function ke(){const e=E.slideover({title:"Notifications settings",size:"md",position:"right"}),t=Je(`
35
35
  <div class="ntx-panel">
36
36
  <div class="ntx-setting-row">
37
37
  <label class="form-label" for="ntx-set-desktop" style="margin:0">Desktop notifications
@@ -59,6 +59,12 @@ import{api as k,apiRequest as f}from"../api.js";import{addBannerAction as B}from
59
59
  </label>
60
60
  <input id="ntx-set-toasts" type="checkbox" class="form-switch" data-model="signInToasts.value">
61
61
  </div>
62
+ <div class="ntx-setting-row">
63
+ <label class="form-label" for="ntx-set-chat-toasts" style="margin:0">Chat pop-ups
64
+ <span data-help="While the admin is open, a message pops up when a visitor starts a chat, asks for a person or leaves a message, or when the AI turns a question down - with a button to open Chats. Checked every 30 seconds. Asking for a person stays until you close it."></span>
65
+ </label>
66
+ <input id="ntx-set-chat-toasts" type="checkbox" class="form-switch" data-model="chatToasts.value">
67
+ </div>
62
68
  <small class="ntx-panel-meta">Saved in this browser as you change them.</small>
63
69
  <div class="ntx-setting-row">
64
70
  <label class="form-label" style="margin:0">Sample notifications
@@ -78,4 +84,4 @@ import{api as k,apiRequest as f}from"../api.js";import{addBannerAction as B}from
78
84
  <span class="spacer"></span>
79
85
  <button type="button" class="btn btn-sm btn-primary" data-on-click="done">Done</button>
80
86
  </div>
81
- </div>`),n=t.querySelector("#ntx-set-desktop"),p=t.querySelector(".ntx-src-list");p.innerHTML=ze;const l=M.observable([]),O=M.observable([]),q=M.observable(!1),xe=M.effect(()=>{O.value=l.value.map(s=>Fe(s))}),Se=M.effect(()=>{const s=O.value;setTimeout(()=>s.forEach(a=>{const o=p.querySelector(`.ntx-src[data-id="${CSS.escape(a.id)}"] .ntx-src-aud`);o&&(o.value=a.audience)}),0)}),U=s=>{l.value=l.peek().map(a=>a.id===s.id?s:a)},te=s=>`/system/notifications/sources/${encodeURIComponent(s)}`;f("/system/notifications/sources",{method:"GET"}).then(s=>{l.value=s.sources||[],q.value=!0}).catch(()=>{q.value=!1});async function se(s,a){const o=l.peek().find(w=>w.id===s);try{const{setting:w}=await f(te(s),{method:"PUT",body:JSON.stringify(a)});U({...o,...w})}catch(w){U({...o}),E.toast(`Not saved: ${w.message||w}`,{type:"error"})}}async function Ee(s,a){a.disabled=!0;try{const o=await f(`${te(s)}/run`,{method:"POST"});o.source&&U(o.source),E.toast(o.ok?"Done - anything it found is in the list.":`It failed: ${o.error}`,{type:o.ok?"success":"error"}),await x({markRead:!1}),b()}catch(o){E.toast(`Could not run it: ${o.message||o}`,{type:"error"})}finally{a.disabled=!1}}const ne=s=>{const a=s.target.closest(".ntx-src");a&&(s.target.matches(".ntx-src-on")?se(a.dataset.id,{enabled:s.target.checked}):s.target.matches(".ntx-src-aud")&&se(a.dataset.id,{audience:s.target.value}))},ae=s=>{const a=s.target.closest(".ntx-src-run");a&&Ee(a.closest(".ntx-src").dataset.id,a)};p.addEventListener("change",ne),p.addEventListener("click",ae);const h=M.observable(le()),Te=M.computed(()=>u.value.desktop&&h.value!=="granted"?`On, but not showing: ${R[h.value]}`:R[h.value]),Me=M.computed(()=>h.value==="denied"||h.value==="unsupported"?"is-bad":""),Ce=M.computed(()=>u.value.desktop&&h.value==="granted"),_=()=>{n.checked=u.peek().desktop};function Le(){const s=le();if(s==="unsupported"||s==="denied"){h.value=s,E.toast(R[s],{type:"warning"}),_();return}(s==="granted"?Promise.resolve("granted"):He()).then(async o=>{h.value=o,o==="granted"?(We(await k.system.notifications.list().catch(()=>[])),D("desktop",!0),E.toast("Desktop notifications are on for this browser.",{type:"success"})):E.toast(o==="denied"?R.denied:"Not turned on - the browser was not given permission.",{type:"warning"}),_()})}const Ae=s=>M.computed({read:()=>u.value[s],write:a=>D(s,a)}),Re={...Object.fromEntries(Object.keys(re).map(s=>[s,Ae(s)])),desktop:M.computed({read:()=>u.value.desktop,write:s=>s?Le():D("desktop",!1)}),permText:Te,permTone:Me,canTest:Ce,sourceRows:O,sourcesShown:q};e.element.appendChild(t);const Ne=oe(t),De=M.applyBindings(Re,t,{methods:{done:()=>e.close(),reset:()=>{u.value={...re},_()},samples:()=>{we()},test:()=>{je()||E.toast("The browser would not show it - check its notification settings.",{type:"warning"})}}});Ie(e,()=>{De.dispose(),Ne(),xe(),Se(),p.removeEventListener("change",ne),p.removeEventListener("click",ae)}),e.open()}B(r,{id:"notifications-settings",icon:"settings",title:"Notifications settings",onClick:ke}),B(r,{id:"notifications-dismiss-all",icon:"check-circle",title:"Dismiss all",onClick:()=>fe()}),B(r,{id:"notifications-refresh",icon:"refresh-cw",title:"Refresh",onClick:()=>{T.value=!0,x()}}),I.scan(c),await x(),y()&&I.scan(c)}};
87
+ </div>`),n=t.querySelector("#ntx-set-desktop"),u=t.querySelector(".ntx-src-list");u.innerHTML=ze;const c=M.observable([]),O=M.observable([]),q=M.observable(!1),xe=M.effect(()=>{O.value=c.value.map(s=>We(s))}),Se=M.effect(()=>{const s=O.value;setTimeout(()=>s.forEach(a=>{const o=u.querySelector(`.ntx-src[data-id="${CSS.escape(a.id)}"] .ntx-src-aud`);o&&(o.value=a.audience)}),0)}),U=s=>{c.value=c.peek().map(a=>a.id===s.id?s:a)},te=s=>`/system/notifications/sources/${encodeURIComponent(s)}`;f("/system/notifications/sources",{method:"GET"}).then(s=>{c.value=s.sources||[],q.value=!0}).catch(()=>{q.value=!1});async function se(s,a){const o=c.peek().find(w=>w.id===s);try{const{setting:w}=await f(te(s),{method:"PUT",body:JSON.stringify(a)});U({...o,...w})}catch(w){U({...o}),E.toast(`Not saved: ${w.message||w}`,{type:"error"})}}async function Ee(s,a){a.disabled=!0;try{const o=await f(`${te(s)}/run`,{method:"POST"});o.source&&U(o.source),E.toast(o.ok?"Done - anything it found is in the list.":`It failed: ${o.error}`,{type:o.ok?"success":"error"}),await x({markRead:!1}),b()}catch(o){E.toast(`Could not run it: ${o.message||o}`,{type:"error"})}finally{a.disabled=!1}}const ne=s=>{const a=s.target.closest(".ntx-src");a&&(s.target.matches(".ntx-src-on")?se(a.dataset.id,{enabled:s.target.checked}):s.target.matches(".ntx-src-aud")&&se(a.dataset.id,{audience:s.target.value}))},ae=s=>{const a=s.target.closest(".ntx-src-run");a&&Ee(a.closest(".ntx-src").dataset.id,a)};u.addEventListener("change",ne),u.addEventListener("click",ae);const m=M.observable(ce()),Te=M.computed(()=>p.value.desktop&&m.value!=="granted"?`On, but not showing: ${R[m.value]}`:R[m.value]),Ce=M.computed(()=>m.value==="denied"||m.value==="unsupported"?"is-bad":""),Me=M.computed(()=>p.value.desktop&&m.value==="granted"),_=()=>{n.checked=p.peek().desktop};function Ae(){const s=ce();if(s==="unsupported"||s==="denied"){m.value=s,E.toast(R[s],{type:"warning"}),_();return}(s==="granted"?Promise.resolve("granted"):He()).then(async o=>{m.value=o,o==="granted"?(Fe(await k.system.notifications.list().catch(()=>[])),D("desktop",!0),E.toast("Desktop notifications are on for this browser.",{type:"success"})):E.toast(o==="denied"?R.denied:"Not turned on - the browser was not given permission.",{type:"warning"}),_()})}const Le=s=>M.computed({read:()=>p.value[s],write:a=>D(s,a)}),Re={...Object.fromEntries(Object.keys(re).map(s=>[s,Le(s)])),desktop:M.computed({read:()=>p.value.desktop,write:s=>s?Ae():D("desktop",!1)}),permText:Te,permTone:Ce,canTest:Me,sourceRows:O,sourcesShown:q};e.element.appendChild(t);const Ne=oe(t),De=M.applyBindings(Re,t,{methods:{done:()=>e.close(),reset:()=>{p.value={...re},_()},samples:()=>{we()},test:()=>{je()||E.toast("The browser would not show it - check its notification settings.",{type:"warning"})}}});Pe(e,()=>{De.dispose(),Ne(),xe(),Se(),u.removeEventListener("change",ne),u.removeEventListener("click",ae)}),e.open()}B(r,{id:"notifications-settings",icon:"settings",title:"Notifications settings",onClick:ke}),B(r,{id:"notifications-dismiss-all",icon:"check-circle",title:"Dismiss all",onClick:()=>fe()}),B(r,{id:"notifications-refresh",icon:"refresh-cw",title:"Refresh",onClick:()=>{T.value=!0,x()}}),I.scan(l),await x(),y()&&I.scan(l)}};
@@ -1,11 +1,11 @@
1
- import{api as $,apiRequest as w}from"../api.js";import{placeTools as Oe,WITHHELD_URL as Re}from"../lib/sidebar-grouping.js";import{addBannerAction as me}from"../lib/plugin-chrome.js";import{helpPopovers as Ie}from"../lib/help-popover.js";import{openMenuAt as G,sidebarCount as fe}from"../lib/tool-kit.js";import{changedTabs as Ae,describeCacheKey as J,draftOf as De,expiresIn as He,formFromDraft as Pe,siteSettingsForm as $e,homeValue as Be,siteSettingsPayload as je,siteUrlError as he,settingsProblems as Ue,snapshot as ve,TAB_FIELDS as qe}from"../lib/site-settings-arrange.js";import{pickMedia as _e}from"../lib/media-picker.js";import{makeIconInput as Ke}from"../lib/shortcode-modal.js";import{fmtDateTime as Fe}from"../lib/dates.js";const Q=/^\/settings(\?.*)?$/,be="#/settings",g="settings.draft",We=`
1
+ import{api as $,apiRequest as g}from"../api.js";import{placeTools as Re,WITHHELD_URL as Ie}from"../lib/sidebar-grouping.js";import{addBannerAction as fe}from"../lib/plugin-chrome.js";import{helpPopovers as Ae}from"../lib/help-popover.js";import{openMenuAt as G,sidebarCount as he}from"../lib/tool-kit.js";import{changedTabs as De,describeCacheKey as J,draftOf as He,expiresIn as Pe,formFromDraft as $e,siteSettingsForm as Be,homeValue as je,siteSettingsPayload as Ue,siteUrlError as ve,settingsProblems as qe,snapshot as be,TAB_FIELDS as _e}from"../lib/site-settings-arrange.js";import{pickMedia as Ke}from"../lib/media-picker.js";import{makeIconInput as Fe}from"../lib/shortcode-modal.js";import{fmtDateTime as We}from"../lib/dates.js";const Q=/^\/settings(\?.*)?$/,ge="#/settings",y="settings.draft",ze=`
2
2
  <div class="stx-problem">
3
3
  <span class="stx-chip" data-bind-class="tone === 'danger' ? 'is-bad' : 'is-warn'">{{label}}</span>
4
4
  <span>{{text}}</span>
5
5
  <button type="button" class="btn btn-sm btn-ghost" data-go="{{tab}}">Go there</button>
6
- </div>`,ze=`
6
+ </div>`,Ne=`
7
7
  <div class="stx-row" data-id="{{id}}" tabindex="0">
8
8
  <span class="stx-main"><strong>{{path}}</strong><small>{{meta}}</small></span>
9
9
  <span class="stx-chip">{{expires}}</span>
10
10
  <button type="button" class="stx-kebab" aria-label="Actions for {{path}}" title="Actions">\u22EE</button>
11
- </div>`,B=["general","branding","email","cookies","cache"];async function Ne(c,l){const[r,y]=await Promise.all([H.get("/api/sidebar/menu").catch(()=>({items:[]})),H.get("/api/sidebar/registered-items").catch(()=>[])]),n=new Map([["/","Dashboard (built in)"]]),i=(p,u)=>{for(const o of p||[]){if(!o||o.hidden||o.restricted)continue;const a=typeof o.url=="string"?o.url:"";a.startsWith(Re)||(a.startsWith("#/")&&a.length>2&&!n.has(a.slice(1))&&n.set(a.slice(1),`${u?`${u} \u203A `:""}${o.text||a}`),i(o.items,o.url?u:o.text||u))}},k=(y||[]).filter(p=>!/^~\d+$/.test(String(p?.item?.text||"")));i(Oe(r?.items||[],k),""),n.has(l)||n.set(l,`${l} (not in the sidebar)`),c.replaceChildren();for(const[p,u]of n){const o=document.createElement("option");o.value=p,o.textContent=u,c.appendChild(o)}}let f=null,ge=!1;function Ve(){ge||!window.R?.use||(ge=!0,R.use((c,l,r)=>!(Q.test(l?.path||"")&&!Q.test(c?.path||""))||!f?.dirty()?r():E.confirm("You have unsaved settings. Leave anyway? They are kept as a draft for your next visit (not the SMTP password).").then(n=>{n?r():history.replaceState(null,"","#/settings")})),M.subscribe("router:afterChange",({to:c}={})=>{if(f&&!Q.test(c?.path||"")){const l=f;f=null,l.dispose()}}))}export const settingsView={templateUrl:"/admin/js/templates/settings.html",async onMount(c){if(Ve(),f){const e=f;f=null,e.dispose()}const l=[],r=e=>(l.push(e),e);let y=!1;const n=c.get(0).querySelector(".stx")||c.get(0),i=()=>!y&&n.isConnected,k=E.loader(c.get(0),{type:"dots"});let p;try{p=await $.settings.get()}catch(e){k.destroy(),E.toast(`Could not load the settings: ${e.message||e}`,{type:"error"});return}if(k.destroy(),!n.isConnected)return;const u=M.observable(p||{}),o=$e(p||{}),a={};for(const[e,t]of Object.entries(o))a[e]=M.observable(t);const j=()=>Object.fromEntries(Object.keys(a).map(e=>[e,a[e].value])),X=()=>Object.fromEntries(Object.keys(a).map(e=>[e,a[e].peek()])),v=M.observable(o),U=M.computed(()=>ve(v.value)),x=M.computed(()=>ve(j())!==U.value),C=M.observable(!1),T=M.observable(""),Z=M.observable(!1);$.plugins.policy().then(e=>{i()&&(Z.value=e?.signedOnly===!1)}).catch(()=>{});const q=M.observable(!1),ee=M.computed(()=>{const e=new Set(Ae(j(),v.value));return Object.fromEntries(Object.keys(qe).map(t=>[t,e.has(t)]))}),_=M.observable([]);r(M.effect(()=>{_.value=Ue(j(),u.value).map(e=>({...e,label:e.tone==="danger"?"Mail":"Check"}))}));const te=M.observable(""),L=M.observable(!1),O=M.observable(""),A=M.observable(""),m=M.observable(null),K=M.observable([]),F=M.observable(""),W=M.observable(!0),z=M.observable(""),se=M.observable([]);r(M.effect(()=>{const e=F.value.trim().toLowerCase(),t=Date.now();se.value=[...K.value].reverse().filter(s=>!e||String(s.key).toLowerCase().includes(e)||(s.tags||[]).some(d=>String(d).toLowerCase().includes(e))).map(s=>{const d=J(s.key);return{id:s.key,path:d.path,meta:[d.page?`as ${d.role}`:"not a page",(s.tags||[]).join(", ")].filter(Boolean).join(" \xB7 "),expires:He(s.expiresAt,t)}})}));const ye={...a,saving:C,dirty:x,tabs:ee,problems:_,testTo:te,testing:L,testResult:O,testTone:A,cacheQuery:F,cacheLoading:W,cacheError:z,cacheRows:se,errorText:T,problemsText:M.computed(()=>_.value.length?"yes":""),siteUrlError:M.computed(()=>he(a.siteUrl.value)),noSmtp:M.computed(()=>!String(a.smtpHost.value||"").trim()),mayAllowInsecureTLS:Z,dirtyEmail:M.computed(()=>ee.value.email),cacheOn:M.computed(()=>m.value?.enabled===!0),cacheState:M.computed(()=>{const e=m.value;return e?e.enabled?`On (${e.driver})`:"Off":"Status unknown"}),cacheSize:M.computed(()=>{const e=m.value;return e?.enabled&&e.size!==null&&e.size!==void 0?`${e.size}${e.maxItems?` of ${e.maxItems}`:""} entries`:""}),cacheHits:M.computed(()=>{const e=m.value?.hitRate;return e==null?"":`${Math.round(e*100)}% served from the cache`}),cacheToggleText:M.computed(()=>m.value?.enabled?"Turn off":"Turn on"),cacheEmpty:M.computed(()=>F.value.trim()?"Nothing matches.":m.value?.enabled?"The cache is empty - pages are cached as visitors open them.":"The cache is off.")};async function N(){if(C.peek())return;const e=X(),t=v.peek(),s=he(e.siteUrl);if(s){E.toast(`Site URL: ${s}`,{type:"error"});return}C.value=!0,T.value="";const d=String(e.title).trim()!==String(t.title).trim();try{await $.settings.save(je(e,u.peek(),{adminHomeReady:q.peek()})),window.dispatchEvent(new Event("admin-assistant:settings"));const P=await $.settings.get().catch(()=>null);if(!i())return;P&&(u.value=P);const Le={...e,smtpPass:""};a.smtpPass.value="",v.value=Le;try{S.remove?S.remove(g):S.set(g,null)}catch{}document.dispatchEvent(new CustomEvent("dm:admin-home-changed")),(d||["adminBrandEnabled","adminBrandTitle","adminBrandLogo","adminBrandLogoDark","adminBrandIcon"].some(pe=>e[pe]!==t[pe]))&&document.dispatchEvent(new CustomEvent("dm:sidebar-rebuild")),fe(be),E.toast("Settings saved.",{type:"success"})}catch(P){T.value=P.message||"Could not save the settings.",E.toast("Settings not saved - see the message at the top.",{type:"error"})}finally{C.value=!1}}async function we(){await E.confirm("Throw away your unsaved settings?")&&(ae(v.peek()),T.value="")}function ae(e){for(const[t,s]of Object.entries(e))a[t]&&(a[t].value=s)}async function ke(){if(!L.peek()){L.value=!0,A.value="",O.value="Sending\u2026";try{const e=await w("/settings/test-email",{method:"POST",body:JSON.stringify({to:te.peek().trim()||void 0})});if(!i())return;O.value=e?.message||"Test email sent.",A.value="is-ok"}catch(e){if(!i())return;O.value=e.message||"Could not send the test email.",A.value="is-bad"}finally{L.value=!1}}}async function D(){W.value=!0;try{const[e,t]=await Promise.all([w("/cache/status").catch(()=>null),w("/cache/keys")]);if(!i())return;m.value=e,K.value=Array.isArray(t?.entries)?t.entries:[],z.value=""}catch(e){if(!i())return;z.value=`Could not read the cache: ${e.message||e}`}finally{W.value=!1}}async function Ee(){if(await E.confirm("Clear the whole response cache? The next visitor to each page renders it afresh.")){try{await w("/cache/clear",{method:"POST"}),E.toast("Cache cleared.",{type:"success"})}catch(e){E.toast(e.message||"Could not clear the cache.",{type:"error"})}i()&&await D()}}async function Se(){const e=m.peek()?.enabled===!0;if(!(e&&!await E.confirm("Turn the response cache off? Every visit will render its page afresh until it is turned back on. The choice is saved (config/cache.json)."))){try{m.value=await w("/cache/toggle",{method:"POST",body:JSON.stringify({enabled:!e})}),E.toast(e?"Cache turned off.":"Cache turned on.",{type:"success"}),fe(be)}catch(t){E.toast(t.message||"Could not change the cache.",{type:"error"})}i()&&await D()}}const ne=e=>K.peek().find(t=>t.key===e);function Me(e){const t=ne(e);if(!t)return[];const s=J(t.key);return[{header:s.path},{label:"Open the page",icon:"external-link",disabled:!s.page,action:()=>window.open(s.path,"_blank","noopener")},{label:"Copy key",icon:"copy",action:async()=>{try{await navigator.clipboard.writeText(t.key),E.toast("Key copied.",{type:"success"})}catch{E.toast("Could not copy - your browser blocked the clipboard.",{type:"warning"})}}},...s.page?[{label:"Copy address",icon:"link",action:async()=>{try{await navigator.clipboard.writeText(new URL(s.path,location.origin).href),E.toast("Address copied.",{type:"success"})}catch{E.toast("Could not copy - your browser blocked the clipboard.",{type:"warning"})}}}]:[]]}n.querySelector(".stx-problems").innerHTML=We;const b=n.querySelector(".stx-list");b.innerHTML=ze;const V=E.tabs(n.querySelector(".stx-tabs"),{tabSelector:".tab-item",panelSelector:".tab-panel"}),oe=new URLSearchParams(location.hash.split("?")[1]||"").get("tab");B.includes(oe)&&V.activate(B.indexOf(oe));const xe=M.applyBindings(ye,n,{methods:{save:N,discard:we,sendTest:ke,refreshCache:D,clearCache:Ee,toggleCache:Se,pickBrandImage:async e=>{const t=await _e({title:"Choose a branding image",current:a[e].peek()});t&&i()&&(a[e].value=t)},clearBrandImage:e=>{a[e].value=""},goTab:e=>{const t=B.indexOf(e);t>=0&&V.activate(t)}}});r(()=>xe.dispose());for(const e of n.querySelectorAll("[data-brand-icon]")){const t=e.dataset.brandIcon,s=Ke("Choose an icon",a[t].peek());s.input.id=`stx-${t}`,s.input.classList.add("form-input");const d=()=>{a[t].value=s.input.value};s.input.addEventListener("input",d),r(()=>s.input.removeEventListener("input",d)),r(M.effect(()=>{s.input.value=a[t].value})),e.appendChild(s.el)}r(Ie(n,{position:"bottom"}));const Ce=e=>{const t=e.target.closest("[data-go]");if(!t)return;const s=B.indexOf(t.dataset.go);s>=0&&V.activate(s)};n.querySelector(".stx-problems").addEventListener("click",Ce);const Y=n.querySelector("#stx-admin-home");Ne(Y,Be(a.adminHome.peek())).then(()=>{i()&&(Y.value=a.adminHome.peek(),q.value=!0)}).catch(()=>{});const Te=E.contextMenu(b,{cursor:"glyph",match:".stx-row",inherit:!1,density:"compact",items:e=>Me(e.dataset.id)});r(()=>Te?.destroy?.());const re=e=>{const t=ne(e.dataset.id),s=t&&J(t.key);s?.page?window.open(s.path,"_blank","noopener"):G(e)},ie=e=>{const t=e.target.closest(".stx-row");if(!t)return;const s=e.target.closest(".stx-kebab");if(s){G(s);return}re(t)},ce=e=>{const t=e.target.closest(".stx-row");t&&(e.key==="F10"&&e.shiftKey?(e.preventDefault(),G(t)):e.key==="Enter"&&e.target===t&&re(t))};b.addEventListener("click",ie),b.addEventListener("keydown",ce),r(()=>{b.removeEventListener("click",ie),b.removeEventListener("keydown",ce)}),me(c,{id:"settings-view-site",icon:"external-link",title:"View site",onClick:()=>window.open("/","_blank","noopener")}),me(c,{id:"settings-save",icon:"save",title:"Save (Ctrl+S)",onClick:()=>N()});const le=e=>{!(e.ctrlKey||e.metaKey)||e.key!=="s"||(e.preventDefault(),e.stopImmediatePropagation(),N())};document.addEventListener("keydown",le,!0),r(()=>document.removeEventListener("keydown",le,!0));const ue=()=>{if(x.peek())try{S.set(g,{form:De(X()),base:U.peek(),at:new Date().toISOString()})}catch{}},de=e=>{x.peek()&&(ue(),e.preventDefault(),e.returnValue="")};window.addEventListener("beforeunload",de),r(()=>window.removeEventListener("beforeunload",de)),f={dirty:()=>x.peek(),dispose(){y=!0,ue(),l.splice(0).reverse().forEach(e=>{try{e()}catch{}})}},I.scan(n),D();let h=null;try{h=S.get(g)}catch{}if(h?.form){try{S.remove?S.remove(g):S.set(g,null)}catch{}const e=h.base&&h.base!==U.peek(),t=h.at?` (${Fe(h.at)})`:"",s=e?`You left unsaved settings${t}, but the saved settings have changed since. Restore your version anyway?`:`You left unsaved settings${t}. Restore them?`;await E.confirm(s)&&i()&&(ae(Pe(v.peek(),h.form)),q.peek()&&(Y.value=a.adminHome.peek()))}}};
11
+ </div>`,B=["general","branding","email","cookies","cache"];async function Ve(c,l){const[r,w]=await Promise.all([H.get("/api/sidebar/menu").catch(()=>({items:[]})),H.get("/api/sidebar/registered-items").catch(()=>[])]),n=new Map([["/","Dashboard (built in)"]]),i=(p,u)=>{for(const o of p||[]){if(!o||o.hidden||o.restricted)continue;const a=typeof o.url=="string"?o.url:"";a.startsWith(Ie)||(a.startsWith("#/")&&a.length>2&&!n.has(a.slice(1))&&n.set(a.slice(1),`${u?`${u} \u203A `:""}${o.text||a}`),i(o.items,o.url?u:o.text||u))}},k=(w||[]).filter(p=>!/^~\d+$/.test(String(p?.item?.text||"")));i(Re(r?.items||[],k),""),n.has(l)||n.set(l,`${l} (not in the sidebar)`),c.replaceChildren();for(const[p,u]of n){const o=document.createElement("option");o.value=p,o.textContent=u,c.appendChild(o)}}let f=null,ye=!1;function Ye(){ye||!window.R?.use||(ye=!0,R.use((c,l,r)=>!(Q.test(l?.path||"")&&!Q.test(c?.path||""))||!f?.dirty()?r():E.confirm("You have unsaved settings. Leave anyway? They are kept as a draft for your next visit (not the SMTP password).").then(n=>{n?r():history.replaceState(null,"","#/settings")})),M.subscribe("router:afterChange",({to:c}={})=>{if(f&&!Q.test(c?.path||"")){const l=f;f=null,l.dispose()}}))}export const settingsView={templateUrl:"/admin/js/templates/settings.html",async onMount(c){if(Ye(),f){const e=f;f=null,e.dispose()}const l=[],r=e=>(l.push(e),e);let w=!1;const n=c.get(0).querySelector(".stx")||c.get(0),i=()=>!w&&n.isConnected,k=E.loader(c.get(0),{type:"dots"});let p;try{p=await $.settings.get()}catch(e){k.destroy(),E.toast(`Could not load the settings: ${e.message||e}`,{type:"error"});return}if(k.destroy(),!n.isConnected)return;const u=M.observable(p||{}),o=Be(p||{}),a={};for(const[e,t]of Object.entries(o))a[e]=M.observable(t);const j=()=>Object.fromEntries(Object.keys(a).map(e=>[e,a[e].value])),X=()=>Object.fromEntries(Object.keys(a).map(e=>[e,a[e].peek()])),v=M.observable(o),U=M.computed(()=>be(v.value)),x=M.computed(()=>be(j())!==U.value),C=M.observable(!1),T=M.observable(""),Z=M.observable(!1);$.plugins.policy().then(e=>{i()&&(Z.value=e?.signedOnly===!1)}).catch(()=>{});const q=M.observable(!1),ee=M.computed(()=>{const e=new Set(De(j(),v.value));return Object.fromEntries(Object.keys(_e).map(t=>[t,e.has(t)]))}),_=M.observable([]);r(M.effect(()=>{_.value=qe(j(),u.value).map(e=>({...e,label:e.tone==="danger"?"Mail":"Check"}))}));const te=M.observable(""),L=M.observable(!1),O=M.observable(""),A=M.observable(""),m=M.observable(null),K=M.observable([]),F=M.observable(""),W=M.observable(!0),z=M.observable(""),se=M.observable([]);r(M.effect(()=>{const e=F.value.trim().toLowerCase(),t=Date.now();se.value=[...K.value].reverse().filter(s=>!e||String(s.key).toLowerCase().includes(e)||(s.tags||[]).some(d=>String(d).toLowerCase().includes(e))).map(s=>{const d=J(s.key);return{id:s.key,path:d.path,meta:[d.page?`as ${d.role}`:"not a page",(s.tags||[]).join(", ")].filter(Boolean).join(" \xB7 "),expires:Pe(s.expiresAt,t)}})}));const ae=M.observable(!1);g("/ai-assist").catch(()=>null).then(e=>{i()&&(ae.value=e?.on===!0)});const we={...a,saving:C,dirty:x,tabs:ee,problems:_,testTo:te,testing:L,testResult:O,testTone:A,aiAssistOn:ae,cacheQuery:F,cacheLoading:W,cacheError:z,cacheRows:se,errorText:T,problemsText:M.computed(()=>_.value.length?"yes":""),siteUrlError:M.computed(()=>ve(a.siteUrl.value)),noSmtp:M.computed(()=>!String(a.smtpHost.value||"").trim()),mayAllowInsecureTLS:Z,dirtyEmail:M.computed(()=>ee.value.email),cacheOn:M.computed(()=>m.value?.enabled===!0),cacheState:M.computed(()=>{const e=m.value;return e?e.enabled?`On (${e.driver})`:"Off":"Status unknown"}),cacheSize:M.computed(()=>{const e=m.value;return e?.enabled&&e.size!==null&&e.size!==void 0?`${e.size}${e.maxItems?` of ${e.maxItems}`:""} entries`:""}),cacheHits:M.computed(()=>{const e=m.value?.hitRate;return e==null?"":`${Math.round(e*100)}% served from the cache`}),cacheToggleText:M.computed(()=>m.value?.enabled?"Turn off":"Turn on"),cacheEmpty:M.computed(()=>F.value.trim()?"Nothing matches.":m.value?.enabled?"The cache is empty - pages are cached as visitors open them.":"The cache is off.")};async function N(){if(C.peek())return;const e=X(),t=v.peek(),s=ve(e.siteUrl);if(s){E.toast(`Site URL: ${s}`,{type:"error"});return}C.value=!0,T.value="";const d=String(e.title).trim()!==String(t.title).trim();try{await $.settings.save(Ue(e,u.peek(),{adminHomeReady:q.peek()})),window.dispatchEvent(new Event("admin-assistant:settings"));const P=await $.settings.get().catch(()=>null);if(!i())return;P&&(u.value=P);const Oe={...e,smtpPass:""};a.smtpPass.value="",v.value=Oe;try{S.remove?S.remove(y):S.set(y,null)}catch{}document.dispatchEvent(new CustomEvent("dm:admin-home-changed")),(d||["adminBrandEnabled","adminBrandTitle","adminBrandLogo","adminBrandLogoDark","adminBrandIcon"].some(me=>e[me]!==t[me]))&&document.dispatchEvent(new CustomEvent("dm:sidebar-rebuild")),he(ge),E.toast("Settings saved.",{type:"success"})}catch(P){T.value=P.message||"Could not save the settings.",E.toast("Settings not saved - see the message at the top.",{type:"error"})}finally{C.value=!1}}async function ke(){await E.confirm("Throw away your unsaved settings?")&&(ne(v.peek()),T.value="")}function ne(e){for(const[t,s]of Object.entries(e))a[t]&&(a[t].value=s)}async function Ee(){if(!L.peek()){L.value=!0,A.value="",O.value="Sending\u2026";try{const e=await g("/settings/test-email",{method:"POST",body:JSON.stringify({to:te.peek().trim()||void 0})});if(!i())return;O.value=e?.message||"Test email sent.",A.value="is-ok"}catch(e){if(!i())return;O.value=e.message||"Could not send the test email.",A.value="is-bad"}finally{L.value=!1}}}async function D(){W.value=!0;try{const[e,t]=await Promise.all([g("/cache/status").catch(()=>null),g("/cache/keys")]);if(!i())return;m.value=e,K.value=Array.isArray(t?.entries)?t.entries:[],z.value=""}catch(e){if(!i())return;z.value=`Could not read the cache: ${e.message||e}`}finally{W.value=!1}}async function Se(){if(await E.confirm("Clear the whole response cache? The next visitor to each page renders it afresh.")){try{await g("/cache/clear",{method:"POST"}),E.toast("Cache cleared.",{type:"success"})}catch(e){E.toast(e.message||"Could not clear the cache.",{type:"error"})}i()&&await D()}}async function Me(){const e=m.peek()?.enabled===!0;if(!(e&&!await E.confirm("Turn the response cache off? Every visit will render its page afresh until it is turned back on. The choice is saved (config/cache.json)."))){try{m.value=await g("/cache/toggle",{method:"POST",body:JSON.stringify({enabled:!e})}),E.toast(e?"Cache turned off.":"Cache turned on.",{type:"success"}),he(ge)}catch(t){E.toast(t.message||"Could not change the cache.",{type:"error"})}i()&&await D()}}const oe=e=>K.peek().find(t=>t.key===e);function xe(e){const t=oe(e);if(!t)return[];const s=J(t.key);return[{header:s.path},{label:"Open the page",icon:"external-link",disabled:!s.page,action:()=>window.open(s.path,"_blank","noopener")},{label:"Copy key",icon:"copy",action:async()=>{try{await navigator.clipboard.writeText(t.key),E.toast("Key copied.",{type:"success"})}catch{E.toast("Could not copy - your browser blocked the clipboard.",{type:"warning"})}}},...s.page?[{label:"Copy address",icon:"link",action:async()=>{try{await navigator.clipboard.writeText(new URL(s.path,location.origin).href),E.toast("Address copied.",{type:"success"})}catch{E.toast("Could not copy - your browser blocked the clipboard.",{type:"warning"})}}}]:[]]}n.querySelector(".stx-problems").innerHTML=ze;const b=n.querySelector(".stx-list");b.innerHTML=Ne;const V=E.tabs(n.querySelector(".stx-tabs"),{tabSelector:".tab-item",panelSelector:".tab-panel"}),re=new URLSearchParams(location.hash.split("?")[1]||"").get("tab");B.includes(re)&&V.activate(B.indexOf(re));const Ce=M.applyBindings(we,n,{methods:{save:N,discard:ke,sendTest:Ee,refreshCache:D,clearCache:Se,toggleCache:Me,pickBrandImage:async e=>{const t=await Ke({title:"Choose a branding image",current:a[e].peek()});t&&i()&&(a[e].value=t)},clearBrandImage:e=>{a[e].value=""},goTab:e=>{const t=B.indexOf(e);t>=0&&V.activate(t)}}});r(()=>Ce.dispose());for(const e of n.querySelectorAll("[data-brand-icon]")){const t=e.dataset.brandIcon,s=Fe("Choose an icon",a[t].peek());s.input.id=`stx-${t}`,s.input.classList.add("form-input");const d=()=>{a[t].value=s.input.value};s.input.addEventListener("input",d),r(()=>s.input.removeEventListener("input",d)),r(M.effect(()=>{s.input.value=a[t].value})),e.appendChild(s.el)}r(Ae(n,{position:"bottom"}));const Te=e=>{const t=e.target.closest("[data-go]");if(!t)return;const s=B.indexOf(t.dataset.go);s>=0&&V.activate(s)};n.querySelector(".stx-problems").addEventListener("click",Te);const Y=n.querySelector("#stx-admin-home");Ve(Y,je(a.adminHome.peek())).then(()=>{i()&&(Y.value=a.adminHome.peek(),q.value=!0)}).catch(()=>{});const Le=E.contextMenu(b,{cursor:"glyph",match:".stx-row",inherit:!1,density:"compact",items:e=>xe(e.dataset.id)});r(()=>Le?.destroy?.());const ie=e=>{const t=oe(e.dataset.id),s=t&&J(t.key);s?.page?window.open(s.path,"_blank","noopener"):G(e)},ce=e=>{const t=e.target.closest(".stx-row");if(!t)return;const s=e.target.closest(".stx-kebab");if(s){G(s);return}ie(t)},le=e=>{const t=e.target.closest(".stx-row");t&&(e.key==="F10"&&e.shiftKey?(e.preventDefault(),G(t)):e.key==="Enter"&&e.target===t&&ie(t))};b.addEventListener("click",ce),b.addEventListener("keydown",le),r(()=>{b.removeEventListener("click",ce),b.removeEventListener("keydown",le)}),fe(c,{id:"settings-view-site",icon:"external-link",title:"View site",onClick:()=>window.open("/","_blank","noopener")}),fe(c,{id:"settings-save",icon:"save",title:"Save (Ctrl+S)",onClick:()=>N()});const ue=e=>{!(e.ctrlKey||e.metaKey)||e.key!=="s"||(e.preventDefault(),e.stopImmediatePropagation(),N())};document.addEventListener("keydown",ue,!0),r(()=>document.removeEventListener("keydown",ue,!0));const de=()=>{if(x.peek())try{S.set(y,{form:He(X()),base:U.peek(),at:new Date().toISOString()})}catch{}},pe=e=>{x.peek()&&(de(),e.preventDefault(),e.returnValue="")};window.addEventListener("beforeunload",pe),r(()=>window.removeEventListener("beforeunload",pe)),f={dirty:()=>x.peek(),dispose(){w=!0,de(),l.splice(0).reverse().forEach(e=>{try{e()}catch{}})}},I.scan(n),D();let h=null;try{h=S.get(y)}catch{}if(h?.form){try{S.remove?S.remove(y):S.set(y,null)}catch{}const e=h.base&&h.base!==U.peek(),t=h.at?` (${We(h.at)})`:"",s=e?`You left unsaved settings${t}, but the saved settings have changed since. Restore your version anyway?`:`You left unsaved settings${t}. Restore them?`;await E.confirm(s)&&i()&&(ne($e(v.peek(),h.form)),q.peek()&&(Y.value=a.adminHome.peek()))}}};
@@ -1237,7 +1237,7 @@ The four Tools below were plugins until 0.67.0 and are now part of the CMS. They
1237
1237
  - The bot (`server/services/chat/matcher.js`, pure): normalises text (accents, contractions, punctuation), drops stop words, stems lightly (bookings/booked/booking -> book), folds synonym groups onto one word (cost/fee/charge -> price, open/hours/close, delivery/shipping/postage, ...), forgives a one-edit typo in words of five letters or more, and weights words by rarity across the Knowledge. A phrasing's score blends how much of the question it covers with how much of the phrasing the question covers, plus a bonus when one contains the other and a nudge per keyword. `answer` (one clear winner over a margin), `suggest` (top three "Did you mean", plus None of these), or `none` (logged as unanswered; after two misses in a row it offers a person). Handover phrases ("talk to a person", "real human", "customer service"), greetings and thanks are recognised first. Confidence Strict / Balanced / Relaxed in the settings cog.
1238
1238
  - Storage: four presets - `chat-knowledge`, `chat-sessions`, `chat-messages`, `chat-unanswered` (`CHAT_PRESET_SLUGS`) - declared MongoDB and resolved like the user-data presets (`MONGO_ELIGIBLE_PRESET_SLUGS`, adapterRegistry `resolveUserDataPreset`): MongoDB where the site has a working connection and the files hold none of their rows, files otherwise; the storage block survives the reseed. Through the generic collections API, views, forms and endpoints they need `chats.manage` (collectionAccess `CORE_TOOL_COLLECTIONS`). Four example Knowledge entries (marked `sample`, removable in one click) are added once per site (`config/chat.json` `examplesSeeded`).
1239
1239
  - Visitor API `/api/chat/*` (`config`, `state` poll, `send`, `pick`, `person`, `details`, `end`): 404 unless `launcher` names an enabled chat launcher (`services/chat/launcher-bridge.js` asks `services/launchers.js` `chatLaunchers()`; the launcher's chat settings are always read server-side). The chat is the visitor's by a random 256-bit token in the `X-Chat-Token` header (only its SHA-256 is stored; kept in the browser as `chat:<launcherId>`); resumable for a day, two weeks after leaving a message. Plain text, 1000 characters, 300 messages a chat; per-route rate limits; per address 6 new chats and 120 messages an hour, and `maxNewChatsPerHour` (300) new chats for the whole site; a honeypot, a missing `_t` or a first message within 1.5s is dropped quietly; details only where the launcher asks and the chat was offered the form (else 403); a bot answer is stored as its Knowledge id plus a 200-character snapshot; messages are numbered within the chat and choices offered by position, so no internal id reaches the browser. Answers render through a strict sanitiser (paragraphs, lists, emphasis, code, http(s)/mailto/tel/site-path links).
1240
- - Hand-over: with staff available (the Chats screen open and Available on - memory presence, 75s) the chat goes to `waiting` and staff are notified (source `core:chat`, admins); with nobody available the visitor leaves name and email (`message`) unless the launcher says never; `askDetails: always` asks before putting them through. A staff reply makes it `open` and the bot stays quiet. Hourly tidy-up closes quiet chats (bot 2h, waiting/open 24h) and deletes ended ones after `retentionDays` (90) - bot-only chats with no details after 7 days - with their messages and any orphan messages, one write per collection (adapters' `removeMany`). Chats in memory are an LRU of 2000; unknown tokens are remembered for a minute. A Launchers module that is missing refuses every chat.
1240
+ - Hand-over: with staff available (the Chats screen open and Available on - memory presence, 75s) the chat goes to `waiting` and staff are notified (source `core:chat`, admins); a visitor's first message notifies admins too (`core:chat-started`, one per chat), and so does a question the AI turned down (`core:chat-declined`, one per chat, said again in place: the Manager's launcher-chat answer carries `declined: true` when Claude's reply starts `DECLINED:`, which it strips); open admins get these as toasts with an Open Chats button (lib/chat-toast.js: the bell's poll, now every 30s, fetches the list when the unread count rises; per-browser "Chat pop-ups" setting, on by default; "wants a person" stays until closed); with nobody available the visitor leaves name and email (`message`) unless the launcher says never; `askDetails: always` asks before putting them through. A staff reply makes it `open` and the bot stays quiet. Hourly tidy-up closes quiet chats (bot 2h, waiting/open 24h) and deletes ended ones after `retentionDays` (90) - bot-only chats with no details after 7 days - with their messages and any orphan messages, one write per collection (adapters' `removeMany`). Chats in memory are an LRU of 2000; unknown tokens are remembered for a minute. A Launchers module that is missing refuses every chat.
1241
1241
  - Admin: **Content > Chats** (`#/launchers/chats`, `#/launchers/chats/:id`) - the inbox, waiting first, the live thread (3s poll), replies with per-chat drafts, end/delete/email in a context menu, Available switch, settings cog; sidebar badge `/api/chats/_count` (live while someone waits, red after 5 minutes). **Chats > Knowledge** (`#/launchers/knowledge`) - entries with an editor slideover (question, other ways of asking, keywords, Markdown answer, up to five buttons, on/off), Try the bot with scores, and the Unanswered list (Make an entry, add to the closest entry, dismiss). Visitor panel `public/js/launcher-chat.mjs` `mountChat(container, {launcherId, title, chat})` + `public/css/launcher-chat.css`, domma-reactive.
1242
1242
  - Permission `chats` (`read`, `reply`, `manage`) in the Tools group; Admin is granted it once. All of it is behind the Launchers switch.
1243
1243
  - AI Assist (unreleased): the paid `ai-assist` Tool (Pro plan) calls `hooks.enableAiAssist()` (`services/aiAssist.js`, paid + closedSource only, off when the Tool is disabled). Without it `aiAvailable()` is false (chat config says `ai: false`, nothing is asked) and the admin assistant is unavailable (`requestAdminAnswer` 403). `GET /api/launchers/items` says `aiAssist`, and the launcher editor notes under AI answers when it is off. The Manager checks the `ai-assist` licence (no longer the Site Builder's).
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "domma-cms",
3
- "version": "1.58.0",
3
+ "version": "1.60.0",
4
4
  "description": "File-based CMS powered by Domma and Fastify. Run npx domma-cms my-site to create a new project.",
5
5
  "type": "module",
6
6
  "main": "server/server.js",
@@ -3,9 +3,14 @@ import {authenticate as defaultAuthenticate} from '../../middleware/auth.js';
3
3
  import {getConfig} from '../../config.js';
4
4
  import {siteAssistant} from '../../services/assistant.js';
5
5
  import {adminAssistantConfig, adminAssistantContext, requestAdminAnswer} from '../../services/adminAssistant.js';
6
+ import {chatsHome, isAiAssist} from '../../services/aiAssist.js';
7
+ import {isToolEnabled} from '../../services/tools.js';
6
8
 
7
- export async function adminAssistantRoutes(fastify, {authenticate = defaultAuthenticate, contextFor = adminAssistantContext, settings = adminAssistantConfig, answer = requestAdminAnswer} = {}) {
9
+ export async function adminAssistantRoutes(fastify, {authenticate = defaultAuthenticate, contextFor = adminAssistantContext, settings = adminAssistantConfig, answer = requestAdminAnswer,
10
+ aiAssist = isAiAssist, chatsOn = () => isToolEnabled('launchers')} = {}) {
8
11
  const guard = {preHandler: [authenticate]};
12
+ // Whether this site has AI Assist (Pro) - the admin's screen, routes and pop-ups follow it.
13
+ fastify.get('/ai-assist', guard, async () => ({on: aiAssist() === true, chats: chatsOn() === true, chatsHome: chatsHome()}));
9
14
  fastify.get('/admin-assistant/config', guard, async request => {
10
15
  const cfg = settings();
11
16
  if (!cfg.enabled) return {enabled: false};