domma-cms 1.59.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,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()))}}};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "domma-cms",
3
- "version": "1.59.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};
package/server/server.js CHANGED
@@ -778,6 +778,17 @@ try {
778
778
  (await import('./services/passwordReset.js')).registerPasswordChangeNotice({log: app.log});
779
779
 
780
780
  await registerPlugins(app);
781
+ // AI Assist (Pro) owns every chat: its screen takes the Chats entry's place, which keeps
782
+ // its spot in a saved menu. Plugins load once per process (a switch restarts it).
783
+ {
784
+ const {isAiAssist} = await import('./services/aiAssist.js');
785
+ if (isAiAssist()) {
786
+ const url = isToolEnabled('launchers') ? '#/ai-assist/chats' : '#/ai-assist/settings';
787
+ registerSidebarItem({item: {source: 'Built in', text: 'AI Assist', url, icon: 'sparkles', permission: isToolEnabled('launchers') ? 'chats' : 'settings',
788
+ ...(isToolEnabled('launchers') && {countUrl: '/api/chats/_count'})}});
789
+ hideSidebarUrl('#/launchers/chats', url);
790
+ }
791
+ }
781
792
  // After the plugins' onRequest hooks - see serve() in services/adminAssets.js.
782
793
  adminAssets.serve();
783
794
 
@@ -38,6 +38,18 @@ export function isAiAssist() {
38
38
  return owners.size > 0;
39
39
  }
40
40
 
41
+ /** The AI Assist screen (admin #/ai-assist): Chats, Knowledge and Settings when the Tool is on. */
42
+ export const AI_ASSIST_CHATS = '#/ai-assist/chats';
43
+ export const LAUNCHER_CHATS = '#/launchers/chats';
44
+
45
+ /**
46
+ * Where the staff answer chats: AI Assist owns every chat on a site that has it;
47
+ * a site without it keeps the plain Chats screen under Launchers.
48
+ */
49
+ export function chatsHome() {
50
+ return isAiAssist() ? AI_ASSIST_CHATS : LAUNCHER_CHATS;
51
+ }
52
+
41
53
  /** Tests only: forget every owner. */
42
54
  export function _resetAiAssistForTests() {
43
55
  owners.clear();
@@ -22,6 +22,7 @@
22
22
  */
23
23
  import {match} from './matcher.js';
24
24
  import {notify, registerNotificationSource, resolveNotification} from '../notify.js';
25
+ import {chatsHome} from '../aiAssist.js';
25
26
  import {
26
27
  addMessage, cleanText, countHit, forgetSession, getSession, knowledgeIndex, listSessions, logUnanswered, messagesAfter,
27
28
  patchSession, removeSession, removeSessionsAndOrphans, renderAnswer, staffAvailable, withChat
@@ -86,10 +87,17 @@ function raise(session, kind) {
86
87
  const notice = kind === 'message'
87
88
  ? {severity: 'info', title: `${who} left a message in chat`, body: `Nobody was available, so they left their details${d.visitorEmail ? ` (${d.visitorEmail})` : ''}.${about}${where}`}
88
89
  : {severity: 'warning', title: `${who} wants to talk to a person`, body: `They are waiting in chat now.${about}${where}`};
89
- return notify({...notice, source: SOURCE, dedupeKey: noticeKey(session.id), link: '#/launchers/chats'}).catch(() => null);
90
+ return notify({...notice, source: SOURCE, dedupeKey: noticeKey(session.id), link: chatsHome()}).catch(() => null);
90
91
  }
91
92
 
92
- const settle = (id) => resolveNotification(noticeKey(id), SOURCE).catch(() => 0);
93
+ /**
94
+ * Someone took the chat, or it ended: its "wants a person" and "started a chat"
95
+ * notices are settled, which also closes their pop-ups in every admin (chat-toast.js).
96
+ */
97
+ const settle = (id) => Promise.all([
98
+ resolveNotification(noticeKey(id), SOURCE).catch(() => 0),
99
+ resolveNotification(`chat-started:${id}`, STARTED_SOURCE).catch(() => 0)
100
+ ]);
93
101
 
94
102
  /** What the admins are told about the chat: the visitor's words (as the Chats screen shows them) and the page. */
95
103
  const quoted = (text) => `"${cleanText(text, 200).replace(/\n/g, ' ')}"`;
@@ -100,7 +108,7 @@ function raiseStarted(session, text, chat) {
100
108
  const where = d.page ? `\nPage: ${d.page}` : '';
101
109
  const who = chat.bot ? `${chat.botName || 'The bot'} is answering.` : 'It is waiting for a person.';
102
110
  return notify({severity: 'info', title: `${d.visitorName || 'A visitor'} started a chat`, body: `${quoted(text)}\n\n${who}${where}`,
103
- source: STARTED_SOURCE, dedupeKey: `chat-started:${session.id}`, link: '#/launchers/chats'}).catch(() => null);
111
+ source: STARTED_SOURCE, dedupeKey: `chat-started:${session.id}`, link: chatsHome()}).catch(() => null);
104
112
  }
105
113
 
106
114
  /** The AI turned a question down. One notice per chat, said again in place for the next. */
@@ -109,7 +117,7 @@ function raiseDeclined(session, text, chat) {
109
117
  const where = d.page ? `\nPage: ${d.page}` : '';
110
118
  return notify({severity: 'info', title: `${chat.botName || 'The bot'} turned down a question in chat`,
111
119
  body: `${d.visitorName || 'A visitor'} asked: ${quoted(text)}\n\nIt is off-topic or against the launcher's rules, so it was not answered.${where}`,
112
- source: DECLINED_SOURCE, dedupeKey: `chat-declined:${session.id}`, link: '#/launchers/chats'}).catch(() => null);
120
+ source: DECLINED_SOURCE, dedupeKey: `chat-declined:${session.id}`, link: chatsHome()}).catch(() => null);
113
121
  }
114
122
 
115
123
  // ---------------------------------------------------------------------------
@@ -99,7 +99,7 @@ const _registeredSidebarItems = [];
99
99
  */
100
100
  const TOOL_GROUPS = new Map(Object.entries({
101
101
  Productivity: ['#/notes', '#/todo', '#/calculator', '#/plugins/calendar', '#/plugins/waypoint-pro', '#/plugins/sheets'],
102
- Communication: ['#/contacts', '#/plugins/contacts-pro', '#/plugins/mail-reader', '#/plugins/email-pro', '#/plugins/messages'],
102
+ Communication: ['#/ai-assist/chats', '#/ai-assist/settings', '#/contacts', '#/plugins/contacts-pro', '#/plugins/mail-reader', '#/plugins/email-pro', '#/plugins/messages'],
103
103
  Marketing: ['#/analytics', '#/seo', '#/plugins/analytics-pro/dashboard', '#/plugins/social', '#/plugins/feedback', '#/plugins/surveys', '#/plugins/campaigns-pro', '#/plugins/ecards'],
104
104
  Publishing: ['#/plugins/blog', '#/plugins/blog-pro', '#/plugins/docs', '#/plugins/theme-roller', '#/plugins/wiki', '#/plugins/wiki-pro', '#/plugins/scraper', '#/plugins/scraper-pro'],
105
105
  Business: ['#/plugins/shopping-cart', '#/plugins/booking', '#/plugins/booking-pro', '#/plugins/invoice', '#/job-board', '#/plugins/garage', '#/plugins/takeaway', '#/plugins/support', '#/plugins/onboard-pro'],