@prodantix/sdk 0.4.1 → 0.4.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/chat.cjs +12 -7
- package/dist/chat.js +21 -16
- package/dist/messenger.iife.js +8 -3
- package/package.json +1 -1
package/dist/chat.cjs
CHANGED
|
@@ -1,10 +1,10 @@
|
|
|
1
|
-
'use strict';var G=Object.defineProperty;var q=(a,e,t)=>e in a?G(a,e,{enumerable:true,configurable:true,writable:true,value:t}):a[e]=t;var l=(a,e,t)=>q(a,typeof e!="symbol"?e+"":e,t);function F(a){if(a)return a;let e=globalThis.fetch;if(typeof e=="function")return e.bind(globalThis)}function H(a){return a.replace(/\/+$/,"")}var W="X-Prodantix-Conversation-Token",L="prodantix.chat.handle";function Y(){let a=globalThis.localStorage;if(a)return {get:e=>a.getItem(e),remove:e=>a.removeItem(e),set:(e,t)=>a.setItem(e,t)}}var k=class{constructor(e){this.options=e;l(this,"fetchImpl");l(this,"host");l(this,"storage");l(this,"handle");l(this,"identity",null);this.fetchImpl=F(e.fetchImpl),this.host=H(e.host),this.storage=e.storage??Y(),this.handle=this.readHandle();}get hasThread(){return this.handle!==null}avatarUrl(e){return e.startsWith("/")?`${this.host}${e}?api_key=${encodeURIComponent(this.options.apiKey)}`:e}get socketAuth(){return this.handle?{conversationId:this.handle.conversationId,conversationToken:this.handle.token,projectKey:this.options.apiKey}:null}identify(e){this.identity=e;}async ensureThread(e){if(this.handle)return true;let t=await this.request("POST","/v1/conversations",{body:{distinctId:this.options.distinctId,subject:e,userHash:this.identity?.userHash,userId:this.identity?.userId}});return !t?.conversationId||!t.token?false:(this.handle={conversationId:t.conversationId,token:t.token},this.storage?.set(L,JSON.stringify(this.handle)),true)}async send(e,t){if(!await this.ensureThread())return null;let n=this.handle;return n?(await this.request("POST",`/v1/conversations/${encodeURIComponent(n.conversationId)}/turns`,{body:{body:e,pageContext:t},token:n.token}))?.turn??null:null}async load(){let e=this.handle;return e?this.request("GET",`/v1/conversations/${encodeURIComponent(e.conversationId)}`,{token:e.token}):null}readHandle(){let e=this.storage?.get(L);if(!e)return null;try{let t=JSON.parse(e);if(typeof t.conversationId=="string"&&typeof t.token=="string")return {conversationId:t.conversationId,token:t.token}}catch{}return this.storage?.remove(L),null}async request(e,t,n={}){let r=this.fetchImpl;if(!r)return this.options.onError?.(new Error("no fetch available for prodantix chat")),null;let o={authorization:`Bearer ${this.options.apiKey}`,"content-type":"application/json"};n.token&&(o[W]=n.token);try{let s=await r(`${this.host}${t}`,{body:n.body===void 0?void 0:JSON.stringify(n.body),headers:o,method:e}),i=await s.text();return s.ok?i?JSON.parse(i):{}:(this.options.onError?.(new Error(`prodantix chat ${t}: ${s.status}`)),null)}catch(s){return this.options.onError?.(s),null}}};var j={Fri:"fri",Mon:"mon",Sat:"sat",Sun:"sun",Thu:"thu",Tue:"tue",Wed:"wed"};function w(a,e){let t=new Intl.DateTimeFormat(void 0,{hour:"2-digit",hour12:false,minute:"2-digit",timeZone:a.timezone,weekday:"short"}).formatToParts(e),n=j[t.find(i=>i.type==="weekday")?.value??""];if(!n)return false;let r=t.find(i=>i.type==="hour")?.value??"",o=t.find(i=>i.type==="minute")?.value??"",s=`${r}:${o}`;return a.windows.some(i=>i.days.includes(n)&&i.open<=s&&s<i.close)}var u={bubbleFill:"filled",bubbleShape:"tailed",composerShape:"round",dayDividers:true,launcherContent:"glyph",launcherFill:"outlined",launcherShape:"circle",launcherSize:"small",nameAvatar:true,namePlacement:"hidden",skin:"standard",stampContent:"time",stampPlacement:"none"},J=["quiet","standard"],V=["round","square"],X=["rounded","tailed"],Z=["filled","outlined"],Q=["circle","pill","squircle"],ee=["filled","outlined"],te=["avatar","glyph","team_faces"],ne=["large","medium","small"],ae=["above","hidden","inline"],re=["beside_name","none","under_turn"],ie=["time","time_and_latency"],f=(a,e,t)=>typeof a=="string"&&e.includes(a)?a:t,R=(a,e)=>typeof a=="boolean"?a:e,oe={avatar_circle:["circle","outlined","avatar","large"],circle_filled:["circle","filled","glyph","medium"],circle_outlined:["circle","outlined","glyph","small"],pill_labelled:["pill","filled","glyph","medium"],pill_team:["pill","outlined","team_faces","medium"],squircle_filled:["squircle","filled","glyph","medium"]},se={above:["above",false],avatar_only:["hidden",true],gutter:["above",true],hidden:["hidden",false],inline:["inline",false]},le={cluster:[true,"none","time"],latency:[false,"beside_name","time_and_latency"],none:[false,"none","time"],trailing:[false,"under_turn","time"],with_name:[false,"beside_name","time"]},ce={concierge:["standard","round"],console:["standard","square"],quiet:["quiet","square"]},de={hairline:["rounded","outlined"],outlined:["rounded","outlined"],rounded:["rounded","filled"],tailed:["tailed","filled"]};function C(a){let e=typeof a=="object"&&a!==null?a:{},t=typeof e.launcherStyle=="string"?e.launcherStyle:void 0,n=t===void 0?void 0:oe[t],r=typeof e.namePlacement=="string"?e.namePlacement:void 0,o=r===void 0?void 0:se[r],s=typeof e.timestampStyle=="string"?e.timestampStyle:void 0,i=s===void 0?void 0:le[s],h=typeof e.skin=="string"?e.skin:void 0,d=h===void 0?void 0:ce[h],c=typeof e.bubbleStyle=="string"?e.bubbleStyle:void 0,p=c===void 0?void 0:de[c],m={bubbleFill:f(e.bubbleFill,Z,p?.[1]??u.bubbleFill),bubbleShape:f(e.bubbleShape,X,p?.[0]??u.bubbleShape),composerShape:f(e.composerShape,V,d?.[1]??u.composerShape),dayDividers:R(e.dayDividers,i?.[0]??u.dayDividers),launcherContent:f(e.launcherContent,te,n?.[2]??u.launcherContent),launcherFill:f(e.launcherFill,ee,n?.[1]??u.launcherFill),launcherShape:f(e.launcherShape,Q,n?.[0]??u.launcherShape),launcherSize:f(e.launcherSize,ne,n?.[3]??u.launcherSize),nameAvatar:R(e.nameAvatar,o?.[1]??u.nameAvatar),namePlacement:f(e.namePlacement,ae,o?.[0]??u.namePlacement),skin:f(e.skin,J,d?.[0]??u.skin),stampContent:f(e.stampContent,ie,i?.[2]??u.stampContent),stampPlacement:f(e.stampPlacement,re,i?.[1]??u.stampPlacement)};return m.stampPlacement==="beside_name"&&m.namePlacement==="hidden"&&(m.stampPlacement="under_turn"),m}function M(a){let e=a.split(/\s+/).filter(n=>n.length>0);return (e.length>1?`${e[0]?.slice(0,1)}${e[1]?.slice(0,1)}`:e[0]?.slice(0,2)??"").toUpperCase()}var pe="M20 11.6a7.4 7.4 0 0 1-7.4 7.4H8.2L4 21.8l1-4.1A7.4 7.4 0 1 1 20 11.6Z",he={large:66,medium:56,small:46},ue={circle:"width:var(--fab-size);height:var(--fab-size);border-radius:calc(var(--fab-size) / 2);",pill:"width:auto;height:var(--fab-size);border-radius:calc(var(--fab-size) / 2);padding:0 22px;gap:10px;",squircle:"width:var(--fab-size);height:var(--fab-size);border-radius:16px;"},me={filled:"background:var(--a);color:#fff;",outlined:"background:var(--paper);border:1px solid var(--hairline);color:var(--ink-2);box-shadow:0 1px 2px rgba(0,0,0,.08);"},ge={avatar:"",glyph:".launcher svg{width:calc(var(--fab-size) * 0.375);height:calc(var(--fab-size) * 0.375);}",team_faces:".launcher .faces{display:flex;}.launcher .faces .av{box-shadow:0 0 0 2px var(--paper);}.launcher .faces .av+.av{margin-left:-10px;}"},fe=".launcher .live{width:10px;height:10px;position:absolute;right:3px;bottom:3px;border-radius:50%;background:var(--online);box-shadow:0 0 0 2px var(--paper);}.launcher.closed .live{display:none}",be={circle:"",pill:".badge{position:static;box-shadow:none}",squircle:""},ye={filled:"",outlined:".badge{background:var(--a);top:-7px;right:-7px;min-width:19px;height:19px;font-size:11.5px}"},xe={circle:"",pill:".launcher .label{font-size:14px;font-weight:600;white-space:nowrap;}",squircle:""},ve={circle:"",pill:"@media (max-width:480px){.launcher{width:var(--fab-size);padding:0}.launcher .label{display:none}}",squircle:""};function O(a,e,t,n){return `.launcher{--fab-size:${he[n]}px;${ue[a]}${me[e]}}${ge[t]}${fe}${be[a]}${ye[e]}${xe[a]}${ve[a]}`}function $(a,e,t,n=r=>r){let r=document.createDocumentFragment();if(a==="glyph"||t.length===0){let o=document.createElement("span");return o.innerHTML=`<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="${pe}"/></svg>`,r.append(...o.childNodes,N()),r}return a==="avatar"?(r.append(z(t[0],e,n),N()),r):(r.append(P(t,e,n),N()),r)}function P(a,e,t=n=>n){let n=document.createElement("span");n.className="faces";for(let r of a.slice(0,2))n.append(z(r,e,t));return n}function z(a,e,t){let n=document.createElement("span");if(n.className="av",n.setAttribute("aria-hidden","true"),a&&(n.style.background=a.tone),a?.avatarUrl){let r=document.createElement("img");return r.alt="",r.src=t(a.avatarUrl),n.append(r),n}return n.textContent=a?a.initials:e.agentLabel.slice(0,2).toUpperCase(),n}function N(){let a=document.createElement("span");return a.className="live",a.setAttribute("aria-hidden","true"),a}var Se={agentLabel:"Agent",aiLabel:"AI",awayBody:"We are away right now, but we will reply as soon as we are back.",closeLabel:"Close chat",emptyBody:"We usually reply within a few minutes.",emptyTitle:"Ask us anything.",inputPlaceholder:"Type a message",launcherLabel:"Chat with us",replyTime:"Usually replying in a few minutes",retryLabel:"Not delivered. Retry",sendLabel:"Send",timeLabel:a=>{let e=new Date(a);return Number.isNaN(e.getTime())?"":`${String(e.getHours()).padStart(2,"0")}:${String(e.getMinutes()).padStart(2,"0")}`},title:"Support",unreadLabel:a=>`${a} unread`},x={accentColor:"#5b5bff",availability:{timezone:"UTC",windows:[]},awayMessage:"",greeting:"",launcherOffsetX:20,launcherOffsetY:20,launcherPosition:"bottom_right",starterPrompts:[],team:[],...u},ke={quiet:".composer{position:relative;padding:8px 10px 10px}.composer input{padding-right:36px}.composer button{position:absolute;top:50%;right:14px;width:28px;min-width:28px;height:28px;padding:0;background:transparent;color:var(--ink);border-radius:7px;transform:translateY(-50%)}.composer button .sendglyph{display:block;width:16px;height:16px}.composer button .sendtext{display:none}.panel{border-radius:8px;box-shadow:0 2px 8px rgba(0,0,0,.12)}.header{background:var(--paper);color:var(--ink);height:44px;padding:0 8px 0 16px;border-bottom:1px solid var(--hairline)}.header h2{font-size:11px;letter-spacing:.11em;text-transform:uppercase;color:var(--ink-3)}.header .status{color:var(--ink-3)}.header .av,.header .status .live{box-shadow:0 0 0 2px var(--paper)}.close{color:var(--ink-2)}",standard:".panel{border-radius:16px;box-shadow:0 16px 40px rgba(0,0,0,.2)}.header{background:var(--a);color:#fff;flex-direction:column;align-items:flex-start;gap:14px;padding:18px 14px 20px 20px}.header h2{font-size:19px;font-weight:640}"},Ce={round:".composer{padding:10px 10px 12px;gap:6px}.composer input{height:36px;border-radius:18px;padding:0 14px}.composer button{width:36px;min-width:36px;height:36px;padding:0;border-radius:18px}.composer button .sendglyph{display:block}.composer button .sendtext{display:none}",square:".composer input{height:36px;border-radius:8px;padding:0 12px}"},Ee={rounded:".turn{border-radius:18px;padding:10px 15px}",tailed:".turn.agent,.turn.ai{border-radius:12px 12px 12px 4px}.turn.end_user{border-radius:12px 12px 4px 12px}"},we={filled:"",outlined:".turn{background:none;border:1px solid var(--hairline)}.turn.end_user{background:none;border-color:var(--a);color:var(--ink)}"},Te={above:"",hidden:".turn.agent .author,.turn.ai .author:not(.ai){display:none}",inline:".body .author.below{display:block;margin:4px 0 0;font-size:11.5px;font-weight:500;color:var(--ink-2);text-transform:none;letter-spacing:0;opacity:1}"},Ae=".turn.agent,.turn.ai{display:flex;gap:10px;max-width:100%;background:none;padding:0}.turn.agent .body,.turn.ai .body{background:var(--fill);padding:9px 13px;border-radius:inherit}.author{text-transform:none;letter-spacing:0;font-size:12.5px;font-weight:600;opacity:1}",Le='.divider{display:flex;align-items:center;gap:10px;margin:0;font-size:11px;opacity:.6}.divider:before,.divider:after{content:"";flex:1;height:1px;background:var(--hairline)}',Ne={beside_name:".stamp{font-size:11px;opacity:.7;margin-left:6px}",none:"",under_turn:".stamp{display:block;font-size:11px;opacity:.7;margin-top:4px}.turn.end_user .stamp{text-align:right}"},Pe=".lat{font-size:11px;opacity:.7;margin-left:6px}",B=`--paper: oklch(24.6% 0.015 257); --ink: #fff; --ink-3: rgba(255,255,255,.55);
|
|
1
|
+
'use strict';var G=Object.defineProperty;var q=(n,e,t)=>e in n?G(n,e,{enumerable:true,configurable:true,writable:true,value:t}):n[e]=t;var l=(n,e,t)=>q(n,typeof e!="symbol"?e+"":e,t);function F(n){if(n)return n;let e=globalThis.fetch;if(typeof e=="function")return e.bind(globalThis)}function H(n){return n.replace(/\/+$/,"")}var j="X-Prodantix-Conversation-Token",L="prodantix.chat.handle";function W(){let n=globalThis.localStorage;if(n)return {get:e=>n.getItem(e),remove:e=>n.removeItem(e),set:(e,t)=>n.setItem(e,t)}}var k=class{constructor(e){this.options=e;l(this,"fetchImpl");l(this,"host");l(this,"storage");l(this,"handle");l(this,"identity",null);this.fetchImpl=F(e.fetchImpl),this.host=H(e.host),this.storage=e.storage??W(),this.handle=this.readHandle();}get hasThread(){return this.handle!==null}avatarUrl(e){return e.startsWith("/")?`${this.host}${e}?api_key=${encodeURIComponent(this.options.apiKey)}`:e}get socketAuth(){return this.handle?{conversationId:this.handle.conversationId,conversationToken:this.handle.token,projectKey:this.options.apiKey}:null}identify(e){this.identity=e;}async ensureThread(e){if(this.handle)return true;let t=await this.request("POST","/v1/conversations",{body:{distinctId:this.options.distinctId,subject:e,userHash:this.identity?.userHash,userId:this.identity?.userId}});return !t?.conversationId||!t.token?false:(this.handle={conversationId:t.conversationId,token:t.token},this.storage?.set(L,JSON.stringify(this.handle)),true)}async send(e,t){if(!await this.ensureThread())return null;let a=this.handle;return a?(await this.request("POST",`/v1/conversations/${encodeURIComponent(a.conversationId)}/turns`,{body:{body:e,pageContext:t},token:a.token}))?.turn??null:null}async load(){let e=this.handle;return e?this.request("GET",`/v1/conversations/${encodeURIComponent(e.conversationId)}`,{token:e.token}):null}readHandle(){let e=this.storage?.get(L);if(!e)return null;try{let t=JSON.parse(e);if(typeof t.conversationId=="string"&&typeof t.token=="string")return {conversationId:t.conversationId,token:t.token}}catch{}return this.storage?.remove(L),null}async request(e,t,a={}){let r=this.fetchImpl;if(!r)return this.options.onError?.(new Error("no fetch available for prodantix chat")),null;let i={authorization:`Bearer ${this.options.apiKey}`,"content-type":"application/json"};a.token&&(i[j]=a.token);try{let s=await r(`${this.host}${t}`,{body:a.body===void 0?void 0:JSON.stringify(a.body),headers:i,method:e}),o=await s.text();return s.ok?o?JSON.parse(o):{}:(this.options.onError?.(new Error(`prodantix chat ${t}: ${s.status}`)),null)}catch(s){return this.options.onError?.(s),null}}};var Y={Fri:"fri",Mon:"mon",Sat:"sat",Sun:"sun",Thu:"thu",Tue:"tue",Wed:"wed"};function w(n,e){let t=new Intl.DateTimeFormat(void 0,{hour:"2-digit",hour12:false,minute:"2-digit",timeZone:n.timezone,weekday:"short"}).formatToParts(e),a=Y[t.find(o=>o.type==="weekday")?.value??""];if(!a)return false;let r=t.find(o=>o.type==="hour")?.value??"",i=t.find(o=>o.type==="minute")?.value??"",s=`${r}:${i}`;return n.windows.some(o=>o.days.includes(a)&&o.open<=s&&s<o.close)}var u={bubbleFill:"filled",bubbleShape:"tailed",composerShape:"round",dayDividers:true,launcherContent:"glyph",launcherFill:"outlined",launcherShape:"circle",launcherSize:"small",nameAvatar:true,namePlacement:"hidden",skin:"standard",stampContent:"time",stampPlacement:"none"},V=["quiet","standard"],J=["round","square"],X=["rounded","tailed"],Z=["filled","outlined"],Q=["circle","pill","squircle"],ee=["filled","outlined"],te=["avatar","glyph","team_faces"],ne=["large","medium","small"],ae=["above","hidden","inline"],re=["beside_name","none","under_turn"],ie=["time","time_and_latency"],f=(n,e,t)=>typeof n=="string"&&e.includes(n)?n:t,R=(n,e)=>typeof n=="boolean"?n:e,oe={avatar_circle:["circle","outlined","avatar","large"],circle_filled:["circle","filled","glyph","medium"],circle_outlined:["circle","outlined","glyph","small"],pill_labelled:["pill","filled","glyph","medium"],pill_team:["pill","outlined","team_faces","medium"],squircle_filled:["squircle","filled","glyph","medium"]},se={above:["above",false],avatar_only:["hidden",true],gutter:["above",true],hidden:["hidden",false],inline:["inline",false]},le={cluster:[true,"none","time"],latency:[false,"beside_name","time_and_latency"],none:[false,"none","time"],trailing:[false,"under_turn","time"],with_name:[false,"beside_name","time"]},ce={concierge:["standard","round"],console:["standard","square"],quiet:["quiet","square"]},de={hairline:["rounded","outlined"],outlined:["rounded","outlined"],rounded:["rounded","filled"],tailed:["tailed","filled"]};function C(n){let e=typeof n=="object"&&n!==null?n:{},t=typeof e.launcherStyle=="string"?e.launcherStyle:void 0,a=t===void 0?void 0:oe[t],r=typeof e.namePlacement=="string"?e.namePlacement:void 0,i=r===void 0?void 0:se[r],s=typeof e.timestampStyle=="string"?e.timestampStyle:void 0,o=s===void 0?void 0:le[s],h=typeof e.skin=="string"?e.skin:void 0,d=h===void 0?void 0:ce[h],c=typeof e.bubbleStyle=="string"?e.bubbleStyle:void 0,p=c===void 0?void 0:de[c],m={bubbleFill:f(e.bubbleFill,Z,p?.[1]??u.bubbleFill),bubbleShape:f(e.bubbleShape,X,p?.[0]??u.bubbleShape),composerShape:f(e.composerShape,J,d?.[1]??u.composerShape),dayDividers:R(e.dayDividers,o?.[0]??u.dayDividers),launcherContent:f(e.launcherContent,te,a?.[2]??u.launcherContent),launcherFill:f(e.launcherFill,ee,a?.[1]??u.launcherFill),launcherShape:f(e.launcherShape,Q,a?.[0]??u.launcherShape),launcherSize:f(e.launcherSize,ne,a?.[3]??u.launcherSize),nameAvatar:R(e.nameAvatar,i?.[1]??u.nameAvatar),namePlacement:f(e.namePlacement,ae,i?.[0]??u.namePlacement),skin:f(e.skin,V,d?.[0]??u.skin),stampContent:f(e.stampContent,ie,o?.[2]??u.stampContent),stampPlacement:f(e.stampPlacement,re,o?.[1]??u.stampPlacement)};return m.stampPlacement==="beside_name"&&m.namePlacement==="hidden"&&(m.stampPlacement="under_turn"),m}function M(n){let e=n.split(/\s+/).filter(a=>a.length>0);return (e.length>1?`${e[0]?.slice(0,1)}${e[1]?.slice(0,1)}`:e[0]?.slice(0,2)??"").toUpperCase()}var pe="M20 11.6a7.4 7.4 0 0 1-7.4 7.4H8.2L4 21.8l1-4.1A7.4 7.4 0 1 1 20 11.6Z",he={large:66,medium:56,small:46},ue={circle:"width:var(--fab-size);height:var(--fab-size);border-radius:calc(var(--fab-size) / 2);",pill:"width:auto;height:var(--fab-size);border-radius:calc(var(--fab-size) / 2);padding:0 22px;gap:10px;",squircle:"width:var(--fab-size);height:var(--fab-size);border-radius:16px;"},me={filled:"background:var(--a);color:#fff;",outlined:"background:var(--paper);border:1px solid var(--hairline);color:var(--ink-2);box-shadow:0 1px 2px rgba(0,0,0,.08);"},ge={avatar:"",glyph:".launcher svg{width:calc(var(--fab-size) * 0.375);height:calc(var(--fab-size) * 0.375);}",team_faces:".launcher .faces{display:flex;}.launcher .faces .av{box-shadow:0 0 0 2px var(--paper);}.launcher .faces .av+.av{margin-left:-10px;}"},fe=".launcher .live{width:10px;height:10px;position:absolute;right:3px;bottom:3px;border-radius:50%;background:var(--online);box-shadow:0 0 0 2px var(--paper);}.launcher.closed .live{display:none}",be={circle:"",pill:".badge{position:static;box-shadow:none}",squircle:""},ye={filled:"",outlined:".badge{background:var(--a);top:-7px;right:-7px;min-width:19px;height:19px;font-size:11.5px}"},xe={circle:"",pill:".launcher .label{font-size:14px;font-weight:600;white-space:nowrap;}",squircle:""},ve={circle:"",pill:"@media (max-width:480px){.launcher{width:var(--fab-size);padding:0}.launcher .label{display:none}}",squircle:""};function O(n,e,t,a){return `.launcher{--fab-size:${he[a]}px;${ue[n]}${me[e]}}${ge[t]}${fe}${be[n]}${ye[e]}${xe[n]}${ve[n]}`}function $(n,e,t,a=r=>r){let r=document.createDocumentFragment();if(n==="glyph"||t.length===0){let i=document.createElement("span");return i.innerHTML=`<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="${pe}"/></svg>`,r.append(...i.childNodes,N()),r}return n==="avatar"?(r.append(z(t[0],e,a),N()),r):(r.append(P(t,e,a),N()),r)}function P(n,e,t=r=>r,a=true){let r=document.createElement("span");r.className="faces";for(let i of n.slice(0,2))r.append(z(i,e,t,a));return r}function z(n,e,t,a=true){let r=document.createElement("span");if(r.className="av",r.setAttribute("aria-hidden","true"),n&&a&&(r.style.background=n.tone),n?.avatarUrl){let i=document.createElement("img");return i.alt="",i.src=t(n.avatarUrl),r.append(i),r}return r.textContent=n?n.initials:e.agentLabel.slice(0,2).toUpperCase(),r}function N(){let n=document.createElement("span");return n.className="live",n.setAttribute("aria-hidden","true"),n}var Se={agentLabel:"Agent",aiLabel:"AI",awayBody:"We are away right now, but we will reply as soon as we are back.",closeLabel:"Close chat",emptyBody:"We usually reply within a few minutes.",emptyTitle:"Ask us anything.",inputPlaceholder:"Type a message",launcherLabel:"Chat with us",replyTime:"Usually replying in a few minutes",retryLabel:"Not delivered. Retry",sendLabel:"Send",timeLabel:n=>{let e=new Date(n);return Number.isNaN(e.getTime())?"":`${String(e.getHours()).padStart(2,"0")}:${String(e.getMinutes()).padStart(2,"0")}`},title:"Support",unreadLabel:n=>`${n} unread`},x={accentColor:"#5b5bff",availability:{timezone:"UTC",windows:[]},awayMessage:"",greeting:"",launcherOffsetX:20,launcherOffsetY:20,launcherPosition:"bottom_right",starterPrompts:[],team:[],...u},ke={quiet:".composer{position:relative;padding:8px 10px 10px}.composer input{padding-right:36px}.composer button{position:absolute;top:50%;right:14px;width:28px;min-width:28px;height:28px;padding:0;background:transparent;color:var(--ink);border-radius:7px;transform:translateY(-50%)}.composer button .sendglyph{display:block;width:16px;height:16px}.composer button .sendtext{display:none}.panel{border-radius:8px;box-shadow:0 2px 8px rgba(0,0,0,.12)}.header{background:var(--paper);color:var(--ink);height:44px;padding:0 8px 0 16px;border-bottom:1px solid var(--hairline)}.header h2{font-size:11px;letter-spacing:.11em;text-transform:uppercase;color:var(--ink-3)}.header .status{color:var(--ink-3)}.header .av,.header .status .live{box-shadow:0 0 0 2px var(--paper)}.close{color:var(--ink-2)}",standard:".panel{border-radius:16px;box-shadow:0 16px 40px rgba(0,0,0,.2)}.header{background:var(--a);color:#fff;flex-direction:column;align-items:flex-start;gap:14px;padding:18px 14px 20px 20px}.header h2{font-size:19px;font-weight:640}"},Ce={round:".composer{padding:10px 10px 12px;gap:6px}.composer input{height:36px;border-radius:18px;padding:0 14px}.composer button{width:36px;min-width:36px;height:36px;padding:0;border-radius:18px}.composer button .sendglyph{display:block}.composer button .sendtext{display:none}",square:".composer input{height:36px;border-radius:8px;padding:0 12px}"},Ee={rounded:".turn{border-radius:18px;padding:10px 15px}",tailed:".turn.agent,.turn.ai{border-radius:12px 12px 12px 4px}.turn.end_user{border-radius:12px 12px 4px 12px}"},we={filled:"",outlined:".turn{background:none;border:1px solid var(--hairline)}.turn.end_user{background:none;border-color:var(--a);color:var(--ink)}"},Te={above:"",hidden:".turn.agent .author,.turn.ai .author:not(.ai){display:none}",inline:".body .author.below{display:block;margin:4px 0 0;font-size:11.5px;font-weight:500;color:var(--ink-2);text-transform:none;letter-spacing:0;opacity:1}"},Ae=".turn.agent,.turn.ai{display:flex;gap:10px;max-width:100%;background:none;padding:0}.turn.agent .body,.turn.ai .body{background:var(--fill);padding:9px 13px;border-radius:inherit}.author{text-transform:none;letter-spacing:0;font-size:12.5px;font-weight:600;opacity:1}",Le='.divider{display:flex;align-items:center;gap:10px;margin:0;font-size:11px;opacity:.6}.divider:before,.divider:after{content:"";flex:1;height:1px;background:var(--hairline)}',Ne={beside_name:".stamp{font-size:11px;opacity:.7;margin-left:6px}",none:"",under_turn:".stamp{display:block;font-size:11px;opacity:.7;margin-top:4px}.turn.end_user .stamp{text-align:right}"},Pe=".lat{font-size:11px;opacity:.7;margin-left:6px}",B=`--paper: oklch(24.6% 0.015 257); --ink: #fff; --ink-3: rgba(255,255,255,.55);
|
|
2
2
|
--fill: rgba(255,255,255,.06); --hairline: rgba(255,255,255,.13); --ink-2: rgba(255,255,255,.70);
|
|
3
|
-
--online: oklch(72% 0.13 163.23);`;function _e(
|
|
3
|
+
--online: oklch(72% 0.13 163.23);`;function _e(n){return n==="light"?"":n==="dark"?`:host { ${B} }`:`@media (prefers-color-scheme: dark) {
|
|
4
4
|
:host {
|
|
5
5
|
${B}
|
|
6
6
|
}
|
|
7
|
-
}`}function _(
|
|
7
|
+
}`}function _(n,e="system"){let t=C(n),a=n.launcherPosition==="bottom_left"?"left":"right",r=n.accentColor;return `${`
|
|
8
8
|
:host {
|
|
9
9
|
/* The widget sits above the host page's own furniture. The reset above sends
|
|
10
10
|
z-index back to auto, so without this the launcher and panel stack at the
|
|
@@ -21,7 +21,7 @@
|
|
|
21
21
|
${_e(e)}
|
|
22
22
|
* { box-sizing: border-box; font-family: system-ui, sans-serif; }
|
|
23
23
|
.launcher {
|
|
24
|
-
z-index: 2147483000; position: fixed; ${
|
|
24
|
+
z-index: 2147483000; position: fixed; ${a}: ${n.launcherOffsetX}px; bottom: ${n.launcherOffsetY}px; width: 56px; height: 56px;
|
|
25
25
|
border-radius: 28px; border: none; cursor: pointer;
|
|
26
26
|
display: inline-flex; align-items: center; justify-content: center;
|
|
27
27
|
background: ${r}; color: #fff; font-size: 24px;
|
|
@@ -52,7 +52,7 @@ ${_e(e)}
|
|
|
52
52
|
the one that needs it. */
|
|
53
53
|
.badge[hidden] { display: none; }
|
|
54
54
|
.panel {
|
|
55
|
-
z-index: 2147483001; position: fixed; ${
|
|
55
|
+
z-index: 2147483001; position: fixed; ${a}: ${n.launcherOffsetX}px; bottom: ${n.launcherOffsetY+68}px; width: 360px; max-width: calc(100vw - 40px);
|
|
56
56
|
height: 520px; max-height: calc(100vh - 120px); background: var(--paper); color: var(--ink);
|
|
57
57
|
border-radius: 12px; box-shadow: 0 8px 32px rgba(0,0,0,.24);
|
|
58
58
|
display: flex; flex-direction: column; overflow: hidden;
|
|
@@ -63,7 +63,12 @@ ${_e(e)}
|
|
|
63
63
|
status line 12.5px at 80% under the title. The ring is the header's own
|
|
64
64
|
ground so overlapping faces separate from it and from each other. */
|
|
65
65
|
.header .faces { display: flex; }
|
|
66
|
-
|
|
66
|
+
/* The fill is the stylesheet's on the header, never the face's own tone, which
|
|
67
|
+
arrives as the project accent and would be this header's own colour. Mixed
|
|
68
|
+
down from the accent rather than a fixed colour so it still belongs to the
|
|
69
|
+
project's palette, and the ring stays the accent because its job is to part
|
|
70
|
+
two OVERLAPPING discs from each other and from the header behind them. */
|
|
71
|
+
.header .av { width: 36px; height: 36px; background: color-mix(in srgb, #000 30%, var(--a)); box-shadow: 0 0 0 2px var(--a); }
|
|
67
72
|
.header .av + .av { margin-left: -12px; }
|
|
68
73
|
.headmain { display: flex; flex-direction: column; }
|
|
69
74
|
.header .status { display: flex; align-items: center; gap: 6px; margin: 5px 0 0; font-size: 12.5px; color: rgb(255 255 255 / 80%); }
|
|
@@ -146,5 +151,5 @@ ${_e(e)}
|
|
|
146
151
|
.panel { animation: rise 180ms ease-out; }
|
|
147
152
|
@keyframes rise { from { transform: translateY(8px); opacity: 0; } to { transform: none; opacity: 1; } }
|
|
148
153
|
}
|
|
149
|
-
`}${Ce[t.composerShape]}${ke[t.skin]}${O(t.launcherShape,t.launcherFill,t.launcherContent,t.launcherSize)}${Ee[t.bubbleShape]}${we[t.bubbleFill]}${Te[t.namePlacement]}${t.nameAvatar?Ae:""}${t.dayDividers?Le:""}${Ne[t.stampPlacement]}${t.stampContent==="time_and_latency"?Pe:""}`}var Ie=["end_user","agent","ai"];function Fe(){let a=globalThis.location;if(a)return {host:a.host,path:a.pathname,title:document.title}}var E=class{constructor(e,t,n={},r={},o={}){this.host=e;this.client=t;l(this,"root");l(this,"strings");l(this,"settings");l(this,"appearance");l(this,"launcher");l(this,"badge");l(this,"panel",null);l(this,"lastFocused",null);l(this,"unread",0);l(this,"pendingTurns",0);l(this,"openNow");l(this,"style");l(this,"scheme");this.strings={...Se,...n},this.appearance={...x,...r},this.settings=C({...x,...r}),this.root=e.attachShadow({mode:o.shadowMode??"closed"}),this.openNow=w(this.appearance.availability,new Date),this.scheme=o.scheme,this.style=document.createElement("style"),this.style.textContent=_(this.appearance,this.scheme),this.root.append(this.style),this.launcher=document.createElement("button"),this.launcher.className="launcher",this.launcher.type="button",this.launcher.setAttribute("aria-haspopup","dialog"),this.launcher.addEventListener("click",()=>this.toggle()),this.badge=document.createElement("span"),this.badge.className="badge",this.badge.hidden=true,this.drawLauncher(),this.root.append(this.launcher);}drawLauncher(){if(this.launcher.setAttribute("aria-label",this.strings.launcherLabel),this.launcher.replaceChildren(),this.launcher.append($(this.settings.launcherContent,this.strings,this.appearance.team,e=>this.client.avatarUrl(e))),this.settings.launcherShape==="pill"){let e=document.createElement("span");e.className="label",e.textContent=this.settings.launcherContent==="team_faces"?this.strings.agentLabel:this.strings.launcherLabel,this.launcher.append(e);}this.launcher.append(this.badge),this.launcher.classList.toggle("closed",!this.openNow);}update(e,t){this.appearance={...x,...e},this.settings=C(this.appearance),t!==void 0&&(this.scheme=t),this.style.textContent=_(this.appearance,this.scheme),this.drawLauncher(),this.panel&&(this.close(),this.open());}toggle(){this.panel?this.close():this.open();}setOpenNow(e){this.openNow=e,this.launcher.classList.toggle("closed",!e),this.panel?.classList.toggle("closed",!e);}async open(){if(this.panel)return;this.lastFocused=this.host.ownerDocument.activeElement,this.unread=0,this.renderBadge();let e=document.createElement("section");e.className=this.openNow?"panel":"panel closed",e.setAttribute("role","dialog"),e.setAttribute("aria-modal","true"),e.setAttribute("aria-label",this.strings.title);let t=document.createElement("div");t.className="header";let n=this.appearance.team??[];n.length>0&&t.append(P(n,this.strings,b=>this.client.avatarUrl(b)));let r=document.createElement("div");r.className="headmain";let o=document.createElement("h2");o.textContent=this.strings.title;let s=document.createElement("p");s.className="status";let i=document.createElement("span");i.className="live",i.setAttribute("aria-hidden","true"),s.append(i,this.strings.replyTime),r.append(o,s);let h=document.createElement("button");h.className="close",h.type="button",h.setAttribute("aria-label",this.strings.closeLabel),h.textContent="\xD7",h.addEventListener("click",()=>this.close()),t.append(r,h);let d=document.createElement("div");d.className="log",d.setAttribute("role","log"),d.setAttribute("aria-live","polite"),d.setAttribute("aria-label",this.strings.title);let c=document.createElement("form");c.className="composer";let p=document.createElement("input");p.type="text",p.setAttribute("aria-label",this.strings.inputPlaceholder),p.placeholder=this.strings.inputPlaceholder;let m=document.createElement("button");m.type="submit",m.setAttribute("aria-label",this.strings.sendLabel),m.innerHTML='<svg class="sendglyph" aria-hidden="true" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M4.5 12 20 4.5 15 20l-3.6-5.4L4.5 12Z"/></svg>';let v=document.createElement("span");v.className="sendtext",v.textContent=this.strings.sendLabel,m.append(v),c.append(p,m),c.addEventListener("submit",b=>{b.preventDefault(),this.submit(p,d);}),e.append(t,d,c),e.addEventListener("keydown",b=>this.onKeydown(b,e,h)),this.root.append(e),this.panel=e,p.focus();let y=await this.client.load();y&&y.turns.length>0?this.renderThread(d,y):this.renderFirstRun(d,p),this.openNow||this.renderAway(d);}renderFirstRun(e,t){let n=document.createElement("div");n.className="empty";let r=document.createElement("h3");r.textContent=this.appearance.greeting.trim()||this.strings.emptyTitle;let o=document.createElement("p");o.textContent=this.strings.emptyBody,n.append(r,o);for(let s of this.appearance.starterPrompts){let i=document.createElement("button");i.className="prompt",i.type="button",i.textContent=s,i.addEventListener("click",()=>{t.value=s,this.submit(t,e);}),n.append(i);}e.replaceChildren(n);}renderAway(e){let t=document.createElement("div");t.className="away",t.textContent=this.appearance.awayMessage.trim()||this.strings.awayBody,e.prepend(t);}close(){this.panel&&(this.panel.remove(),this.panel=null,this.lastFocused instanceof HTMLElement?this.lastFocused.focus():this.launcher.focus());}onIncomingTurn(e){if(this.panel){let t=this.panel.querySelector(".log");t instanceof HTMLElement&&!this.hasTurn(t,e.id)&&this.appendTurn(t,e);return}e.authorKind!=="end_user"&&(this.unread+=1,this.renderBadge());}async submit(e,t){let n=e.value.trim();n&&(e.value="",await this.sendBody(t,n));}async sendBody(e,t){e.querySelector(".empty")?.remove(),this.pendingTurns+=1;let n=this.appendTurn(e,{authorId:null,authorKind:"end_user",body:t,createdAt:new Date().toISOString(),id:`pending-${this.pendingTurns}`});n.setAttribute("data-pending","");let r=await this.client.send(t,Fe());if(n.removeAttribute("data-pending"),r){n.dataset.turnId=r.id;return}this.markFailed(e,n,t);}markFailed(e,t,n){t.setAttribute("data-failed","");let r=document.createElement("button");r.type="button",r.className="retry",r.textContent=this.strings.retryLabel,r.addEventListener("click",()=>{t.remove(),this.sendBody(e,n);}),(t.querySelector(".body")??t).append(r);}hasTurn(e,t){for(let n of e.children)if(n instanceof HTMLElement&&n.dataset.turnId===t)return true;return false}renderThread(e,t){e.replaceChildren();for(let n of t.turns)this.appendTurn(e,n);}appendTurn(e,t){e.querySelector(".empty")?.remove();let n=Ie.includes(t.authorKind)?t.authorKind:"agent",r=this.settings,o=document.createElement("div");if(o.className=`turn ${n}`,o.dataset.turnId=t.id,n!=="end_user"&&r.nameAvatar){let c=document.createElement("span");if(c.className=n==="ai"?"av bot":"av",c.setAttribute("aria-hidden","true"),n==="agent"&&t.authorAvatarUrl){let p=document.createElement("img");p.alt="",p.src=this.client.avatarUrl(t.authorAvatarUrl),c.append(p);}else c.textContent=n==="ai"?this.strings.aiLabel:M(this.agentName(t));o.append(c);}let i=document.createElement("div");i.className="body";let h=n!=="end_user"&&r.namePlacement!=="hidden",d=document.createElement("div");if(d.textContent=t.body,h||n==="ai"&&r.namePlacement==="hidden"){let c=document.createElement("div");c.className=n==="ai"?"author ai":"author",c.textContent=n==="ai"?this.strings.aiLabel:this.agentName(t),r.stampPlacement==="beside_name"&&c.append(this.stamp(t)),r.namePlacement==="inline"?(c.classList.add("below"),i.append(d,c)):i.append(c,d);}else i.append(d);return r.stampPlacement==="under_turn"&&i.append(this.stamp(t)),o.append(i),e.append(o),e.scrollTop=e.scrollHeight,o}agentName(e){return e.authorName||this.strings.agentLabel}stamp(e){let t=document.createElement("span");return t.className="stamp",t.textContent=this.strings.timeLabel(e.createdAt),t}onKeydown(e,t,n){if(e.key==="Escape"){e.preventDefault(),this.close();return}if(e.key!=="Tab")return;let r=t.querySelectorAll('button, input, [tabindex]:not([tabindex="-1"])');if(r.length===0)return;let o=r[0],s=r[r.length-1],i=this.root.activeElement;e.shiftKey&&i===o?(e.preventDefault(),s.focus()):!e.shiftKey&&i===s?(e.preventDefault(),o.focus()):i===null&&(e.preventDefault(),n.focus());}renderBadge(){this.unread>0?(this.badge.hidden=false,this.badge.textContent=String(this.unread),this.launcher.setAttribute("aria-label",`${this.strings.launcherLabel}, ${this.strings.unreadLabel(this.unread)}`)):(this.badge.hidden=true,this.badge.textContent="",this.launcher.setAttribute("aria-label",this.strings.launcherLabel));}};function U(a){return `40${JSON.stringify(a)}`}function D(){return "3"}function K(a){let e=a.charAt(0),t=a.slice(1);if(e==="2")return {kind:"ping"};if(e==="1")return {kind:"disconnect"};if(e==="0"){let s=I(t);return {kind:"open",pingInterval:typeof s?.pingInterval=="number"?s.pingInterval:25e3,pingTimeout:typeof s?.pingTimeout=="number"?s.pingTimeout:2e4}}if(e!=="4")return {kind:"other"};let n=t.charAt(0),r=t.slice(1);if(n==="0")return {kind:"connected"};if(n==="1")return {kind:"disconnect"};if(n==="4"){let s=I(r);return {kind:"connectError",message:typeof s?.message=="string"?s.message:"refused"}}if(n!=="2")return {kind:"other"};let o=I(r);return !Array.isArray(o)||typeof o[0]!="string"?{kind:"other"}:{kind:"event",name:o[0],payload:o[1]}}function I(a){try{return JSON.parse(a)}catch{return null}}var He="/socket.io/?EIO=4&transport=websocket",T=class{constructor(e){this.options=e;l(this,"socket",null);l(this,"heartbeat",null);l(this,"ready",false);l(this,"closed",false);l(this,"heartbeatWindow",45e3);l(this,"factory");l(this,"setTimer");l(this,"clearTimer");this.factory=e.socketFactory??Re,this.setTimer=e.setTimer??((t,n)=>setTimeout(t,n)),this.clearTimer=e.clearTimer??(t=>clearTimeout(t));}open(){if(this.socket||this.closed)return;let e=`${this.options.host.replace(/^http/,"ws").replace(/\/+$/,"")}${He}`,t;try{t=this.factory(e);}catch{this.options.onClosed(false);return}this.socket=t,t.onmessage=n=>this.receive(String(n.data)),t.onerror=()=>t.close(),t.onclose=()=>this.fell();}close(){this.closed=true,this.stopHeartbeat();let e=this.socket;this.socket=null,e?.close();}receive(e){let t=K(e);if(t.kind==="open"){this.armHeartbeat(t.pingInterval+t.pingTimeout),this.socket?.send(U(this.options.auth));return}if(t.kind==="ping"){this.armHeartbeat(),this.socket?.send(D());return}if(t.kind==="connectError"||t.kind==="disconnect"){this.stopHeartbeat(),this.socket?.close();return}if(t.kind==="event"){if(t.name==="ready"){this.ready=true,this.options.onReady();return}if(t.name==="conversation.turn"){let n=t.payload?.turn;n&&this.options.onTurn(n);}}}fell(){this.stopHeartbeat();let e=this.ready;this.socket=null,this.ready=false,this.closed||this.options.onClosed(e);}armHeartbeat(e){e!==void 0&&(this.heartbeatWindow=e),this.stopHeartbeat(),this.heartbeat=this.setTimer(()=>this.socket?.close(),this.heartbeatWindow);}stopHeartbeat(){this.heartbeat!==null&&this.clearTimer(this.heartbeat),this.heartbeat=null;}};function Re(a){let e=globalThis.WebSocket;if(!e)throw new Error("no WebSocket");return new e(a)}var Me=6e4;function rt(a){let e=globalThis.document;if(!e)throw new Error("prodantix chat requires a document; mount it in the browser");let t=a.mountPoint??e.createElement("div");a.mountPoint||e.body.append(t);let n=new k(a),r=new E(t,n,a.strings,a.appearance),o=a.appearance?.availability??x.availability,s,i=()=>{r.setOpenNow(w(o,new Date)),s=setTimeout(i,Me);};i();let h=new Set,d,c=null,p=a.pollIntervalMs??15e3,m=g=>{h.has(g.id)||g.authorKind==="end_user"||(h.add(g.id),r.onIncomingTurn(g));},v=async()=>{if(!n.hasThread)return;let g=await n.load();if(g){for(let S of g.turns)m(S);h=new Set(g.turns.map(S=>S.id));}},y=()=>{d||p<=0||(d=setInterval(()=>void v(),p));},b=()=>{d&&clearInterval(d),d=void 0;},A=()=>{if(c||!a.socketHost)return;let g=n.socketAuth;g&&(c=new T({auth:g,host:a.socketHost,onClosed:S=>{c=null,y(),S&&A();},onReady:b,onTurn:m,socketFactory:a.socketFactory}),c.open());};return y(),A(),{close:()=>r.close(),destroy:()=>{b(),clearTimeout(s),c?.close(),c=null,r.close(),t.remove();},identify:g=>n.identify(g),open:()=>{r.open().then(A);}}}exports.ChatClient=k;exports.ChatPanel=E;exports.DEFAULT_APPEARANCE=x;exports.DEFAULT_APPEARANCE_SETTINGS=u;exports.mountChat=rt;exports.panelStyles=_;exports.resolveAppearance=C;//# sourceMappingURL=chat.cjs.map
|
|
154
|
+
`}${Ce[t.composerShape]}${ke[t.skin]}${O(t.launcherShape,t.launcherFill,t.launcherContent,t.launcherSize)}${Ee[t.bubbleShape]}${we[t.bubbleFill]}${Te[t.namePlacement]}${t.nameAvatar?Ae:""}${t.dayDividers?Le:""}${Ne[t.stampPlacement]}${t.stampContent==="time_and_latency"?Pe:""}`}var Ie=["end_user","agent","ai"];function Fe(){let n=globalThis.location;if(n)return {host:n.host,path:n.pathname,title:document.title}}var E=class{constructor(e,t,a={},r={},i={}){this.host=e;this.client=t;l(this,"root");l(this,"strings");l(this,"settings");l(this,"appearance");l(this,"launcher");l(this,"badge");l(this,"panel",null);l(this,"lastFocused",null);l(this,"unread",0);l(this,"pendingTurns",0);l(this,"openNow");l(this,"style");l(this,"scheme");this.strings={...Se,...a},this.appearance={...x,...r},this.settings=C({...x,...r}),this.root=e.attachShadow({mode:i.shadowMode??"closed"}),this.openNow=w(this.appearance.availability,new Date),this.scheme=i.scheme,this.style=document.createElement("style"),this.style.textContent=_(this.appearance,this.scheme),this.root.append(this.style),this.launcher=document.createElement("button"),this.launcher.className="launcher",this.launcher.type="button",this.launcher.setAttribute("aria-haspopup","dialog"),this.launcher.addEventListener("click",()=>this.toggle()),this.badge=document.createElement("span"),this.badge.className="badge",this.badge.hidden=true,this.drawLauncher(),this.root.append(this.launcher);}drawLauncher(){if(this.launcher.setAttribute("aria-label",this.strings.launcherLabel),this.launcher.replaceChildren(),this.launcher.append($(this.settings.launcherContent,this.strings,this.appearance.team,e=>this.client.avatarUrl(e))),this.settings.launcherShape==="pill"){let e=document.createElement("span");e.className="label",e.textContent=this.settings.launcherContent==="team_faces"?this.strings.agentLabel:this.strings.launcherLabel,this.launcher.append(e);}this.launcher.append(this.badge),this.launcher.classList.toggle("closed",!this.openNow);}update(e,t){this.appearance={...x,...e},this.settings=C(this.appearance),t!==void 0&&(this.scheme=t),this.style.textContent=_(this.appearance,this.scheme),this.drawLauncher(),this.panel&&(this.close(),this.open());}toggle(){this.panel?this.close():this.open();}setOpenNow(e){this.openNow=e,this.launcher.classList.toggle("closed",!e),this.panel?.classList.toggle("closed",!e);}async open(){if(this.panel)return;this.lastFocused=this.host.ownerDocument.activeElement,this.unread=0,this.renderBadge();let e=document.createElement("section");e.className=this.openNow?"panel":"panel closed",e.setAttribute("role","dialog"),e.setAttribute("aria-modal","true"),e.setAttribute("aria-label",this.strings.title);let t=document.createElement("div");t.className="header";let a=this.appearance.team??[];a.length>0&&t.append(P(a,this.strings,b=>this.client.avatarUrl(b),false));let r=document.createElement("div");r.className="headmain";let i=document.createElement("h2");i.textContent=this.strings.title;let s=document.createElement("p");s.className="status";let o=document.createElement("span");o.className="live",o.setAttribute("aria-hidden","true"),s.append(o,this.strings.replyTime),r.append(i,s);let h=document.createElement("button");h.className="close",h.type="button",h.setAttribute("aria-label",this.strings.closeLabel),h.textContent="\xD7",h.addEventListener("click",()=>this.close()),t.append(r,h);let d=document.createElement("div");d.className="log",d.setAttribute("role","log"),d.setAttribute("aria-live","polite"),d.setAttribute("aria-label",this.strings.title);let c=document.createElement("form");c.className="composer";let p=document.createElement("input");p.type="text",p.setAttribute("aria-label",this.strings.inputPlaceholder),p.placeholder=this.strings.inputPlaceholder;let m=document.createElement("button");m.type="submit",m.setAttribute("aria-label",this.strings.sendLabel),m.innerHTML='<svg class="sendglyph" aria-hidden="true" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M4.5 12 20 4.5 15 20l-3.6-5.4L4.5 12Z"/></svg>';let v=document.createElement("span");v.className="sendtext",v.textContent=this.strings.sendLabel,m.append(v),c.append(p,m),c.addEventListener("submit",b=>{b.preventDefault(),this.submit(p,d);}),e.append(t,d,c),e.addEventListener("keydown",b=>this.onKeydown(b,e,h)),this.root.append(e),this.panel=e,p.focus();let y=await this.client.load();y&&y.turns.length>0?this.renderThread(d,y):this.renderFirstRun(d,p),this.openNow||this.renderAway(d);}renderFirstRun(e,t){let a=document.createElement("div");a.className="empty";let r=document.createElement("h3");r.textContent=this.appearance.greeting.trim()||this.strings.emptyTitle;let i=document.createElement("p");i.textContent=this.strings.emptyBody,a.append(r,i);for(let s of this.appearance.starterPrompts){let o=document.createElement("button");o.className="prompt",o.type="button",o.textContent=s,o.addEventListener("click",()=>{t.value=s,this.submit(t,e);}),a.append(o);}e.replaceChildren(a);}renderAway(e){let t=document.createElement("div");t.className="away",t.textContent=this.appearance.awayMessage.trim()||this.strings.awayBody,e.prepend(t);}close(){this.panel&&(this.panel.remove(),this.panel=null,this.lastFocused instanceof HTMLElement?this.lastFocused.focus():this.launcher.focus());}onIncomingTurn(e){if(this.panel){let t=this.panel.querySelector(".log");t instanceof HTMLElement&&!this.hasTurn(t,e.id)&&this.appendTurn(t,e);return}e.authorKind!=="end_user"&&(this.unread+=1,this.renderBadge());}async submit(e,t){let a=e.value.trim();a&&(e.value="",await this.sendBody(t,a));}async sendBody(e,t){e.querySelector(".empty")?.remove(),this.pendingTurns+=1;let a=this.appendTurn(e,{authorId:null,authorKind:"end_user",body:t,createdAt:new Date().toISOString(),id:`pending-${this.pendingTurns}`});a.setAttribute("data-pending","");let r=await this.client.send(t,Fe());if(a.removeAttribute("data-pending"),r){a.dataset.turnId=r.id;return}this.markFailed(e,a,t);}markFailed(e,t,a){t.setAttribute("data-failed","");let r=document.createElement("button");r.type="button",r.className="retry",r.textContent=this.strings.retryLabel,r.addEventListener("click",()=>{t.remove(),this.sendBody(e,a);}),(t.querySelector(".body")??t).append(r);}hasTurn(e,t){for(let a of e.children)if(a instanceof HTMLElement&&a.dataset.turnId===t)return true;return false}renderThread(e,t){e.replaceChildren();for(let a of t.turns)this.appendTurn(e,a);}appendTurn(e,t){e.querySelector(".empty")?.remove();let a=Ie.includes(t.authorKind)?t.authorKind:"agent",r=this.settings,i=document.createElement("div");if(i.className=`turn ${a}`,i.dataset.turnId=t.id,a!=="end_user"&&r.nameAvatar){let c=document.createElement("span");if(c.className=a==="ai"?"av bot":"av",c.setAttribute("aria-hidden","true"),a==="agent"&&t.authorAvatarUrl){let p=document.createElement("img");p.alt="",p.src=this.client.avatarUrl(t.authorAvatarUrl),c.append(p);}else c.textContent=a==="ai"?this.strings.aiLabel:M(this.agentName(t));i.append(c);}let o=document.createElement("div");o.className="body";let h=a!=="end_user"&&r.namePlacement!=="hidden",d=document.createElement("div");if(d.textContent=t.body,h||a==="ai"&&r.namePlacement==="hidden"){let c=document.createElement("div");c.className=a==="ai"?"author ai":"author",c.textContent=a==="ai"?this.strings.aiLabel:this.agentName(t),r.stampPlacement==="beside_name"&&c.append(this.stamp(t)),r.namePlacement==="inline"?(c.classList.add("below"),o.append(d,c)):o.append(c,d);}else o.append(d);return r.stampPlacement==="under_turn"&&o.append(this.stamp(t)),i.append(o),e.append(i),e.scrollTop=e.scrollHeight,i}agentName(e){return e.authorName||this.strings.agentLabel}stamp(e){let t=document.createElement("span");return t.className="stamp",t.textContent=this.strings.timeLabel(e.createdAt),t}onKeydown(e,t,a){if(e.key==="Escape"){e.preventDefault(),this.close();return}if(e.key!=="Tab")return;let r=t.querySelectorAll('button, input, [tabindex]:not([tabindex="-1"])');if(r.length===0)return;let i=r[0],s=r[r.length-1],o=this.root.activeElement;e.shiftKey&&o===i?(e.preventDefault(),s.focus()):!e.shiftKey&&o===s?(e.preventDefault(),i.focus()):o===null&&(e.preventDefault(),a.focus());}renderBadge(){this.unread>0?(this.badge.hidden=false,this.badge.textContent=String(this.unread),this.launcher.setAttribute("aria-label",`${this.strings.launcherLabel}, ${this.strings.unreadLabel(this.unread)}`)):(this.badge.hidden=true,this.badge.textContent="",this.launcher.setAttribute("aria-label",this.strings.launcherLabel));}};function U(n){return `40${JSON.stringify(n)}`}function D(){return "3"}function K(n){let e=n.charAt(0),t=n.slice(1);if(e==="2")return {kind:"ping"};if(e==="1")return {kind:"disconnect"};if(e==="0"){let s=I(t);return {kind:"open",pingInterval:typeof s?.pingInterval=="number"?s.pingInterval:25e3,pingTimeout:typeof s?.pingTimeout=="number"?s.pingTimeout:2e4}}if(e!=="4")return {kind:"other"};let a=t.charAt(0),r=t.slice(1);if(a==="0")return {kind:"connected"};if(a==="1")return {kind:"disconnect"};if(a==="4"){let s=I(r);return {kind:"connectError",message:typeof s?.message=="string"?s.message:"refused"}}if(a!=="2")return {kind:"other"};let i=I(r);return !Array.isArray(i)||typeof i[0]!="string"?{kind:"other"}:{kind:"event",name:i[0],payload:i[1]}}function I(n){try{return JSON.parse(n)}catch{return null}}var He="/socket.io/?EIO=4&transport=websocket",T=class{constructor(e){this.options=e;l(this,"socket",null);l(this,"heartbeat",null);l(this,"ready",false);l(this,"closed",false);l(this,"heartbeatWindow",45e3);l(this,"factory");l(this,"setTimer");l(this,"clearTimer");this.factory=e.socketFactory??Re,this.setTimer=e.setTimer??((t,a)=>setTimeout(t,a)),this.clearTimer=e.clearTimer??(t=>clearTimeout(t));}open(){if(this.socket||this.closed)return;let e=`${this.options.host.replace(/^http/,"ws").replace(/\/+$/,"")}${He}`,t;try{t=this.factory(e);}catch{this.options.onClosed(false);return}this.socket=t,t.onmessage=a=>this.receive(String(a.data)),t.onerror=()=>t.close(),t.onclose=()=>this.fell();}close(){this.closed=true,this.stopHeartbeat();let e=this.socket;this.socket=null,e?.close();}receive(e){let t=K(e);if(t.kind==="open"){this.armHeartbeat(t.pingInterval+t.pingTimeout),this.socket?.send(U(this.options.auth));return}if(t.kind==="ping"){this.armHeartbeat(),this.socket?.send(D());return}if(t.kind==="connectError"||t.kind==="disconnect"){this.stopHeartbeat(),this.socket?.close();return}if(t.kind==="event"){if(t.name==="ready"){this.ready=true,this.options.onReady();return}if(t.name==="conversation.turn"){let a=t.payload?.turn;a&&this.options.onTurn(a);}}}fell(){this.stopHeartbeat();let e=this.ready;this.socket=null,this.ready=false,this.closed||this.options.onClosed(e);}armHeartbeat(e){e!==void 0&&(this.heartbeatWindow=e),this.stopHeartbeat(),this.heartbeat=this.setTimer(()=>this.socket?.close(),this.heartbeatWindow);}stopHeartbeat(){this.heartbeat!==null&&this.clearTimer(this.heartbeat),this.heartbeat=null;}};function Re(n){let e=globalThis.WebSocket;if(!e)throw new Error("no WebSocket");return new e(n)}var Me=6e4;function rt(n){let e=globalThis.document;if(!e)throw new Error("prodantix chat requires a document; mount it in the browser");let t=n.mountPoint??e.createElement("div");n.mountPoint||e.body.append(t);let a=new k(n),r=new E(t,a,n.strings,n.appearance),i=n.appearance?.availability??x.availability,s,o=()=>{r.setOpenNow(w(i,new Date)),s=setTimeout(o,Me);};o();let h=new Set,d,c=null,p=n.pollIntervalMs??15e3,m=g=>{h.has(g.id)||g.authorKind==="end_user"||(h.add(g.id),r.onIncomingTurn(g));},v=async()=>{if(!a.hasThread)return;let g=await a.load();if(g){for(let S of g.turns)m(S);h=new Set(g.turns.map(S=>S.id));}},y=()=>{d||p<=0||(d=setInterval(()=>void v(),p));},b=()=>{d&&clearInterval(d),d=void 0;},A=()=>{if(c||!n.socketHost)return;let g=a.socketAuth;g&&(c=new T({auth:g,host:n.socketHost,onClosed:S=>{c=null,y(),S&&A();},onReady:b,onTurn:m,socketFactory:n.socketFactory}),c.open());};return y(),A(),{close:()=>r.close(),destroy:()=>{b(),clearTimeout(s),c?.close(),c=null,r.close(),t.remove();},identify:g=>a.identify(g),open:()=>{r.open().then(A);}}}exports.ChatClient=k;exports.ChatPanel=E;exports.DEFAULT_APPEARANCE=x;exports.DEFAULT_APPEARANCE_SETTINGS=u;exports.mountChat=rt;exports.panelStyles=_;exports.resolveAppearance=C;//# sourceMappingURL=chat.cjs.map
|
|
150
155
|
//# sourceMappingURL=chat.cjs.map
|
package/dist/chat.js
CHANGED
|
@@ -1,10 +1,10 @@
|
|
|
1
|
-
import {c,a as a$2,b}from'./chunk-V77KYPOF.js';import {a as a$1,d}from'./chunk-VG77TYVX.js';import {a}from'./chunk-5XGN7UAV.js';var q="X-Prodantix-Conversation-Token",L="prodantix.chat.handle";function K(){let a=globalThis.localStorage;if(a)return {get:e=>a.getItem(e),remove:e=>a.removeItem(e),set:(e,t)=>a.setItem(e,t)}}var k=class{constructor(e){this.options=e;a(this,"fetchImpl");a(this,"host");a(this,"storage");a(this,"handle");a(this,"identity",null);this.fetchImpl=a$1(e.fetchImpl),this.host=d(e.host),this.storage=e.storage??K(),this.handle=this.readHandle();}get hasThread(){return this.handle!==null}avatarUrl(e){return e.startsWith("/")?`${this.host}${e}?api_key=${encodeURIComponent(this.options.apiKey)}`:e}get socketAuth(){return this.handle?{conversationId:this.handle.conversationId,conversationToken:this.handle.token,projectKey:this.options.apiKey}:null}identify(e){this.identity=e;}async ensureThread(e){if(this.handle)return true;let t=await this.request("POST","/v1/conversations",{body:{distinctId:this.options.distinctId,subject:e,userHash:this.identity?.userHash,userId:this.identity?.userId}});return !t?.conversationId||!t.token?false:(this.handle={conversationId:t.conversationId,token:t.token},this.storage?.set(L,JSON.stringify(this.handle)),true)}async send(e,t){if(!await this.ensureThread())return null;let n=this.handle;return n?(await this.request("POST",`/v1/conversations/${encodeURIComponent(n.conversationId)}/turns`,{body:{body:e,pageContext:t},token:n.token}))?.turn??null:null}async load(){let e=this.handle;return e?this.request("GET",`/v1/conversations/${encodeURIComponent(e.conversationId)}`,{token:e.token}):null}readHandle(){let e=this.storage?.get(L);if(!e)return null;try{let t=JSON.parse(e);if(typeof t.conversationId=="string"&&typeof t.token=="string")return {conversationId:t.conversationId,token:t.token}}catch{}return this.storage?.remove(L),null}async request(e,t,n={}){let r=this.fetchImpl;if(!r)return this.options.onError?.(new Error("no fetch available for prodantix chat")),null;let o={authorization:`Bearer ${this.options.apiKey}`,"content-type":"application/json"};n.token&&(o[q]=n.token);try{let d=await r(`${this.host}${t}`,{body:n.body===void 0?void 0:JSON.stringify(n.body),headers:o,method:e}),i=await d.text();return d.ok?i?JSON.parse(i):{}:(this.options.onError?.(new Error(`prodantix chat ${t}: ${d.status}`)),null)}catch(d){return this.options.onError?.(d),null}}};var W={Fri:"fri",Mon:"mon",Sat:"sat",Sun:"sun",Thu:"thu",Tue:"tue",Wed:"wed"};function T(a,e){let t=new Intl.DateTimeFormat(void 0,{hour:"2-digit",hour12:false,minute:"2-digit",timeZone:a.timezone,weekday:"short"}).formatToParts(e),n=W[t.find(i=>i.type==="weekday")?.value??""];if(!n)return false;let r=t.find(i=>i.type==="hour")?.value??"",o=t.find(i=>i.type==="minute")?.value??"",d=`${r}:${o}`;return a.windows.some(i=>i.days.includes(n)&&i.open<=d&&d<i.close)}var u={bubbleFill:"filled",bubbleShape:"tailed",composerShape:"round",dayDividers:true,launcherContent:"glyph",launcherFill:"outlined",launcherShape:"circle",launcherSize:"small",nameAvatar:true,namePlacement:"hidden",skin:"standard",stampContent:"time",stampPlacement:"none"},Y=["quiet","standard"],j=["round","square"],G=["rounded","tailed"],X=["filled","outlined"],Z=["circle","pill","squircle"],J=["filled","outlined"],V=["avatar","glyph","team_faces"],Q=["large","medium","small"],ee=["above","hidden","inline"],te=["beside_name","none","under_turn"],ne=["time","time_and_latency"],f=(a,e,t)=>typeof a=="string"&&e.includes(a)?a:t,$=(a,e)=>typeof a=="boolean"?a:e,ae={avatar_circle:["circle","outlined","avatar","large"],circle_filled:["circle","filled","glyph","medium"],circle_outlined:["circle","outlined","glyph","small"],pill_labelled:["pill","filled","glyph","medium"],pill_team:["pill","outlined","team_faces","medium"],squircle_filled:["squircle","filled","glyph","medium"]},re={above:["above",false],avatar_only:["hidden",true],gutter:["above",true],hidden:["hidden",false],inline:["inline",false]},ie={cluster:[true,"none","time"],latency:[false,"beside_name","time_and_latency"],none:[false,"none","time"],trailing:[false,"under_turn","time"],with_name:[false,"beside_name","time"]},oe={concierge:["standard","round"],console:["standard","square"],quiet:["quiet","square"]},se={hairline:["rounded","outlined"],outlined:["rounded","outlined"],rounded:["rounded","filled"],tailed:["tailed","filled"]};function C(a){let e=typeof a=="object"&&a!==null?a:{},t=typeof e.launcherStyle=="string"?e.launcherStyle:void 0,n=t===void 0?void 0:ae[t],r=typeof e.namePlacement=="string"?e.namePlacement:void 0,o=r===void 0?void 0:re[r],d=typeof e.timestampStyle=="string"?e.timestampStyle:void 0,i=d===void 0?void 0:ie[d],h=typeof e.skin=="string"?e.skin:void 0,c=h===void 0?void 0:oe[h],l=typeof e.bubbleStyle=="string"?e.bubbleStyle:void 0,p=l===void 0?void 0:se[l],m={bubbleFill:f(e.bubbleFill,X,p?.[1]??u.bubbleFill),bubbleShape:f(e.bubbleShape,G,p?.[0]??u.bubbleShape),composerShape:f(e.composerShape,j,c?.[1]??u.composerShape),dayDividers:$(e.dayDividers,i?.[0]??u.dayDividers),launcherContent:f(e.launcherContent,V,n?.[2]??u.launcherContent),launcherFill:f(e.launcherFill,J,n?.[1]??u.launcherFill),launcherShape:f(e.launcherShape,Z,n?.[0]??u.launcherShape),launcherSize:f(e.launcherSize,Q,n?.[3]??u.launcherSize),nameAvatar:$(e.nameAvatar,o?.[1]??u.nameAvatar),namePlacement:f(e.namePlacement,ee,o?.[0]??u.namePlacement),skin:f(e.skin,Y,c?.[0]??u.skin),stampContent:f(e.stampContent,ne,i?.[2]??u.stampContent),stampPlacement:f(e.stampPlacement,te,i?.[1]??u.stampPlacement)};return m.stampPlacement==="beside_name"&&m.namePlacement==="hidden"&&(m.stampPlacement="under_turn"),m}function z(a){let e=a.split(/\s+/).filter(n=>n.length>0);return (e.length>1?`${e[0]?.slice(0,1)}${e[1]?.slice(0,1)}`:e[0]?.slice(0,2)??"").toUpperCase()}var le="M20 11.6a7.4 7.4 0 0 1-7.4 7.4H8.2L4 21.8l1-4.1A7.4 7.4 0 1 1 20 11.6Z",de={large:66,medium:56,small:46},ce={circle:"width:var(--fab-size);height:var(--fab-size);border-radius:calc(var(--fab-size) / 2);",pill:"width:auto;height:var(--fab-size);border-radius:calc(var(--fab-size) / 2);padding:0 22px;gap:10px;",squircle:"width:var(--fab-size);height:var(--fab-size);border-radius:16px;"},pe={filled:"background:var(--a);color:#fff;",outlined:"background:var(--paper);border:1px solid var(--hairline);color:var(--ink-2);box-shadow:0 1px 2px rgba(0,0,0,.08);"},he={avatar:"",glyph:".launcher svg{width:calc(var(--fab-size) * 0.375);height:calc(var(--fab-size) * 0.375);}",team_faces:".launcher .faces{display:flex;}.launcher .faces .av{box-shadow:0 0 0 2px var(--paper);}.launcher .faces .av+.av{margin-left:-10px;}"},ue=".launcher .live{width:10px;height:10px;position:absolute;right:3px;bottom:3px;border-radius:50%;background:var(--online);box-shadow:0 0 0 2px var(--paper);}.launcher.closed .live{display:none}",me={circle:"",pill:".badge{position:static;box-shadow:none}",squircle:""},ge={filled:"",outlined:".badge{background:var(--a);top:-7px;right:-7px;min-width:19px;height:19px;font-size:11.5px}"},fe={circle:"",pill:".launcher .label{font-size:14px;font-weight:600;white-space:nowrap;}",squircle:""},be={circle:"",pill:"@media (max-width:480px){.launcher{width:var(--fab-size);padding:0}.launcher .label{display:none}}",squircle:""};function B(a,e,t,n){return `.launcher{--fab-size:${de[n]}px;${ce[a]}${pe[e]}}${he[t]}${ue}${me[a]}${ge[e]}${fe[a]}${be[a]}`}function O(a,e,t,n=r=>r){let r=document.createDocumentFragment();if(a==="glyph"||t.length===0){let o=document.createElement("span");return o.innerHTML=`<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="${le}"/></svg>`,r.append(...o.childNodes,P()),r}return a==="avatar"?(r.append(U(t[0],e,n),P()),r):(r.append(_(t,e,n),P()),r)}function _(a,e,t=n=>n){let n=document.createElement("span");n.className="faces";for(let r of a.slice(0,2))n.append(U(r,e,t));return n}function U(a,e,t){let n=document.createElement("span");if(n.className="av",n.setAttribute("aria-hidden","true"),a&&(n.style.background=a.tone),a?.avatarUrl){let r=document.createElement("img");return r.alt="",r.src=t(a.avatarUrl),n.append(r),n}return n.textContent=a?a.initials:e.agentLabel.slice(0,2).toUpperCase(),n}function P(){let a=document.createElement("span");return a.className="live",a.setAttribute("aria-hidden","true"),a}var ye={agentLabel:"Agent",aiLabel:"AI",awayBody:"We are away right now, but we will reply as soon as we are back.",closeLabel:"Close chat",emptyBody:"We usually reply within a few minutes.",emptyTitle:"Ask us anything.",inputPlaceholder:"Type a message",launcherLabel:"Chat with us",replyTime:"Usually replying in a few minutes",retryLabel:"Not delivered. Retry",sendLabel:"Send",timeLabel:a=>{let e=new Date(a);return Number.isNaN(e.getTime())?"":`${String(e.getHours()).padStart(2,"0")}:${String(e.getMinutes()).padStart(2,"0")}`},title:"Support",unreadLabel:a=>`${a} unread`},x={accentColor:"#5b5bff",availability:{timezone:"UTC",windows:[]},awayMessage:"",greeting:"",launcherOffsetX:20,launcherOffsetY:20,launcherPosition:"bottom_right",starterPrompts:[],team:[],...u},xe={quiet:".composer{position:relative;padding:8px 10px 10px}.composer input{padding-right:36px}.composer button{position:absolute;top:50%;right:14px;width:28px;min-width:28px;height:28px;padding:0;background:transparent;color:var(--ink);border-radius:7px;transform:translateY(-50%)}.composer button .sendglyph{display:block;width:16px;height:16px}.composer button .sendtext{display:none}.panel{border-radius:8px;box-shadow:0 2px 8px rgba(0,0,0,.12)}.header{background:var(--paper);color:var(--ink);height:44px;padding:0 8px 0 16px;border-bottom:1px solid var(--hairline)}.header h2{font-size:11px;letter-spacing:.11em;text-transform:uppercase;color:var(--ink-3)}.header .status{color:var(--ink-3)}.header .av,.header .status .live{box-shadow:0 0 0 2px var(--paper)}.close{color:var(--ink-2)}",standard:".panel{border-radius:16px;box-shadow:0 16px 40px rgba(0,0,0,.2)}.header{background:var(--a);color:#fff;flex-direction:column;align-items:flex-start;gap:14px;padding:18px 14px 20px 20px}.header h2{font-size:19px;font-weight:640}"},ve={round:".composer{padding:10px 10px 12px;gap:6px}.composer input{height:36px;border-radius:18px;padding:0 14px}.composer button{width:36px;min-width:36px;height:36px;padding:0;border-radius:18px}.composer button .sendglyph{display:block}.composer button .sendtext{display:none}",square:".composer input{height:36px;border-radius:8px;padding:0 12px}"},Se={rounded:".turn{border-radius:18px;padding:10px 15px}",tailed:".turn.agent,.turn.ai{border-radius:12px 12px 12px 4px}.turn.end_user{border-radius:12px 12px 4px 12px}"},ke={filled:"",outlined:".turn{background:none;border:1px solid var(--hairline)}.turn.end_user{background:none;border-color:var(--a);color:var(--ink)}"},Ce={above:"",hidden:".turn.agent .author,.turn.ai .author:not(.ai){display:none}",inline:".body .author.below{display:block;margin:4px 0 0;font-size:11.5px;font-weight:500;color:var(--ink-2);text-transform:none;letter-spacing:0;opacity:1}"},we=".turn.agent,.turn.ai{display:flex;gap:10px;max-width:100%;background:none;padding:0}.turn.agent .body,.turn.ai .body{background:var(--fill);padding:9px 13px;border-radius:inherit}.author{text-transform:none;letter-spacing:0;font-size:12.5px;font-weight:600;opacity:1}",Te='.divider{display:flex;align-items:center;gap:10px;margin:0;font-size:11px;opacity:.6}.divider:before,.divider:after{content:"";flex:1;height:1px;background:var(--hairline)}',Ee={beside_name:".stamp{font-size:11px;opacity:.7;margin-left:6px}",none:"",under_turn:".stamp{display:block;font-size:11px;opacity:.7;margin-top:4px}.turn.end_user .stamp{text-align:right}"},Ae=".lat{font-size:11px;opacity:.7;margin-left:6px}",D=`--paper: oklch(24.6% 0.015 257); --ink: #fff; --ink-3: rgba(255,255,255,.55);
|
|
1
|
+
import {c,a as a$2,b}from'./chunk-V77KYPOF.js';import {a as a$1,d}from'./chunk-VG77TYVX.js';import {a}from'./chunk-5XGN7UAV.js';var q="X-Prodantix-Conversation-Token",L="prodantix.chat.handle";function K(){let r=globalThis.localStorage;if(r)return {get:e=>r.getItem(e),remove:e=>r.removeItem(e),set:(e,t)=>r.setItem(e,t)}}var k=class{constructor(e){this.options=e;a(this,"fetchImpl");a(this,"host");a(this,"storage");a(this,"handle");a(this,"identity",null);this.fetchImpl=a$1(e.fetchImpl),this.host=d(e.host),this.storage=e.storage??K(),this.handle=this.readHandle();}get hasThread(){return this.handle!==null}avatarUrl(e){return e.startsWith("/")?`${this.host}${e}?api_key=${encodeURIComponent(this.options.apiKey)}`:e}get socketAuth(){return this.handle?{conversationId:this.handle.conversationId,conversationToken:this.handle.token,projectKey:this.options.apiKey}:null}identify(e){this.identity=e;}async ensureThread(e){if(this.handle)return true;let t=await this.request("POST","/v1/conversations",{body:{distinctId:this.options.distinctId,subject:e,userHash:this.identity?.userHash,userId:this.identity?.userId}});return !t?.conversationId||!t.token?false:(this.handle={conversationId:t.conversationId,token:t.token},this.storage?.set(L,JSON.stringify(this.handle)),true)}async send(e,t){if(!await this.ensureThread())return null;let n=this.handle;return n?(await this.request("POST",`/v1/conversations/${encodeURIComponent(n.conversationId)}/turns`,{body:{body:e,pageContext:t},token:n.token}))?.turn??null:null}async load(){let e=this.handle;return e?this.request("GET",`/v1/conversations/${encodeURIComponent(e.conversationId)}`,{token:e.token}):null}readHandle(){let e=this.storage?.get(L);if(!e)return null;try{let t=JSON.parse(e);if(typeof t.conversationId=="string"&&typeof t.token=="string")return {conversationId:t.conversationId,token:t.token}}catch{}return this.storage?.remove(L),null}async request(e,t,n={}){let a=this.fetchImpl;if(!a)return this.options.onError?.(new Error("no fetch available for prodantix chat")),null;let o={authorization:`Bearer ${this.options.apiKey}`,"content-type":"application/json"};n.token&&(o[q]=n.token);try{let d=await a(`${this.host}${t}`,{body:n.body===void 0?void 0:JSON.stringify(n.body),headers:o,method:e}),i=await d.text();return d.ok?i?JSON.parse(i):{}:(this.options.onError?.(new Error(`prodantix chat ${t}: ${d.status}`)),null)}catch(d){return this.options.onError?.(d),null}}};var j={Fri:"fri",Mon:"mon",Sat:"sat",Sun:"sun",Thu:"thu",Tue:"tue",Wed:"wed"};function T(r,e){let t=new Intl.DateTimeFormat(void 0,{hour:"2-digit",hour12:false,minute:"2-digit",timeZone:r.timezone,weekday:"short"}).formatToParts(e),n=j[t.find(i=>i.type==="weekday")?.value??""];if(!n)return false;let a=t.find(i=>i.type==="hour")?.value??"",o=t.find(i=>i.type==="minute")?.value??"",d=`${a}:${o}`;return r.windows.some(i=>i.days.includes(n)&&i.open<=d&&d<i.close)}var u={bubbleFill:"filled",bubbleShape:"tailed",composerShape:"round",dayDividers:true,launcherContent:"glyph",launcherFill:"outlined",launcherShape:"circle",launcherSize:"small",nameAvatar:true,namePlacement:"hidden",skin:"standard",stampContent:"time",stampPlacement:"none"},W=["quiet","standard"],Y=["round","square"],G=["rounded","tailed"],X=["filled","outlined"],V=["circle","pill","squircle"],Z=["filled","outlined"],J=["avatar","glyph","team_faces"],Q=["large","medium","small"],ee=["above","hidden","inline"],te=["beside_name","none","under_turn"],ne=["time","time_and_latency"],f=(r,e,t)=>typeof r=="string"&&e.includes(r)?r:t,$=(r,e)=>typeof r=="boolean"?r:e,ae={avatar_circle:["circle","outlined","avatar","large"],circle_filled:["circle","filled","glyph","medium"],circle_outlined:["circle","outlined","glyph","small"],pill_labelled:["pill","filled","glyph","medium"],pill_team:["pill","outlined","team_faces","medium"],squircle_filled:["squircle","filled","glyph","medium"]},re={above:["above",false],avatar_only:["hidden",true],gutter:["above",true],hidden:["hidden",false],inline:["inline",false]},ie={cluster:[true,"none","time"],latency:[false,"beside_name","time_and_latency"],none:[false,"none","time"],trailing:[false,"under_turn","time"],with_name:[false,"beside_name","time"]},oe={concierge:["standard","round"],console:["standard","square"],quiet:["quiet","square"]},se={hairline:["rounded","outlined"],outlined:["rounded","outlined"],rounded:["rounded","filled"],tailed:["tailed","filled"]};function C(r){let e=typeof r=="object"&&r!==null?r:{},t=typeof e.launcherStyle=="string"?e.launcherStyle:void 0,n=t===void 0?void 0:ae[t],a=typeof e.namePlacement=="string"?e.namePlacement:void 0,o=a===void 0?void 0:re[a],d=typeof e.timestampStyle=="string"?e.timestampStyle:void 0,i=d===void 0?void 0:ie[d],h=typeof e.skin=="string"?e.skin:void 0,c=h===void 0?void 0:oe[h],l=typeof e.bubbleStyle=="string"?e.bubbleStyle:void 0,p=l===void 0?void 0:se[l],m={bubbleFill:f(e.bubbleFill,X,p?.[1]??u.bubbleFill),bubbleShape:f(e.bubbleShape,G,p?.[0]??u.bubbleShape),composerShape:f(e.composerShape,Y,c?.[1]??u.composerShape),dayDividers:$(e.dayDividers,i?.[0]??u.dayDividers),launcherContent:f(e.launcherContent,J,n?.[2]??u.launcherContent),launcherFill:f(e.launcherFill,Z,n?.[1]??u.launcherFill),launcherShape:f(e.launcherShape,V,n?.[0]??u.launcherShape),launcherSize:f(e.launcherSize,Q,n?.[3]??u.launcherSize),nameAvatar:$(e.nameAvatar,o?.[1]??u.nameAvatar),namePlacement:f(e.namePlacement,ee,o?.[0]??u.namePlacement),skin:f(e.skin,W,c?.[0]??u.skin),stampContent:f(e.stampContent,ne,i?.[2]??u.stampContent),stampPlacement:f(e.stampPlacement,te,i?.[1]??u.stampPlacement)};return m.stampPlacement==="beside_name"&&m.namePlacement==="hidden"&&(m.stampPlacement="under_turn"),m}function z(r){let e=r.split(/\s+/).filter(n=>n.length>0);return (e.length>1?`${e[0]?.slice(0,1)}${e[1]?.slice(0,1)}`:e[0]?.slice(0,2)??"").toUpperCase()}var le="M20 11.6a7.4 7.4 0 0 1-7.4 7.4H8.2L4 21.8l1-4.1A7.4 7.4 0 1 1 20 11.6Z",de={large:66,medium:56,small:46},ce={circle:"width:var(--fab-size);height:var(--fab-size);border-radius:calc(var(--fab-size) / 2);",pill:"width:auto;height:var(--fab-size);border-radius:calc(var(--fab-size) / 2);padding:0 22px;gap:10px;",squircle:"width:var(--fab-size);height:var(--fab-size);border-radius:16px;"},pe={filled:"background:var(--a);color:#fff;",outlined:"background:var(--paper);border:1px solid var(--hairline);color:var(--ink-2);box-shadow:0 1px 2px rgba(0,0,0,.08);"},he={avatar:"",glyph:".launcher svg{width:calc(var(--fab-size) * 0.375);height:calc(var(--fab-size) * 0.375);}",team_faces:".launcher .faces{display:flex;}.launcher .faces .av{box-shadow:0 0 0 2px var(--paper);}.launcher .faces .av+.av{margin-left:-10px;}"},ue=".launcher .live{width:10px;height:10px;position:absolute;right:3px;bottom:3px;border-radius:50%;background:var(--online);box-shadow:0 0 0 2px var(--paper);}.launcher.closed .live{display:none}",me={circle:"",pill:".badge{position:static;box-shadow:none}",squircle:""},ge={filled:"",outlined:".badge{background:var(--a);top:-7px;right:-7px;min-width:19px;height:19px;font-size:11.5px}"},fe={circle:"",pill:".launcher .label{font-size:14px;font-weight:600;white-space:nowrap;}",squircle:""},be={circle:"",pill:"@media (max-width:480px){.launcher{width:var(--fab-size);padding:0}.launcher .label{display:none}}",squircle:""};function B(r,e,t,n){return `.launcher{--fab-size:${de[n]}px;${ce[r]}${pe[e]}}${he[t]}${ue}${me[r]}${ge[e]}${fe[r]}${be[r]}`}function O(r,e,t,n=a=>a){let a=document.createDocumentFragment();if(r==="glyph"||t.length===0){let o=document.createElement("span");return o.innerHTML=`<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="${le}"/></svg>`,a.append(...o.childNodes,P()),a}return r==="avatar"?(a.append(U(t[0],e,n),P()),a):(a.append(_(t,e,n),P()),a)}function _(r,e,t=a=>a,n=true){let a=document.createElement("span");a.className="faces";for(let o of r.slice(0,2))a.append(U(o,e,t,n));return a}function U(r,e,t,n=true){let a=document.createElement("span");if(a.className="av",a.setAttribute("aria-hidden","true"),r&&n&&(a.style.background=r.tone),r?.avatarUrl){let o=document.createElement("img");return o.alt="",o.src=t(r.avatarUrl),a.append(o),a}return a.textContent=r?r.initials:e.agentLabel.slice(0,2).toUpperCase(),a}function P(){let r=document.createElement("span");return r.className="live",r.setAttribute("aria-hidden","true"),r}var ye={agentLabel:"Agent",aiLabel:"AI",awayBody:"We are away right now, but we will reply as soon as we are back.",closeLabel:"Close chat",emptyBody:"We usually reply within a few minutes.",emptyTitle:"Ask us anything.",inputPlaceholder:"Type a message",launcherLabel:"Chat with us",replyTime:"Usually replying in a few minutes",retryLabel:"Not delivered. Retry",sendLabel:"Send",timeLabel:r=>{let e=new Date(r);return Number.isNaN(e.getTime())?"":`${String(e.getHours()).padStart(2,"0")}:${String(e.getMinutes()).padStart(2,"0")}`},title:"Support",unreadLabel:r=>`${r} unread`},x={accentColor:"#5b5bff",availability:{timezone:"UTC",windows:[]},awayMessage:"",greeting:"",launcherOffsetX:20,launcherOffsetY:20,launcherPosition:"bottom_right",starterPrompts:[],team:[],...u},xe={quiet:".composer{position:relative;padding:8px 10px 10px}.composer input{padding-right:36px}.composer button{position:absolute;top:50%;right:14px;width:28px;min-width:28px;height:28px;padding:0;background:transparent;color:var(--ink);border-radius:7px;transform:translateY(-50%)}.composer button .sendglyph{display:block;width:16px;height:16px}.composer button .sendtext{display:none}.panel{border-radius:8px;box-shadow:0 2px 8px rgba(0,0,0,.12)}.header{background:var(--paper);color:var(--ink);height:44px;padding:0 8px 0 16px;border-bottom:1px solid var(--hairline)}.header h2{font-size:11px;letter-spacing:.11em;text-transform:uppercase;color:var(--ink-3)}.header .status{color:var(--ink-3)}.header .av,.header .status .live{box-shadow:0 0 0 2px var(--paper)}.close{color:var(--ink-2)}",standard:".panel{border-radius:16px;box-shadow:0 16px 40px rgba(0,0,0,.2)}.header{background:var(--a);color:#fff;flex-direction:column;align-items:flex-start;gap:14px;padding:18px 14px 20px 20px}.header h2{font-size:19px;font-weight:640}"},ve={round:".composer{padding:10px 10px 12px;gap:6px}.composer input{height:36px;border-radius:18px;padding:0 14px}.composer button{width:36px;min-width:36px;height:36px;padding:0;border-radius:18px}.composer button .sendglyph{display:block}.composer button .sendtext{display:none}",square:".composer input{height:36px;border-radius:8px;padding:0 12px}"},Se={rounded:".turn{border-radius:18px;padding:10px 15px}",tailed:".turn.agent,.turn.ai{border-radius:12px 12px 12px 4px}.turn.end_user{border-radius:12px 12px 4px 12px}"},ke={filled:"",outlined:".turn{background:none;border:1px solid var(--hairline)}.turn.end_user{background:none;border-color:var(--a);color:var(--ink)}"},Ce={above:"",hidden:".turn.agent .author,.turn.ai .author:not(.ai){display:none}",inline:".body .author.below{display:block;margin:4px 0 0;font-size:11.5px;font-weight:500;color:var(--ink-2);text-transform:none;letter-spacing:0;opacity:1}"},we=".turn.agent,.turn.ai{display:flex;gap:10px;max-width:100%;background:none;padding:0}.turn.agent .body,.turn.ai .body{background:var(--fill);padding:9px 13px;border-radius:inherit}.author{text-transform:none;letter-spacing:0;font-size:12.5px;font-weight:600;opacity:1}",Te='.divider{display:flex;align-items:center;gap:10px;margin:0;font-size:11px;opacity:.6}.divider:before,.divider:after{content:"";flex:1;height:1px;background:var(--hairline)}',Ee={beside_name:".stamp{font-size:11px;opacity:.7;margin-left:6px}",none:"",under_turn:".stamp{display:block;font-size:11px;opacity:.7;margin-top:4px}.turn.end_user .stamp{text-align:right}"},Ae=".lat{font-size:11px;opacity:.7;margin-left:6px}",D=`--paper: oklch(24.6% 0.015 257); --ink: #fff; --ink-3: rgba(255,255,255,.55);
|
|
2
2
|
--fill: rgba(255,255,255,.06); --hairline: rgba(255,255,255,.13); --ink-2: rgba(255,255,255,.70);
|
|
3
|
-
--online: oklch(72% 0.13 163.23);`;function Le(
|
|
3
|
+
--online: oklch(72% 0.13 163.23);`;function Le(r){return r==="light"?"":r==="dark"?`:host { ${D} }`:`@media (prefers-color-scheme: dark) {
|
|
4
4
|
:host {
|
|
5
5
|
${D}
|
|
6
6
|
}
|
|
7
|
-
}`}function N(
|
|
7
|
+
}`}function N(r,e="system"){let t=C(r),n=r.launcherPosition==="bottom_left"?"left":"right",a=r.accentColor;return `${`
|
|
8
8
|
:host {
|
|
9
9
|
/* The widget sits above the host page's own furniture. The reset above sends
|
|
10
10
|
z-index back to auto, so without this the launcher and panel stack at the
|
|
@@ -12,7 +12,7 @@ import {c,a as a$2,b}from'./chunk-V77KYPOF.js';import {a as a$1,d}from'./chunk-V
|
|
|
12
12
|
draws over them: the WebMCP chip covered the launcher on clepit's landing.
|
|
13
13
|
Below the 32-bit ceiling so a host can still put something over us
|
|
14
14
|
deliberately. */
|
|
15
|
-
all: initial; z-index: 2147483000; --a: ${
|
|
15
|
+
all: initial; z-index: 2147483000; --a: ${a};
|
|
16
16
|
--paper: #fff; --ink: #0f172a; --ink-3: var(--ink-3);
|
|
17
17
|
--fill: #f1f5f9; --hairline: #e2e8f0; --ink-2: rgba(0,0,0,.72);
|
|
18
18
|
--online: oklch(53.8% 0.1274 163.23);
|
|
@@ -21,10 +21,10 @@ import {c,a as a$2,b}from'./chunk-V77KYPOF.js';import {a as a$1,d}from'./chunk-V
|
|
|
21
21
|
${Le(e)}
|
|
22
22
|
* { box-sizing: border-box; font-family: system-ui, sans-serif; }
|
|
23
23
|
.launcher {
|
|
24
|
-
z-index: 2147483000; position: fixed; ${n}: ${
|
|
24
|
+
z-index: 2147483000; position: fixed; ${n}: ${r.launcherOffsetX}px; bottom: ${r.launcherOffsetY}px; width: 56px; height: 56px;
|
|
25
25
|
border-radius: 28px; border: none; cursor: pointer;
|
|
26
26
|
display: inline-flex; align-items: center; justify-content: center;
|
|
27
|
-
background: ${
|
|
27
|
+
background: ${a}; color: #fff; font-size: 24px;
|
|
28
28
|
box-shadow: 0 4px 12px rgba(0,0,0,.2);
|
|
29
29
|
}
|
|
30
30
|
.launcher:focus-visible { outline: 3px solid #0b0e14; outline-offset: 2px; }
|
|
@@ -34,8 +34,8 @@ ${Le(e)}
|
|
|
34
34
|
control a visitor is meant to click the only element in the product that
|
|
35
35
|
shifted when pointed at. */
|
|
36
36
|
.launcher { transition: background-color 120ms ease; }
|
|
37
|
-
.launcher:hover { background: color-mix(in srgb, #000 12%, ${
|
|
38
|
-
.launcher:active { background: color-mix(in srgb, #000 20%, ${
|
|
37
|
+
.launcher:hover { background: color-mix(in srgb, #000 12%, ${a}); }
|
|
38
|
+
.launcher:active { background: color-mix(in srgb, #000 20%, ${a}); }
|
|
39
39
|
@media (prefers-reduced-motion: reduce) {
|
|
40
40
|
.launcher { transition: none; }
|
|
41
41
|
}
|
|
@@ -52,7 +52,7 @@ ${Le(e)}
|
|
|
52
52
|
the one that needs it. */
|
|
53
53
|
.badge[hidden] { display: none; }
|
|
54
54
|
.panel {
|
|
55
|
-
z-index: 2147483001; position: fixed; ${n}: ${
|
|
55
|
+
z-index: 2147483001; position: fixed; ${n}: ${r.launcherOffsetX}px; bottom: ${r.launcherOffsetY+68}px; width: 360px; max-width: calc(100vw - 40px);
|
|
56
56
|
height: 520px; max-height: calc(100vh - 120px); background: var(--paper); color: var(--ink);
|
|
57
57
|
border-radius: 12px; box-shadow: 0 8px 32px rgba(0,0,0,.24);
|
|
58
58
|
display: flex; flex-direction: column; overflow: hidden;
|
|
@@ -63,7 +63,12 @@ ${Le(e)}
|
|
|
63
63
|
status line 12.5px at 80% under the title. The ring is the header's own
|
|
64
64
|
ground so overlapping faces separate from it and from each other. */
|
|
65
65
|
.header .faces { display: flex; }
|
|
66
|
-
|
|
66
|
+
/* The fill is the stylesheet's on the header, never the face's own tone, which
|
|
67
|
+
arrives as the project accent and would be this header's own colour. Mixed
|
|
68
|
+
down from the accent rather than a fixed colour so it still belongs to the
|
|
69
|
+
project's palette, and the ring stays the accent because its job is to part
|
|
70
|
+
two OVERLAPPING discs from each other and from the header behind them. */
|
|
71
|
+
.header .av { width: 36px; height: 36px; background: color-mix(in srgb, #000 30%, var(--a)); box-shadow: 0 0 0 2px var(--a); }
|
|
67
72
|
.header .av + .av { margin-left: -12px; }
|
|
68
73
|
.headmain { display: flex; flex-direction: column; }
|
|
69
74
|
.header .status { display: flex; align-items: center; gap: 6px; margin: 5px 0 0; font-size: 12.5px; color: rgb(255 255 255 / 80%); }
|
|
@@ -99,7 +104,7 @@ ${Le(e)}
|
|
|
99
104
|
.close:focus-visible { outline: 2px solid currentColor; outline-offset: 1px; }
|
|
100
105
|
.log { flex: 1; overflow-y: auto; padding: 12px; display: flex; flex-direction: column; gap: 8px; }
|
|
101
106
|
.turn { max-width: 80%; padding: 8px 12px; border-radius: 12px; font-size: 14px; }
|
|
102
|
-
.turn.end_user { align-self: flex-end; background: ${
|
|
107
|
+
.turn.end_user { align-self: flex-end; background: ${a}; color: #fff; }
|
|
103
108
|
.turn.agent, .turn.ai { align-self: flex-start; background: var(--fill); color: var(--ink); }
|
|
104
109
|
.author { font-size: 11px; opacity: .7; margin-bottom: 2px; }
|
|
105
110
|
/* In flight. Dimmed rather than spinner'd or greyed out: the words are already
|
|
@@ -120,7 +125,7 @@ ${Le(e)}
|
|
|
120
125
|
font-family: inherit; font-size: 13.5px; font-weight: 500; color: var(--ink);
|
|
121
126
|
background: none; border: 1px solid var(--hairline); border-radius: 8px; cursor: pointer;
|
|
122
127
|
}
|
|
123
|
-
.prompt:focus-visible { outline: 2px solid ${
|
|
128
|
+
.prompt:focus-visible { outline: 2px solid ${a}; outline-offset: 2px; }
|
|
124
129
|
.av { width: 30px; height: 30px; border-radius: 50%; flex: none; display: inline-flex; align-items: center; justify-content: center; font-size: 11.5px; font-weight: 650; color: #fff; background: #7c3f3f; }
|
|
125
130
|
.av.bot { border-radius: 9px; background: var(--fill); color: var(--ink); }
|
|
126
131
|
.av img { width: 100%; height: 100%; display: block; object-fit: cover; border-radius: inherit; }
|
|
@@ -136,9 +141,9 @@ ${Le(e)}
|
|
|
136
141
|
tagged-template call. Writing a selector as code here cost 124 tests. */
|
|
137
142
|
.composer { display: flex; gap: 6px; padding: 10px; border-top: 1px solid var(--hairline); }
|
|
138
143
|
.composer input { flex: 1; min-width: 0; height: 36px; padding: 0 12px; border: 0; border-radius: 8px; font-size: 14px; background: var(--fill); color: var(--ink); }
|
|
139
|
-
.composer input:focus-visible { outline: 2px solid ${
|
|
140
|
-
.composer button { display: inline-flex; align-items: center; justify-content: center; gap: 0; min-width: 56px; height: 36px; padding: 0 14px; background: ${
|
|
141
|
-
.composer button:hover { background: color-mix(in srgb, #000 12%, ${
|
|
144
|
+
.composer input:focus-visible { outline: 2px solid ${a}; }
|
|
145
|
+
.composer button { display: inline-flex; align-items: center; justify-content: center; gap: 0; min-width: 56px; height: 36px; padding: 0 14px; background: ${a}; color: #fff; border: none; border-radius: 8px; cursor: pointer; font-family: inherit; font-size: 13.5px; font-weight: 550; }
|
|
146
|
+
.composer button:hover { background: color-mix(in srgb, #000 12%, ${a}); }
|
|
142
147
|
.composer button:focus-visible { outline: 2px solid var(--ink); outline-offset: 2px; }
|
|
143
148
|
.composer button .sendglyph { display: none; width: 17px; height: 17px; }
|
|
144
149
|
.composer button:focus-visible { outline: 2px solid #0b0e14; }
|
|
@@ -146,5 +151,5 @@ ${Le(e)}
|
|
|
146
151
|
.panel { animation: rise 180ms ease-out; }
|
|
147
152
|
@keyframes rise { from { transform: translateY(8px); opacity: 0; } to { transform: none; opacity: 1; } }
|
|
148
153
|
}
|
|
149
|
-
`}${ve[t.composerShape]}${xe[t.skin]}${B(t.launcherShape,t.launcherFill,t.launcherContent,t.launcherSize)}${Se[t.bubbleShape]}${ke[t.bubbleFill]}${Ce[t.namePlacement]}${t.nameAvatar?we:""}${t.dayDividers?Te:""}${Ee[t.stampPlacement]}${t.stampContent==="time_and_latency"?Ae:""}`}var Pe=["end_user","agent","ai"];function _e(){let a=globalThis.location;if(a)return {host:a.host,path:a.pathname,title:document.title}}var w=class{constructor(e,t,n={},r={},o={}){this.host=e;this.client=t;a(this,"root");a(this,"strings");a(this,"settings");a(this,"appearance");a(this,"launcher");a(this,"badge");a(this,"panel",null);a(this,"lastFocused",null);a(this,"unread",0);a(this,"pendingTurns",0);a(this,"openNow");a(this,"style");a(this,"scheme");this.strings={...ye,...n},this.appearance={...x,...r},this.settings=C({...x,...r}),this.root=e.attachShadow({mode:o.shadowMode??"closed"}),this.openNow=T(this.appearance.availability,new Date),this.scheme=o.scheme,this.style=document.createElement("style"),this.style.textContent=N(this.appearance,this.scheme),this.root.append(this.style),this.launcher=document.createElement("button"),this.launcher.className="launcher",this.launcher.type="button",this.launcher.setAttribute("aria-haspopup","dialog"),this.launcher.addEventListener("click",()=>this.toggle()),this.badge=document.createElement("span"),this.badge.className="badge",this.badge.hidden=true,this.drawLauncher(),this.root.append(this.launcher);}drawLauncher(){if(this.launcher.setAttribute("aria-label",this.strings.launcherLabel),this.launcher.replaceChildren(),this.launcher.append(O(this.settings.launcherContent,this.strings,this.appearance.team,e=>this.client.avatarUrl(e))),this.settings.launcherShape==="pill"){let e=document.createElement("span");e.className="label",e.textContent=this.settings.launcherContent==="team_faces"?this.strings.agentLabel:this.strings.launcherLabel,this.launcher.append(e);}this.launcher.append(this.badge),this.launcher.classList.toggle("closed",!this.openNow);}update(e,t){this.appearance={...x,...e},this.settings=C(this.appearance),t!==void 0&&(this.scheme=t),this.style.textContent=N(this.appearance,this.scheme),this.drawLauncher(),this.panel&&(this.close(),this.open());}toggle(){this.panel?this.close():this.open();}setOpenNow(e){this.openNow=e,this.launcher.classList.toggle("closed",!e),this.panel?.classList.toggle("closed",!e);}async open(){if(this.panel)return;this.lastFocused=this.host.ownerDocument.activeElement,this.unread=0,this.renderBadge();let e=document.createElement("section");e.className=this.openNow?"panel":"panel closed",e.setAttribute("role","dialog"),e.setAttribute("aria-modal","true"),e.setAttribute("aria-label",this.strings.title);let t=document.createElement("div");t.className="header";let n=this.appearance.team??[];n.length>0&&t.append(_(n,this.strings,b=>this.client.avatarUrl(b)));let r=document.createElement("div");r.className="headmain";let o=document.createElement("h2");o.textContent=this.strings.title;let d=document.createElement("p");d.className="status";let i=document.createElement("span");i.className="live",i.setAttribute("aria-hidden","true"),d.append(i,this.strings.replyTime),r.append(o,d);let h=document.createElement("button");h.className="close",h.type="button",h.setAttribute("aria-label",this.strings.closeLabel),h.textContent="\xD7",h.addEventListener("click",()=>this.close()),t.append(r,h);let c=document.createElement("div");c.className="log",c.setAttribute("role","log"),c.setAttribute("aria-live","polite"),c.setAttribute("aria-label",this.strings.title);let l=document.createElement("form");l.className="composer";let p=document.createElement("input");p.type="text",p.setAttribute("aria-label",this.strings.inputPlaceholder),p.placeholder=this.strings.inputPlaceholder;let m=document.createElement("button");m.type="submit",m.setAttribute("aria-label",this.strings.sendLabel),m.innerHTML='<svg class="sendglyph" aria-hidden="true" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M4.5 12 20 4.5 15 20l-3.6-5.4L4.5 12Z"/></svg>';let v=document.createElement("span");v.className="sendtext",v.textContent=this.strings.sendLabel,m.append(v),l.append(p,m),l.addEventListener("submit",b=>{b.preventDefault(),this.submit(p,c);}),e.append(t,c,l),e.addEventListener("keydown",b=>this.onKeydown(b,e,h)),this.root.append(e),this.panel=e,p.focus();let y=await this.client.load();y&&y.turns.length>0?this.renderThread(c,y):this.renderFirstRun(c,p),this.openNow||this.renderAway(c);}renderFirstRun(e,t){let n=document.createElement("div");n.className="empty";let r=document.createElement("h3");r.textContent=this.appearance.greeting.trim()||this.strings.emptyTitle;let o=document.createElement("p");o.textContent=this.strings.emptyBody,n.append(r,o);for(let d of this.appearance.starterPrompts){let i=document.createElement("button");i.className="prompt",i.type="button",i.textContent=d,i.addEventListener("click",()=>{t.value=d,this.submit(t,e);}),n.append(i);}e.replaceChildren(n);}renderAway(e){let t=document.createElement("div");t.className="away",t.textContent=this.appearance.awayMessage.trim()||this.strings.awayBody,e.prepend(t);}close(){this.panel&&(this.panel.remove(),this.panel=null,this.lastFocused instanceof HTMLElement?this.lastFocused.focus():this.launcher.focus());}onIncomingTurn(e){if(this.panel){let t=this.panel.querySelector(".log");t instanceof HTMLElement&&!this.hasTurn(t,e.id)&&this.appendTurn(t,e);return}e.authorKind!=="end_user"&&(this.unread+=1,this.renderBadge());}async submit(e,t){let n=e.value.trim();n&&(e.value="",await this.sendBody(t,n));}async sendBody(e,t){e.querySelector(".empty")?.remove(),this.pendingTurns+=1;let n=this.appendTurn(e,{authorId:null,authorKind:"end_user",body:t,createdAt:new Date().toISOString(),id:`pending-${this.pendingTurns}`});n.setAttribute("data-pending","");let r=await this.client.send(t,_e());if(n.removeAttribute("data-pending"),r){n.dataset.turnId=r.id;return}this.markFailed(e,n,t);}markFailed(e,t,n){t.setAttribute("data-failed","");let r=document.createElement("button");r.type="button",r.className="retry",r.textContent=this.strings.retryLabel,r.addEventListener("click",()=>{t.remove(),this.sendBody(e,n);}),(t.querySelector(".body")??t).append(r);}hasTurn(e,t){for(let n of e.children)if(n instanceof HTMLElement&&n.dataset.turnId===t)return true;return false}renderThread(e,t){e.replaceChildren();for(let n of t.turns)this.appendTurn(e,n);}appendTurn(e,t){e.querySelector(".empty")?.remove();let n=Pe.includes(t.authorKind)?t.authorKind:"agent",r=this.settings,o=document.createElement("div");if(o.className=`turn ${n}`,o.dataset.turnId=t.id,n!=="end_user"&&r.nameAvatar){let l=document.createElement("span");if(l.className=n==="ai"?"av bot":"av",l.setAttribute("aria-hidden","true"),n==="agent"&&t.authorAvatarUrl){let p=document.createElement("img");p.alt="",p.src=this.client.avatarUrl(t.authorAvatarUrl),l.append(p);}else l.textContent=n==="ai"?this.strings.aiLabel:z(this.agentName(t));o.append(l);}let i=document.createElement("div");i.className="body";let h=n!=="end_user"&&r.namePlacement!=="hidden",c=document.createElement("div");if(c.textContent=t.body,h||n==="ai"&&r.namePlacement==="hidden"){let l=document.createElement("div");l.className=n==="ai"?"author ai":"author",l.textContent=n==="ai"?this.strings.aiLabel:this.agentName(t),r.stampPlacement==="beside_name"&&l.append(this.stamp(t)),r.namePlacement==="inline"?(l.classList.add("below"),i.append(c,l)):i.append(l,c);}else i.append(c);return r.stampPlacement==="under_turn"&&i.append(this.stamp(t)),o.append(i),e.append(o),e.scrollTop=e.scrollHeight,o}agentName(e){return e.authorName||this.strings.agentLabel}stamp(e){let t=document.createElement("span");return t.className="stamp",t.textContent=this.strings.timeLabel(e.createdAt),t}onKeydown(e,t,n){if(e.key==="Escape"){e.preventDefault(),this.close();return}if(e.key!=="Tab")return;let r=t.querySelectorAll('button, input, [tabindex]:not([tabindex="-1"])');if(r.length===0)return;let o=r[0],d=r[r.length-1],i=this.root.activeElement;e.shiftKey&&i===o?(e.preventDefault(),d.focus()):!e.shiftKey&&i===d?(e.preventDefault(),o.focus()):i===null&&(e.preventDefault(),n.focus());}renderBadge(){this.unread>0?(this.badge.hidden=false,this.badge.textContent=String(this.unread),this.launcher.setAttribute("aria-label",`${this.strings.launcherLabel}, ${this.strings.unreadLabel(this.unread)}`)):(this.badge.hidden=true,this.badge.textContent="",this.launcher.setAttribute("aria-label",this.strings.launcherLabel));}};var Ne="/socket.io/?EIO=4&transport=websocket",E=class{constructor(e){this.options=e;a(this,"socket",null);a(this,"heartbeat",null);a(this,"ready",false);a(this,"closed",false);a(this,"heartbeatWindow",45e3);a(this,"factory");a(this,"setTimer");a(this,"clearTimer");this.factory=e.socketFactory??He,this.setTimer=e.setTimer??((t,n)=>setTimeout(t,n)),this.clearTimer=e.clearTimer??(t=>clearTimeout(t));}open(){if(this.socket||this.closed)return;let e=`${this.options.host.replace(/^http/,"ws").replace(/\/+$/,"")}${Ne}`,t;try{t=this.factory(e);}catch{this.options.onClosed(false);return}this.socket=t,t.onmessage=n=>this.receive(String(n.data)),t.onerror=()=>t.close(),t.onclose=()=>this.fell();}close(){this.closed=true,this.stopHeartbeat();let e=this.socket;this.socket=null,e?.close();}receive(e){let t=c(e);if(t.kind==="open"){this.armHeartbeat(t.pingInterval+t.pingTimeout),this.socket?.send(a$2(this.options.auth));return}if(t.kind==="ping"){this.armHeartbeat(),this.socket?.send(b());return}if(t.kind==="connectError"||t.kind==="disconnect"){this.stopHeartbeat(),this.socket?.close();return}if(t.kind==="event"){if(t.name==="ready"){this.ready=true,this.options.onReady();return}if(t.name==="conversation.turn"){let n=t.payload?.turn;n&&this.options.onTurn(n);}}}fell(){this.stopHeartbeat();let e=this.ready;this.socket=null,this.ready=false,this.closed||this.options.onClosed(e);}armHeartbeat(e){e!==void 0&&(this.heartbeatWindow=e),this.stopHeartbeat(),this.heartbeat=this.setTimer(()=>this.socket?.close(),this.heartbeatWindow);}stopHeartbeat(){this.heartbeat!==null&&this.clearTimer(this.heartbeat),this.heartbeat=null;}};function He(a){let e=globalThis.WebSocket;if(!e)throw new Error("no WebSocket");return new e(a)}var Ie=6e4;function Ve(a){let e=globalThis.document;if(!e)throw new Error("prodantix chat requires a document; mount it in the browser");let t=a.mountPoint??e.createElement("div");a.mountPoint||e.body.append(t);let n=new k(a),r=new w(t,n,a.strings,a.appearance),o=a.appearance?.availability??x.availability,d,i=()=>{r.setOpenNow(T(o,new Date)),d=setTimeout(i,Ie);};i();let h=new Set,c,l=null,p=a.pollIntervalMs??15e3,m=g=>{h.has(g.id)||g.authorKind==="end_user"||(h.add(g.id),r.onIncomingTurn(g));},v=async()=>{if(!n.hasThread)return;let g=await n.load();if(g){for(let S of g.turns)m(S);h=new Set(g.turns.map(S=>S.id));}},y=()=>{c||p<=0||(c=setInterval(()=>void v(),p));},b=()=>{c&&clearInterval(c),c=void 0;},A=()=>{if(l||!a.socketHost)return;let g=n.socketAuth;g&&(l=new E({auth:g,host:a.socketHost,onClosed:S=>{l=null,y(),S&&A();},onReady:b,onTurn:m,socketFactory:a.socketFactory}),l.open());};return y(),A(),{close:()=>r.close(),destroy:()=>{b(),clearTimeout(d),l?.close(),l=null,r.close(),t.remove();},identify:g=>n.identify(g),open:()=>{r.open().then(A);}}}export{k as ChatClient,w as ChatPanel,x as DEFAULT_APPEARANCE,u as DEFAULT_APPEARANCE_SETTINGS,Ve as mountChat,N as panelStyles,C as resolveAppearance};//# sourceMappingURL=chat.js.map
|
|
154
|
+
`}${ve[t.composerShape]}${xe[t.skin]}${B(t.launcherShape,t.launcherFill,t.launcherContent,t.launcherSize)}${Se[t.bubbleShape]}${ke[t.bubbleFill]}${Ce[t.namePlacement]}${t.nameAvatar?we:""}${t.dayDividers?Te:""}${Ee[t.stampPlacement]}${t.stampContent==="time_and_latency"?Ae:""}`}var Pe=["end_user","agent","ai"];function _e(){let r=globalThis.location;if(r)return {host:r.host,path:r.pathname,title:document.title}}var w=class{constructor(e,t,n={},a$1={},o={}){this.host=e;this.client=t;a(this,"root");a(this,"strings");a(this,"settings");a(this,"appearance");a(this,"launcher");a(this,"badge");a(this,"panel",null);a(this,"lastFocused",null);a(this,"unread",0);a(this,"pendingTurns",0);a(this,"openNow");a(this,"style");a(this,"scheme");this.strings={...ye,...n},this.appearance={...x,...a$1},this.settings=C({...x,...a$1}),this.root=e.attachShadow({mode:o.shadowMode??"closed"}),this.openNow=T(this.appearance.availability,new Date),this.scheme=o.scheme,this.style=document.createElement("style"),this.style.textContent=N(this.appearance,this.scheme),this.root.append(this.style),this.launcher=document.createElement("button"),this.launcher.className="launcher",this.launcher.type="button",this.launcher.setAttribute("aria-haspopup","dialog"),this.launcher.addEventListener("click",()=>this.toggle()),this.badge=document.createElement("span"),this.badge.className="badge",this.badge.hidden=true,this.drawLauncher(),this.root.append(this.launcher);}drawLauncher(){if(this.launcher.setAttribute("aria-label",this.strings.launcherLabel),this.launcher.replaceChildren(),this.launcher.append(O(this.settings.launcherContent,this.strings,this.appearance.team,e=>this.client.avatarUrl(e))),this.settings.launcherShape==="pill"){let e=document.createElement("span");e.className="label",e.textContent=this.settings.launcherContent==="team_faces"?this.strings.agentLabel:this.strings.launcherLabel,this.launcher.append(e);}this.launcher.append(this.badge),this.launcher.classList.toggle("closed",!this.openNow);}update(e,t){this.appearance={...x,...e},this.settings=C(this.appearance),t!==void 0&&(this.scheme=t),this.style.textContent=N(this.appearance,this.scheme),this.drawLauncher(),this.panel&&(this.close(),this.open());}toggle(){this.panel?this.close():this.open();}setOpenNow(e){this.openNow=e,this.launcher.classList.toggle("closed",!e),this.panel?.classList.toggle("closed",!e);}async open(){if(this.panel)return;this.lastFocused=this.host.ownerDocument.activeElement,this.unread=0,this.renderBadge();let e=document.createElement("section");e.className=this.openNow?"panel":"panel closed",e.setAttribute("role","dialog"),e.setAttribute("aria-modal","true"),e.setAttribute("aria-label",this.strings.title);let t=document.createElement("div");t.className="header";let n=this.appearance.team??[];n.length>0&&t.append(_(n,this.strings,b=>this.client.avatarUrl(b),false));let a=document.createElement("div");a.className="headmain";let o=document.createElement("h2");o.textContent=this.strings.title;let d=document.createElement("p");d.className="status";let i=document.createElement("span");i.className="live",i.setAttribute("aria-hidden","true"),d.append(i,this.strings.replyTime),a.append(o,d);let h=document.createElement("button");h.className="close",h.type="button",h.setAttribute("aria-label",this.strings.closeLabel),h.textContent="\xD7",h.addEventListener("click",()=>this.close()),t.append(a,h);let c=document.createElement("div");c.className="log",c.setAttribute("role","log"),c.setAttribute("aria-live","polite"),c.setAttribute("aria-label",this.strings.title);let l=document.createElement("form");l.className="composer";let p=document.createElement("input");p.type="text",p.setAttribute("aria-label",this.strings.inputPlaceholder),p.placeholder=this.strings.inputPlaceholder;let m=document.createElement("button");m.type="submit",m.setAttribute("aria-label",this.strings.sendLabel),m.innerHTML='<svg class="sendglyph" aria-hidden="true" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M4.5 12 20 4.5 15 20l-3.6-5.4L4.5 12Z"/></svg>';let v=document.createElement("span");v.className="sendtext",v.textContent=this.strings.sendLabel,m.append(v),l.append(p,m),l.addEventListener("submit",b=>{b.preventDefault(),this.submit(p,c);}),e.append(t,c,l),e.addEventListener("keydown",b=>this.onKeydown(b,e,h)),this.root.append(e),this.panel=e,p.focus();let y=await this.client.load();y&&y.turns.length>0?this.renderThread(c,y):this.renderFirstRun(c,p),this.openNow||this.renderAway(c);}renderFirstRun(e,t){let n=document.createElement("div");n.className="empty";let a=document.createElement("h3");a.textContent=this.appearance.greeting.trim()||this.strings.emptyTitle;let o=document.createElement("p");o.textContent=this.strings.emptyBody,n.append(a,o);for(let d of this.appearance.starterPrompts){let i=document.createElement("button");i.className="prompt",i.type="button",i.textContent=d,i.addEventListener("click",()=>{t.value=d,this.submit(t,e);}),n.append(i);}e.replaceChildren(n);}renderAway(e){let t=document.createElement("div");t.className="away",t.textContent=this.appearance.awayMessage.trim()||this.strings.awayBody,e.prepend(t);}close(){this.panel&&(this.panel.remove(),this.panel=null,this.lastFocused instanceof HTMLElement?this.lastFocused.focus():this.launcher.focus());}onIncomingTurn(e){if(this.panel){let t=this.panel.querySelector(".log");t instanceof HTMLElement&&!this.hasTurn(t,e.id)&&this.appendTurn(t,e);return}e.authorKind!=="end_user"&&(this.unread+=1,this.renderBadge());}async submit(e,t){let n=e.value.trim();n&&(e.value="",await this.sendBody(t,n));}async sendBody(e,t){e.querySelector(".empty")?.remove(),this.pendingTurns+=1;let n=this.appendTurn(e,{authorId:null,authorKind:"end_user",body:t,createdAt:new Date().toISOString(),id:`pending-${this.pendingTurns}`});n.setAttribute("data-pending","");let a=await this.client.send(t,_e());if(n.removeAttribute("data-pending"),a){n.dataset.turnId=a.id;return}this.markFailed(e,n,t);}markFailed(e,t,n){t.setAttribute("data-failed","");let a=document.createElement("button");a.type="button",a.className="retry",a.textContent=this.strings.retryLabel,a.addEventListener("click",()=>{t.remove(),this.sendBody(e,n);}),(t.querySelector(".body")??t).append(a);}hasTurn(e,t){for(let n of e.children)if(n instanceof HTMLElement&&n.dataset.turnId===t)return true;return false}renderThread(e,t){e.replaceChildren();for(let n of t.turns)this.appendTurn(e,n);}appendTurn(e,t){e.querySelector(".empty")?.remove();let n=Pe.includes(t.authorKind)?t.authorKind:"agent",a=this.settings,o=document.createElement("div");if(o.className=`turn ${n}`,o.dataset.turnId=t.id,n!=="end_user"&&a.nameAvatar){let l=document.createElement("span");if(l.className=n==="ai"?"av bot":"av",l.setAttribute("aria-hidden","true"),n==="agent"&&t.authorAvatarUrl){let p=document.createElement("img");p.alt="",p.src=this.client.avatarUrl(t.authorAvatarUrl),l.append(p);}else l.textContent=n==="ai"?this.strings.aiLabel:z(this.agentName(t));o.append(l);}let i=document.createElement("div");i.className="body";let h=n!=="end_user"&&a.namePlacement!=="hidden",c=document.createElement("div");if(c.textContent=t.body,h||n==="ai"&&a.namePlacement==="hidden"){let l=document.createElement("div");l.className=n==="ai"?"author ai":"author",l.textContent=n==="ai"?this.strings.aiLabel:this.agentName(t),a.stampPlacement==="beside_name"&&l.append(this.stamp(t)),a.namePlacement==="inline"?(l.classList.add("below"),i.append(c,l)):i.append(l,c);}else i.append(c);return a.stampPlacement==="under_turn"&&i.append(this.stamp(t)),o.append(i),e.append(o),e.scrollTop=e.scrollHeight,o}agentName(e){return e.authorName||this.strings.agentLabel}stamp(e){let t=document.createElement("span");return t.className="stamp",t.textContent=this.strings.timeLabel(e.createdAt),t}onKeydown(e,t,n){if(e.key==="Escape"){e.preventDefault(),this.close();return}if(e.key!=="Tab")return;let a=t.querySelectorAll('button, input, [tabindex]:not([tabindex="-1"])');if(a.length===0)return;let o=a[0],d=a[a.length-1],i=this.root.activeElement;e.shiftKey&&i===o?(e.preventDefault(),d.focus()):!e.shiftKey&&i===d?(e.preventDefault(),o.focus()):i===null&&(e.preventDefault(),n.focus());}renderBadge(){this.unread>0?(this.badge.hidden=false,this.badge.textContent=String(this.unread),this.launcher.setAttribute("aria-label",`${this.strings.launcherLabel}, ${this.strings.unreadLabel(this.unread)}`)):(this.badge.hidden=true,this.badge.textContent="",this.launcher.setAttribute("aria-label",this.strings.launcherLabel));}};var Ne="/socket.io/?EIO=4&transport=websocket",E=class{constructor(e){this.options=e;a(this,"socket",null);a(this,"heartbeat",null);a(this,"ready",false);a(this,"closed",false);a(this,"heartbeatWindow",45e3);a(this,"factory");a(this,"setTimer");a(this,"clearTimer");this.factory=e.socketFactory??He,this.setTimer=e.setTimer??((t,n)=>setTimeout(t,n)),this.clearTimer=e.clearTimer??(t=>clearTimeout(t));}open(){if(this.socket||this.closed)return;let e=`${this.options.host.replace(/^http/,"ws").replace(/\/+$/,"")}${Ne}`,t;try{t=this.factory(e);}catch{this.options.onClosed(false);return}this.socket=t,t.onmessage=n=>this.receive(String(n.data)),t.onerror=()=>t.close(),t.onclose=()=>this.fell();}close(){this.closed=true,this.stopHeartbeat();let e=this.socket;this.socket=null,e?.close();}receive(e){let t=c(e);if(t.kind==="open"){this.armHeartbeat(t.pingInterval+t.pingTimeout),this.socket?.send(a$2(this.options.auth));return}if(t.kind==="ping"){this.armHeartbeat(),this.socket?.send(b());return}if(t.kind==="connectError"||t.kind==="disconnect"){this.stopHeartbeat(),this.socket?.close();return}if(t.kind==="event"){if(t.name==="ready"){this.ready=true,this.options.onReady();return}if(t.name==="conversation.turn"){let n=t.payload?.turn;n&&this.options.onTurn(n);}}}fell(){this.stopHeartbeat();let e=this.ready;this.socket=null,this.ready=false,this.closed||this.options.onClosed(e);}armHeartbeat(e){e!==void 0&&(this.heartbeatWindow=e),this.stopHeartbeat(),this.heartbeat=this.setTimer(()=>this.socket?.close(),this.heartbeatWindow);}stopHeartbeat(){this.heartbeat!==null&&this.clearTimer(this.heartbeat),this.heartbeat=null;}};function He(r){let e=globalThis.WebSocket;if(!e)throw new Error("no WebSocket");return new e(r)}var Ie=6e4;function Je(r){let e=globalThis.document;if(!e)throw new Error("prodantix chat requires a document; mount it in the browser");let t=r.mountPoint??e.createElement("div");r.mountPoint||e.body.append(t);let n=new k(r),a=new w(t,n,r.strings,r.appearance),o=r.appearance?.availability??x.availability,d,i=()=>{a.setOpenNow(T(o,new Date)),d=setTimeout(i,Ie);};i();let h=new Set,c,l=null,p=r.pollIntervalMs??15e3,m=g=>{h.has(g.id)||g.authorKind==="end_user"||(h.add(g.id),a.onIncomingTurn(g));},v=async()=>{if(!n.hasThread)return;let g=await n.load();if(g){for(let S of g.turns)m(S);h=new Set(g.turns.map(S=>S.id));}},y=()=>{c||p<=0||(c=setInterval(()=>void v(),p));},b=()=>{c&&clearInterval(c),c=void 0;},A=()=>{if(l||!r.socketHost)return;let g=n.socketAuth;g&&(l=new E({auth:g,host:r.socketHost,onClosed:S=>{l=null,y(),S&&A();},onReady:b,onTurn:m,socketFactory:r.socketFactory}),l.open());};return y(),A(),{close:()=>a.close(),destroy:()=>{b(),clearTimeout(d),l?.close(),l=null,a.close(),t.remove();},identify:g=>n.identify(g),open:()=>{a.open().then(A);}}}export{k as ChatClient,w as ChatPanel,x as DEFAULT_APPEARANCE,u as DEFAULT_APPEARANCE_SETTINGS,Je as mountChat,N as panelStyles,C as resolveAppearance};//# sourceMappingURL=chat.js.map
|
|
150
155
|
//# sourceMappingURL=chat.js.map
|
package/dist/messenger.iife.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
(function(){'use strict';var ae=Object.defineProperty;var ie=(n,e,t)=>e in n?ae(n,e,{enumerable:true,configurable:true,writable:true,value:t}):n[e]=t;var u=(n,e,t)=>ie(n,typeof e!="symbol"?e+"":e,t);function L(n){if(n)return n;let e=globalThis.fetch;if(typeof e=="function")return e.bind(globalThis)}function N(n){return n.replace(/\/+$/,"")}var oe="X-Prodantix-Conversation-Token",F="prodantix.chat.handle";function se(){let n=globalThis.localStorage;if(n)return {get:e=>n.getItem(e),remove:e=>n.removeItem(e),set:(e,t)=>n.setItem(e,t)}}var P=class{constructor(e){this.options=e;u(this,"fetchImpl");u(this,"host");u(this,"storage");u(this,"handle");u(this,"identity",null);var t;this.fetchImpl=L(e.fetchImpl),this.host=N(e.host),this.storage=(t=e.storage)!=null?t:se(),this.handle=this.readHandle();}get hasThread(){return this.handle!==null}avatarUrl(e){return e.startsWith("/")?`${this.host}${e}?api_key=${encodeURIComponent(this.options.apiKey)}`:e}get socketAuth(){return this.handle?{conversationId:this.handle.conversationId,conversationToken:this.handle.token,projectKey:this.options.apiKey}:null}identify(e){this.identity=e;}async ensureThread(e){var r,a,i;if(this.handle)return true;let t=await this.request("POST","/v1/conversations",{body:{distinctId:this.options.distinctId,subject:e,userHash:(r=this.identity)==null?void 0:r.userHash,userId:(a=this.identity)==null?void 0:a.userId}});return !(t!=null&&t.conversationId)||!t.token?false:(this.handle={conversationId:t.conversationId,token:t.token},(i=this.storage)==null||i.set(F,JSON.stringify(this.handle)),true)}async send(e,t){var i;if(!await this.ensureThread())return null;let r=this.handle;if(!r)return null;let a=await this.request("POST",`/v1/conversations/${encodeURIComponent(r.conversationId)}/turns`,{body:{body:e,pageContext:t},token:r.token});return (i=a==null?void 0:a.turn)!=null?i:null}async load(){let e=this.handle;return e?this.request("GET",`/v1/conversations/${encodeURIComponent(e.conversationId)}`,{token:e.token}):null}readHandle(){var t,r;let e=(t=this.storage)==null?void 0:t.get(F);if(!e)return null;try{let a=JSON.parse(e);if(typeof a.conversationId=="string"&&typeof a.token=="string")return {conversationId:a.conversationId,token:a.token}}catch(a){}return (r=this.storage)==null||r.remove(F),null}async request(e,t,r={}){var o,s,p,l,d,c;let a=this.fetchImpl;if(!a)return (s=(o=this.options).onError)==null||s.call(o,new Error("no fetch available for prodantix chat")),null;let i={authorization:`Bearer ${this.options.apiKey}`,"content-type":"application/json"};r.token&&(i[oe]=r.token);try{let h=await a(`${this.host}${t}`,{body:r.body===void 0?void 0:JSON.stringify(r.body),headers:i,method:e}),g=await h.text();return h.ok?g?JSON.parse(g):{}:((l=(p=this.options).onError)==null||l.call(p,new Error(`prodantix chat ${t}: ${h.status}`)),null)}catch(h){return (c=(d=this.options).onError)==null||c.call(d,h),null}}};var le={Fri:"fri",Mon:"mon",Sat:"sat",Sun:"sun",Thu:"thu",Tue:"tue",Wed:"wed"};function _(n,e){var s,p,l,d,c,h;let t=new Intl.DateTimeFormat(void 0,{hour:"2-digit",hour12:false,minute:"2-digit",timeZone:n.timezone,weekday:"short"}).formatToParts(e),r=le[(p=(s=t.find(g=>g.type==="weekday"))==null?void 0:s.value)!=null?p:""];if(!r)return false;let a=(d=(l=t.find(g=>g.type==="hour"))==null?void 0:l.value)!=null?d:"",i=(h=(c=t.find(g=>g.type==="minute"))==null?void 0:c.value)!=null?h:"",o=`${a}:${i}`;return n.windows.some(g=>g.days.includes(r)&&g.open<=o&&o<g.close)}var y={bubbleFill:"filled",bubbleShape:"tailed",composerShape:"round",dayDividers:true,launcherContent:"glyph",launcherFill:"outlined",launcherShape:"circle",launcherSize:"small",nameAvatar:true,namePlacement:"hidden",skin:"standard",stampContent:"time",stampPlacement:"none"},ce=["quiet","standard"],de=["round","square"],pe=["rounded","tailed"],he=["filled","outlined"],ue=["circle","pill","squircle"],ge=["filled","outlined"],me=["avatar","glyph","team_faces"],fe=["large","medium","small"],be=["above","hidden","inline"],ye=["beside_name","none","under_turn"],xe=["time","time_and_latency"],S=(n,e,t)=>typeof n=="string"&&e.includes(n)?n:t,D=(n,e)=>typeof n=="boolean"?n:e,ve={avatar_circle:["circle","outlined","avatar","large"],circle_filled:["circle","filled","glyph","medium"],circle_outlined:["circle","outlined","glyph","small"],pill_labelled:["pill","filled","glyph","medium"],pill_team:["pill","outlined","team_faces","medium"],squircle_filled:["squircle","filled","glyph","medium"]},Se={above:["above",false],avatar_only:["hidden",true],gutter:["above",true],hidden:["hidden",false],inline:["inline",false]},Ce={cluster:[true,"none","time"],latency:[false,"beside_name","time_and_latency"],none:[false,"none","time"],trailing:[false,"under_turn","time"],with_name:[false,"beside_name","time"]},ke={concierge:["standard","round"],console:["standard","square"],quiet:["quiet","square"]},Ee={hairline:["rounded","outlined"],outlined:["rounded","outlined"],rounded:["rounded","filled"],tailed:["tailed","filled"]};function I(n){var g,x,v,b,m,C,k,w,f,E,U,B,K;let e=typeof n=="object"&&n!==null?n:{},t=typeof e.launcherStyle=="string"?e.launcherStyle:void 0,r=t===void 0?void 0:ve[t],a=typeof e.namePlacement=="string"?e.namePlacement:void 0,i=a===void 0?void 0:Se[a],o=typeof e.timestampStyle=="string"?e.timestampStyle:void 0,s=o===void 0?void 0:Ce[o],p=typeof e.skin=="string"?e.skin:void 0,l=p===void 0?void 0:ke[p],d=typeof e.bubbleStyle=="string"?e.bubbleStyle:void 0,c=d===void 0?void 0:Ee[d],h={bubbleFill:S(e.bubbleFill,he,(g=c==null?void 0:c[1])!=null?g:y.bubbleFill),bubbleShape:S(e.bubbleShape,pe,(x=c==null?void 0:c[0])!=null?x:y.bubbleShape),composerShape:S(e.composerShape,de,(v=l==null?void 0:l[1])!=null?v:y.composerShape),dayDividers:D(e.dayDividers,(b=s==null?void 0:s[0])!=null?b:y.dayDividers),launcherContent:S(e.launcherContent,me,(m=r==null?void 0:r[2])!=null?m:y.launcherContent),launcherFill:S(e.launcherFill,ge,(C=r==null?void 0:r[1])!=null?C:y.launcherFill),launcherShape:S(e.launcherShape,ue,(k=r==null?void 0:r[0])!=null?k:y.launcherShape),launcherSize:S(e.launcherSize,fe,(w=r==null?void 0:r[3])!=null?w:y.launcherSize),nameAvatar:D(e.nameAvatar,(f=i==null?void 0:i[1])!=null?f:y.nameAvatar),namePlacement:S(e.namePlacement,be,(E=i==null?void 0:i[0])!=null?E:y.namePlacement),skin:S(e.skin,ce,(U=l==null?void 0:l[0])!=null?U:y.skin),stampContent:S(e.stampContent,xe,(B=s==null?void 0:s[2])!=null?B:y.stampContent),stampPlacement:S(e.stampPlacement,ye,(K=s==null?void 0:s[1])!=null?K:y.stampPlacement)};return h.stampPlacement==="beside_name"&&h.namePlacement==="hidden"&&(h.stampPlacement="under_turn"),h}function G(n){var r,a,i,o;let e=n.split(/\s+/).filter(s=>s.length>0);return (e.length>1?`${(r=e[0])==null?void 0:r.slice(0,1)}${(a=e[1])==null?void 0:a.slice(0,1)}`:(o=(i=e[0])==null?void 0:i.slice(0,2))!=null?o:"").toUpperCase()}var we="M20 11.6a7.4 7.4 0 0 1-7.4 7.4H8.2L4 21.8l1-4.1A7.4 7.4 0 1 1 20 11.6Z",Te={large:66,medium:56,small:46},Ae={circle:"width:var(--fab-size);height:var(--fab-size);border-radius:calc(var(--fab-size) / 2);",pill:"width:auto;height:var(--fab-size);border-radius:calc(var(--fab-size) / 2);padding:0 22px;gap:10px;",squircle:"width:var(--fab-size);height:var(--fab-size);border-radius:16px;"},Le={filled:"background:var(--a);color:#fff;",outlined:"background:var(--paper);border:1px solid var(--hairline);color:var(--ink-2);box-shadow:0 1px 2px rgba(0,0,0,.08);"},Ne={avatar:"",glyph:".launcher svg{width:calc(var(--fab-size) * 0.375);height:calc(var(--fab-size) * 0.375);}",team_faces:".launcher .faces{display:flex;}.launcher .faces .av{box-shadow:0 0 0 2px var(--paper);}.launcher .faces .av+.av{margin-left:-10px;}"},Pe=".launcher .live{width:10px;height:10px;position:absolute;right:3px;bottom:3px;border-radius:50%;background:var(--online);box-shadow:0 0 0 2px var(--paper);}.launcher.closed .live{display:none}",_e={circle:"",pill:".badge{position:static;box-shadow:none}",squircle:""},Ie={filled:"",outlined:".badge{background:var(--a);top:-7px;right:-7px;min-width:19px;height:19px;font-size:11.5px}"},Me={circle:"",pill:".launcher .label{font-size:14px;font-weight:600;white-space:nowrap;}",squircle:""},He={circle:"",pill:"@media (max-width:480px){.launcher{width:var(--fab-size);padding:0}.launcher .label{display:none}}",squircle:""};function q(n,e,t,r){return `.launcher{--fab-size:${Te[r]}px;${Ae[n]}${Le[e]}}${Ne[t]}${Pe}${_e[n]}${Ie[e]}${Me[n]}${He[n]}`}function W(n,e,t,r=a=>a){let a=document.createDocumentFragment();if(n==="glyph"||t.length===0){let i=document.createElement("span");return i.innerHTML=`<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="${we}"/></svg>`,a.append(...i.childNodes,O()),a}return n==="avatar"?(a.append(j(t[0],e,r),O()),a):(a.append(R(t,e,r),O()),a)}function R(n,e,t=r=>r){let r=document.createElement("span");r.className="faces";for(let a of n.slice(0,2))r.append(j(a,e,t));return r}function j(n,e,t){let r=document.createElement("span");if(r.className="av",r.setAttribute("aria-hidden","true"),n&&(r.style.background=n.tone),n!=null&&n.avatarUrl){let a=document.createElement("img");return a.alt="",a.src=t(n.avatarUrl),r.append(a),r}return r.textContent=n?n.initials:e.agentLabel.slice(0,2).toUpperCase(),r}function O(){let n=document.createElement("span");return n.className="live",n.setAttribute("aria-hidden","true"),n}var Fe={agentLabel:"Agent",aiLabel:"AI",awayBody:"We are away right now, but we will reply as soon as we are back.",closeLabel:"Close chat",emptyBody:"We usually reply within a few minutes.",emptyTitle:"Ask us anything.",inputPlaceholder:"Type a message",launcherLabel:"Chat with us",replyTime:"Usually replying in a few minutes",retryLabel:"Not delivered. Retry",sendLabel:"Send",timeLabel:n=>{let e=new Date(n);return Number.isNaN(e.getTime())?"":`${String(e.getHours()).padStart(2,"0")}:${String(e.getMinutes()).padStart(2,"0")}`},title:"Support",unreadLabel:n=>`${n} unread`},T={accentColor:"#5b5bff",availability:{timezone:"UTC",windows:[]},awayMessage:"",greeting:"",launcherOffsetX:20,launcherOffsetY:20,launcherPosition:"bottom_right",starterPrompts:[],team:[],...y},Oe={quiet:".composer{position:relative;padding:8px 10px 10px}.composer input{padding-right:36px}.composer button{position:absolute;top:50%;right:14px;width:28px;min-width:28px;height:28px;padding:0;background:transparent;color:var(--ink);border-radius:7px;transform:translateY(-50%)}.composer button .sendglyph{display:block;width:16px;height:16px}.composer button .sendtext{display:none}.panel{border-radius:8px;box-shadow:0 2px 8px rgba(0,0,0,.12)}.header{background:var(--paper);color:var(--ink);height:44px;padding:0 8px 0 16px;border-bottom:1px solid var(--hairline)}.header h2{font-size:11px;letter-spacing:.11em;text-transform:uppercase;color:var(--ink-3)}.header .status{color:var(--ink-3)}.header .av,.header .status .live{box-shadow:0 0 0 2px var(--paper)}.close{color:var(--ink-2)}",standard:".panel{border-radius:16px;box-shadow:0 16px 40px rgba(0,0,0,.2)}.header{background:var(--a);color:#fff;flex-direction:column;align-items:flex-start;gap:14px;padding:18px 14px 20px 20px}.header h2{font-size:19px;font-weight:640}"},Re={round:".composer{padding:10px 10px 12px;gap:6px}.composer input{height:36px;border-radius:18px;padding:0 14px}.composer button{width:36px;min-width:36px;height:36px;padding:0;border-radius:18px}.composer button .sendglyph{display:block}.composer button .sendtext{display:none}",square:".composer input{height:36px;border-radius:8px;padding:0 12px}"},$e={rounded:".turn{border-radius:18px;padding:10px 15px}",tailed:".turn.agent,.turn.ai{border-radius:12px 12px 12px 4px}.turn.end_user{border-radius:12px 12px 4px 12px}"},ze={filled:"",outlined:".turn{background:none;border:1px solid var(--hairline)}.turn.end_user{background:none;border-color:var(--a);color:var(--ink)}"},Ue={above:"",hidden:".turn.agent .author,.turn.ai .author:not(.ai){display:none}",inline:".body .author.below{display:block;margin:4px 0 0;font-size:11.5px;font-weight:500;color:var(--ink-2);text-transform:none;letter-spacing:0;opacity:1}"},Be=".turn.agent,.turn.ai{display:flex;gap:10px;max-width:100%;background:none;padding:0}.turn.agent .body,.turn.ai .body{background:var(--fill);padding:9px 13px;border-radius:inherit}.author{text-transform:none;letter-spacing:0;font-size:12.5px;font-weight:600;opacity:1}",Ke='.divider{display:flex;align-items:center;gap:10px;margin:0;font-size:11px;opacity:.6}.divider:before,.divider:after{content:"";flex:1;height:1px;background:var(--hairline)}',De={beside_name:".stamp{font-size:11px;opacity:.7;margin-left:6px}",none:"",under_turn:".stamp{display:block;font-size:11px;opacity:.7;margin-top:4px}.turn.end_user .stamp{text-align:right}"},Ge=".lat{font-size:11px;opacity:.7;margin-left:6px}",Y=`--paper: oklch(24.6% 0.015 257); --ink: #fff; --ink-3: rgba(255,255,255,.55);
|
|
1
|
+
(function(){'use strict';var ae=Object.defineProperty;var ie=(n,e,t)=>e in n?ae(n,e,{enumerable:true,configurable:true,writable:true,value:t}):n[e]=t;var u=(n,e,t)=>ie(n,typeof e!="symbol"?e+"":e,t);function L(n){if(n)return n;let e=globalThis.fetch;if(typeof e=="function")return e.bind(globalThis)}function N(n){return n.replace(/\/+$/,"")}var oe="X-Prodantix-Conversation-Token",F="prodantix.chat.handle";function se(){let n=globalThis.localStorage;if(n)return {get:e=>n.getItem(e),remove:e=>n.removeItem(e),set:(e,t)=>n.setItem(e,t)}}var P=class{constructor(e){this.options=e;u(this,"fetchImpl");u(this,"host");u(this,"storage");u(this,"handle");u(this,"identity",null);var t;this.fetchImpl=L(e.fetchImpl),this.host=N(e.host),this.storage=(t=e.storage)!=null?t:se(),this.handle=this.readHandle();}get hasThread(){return this.handle!==null}avatarUrl(e){return e.startsWith("/")?`${this.host}${e}?api_key=${encodeURIComponent(this.options.apiKey)}`:e}get socketAuth(){return this.handle?{conversationId:this.handle.conversationId,conversationToken:this.handle.token,projectKey:this.options.apiKey}:null}identify(e){this.identity=e;}async ensureThread(e){var r,a,i;if(this.handle)return true;let t=await this.request("POST","/v1/conversations",{body:{distinctId:this.options.distinctId,subject:e,userHash:(r=this.identity)==null?void 0:r.userHash,userId:(a=this.identity)==null?void 0:a.userId}});return !(t!=null&&t.conversationId)||!t.token?false:(this.handle={conversationId:t.conversationId,token:t.token},(i=this.storage)==null||i.set(F,JSON.stringify(this.handle)),true)}async send(e,t){var i;if(!await this.ensureThread())return null;let r=this.handle;if(!r)return null;let a=await this.request("POST",`/v1/conversations/${encodeURIComponent(r.conversationId)}/turns`,{body:{body:e,pageContext:t},token:r.token});return (i=a==null?void 0:a.turn)!=null?i:null}async load(){let e=this.handle;return e?this.request("GET",`/v1/conversations/${encodeURIComponent(e.conversationId)}`,{token:e.token}):null}readHandle(){var t,r;let e=(t=this.storage)==null?void 0:t.get(F);if(!e)return null;try{let a=JSON.parse(e);if(typeof a.conversationId=="string"&&typeof a.token=="string")return {conversationId:a.conversationId,token:a.token}}catch(a){}return (r=this.storage)==null||r.remove(F),null}async request(e,t,r={}){var o,s,p,l,d,c;let a=this.fetchImpl;if(!a)return (s=(o=this.options).onError)==null||s.call(o,new Error("no fetch available for prodantix chat")),null;let i={authorization:`Bearer ${this.options.apiKey}`,"content-type":"application/json"};r.token&&(i[oe]=r.token);try{let h=await a(`${this.host}${t}`,{body:r.body===void 0?void 0:JSON.stringify(r.body),headers:i,method:e}),g=await h.text();return h.ok?g?JSON.parse(g):{}:((l=(p=this.options).onError)==null||l.call(p,new Error(`prodantix chat ${t}: ${h.status}`)),null)}catch(h){return (c=(d=this.options).onError)==null||c.call(d,h),null}}};var le={Fri:"fri",Mon:"mon",Sat:"sat",Sun:"sun",Thu:"thu",Tue:"tue",Wed:"wed"};function _(n,e){var s,p,l,d,c,h;let t=new Intl.DateTimeFormat(void 0,{hour:"2-digit",hour12:false,minute:"2-digit",timeZone:n.timezone,weekday:"short"}).formatToParts(e),r=le[(p=(s=t.find(g=>g.type==="weekday"))==null?void 0:s.value)!=null?p:""];if(!r)return false;let a=(d=(l=t.find(g=>g.type==="hour"))==null?void 0:l.value)!=null?d:"",i=(h=(c=t.find(g=>g.type==="minute"))==null?void 0:c.value)!=null?h:"",o=`${a}:${i}`;return n.windows.some(g=>g.days.includes(r)&&g.open<=o&&o<g.close)}var y={bubbleFill:"filled",bubbleShape:"tailed",composerShape:"round",dayDividers:true,launcherContent:"glyph",launcherFill:"outlined",launcherShape:"circle",launcherSize:"small",nameAvatar:true,namePlacement:"hidden",skin:"standard",stampContent:"time",stampPlacement:"none"},ce=["quiet","standard"],de=["round","square"],pe=["rounded","tailed"],he=["filled","outlined"],ue=["circle","pill","squircle"],ge=["filled","outlined"],me=["avatar","glyph","team_faces"],fe=["large","medium","small"],be=["above","hidden","inline"],ye=["beside_name","none","under_turn"],xe=["time","time_and_latency"],S=(n,e,t)=>typeof n=="string"&&e.includes(n)?n:t,D=(n,e)=>typeof n=="boolean"?n:e,ve={avatar_circle:["circle","outlined","avatar","large"],circle_filled:["circle","filled","glyph","medium"],circle_outlined:["circle","outlined","glyph","small"],pill_labelled:["pill","filled","glyph","medium"],pill_team:["pill","outlined","team_faces","medium"],squircle_filled:["squircle","filled","glyph","medium"]},Se={above:["above",false],avatar_only:["hidden",true],gutter:["above",true],hidden:["hidden",false],inline:["inline",false]},Ce={cluster:[true,"none","time"],latency:[false,"beside_name","time_and_latency"],none:[false,"none","time"],trailing:[false,"under_turn","time"],with_name:[false,"beside_name","time"]},ke={concierge:["standard","round"],console:["standard","square"],quiet:["quiet","square"]},we={hairline:["rounded","outlined"],outlined:["rounded","outlined"],rounded:["rounded","filled"],tailed:["tailed","filled"]};function I(n){var g,x,v,b,m,C,k,E,f,w,U,B,K;let e=typeof n=="object"&&n!==null?n:{},t=typeof e.launcherStyle=="string"?e.launcherStyle:void 0,r=t===void 0?void 0:ve[t],a=typeof e.namePlacement=="string"?e.namePlacement:void 0,i=a===void 0?void 0:Se[a],o=typeof e.timestampStyle=="string"?e.timestampStyle:void 0,s=o===void 0?void 0:Ce[o],p=typeof e.skin=="string"?e.skin:void 0,l=p===void 0?void 0:ke[p],d=typeof e.bubbleStyle=="string"?e.bubbleStyle:void 0,c=d===void 0?void 0:we[d],h={bubbleFill:S(e.bubbleFill,he,(g=c==null?void 0:c[1])!=null?g:y.bubbleFill),bubbleShape:S(e.bubbleShape,pe,(x=c==null?void 0:c[0])!=null?x:y.bubbleShape),composerShape:S(e.composerShape,de,(v=l==null?void 0:l[1])!=null?v:y.composerShape),dayDividers:D(e.dayDividers,(b=s==null?void 0:s[0])!=null?b:y.dayDividers),launcherContent:S(e.launcherContent,me,(m=r==null?void 0:r[2])!=null?m:y.launcherContent),launcherFill:S(e.launcherFill,ge,(C=r==null?void 0:r[1])!=null?C:y.launcherFill),launcherShape:S(e.launcherShape,ue,(k=r==null?void 0:r[0])!=null?k:y.launcherShape),launcherSize:S(e.launcherSize,fe,(E=r==null?void 0:r[3])!=null?E:y.launcherSize),nameAvatar:D(e.nameAvatar,(f=i==null?void 0:i[1])!=null?f:y.nameAvatar),namePlacement:S(e.namePlacement,be,(w=i==null?void 0:i[0])!=null?w:y.namePlacement),skin:S(e.skin,ce,(U=l==null?void 0:l[0])!=null?U:y.skin),stampContent:S(e.stampContent,xe,(B=s==null?void 0:s[2])!=null?B:y.stampContent),stampPlacement:S(e.stampPlacement,ye,(K=s==null?void 0:s[1])!=null?K:y.stampPlacement)};return h.stampPlacement==="beside_name"&&h.namePlacement==="hidden"&&(h.stampPlacement="under_turn"),h}function G(n){var r,a,i,o;let e=n.split(/\s+/).filter(s=>s.length>0);return (e.length>1?`${(r=e[0])==null?void 0:r.slice(0,1)}${(a=e[1])==null?void 0:a.slice(0,1)}`:(o=(i=e[0])==null?void 0:i.slice(0,2))!=null?o:"").toUpperCase()}var Ee="M20 11.6a7.4 7.4 0 0 1-7.4 7.4H8.2L4 21.8l1-4.1A7.4 7.4 0 1 1 20 11.6Z",Te={large:66,medium:56,small:46},Ae={circle:"width:var(--fab-size);height:var(--fab-size);border-radius:calc(var(--fab-size) / 2);",pill:"width:auto;height:var(--fab-size);border-radius:calc(var(--fab-size) / 2);padding:0 22px;gap:10px;",squircle:"width:var(--fab-size);height:var(--fab-size);border-radius:16px;"},Le={filled:"background:var(--a);color:#fff;",outlined:"background:var(--paper);border:1px solid var(--hairline);color:var(--ink-2);box-shadow:0 1px 2px rgba(0,0,0,.08);"},Ne={avatar:"",glyph:".launcher svg{width:calc(var(--fab-size) * 0.375);height:calc(var(--fab-size) * 0.375);}",team_faces:".launcher .faces{display:flex;}.launcher .faces .av{box-shadow:0 0 0 2px var(--paper);}.launcher .faces .av+.av{margin-left:-10px;}"},Pe=".launcher .live{width:10px;height:10px;position:absolute;right:3px;bottom:3px;border-radius:50%;background:var(--online);box-shadow:0 0 0 2px var(--paper);}.launcher.closed .live{display:none}",_e={circle:"",pill:".badge{position:static;box-shadow:none}",squircle:""},Ie={filled:"",outlined:".badge{background:var(--a);top:-7px;right:-7px;min-width:19px;height:19px;font-size:11.5px}"},Me={circle:"",pill:".launcher .label{font-size:14px;font-weight:600;white-space:nowrap;}",squircle:""},He={circle:"",pill:"@media (max-width:480px){.launcher{width:var(--fab-size);padding:0}.launcher .label{display:none}}",squircle:""};function q(n,e,t,r){return `.launcher{--fab-size:${Te[r]}px;${Ae[n]}${Le[e]}}${Ne[t]}${Pe}${_e[n]}${Ie[e]}${Me[n]}${He[n]}`}function W(n,e,t,r=a=>a){let a=document.createDocumentFragment();if(n==="glyph"||t.length===0){let i=document.createElement("span");return i.innerHTML=`<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="${Ee}"/></svg>`,a.append(...i.childNodes,O()),a}return n==="avatar"?(a.append(j(t[0],e,r),O()),a):(a.append(R(t,e,r),O()),a)}function R(n,e,t=a=>a,r=true){let a=document.createElement("span");a.className="faces";for(let i of n.slice(0,2))a.append(j(i,e,t,r));return a}function j(n,e,t,r=true){let a=document.createElement("span");if(a.className="av",a.setAttribute("aria-hidden","true"),n&&r&&(a.style.background=n.tone),n!=null&&n.avatarUrl){let i=document.createElement("img");return i.alt="",i.src=t(n.avatarUrl),a.append(i),a}return a.textContent=n?n.initials:e.agentLabel.slice(0,2).toUpperCase(),a}function O(){let n=document.createElement("span");return n.className="live",n.setAttribute("aria-hidden","true"),n}var Fe={agentLabel:"Agent",aiLabel:"AI",awayBody:"We are away right now, but we will reply as soon as we are back.",closeLabel:"Close chat",emptyBody:"We usually reply within a few minutes.",emptyTitle:"Ask us anything.",inputPlaceholder:"Type a message",launcherLabel:"Chat with us",replyTime:"Usually replying in a few minutes",retryLabel:"Not delivered. Retry",sendLabel:"Send",timeLabel:n=>{let e=new Date(n);return Number.isNaN(e.getTime())?"":`${String(e.getHours()).padStart(2,"0")}:${String(e.getMinutes()).padStart(2,"0")}`},title:"Support",unreadLabel:n=>`${n} unread`},T={accentColor:"#5b5bff",availability:{timezone:"UTC",windows:[]},awayMessage:"",greeting:"",launcherOffsetX:20,launcherOffsetY:20,launcherPosition:"bottom_right",starterPrompts:[],team:[],...y},Oe={quiet:".composer{position:relative;padding:8px 10px 10px}.composer input{padding-right:36px}.composer button{position:absolute;top:50%;right:14px;width:28px;min-width:28px;height:28px;padding:0;background:transparent;color:var(--ink);border-radius:7px;transform:translateY(-50%)}.composer button .sendglyph{display:block;width:16px;height:16px}.composer button .sendtext{display:none}.panel{border-radius:8px;box-shadow:0 2px 8px rgba(0,0,0,.12)}.header{background:var(--paper);color:var(--ink);height:44px;padding:0 8px 0 16px;border-bottom:1px solid var(--hairline)}.header h2{font-size:11px;letter-spacing:.11em;text-transform:uppercase;color:var(--ink-3)}.header .status{color:var(--ink-3)}.header .av,.header .status .live{box-shadow:0 0 0 2px var(--paper)}.close{color:var(--ink-2)}",standard:".panel{border-radius:16px;box-shadow:0 16px 40px rgba(0,0,0,.2)}.header{background:var(--a);color:#fff;flex-direction:column;align-items:flex-start;gap:14px;padding:18px 14px 20px 20px}.header h2{font-size:19px;font-weight:640}"},Re={round:".composer{padding:10px 10px 12px;gap:6px}.composer input{height:36px;border-radius:18px;padding:0 14px}.composer button{width:36px;min-width:36px;height:36px;padding:0;border-radius:18px}.composer button .sendglyph{display:block}.composer button .sendtext{display:none}",square:".composer input{height:36px;border-radius:8px;padding:0 12px}"},$e={rounded:".turn{border-radius:18px;padding:10px 15px}",tailed:".turn.agent,.turn.ai{border-radius:12px 12px 12px 4px}.turn.end_user{border-radius:12px 12px 4px 12px}"},ze={filled:"",outlined:".turn{background:none;border:1px solid var(--hairline)}.turn.end_user{background:none;border-color:var(--a);color:var(--ink)}"},Ue={above:"",hidden:".turn.agent .author,.turn.ai .author:not(.ai){display:none}",inline:".body .author.below{display:block;margin:4px 0 0;font-size:11.5px;font-weight:500;color:var(--ink-2);text-transform:none;letter-spacing:0;opacity:1}"},Be=".turn.agent,.turn.ai{display:flex;gap:10px;max-width:100%;background:none;padding:0}.turn.agent .body,.turn.ai .body{background:var(--fill);padding:9px 13px;border-radius:inherit}.author{text-transform:none;letter-spacing:0;font-size:12.5px;font-weight:600;opacity:1}",Ke='.divider{display:flex;align-items:center;gap:10px;margin:0;font-size:11px;opacity:.6}.divider:before,.divider:after{content:"";flex:1;height:1px;background:var(--hairline)}',De={beside_name:".stamp{font-size:11px;opacity:.7;margin-left:6px}",none:"",under_turn:".stamp{display:block;font-size:11px;opacity:.7;margin-top:4px}.turn.end_user .stamp{text-align:right}"},Ge=".lat{font-size:11px;opacity:.7;margin-left:6px}",Y=`--paper: oklch(24.6% 0.015 257); --ink: #fff; --ink-3: rgba(255,255,255,.55);
|
|
2
2
|
--fill: rgba(255,255,255,.06); --hairline: rgba(255,255,255,.13); --ink-2: rgba(255,255,255,.70);
|
|
3
3
|
--online: oklch(72% 0.13 163.23);`;function qe(n){return n==="light"?"":n==="dark"?`:host { ${Y} }`:`@media (prefers-color-scheme: dark) {
|
|
4
4
|
:host {
|
|
@@ -63,7 +63,12 @@ ${qe(e)}
|
|
|
63
63
|
status line 12.5px at 80% under the title. The ring is the header's own
|
|
64
64
|
ground so overlapping faces separate from it and from each other. */
|
|
65
65
|
.header .faces { display: flex; }
|
|
66
|
-
|
|
66
|
+
/* The fill is the stylesheet's on the header, never the face's own tone, which
|
|
67
|
+
arrives as the project accent and would be this header's own colour. Mixed
|
|
68
|
+
down from the accent rather than a fixed colour so it still belongs to the
|
|
69
|
+
project's palette, and the ring stays the accent because its job is to part
|
|
70
|
+
two OVERLAPPING discs from each other and from the header behind them. */
|
|
71
|
+
.header .av { width: 36px; height: 36px; background: color-mix(in srgb, #000 30%, var(--a)); box-shadow: 0 0 0 2px var(--a); }
|
|
67
72
|
.header .av + .av { margin-left: -12px; }
|
|
68
73
|
.headmain { display: flex; flex-direction: column; }
|
|
69
74
|
.header .status { display: flex; align-items: center; gap: 6px; margin: 5px 0 0; font-size: 12.5px; color: rgb(255 255 255 / 80%); }
|
|
@@ -146,5 +151,5 @@ ${qe(e)}
|
|
|
146
151
|
.panel { animation: rise 180ms ease-out; }
|
|
147
152
|
@keyframes rise { from { transform: translateY(8px); opacity: 0; } to { transform: none; opacity: 1; } }
|
|
148
153
|
}
|
|
149
|
-
`}${Re[t.composerShape]}${Oe[t.skin]}${q(t.launcherShape,t.launcherFill,t.launcherContent,t.launcherSize)}${$e[t.bubbleShape]}${ze[t.bubbleFill]}${Ue[t.namePlacement]}${t.nameAvatar?Be:""}${t.dayDividers?Ke:""}${De[t.stampPlacement]}${t.stampContent==="time_and_latency"?Ge:""}`}var We=["end_user","agent","ai"];function je(){let n=globalThis.location;if(n)return {host:n.host,path:n.pathname,title:document.title}}var M=class{constructor(e,t,r={},a={},i={}){this.host=e;this.client=t;u(this,"root");u(this,"strings");u(this,"settings");u(this,"appearance");u(this,"launcher");u(this,"badge");u(this,"panel",null);u(this,"lastFocused",null);u(this,"unread",0);u(this,"pendingTurns",0);u(this,"openNow");u(this,"style");u(this,"scheme");var o;this.strings={...Fe,...r},this.appearance={...T,...a},this.settings=I({...T,...a}),this.root=e.attachShadow({mode:(o=i.shadowMode)!=null?o:"closed"}),this.openNow=_(this.appearance.availability,new Date),this.scheme=i.scheme,this.style=document.createElement("style"),this.style.textContent=J(this.appearance,this.scheme),this.root.append(this.style),this.launcher=document.createElement("button"),this.launcher.className="launcher",this.launcher.type="button",this.launcher.setAttribute("aria-haspopup","dialog"),this.launcher.addEventListener("click",()=>this.toggle()),this.badge=document.createElement("span"),this.badge.className="badge",this.badge.hidden=true,this.drawLauncher(),this.root.append(this.launcher);}drawLauncher(){if(this.launcher.setAttribute("aria-label",this.strings.launcherLabel),this.launcher.replaceChildren(),this.launcher.append(W(this.settings.launcherContent,this.strings,this.appearance.team,e=>this.client.avatarUrl(e))),this.settings.launcherShape==="pill"){let e=document.createElement("span");e.className="label",e.textContent=this.settings.launcherContent==="team_faces"?this.strings.agentLabel:this.strings.launcherLabel,this.launcher.append(e);}this.launcher.append(this.badge),this.launcher.classList.toggle("closed",!this.openNow);}update(e,t){this.appearance={...T,...e},this.settings=I(this.appearance),t!==void 0&&(this.scheme=t),this.style.textContent=J(this.appearance,this.scheme),this.drawLauncher(),this.panel&&(this.close(),this.open());}toggle(){this.panel?this.close():this.open();}setOpenNow(e){var t;this.openNow=e,this.launcher.classList.toggle("closed",!e),(t=this.panel)==null||t.classList.toggle("closed",!e);}async open(){var v;if(this.panel)return;this.lastFocused=this.host.ownerDocument.activeElement,this.unread=0,this.renderBadge();let e=document.createElement("section");e.className=this.openNow?"panel":"panel closed",e.setAttribute("role","dialog"),e.setAttribute("aria-modal","true"),e.setAttribute("aria-label",this.strings.title);let t=document.createElement("div");t.className="header";let r=(v=this.appearance.team)!=null?v:[];r.length>0&&t.append(R(r,this.strings,b=>this.client.avatarUrl(b)));let a=document.createElement("div");a.className="headmain";let i=document.createElement("h2");i.textContent=this.strings.title;let o=document.createElement("p");o.className="status";let s=document.createElement("span");s.className="live",s.setAttribute("aria-hidden","true"),o.append(s,this.strings.replyTime),a.append(i,o);let p=document.createElement("button");p.className="close",p.type="button",p.setAttribute("aria-label",this.strings.closeLabel),p.textContent="\xD7",p.addEventListener("click",()=>this.close()),t.append(a,p);let l=document.createElement("div");l.className="log",l.setAttribute("role","log"),l.setAttribute("aria-live","polite"),l.setAttribute("aria-label",this.strings.title);let d=document.createElement("form");d.className="composer";let c=document.createElement("input");c.type="text",c.setAttribute("aria-label",this.strings.inputPlaceholder),c.placeholder=this.strings.inputPlaceholder;let h=document.createElement("button");h.type="submit",h.setAttribute("aria-label",this.strings.sendLabel),h.innerHTML='<svg class="sendglyph" aria-hidden="true" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M4.5 12 20 4.5 15 20l-3.6-5.4L4.5 12Z"/></svg>';let g=document.createElement("span");g.className="sendtext",g.textContent=this.strings.sendLabel,h.append(g),d.append(c,h),d.addEventListener("submit",b=>{b.preventDefault(),this.submit(c,l);}),e.append(t,l,d),e.addEventListener("keydown",b=>this.onKeydown(b,e,p)),this.root.append(e),this.panel=e,c.focus();let x=await this.client.load();x&&x.turns.length>0?this.renderThread(l,x):this.renderFirstRun(l,c),this.openNow||this.renderAway(l);}renderFirstRun(e,t){let r=document.createElement("div");r.className="empty";let a=document.createElement("h3");a.textContent=this.appearance.greeting.trim()||this.strings.emptyTitle;let i=document.createElement("p");i.textContent=this.strings.emptyBody,r.append(a,i);for(let o of this.appearance.starterPrompts){let s=document.createElement("button");s.className="prompt",s.type="button",s.textContent=o,s.addEventListener("click",()=>{t.value=o,this.submit(t,e);}),r.append(s);}e.replaceChildren(r);}renderAway(e){let t=document.createElement("div");t.className="away",t.textContent=this.appearance.awayMessage.trim()||this.strings.awayBody,e.prepend(t);}close(){this.panel&&(this.panel.remove(),this.panel=null,this.lastFocused instanceof HTMLElement?this.lastFocused.focus():this.launcher.focus());}onIncomingTurn(e){if(this.panel){let t=this.panel.querySelector(".log");t instanceof HTMLElement&&!this.hasTurn(t,e.id)&&this.appendTurn(t,e);return}e.authorKind!=="end_user"&&(this.unread+=1,this.renderBadge());}async submit(e,t){let r=e.value.trim();r&&(e.value="",await this.sendBody(t,r));}async sendBody(e,t){var i;(i=e.querySelector(".empty"))==null||i.remove(),this.pendingTurns+=1;let r=this.appendTurn(e,{authorId:null,authorKind:"end_user",body:t,createdAt:new Date().toISOString(),id:`pending-${this.pendingTurns}`});r.setAttribute("data-pending","");let a=await this.client.send(t,je());if(r.removeAttribute("data-pending"),a){r.dataset.turnId=a.id;return}this.markFailed(e,r,t);}markFailed(e,t,r){var i;t.setAttribute("data-failed","");let a=document.createElement("button");a.type="button",a.className="retry",a.textContent=this.strings.retryLabel,a.addEventListener("click",()=>{t.remove(),this.sendBody(e,r);}),((i=t.querySelector(".body"))!=null?i:t).append(a);}hasTurn(e,t){for(let r of e.children)if(r instanceof HTMLElement&&r.dataset.turnId===t)return true;return false}renderThread(e,t){e.replaceChildren();for(let r of t.turns)this.appendTurn(e,r);}appendTurn(e,t){var d;(d=e.querySelector(".empty"))==null||d.remove();let r=We.includes(t.authorKind)?t.authorKind:"agent",a=this.settings,i=document.createElement("div");if(i.className=`turn ${r}`,i.dataset.turnId=t.id,r!=="end_user"&&a.nameAvatar){let c=document.createElement("span");if(c.className=r==="ai"?"av bot":"av",c.setAttribute("aria-hidden","true"),r==="agent"&&t.authorAvatarUrl){let h=document.createElement("img");h.alt="",h.src=this.client.avatarUrl(t.authorAvatarUrl),c.append(h);}else c.textContent=r==="ai"?this.strings.aiLabel:G(this.agentName(t));i.append(c);}let s=document.createElement("div");s.className="body";let p=r!=="end_user"&&a.namePlacement!=="hidden",l=document.createElement("div");if(l.textContent=t.body,p||r==="ai"&&a.namePlacement==="hidden"){let c=document.createElement("div");c.className=r==="ai"?"author ai":"author",c.textContent=r==="ai"?this.strings.aiLabel:this.agentName(t),a.stampPlacement==="beside_name"&&c.append(this.stamp(t)),a.namePlacement==="inline"?(c.classList.add("below"),s.append(l,c)):s.append(c,l);}else s.append(l);return a.stampPlacement==="under_turn"&&s.append(this.stamp(t)),i.append(s),e.append(i),e.scrollTop=e.scrollHeight,i}agentName(e){return e.authorName||this.strings.agentLabel}stamp(e){let t=document.createElement("span");return t.className="stamp",t.textContent=this.strings.timeLabel(e.createdAt),t}onKeydown(e,t,r){if(e.key==="Escape"){e.preventDefault(),this.close();return}if(e.key!=="Tab")return;let a=t.querySelectorAll('button, input, [tabindex]:not([tabindex="-1"])');if(a.length===0)return;let i=a[0],o=a[a.length-1],s=this.root.activeElement;e.shiftKey&&s===i?(e.preventDefault(),o.focus()):!e.shiftKey&&s===o?(e.preventDefault(),i.focus()):s===null&&(e.preventDefault(),r.focus());}renderBadge(){this.unread>0?(this.badge.hidden=false,this.badge.textContent=String(this.unread),this.launcher.setAttribute("aria-label",`${this.strings.launcherLabel}, ${this.strings.unreadLabel(this.unread)}`)):(this.badge.hidden=true,this.badge.textContent="",this.launcher.setAttribute("aria-label",this.strings.launcherLabel));}};function X(n){return `40${JSON.stringify(n)}`}function V(){return "3"}function Q(n){let e=n.charAt(0),t=n.slice(1);if(e==="2")return {kind:"ping"};if(e==="1")return {kind:"disconnect"};if(e==="0"){let o=$(t);return {kind:"open",pingInterval:typeof(o==null?void 0:o.pingInterval)=="number"?o.pingInterval:25e3,pingTimeout:typeof(o==null?void 0:o.pingTimeout)=="number"?o.pingTimeout:2e4}}if(e!=="4")return {kind:"other"};let r=t.charAt(0),a=t.slice(1);if(r==="0")return {kind:"connected"};if(r==="1")return {kind:"disconnect"};if(r==="4"){let o=$(a);return {kind:"connectError",message:typeof(o==null?void 0:o.message)=="string"?o.message:"refused"}}if(r!=="2")return {kind:"other"};let i=$(a);return !Array.isArray(i)||typeof i[0]!="string"?{kind:"other"}:{kind:"event",name:i[0],payload:i[1]}}function $(n){try{return JSON.parse(n)}catch(e){return null}}var Ye="/socket.io/?EIO=4&transport=websocket",H=class{constructor(e){this.options=e;u(this,"socket",null);u(this,"heartbeat",null);u(this,"ready",false);u(this,"closed",false);u(this,"heartbeatWindow",45e3);u(this,"factory");u(this,"setTimer");u(this,"clearTimer");var t,r,a;this.factory=(t=e.socketFactory)!=null?t:Je,this.setTimer=(r=e.setTimer)!=null?r:((i,o)=>setTimeout(i,o)),this.clearTimer=(a=e.clearTimer)!=null?a:(i=>clearTimeout(i));}open(){if(this.socket||this.closed)return;let e=`${this.options.host.replace(/^http/,"ws").replace(/\/+$/,"")}${Ye}`,t;try{t=this.factory(e);}catch(r){this.options.onClosed(false);return}this.socket=t,t.onmessage=r=>this.receive(String(r.data)),t.onerror=()=>t.close(),t.onclose=()=>this.fell();}close(){this.closed=true,this.stopHeartbeat();let e=this.socket;this.socket=null,e==null||e.close();}receive(e){var r,a,i,o;let t=Q(e);if(t.kind==="open"){this.armHeartbeat(t.pingInterval+t.pingTimeout),(r=this.socket)==null||r.send(X(this.options.auth));return}if(t.kind==="ping"){this.armHeartbeat(),(a=this.socket)==null||a.send(V());return}if(t.kind==="connectError"||t.kind==="disconnect"){this.stopHeartbeat(),(i=this.socket)==null||i.close();return}if(t.kind==="event"){if(t.name==="ready"){this.ready=true,this.options.onReady();return}if(t.name==="conversation.turn"){let s=(o=t.payload)==null?void 0:o.turn;s&&this.options.onTurn(s);}}}fell(){this.stopHeartbeat();let e=this.ready;this.socket=null,this.ready=false,this.closed||this.options.onClosed(e);}armHeartbeat(e){e!==void 0&&(this.heartbeatWindow=e),this.stopHeartbeat(),this.heartbeat=this.setTimer(()=>{var t;return (t=this.socket)==null?void 0:t.close()},this.heartbeatWindow);}stopHeartbeat(){this.heartbeat!==null&&this.clearTimer(this.heartbeat),this.heartbeat=null;}};function Je(n){let e=globalThis.WebSocket;if(!e)throw new Error("no WebSocket");return new e(n)}var Xe=6e4;function Z(n){var m,C,k,w;let e=globalThis.document;if(!e)throw new Error("prodantix chat requires a document; mount it in the browser");let t=(m=n.mountPoint)!=null?m:e.createElement("div");n.mountPoint||e.body.append(t);let r=new P(n),a=new M(t,r,n.strings,n.appearance),i=(k=(C=n.appearance)==null?void 0:C.availability)!=null?k:T.availability,o,s=()=>{a.setOpenNow(_(i,new Date)),o=setTimeout(s,Xe);};s();let p=new Set,l,d=null,c=(w=n.pollIntervalMs)!=null?w:15e3,h=f=>{p.has(f.id)||f.authorKind==="end_user"||(p.add(f.id),a.onIncomingTurn(f));},g=async()=>{if(!r.hasThread)return;let f=await r.load();if(f){for(let E of f.turns)h(E);p=new Set(f.turns.map(E=>E.id));}},x=()=>{l||c<=0||(l=setInterval(()=>void g(),c));},v=()=>{l&&clearInterval(l),l=void 0;},b=()=>{if(d||!n.socketHost)return;let f=r.socketAuth;f&&(d=new H({auth:f,host:n.socketHost,onClosed:E=>{d=null,x(),E&&b();},onReady:v,onTurn:h,socketFactory:n.socketFactory}),d.open());};return x(),b(),{close:()=>a.close(),destroy:()=>{v(),clearTimeout(o),d==null||d.close(),d=null,a.close(),t.remove();},identify:f=>r.identify(f),open:()=>{a.open().then(b);}}}var z="prodantix.messenger.config";function ee(n,e){let t=n==null?void 0:n.get(z);if(!t)return null;try{let r=JSON.parse(t);return (r==null?void 0:r.apiKey)===e?r.config:null}catch(r){return null}}async function te(n){var a,i,o,s,p;let e=L(n.fetchImpl);if(!e)return (a=n.onError)==null||a.call(n,new Error("no fetch available for the prodantix messenger")),null;let t=N(n.host),r=n.locale?`?locale=${encodeURIComponent(n.locale)}`:"";try{let l=await e(`${t}/v1/messenger/config${r}`,{headers:{authorization:`Bearer ${n.apiKey}`},method:"GET"});if(!l.ok)return (i=n.onError)==null||i.call(n,new Error(`prodantix messenger config: ${l.status}`)),null;let d=JSON.parse(await l.text());return d.enabled?((s=n.storage)==null||s.set(z,JSON.stringify({apiKey:n.apiKey,config:d})),d):((o=n.storage)==null||o.remove(z),d)}catch(l){return (p=n.onError)==null||p.call(n,l),null}}var Ve=["close","identify","open","shutdown","toggle"],A="[prodantix/messenger]";function Qe(n,e){for(let t of n){let[r,...a]=t!=null?t:[];typeof r!="string"||!Ve.includes(r)||e(r,...a);}}function Ze(n){if(!n)return null;try{return new URL(n).origin}catch(e){return null}}async function re(n,e={}){var h,g,x,v,b;let t=(h=e.warn)!=null?h:(m=>console.warn(m)),r=n.prodantix,a=r==null?void 0:r.k;if(!a)return t(`${A} no project key on the install snippet; nothing will load.`),null;let i=Ze((g=e.scriptSrc)!=null?g:et(n));if(!i)return t(`${A} could not tell which host served this script; nothing will load.`),null;let o=tt(n),s=ee(o,a),p=await te({apiKey:a,host:i,locale:((v=(x=n.document)==null?void 0:x.documentElement)==null?void 0:v.lang)||void 0,onError:m=>t(`${A} settings could not be read: ${String(m)}`),storage:o}),l=p!=null?p:s;if(!l)return t(`${A} no settings available; the messenger will not render.`),null;if(!l.enabled)return null;let d=Z({apiKey:a,appearance:l,distinctId:rt(n,o),host:i,socketHost:l.socketUrl||void 0}),c=(m,...C)=>{if((m==="open"||m==="toggle")&&d.open(),m==="close"&&d.close(),m==="shutdown"&&d.destroy(),m==="identify"){let k=nt(C[0]);if(!k){console.error(`${A} identify needs { userId, userHash }: the hash is HMAC-SHA256 of the user id under the project signing secret, computed on your server. Without it the visitor stays anonymous.`);return}d.identify(k);}};return Qe((b=r==null?void 0:r.q)!=null?b:[],c),n.prodantix=Object.assign((m,...C)=>c(m,...C),{k:a,q:[]}),d}function et(n){var t;let e=(t=n.document)==null?void 0:t.currentScript;return e==null?void 0:e.src}function tt(n){let e=n.localStorage;if(e)return {get:t=>e.getItem(t),remove:t=>e.removeItem(t),set:(t,r)=>e.setItem(t,r)}}function nt(n){if(typeof n!="object"||n===null)return null;let{userHash:e,userId:t}=n;return typeof t!="string"||typeof e!="string"||t.trim()===""||e.trim()===""?null:{userHash:e,userId:t}}var ne="prodantix.messenger.anon";function rt(n,e){var a,i,o;let t=e==null?void 0:e.get(ne);if(t)return t;let r=`anon_${(o=(i=(a=n.crypto)==null?void 0:a.randomUUID)==null?void 0:i.call(a))!=null?o:Math.random().toString(36).slice(2)}`;return e==null||e.set(ne,r),r}re(globalThis);})();//# sourceMappingURL=messenger.iife.js.map
|
|
154
|
+
`}${Re[t.composerShape]}${Oe[t.skin]}${q(t.launcherShape,t.launcherFill,t.launcherContent,t.launcherSize)}${$e[t.bubbleShape]}${ze[t.bubbleFill]}${Ue[t.namePlacement]}${t.nameAvatar?Be:""}${t.dayDividers?Ke:""}${De[t.stampPlacement]}${t.stampContent==="time_and_latency"?Ge:""}`}var We=["end_user","agent","ai"];function je(){let n=globalThis.location;if(n)return {host:n.host,path:n.pathname,title:document.title}}var M=class{constructor(e,t,r={},a={},i={}){this.host=e;this.client=t;u(this,"root");u(this,"strings");u(this,"settings");u(this,"appearance");u(this,"launcher");u(this,"badge");u(this,"panel",null);u(this,"lastFocused",null);u(this,"unread",0);u(this,"pendingTurns",0);u(this,"openNow");u(this,"style");u(this,"scheme");var o;this.strings={...Fe,...r},this.appearance={...T,...a},this.settings=I({...T,...a}),this.root=e.attachShadow({mode:(o=i.shadowMode)!=null?o:"closed"}),this.openNow=_(this.appearance.availability,new Date),this.scheme=i.scheme,this.style=document.createElement("style"),this.style.textContent=J(this.appearance,this.scheme),this.root.append(this.style),this.launcher=document.createElement("button"),this.launcher.className="launcher",this.launcher.type="button",this.launcher.setAttribute("aria-haspopup","dialog"),this.launcher.addEventListener("click",()=>this.toggle()),this.badge=document.createElement("span"),this.badge.className="badge",this.badge.hidden=true,this.drawLauncher(),this.root.append(this.launcher);}drawLauncher(){if(this.launcher.setAttribute("aria-label",this.strings.launcherLabel),this.launcher.replaceChildren(),this.launcher.append(W(this.settings.launcherContent,this.strings,this.appearance.team,e=>this.client.avatarUrl(e))),this.settings.launcherShape==="pill"){let e=document.createElement("span");e.className="label",e.textContent=this.settings.launcherContent==="team_faces"?this.strings.agentLabel:this.strings.launcherLabel,this.launcher.append(e);}this.launcher.append(this.badge),this.launcher.classList.toggle("closed",!this.openNow);}update(e,t){this.appearance={...T,...e},this.settings=I(this.appearance),t!==void 0&&(this.scheme=t),this.style.textContent=J(this.appearance,this.scheme),this.drawLauncher(),this.panel&&(this.close(),this.open());}toggle(){this.panel?this.close():this.open();}setOpenNow(e){var t;this.openNow=e,this.launcher.classList.toggle("closed",!e),(t=this.panel)==null||t.classList.toggle("closed",!e);}async open(){var v;if(this.panel)return;this.lastFocused=this.host.ownerDocument.activeElement,this.unread=0,this.renderBadge();let e=document.createElement("section");e.className=this.openNow?"panel":"panel closed",e.setAttribute("role","dialog"),e.setAttribute("aria-modal","true"),e.setAttribute("aria-label",this.strings.title);let t=document.createElement("div");t.className="header";let r=(v=this.appearance.team)!=null?v:[];r.length>0&&t.append(R(r,this.strings,b=>this.client.avatarUrl(b),false));let a=document.createElement("div");a.className="headmain";let i=document.createElement("h2");i.textContent=this.strings.title;let o=document.createElement("p");o.className="status";let s=document.createElement("span");s.className="live",s.setAttribute("aria-hidden","true"),o.append(s,this.strings.replyTime),a.append(i,o);let p=document.createElement("button");p.className="close",p.type="button",p.setAttribute("aria-label",this.strings.closeLabel),p.textContent="\xD7",p.addEventListener("click",()=>this.close()),t.append(a,p);let l=document.createElement("div");l.className="log",l.setAttribute("role","log"),l.setAttribute("aria-live","polite"),l.setAttribute("aria-label",this.strings.title);let d=document.createElement("form");d.className="composer";let c=document.createElement("input");c.type="text",c.setAttribute("aria-label",this.strings.inputPlaceholder),c.placeholder=this.strings.inputPlaceholder;let h=document.createElement("button");h.type="submit",h.setAttribute("aria-label",this.strings.sendLabel),h.innerHTML='<svg class="sendglyph" aria-hidden="true" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M4.5 12 20 4.5 15 20l-3.6-5.4L4.5 12Z"/></svg>';let g=document.createElement("span");g.className="sendtext",g.textContent=this.strings.sendLabel,h.append(g),d.append(c,h),d.addEventListener("submit",b=>{b.preventDefault(),this.submit(c,l);}),e.append(t,l,d),e.addEventListener("keydown",b=>this.onKeydown(b,e,p)),this.root.append(e),this.panel=e,c.focus();let x=await this.client.load();x&&x.turns.length>0?this.renderThread(l,x):this.renderFirstRun(l,c),this.openNow||this.renderAway(l);}renderFirstRun(e,t){let r=document.createElement("div");r.className="empty";let a=document.createElement("h3");a.textContent=this.appearance.greeting.trim()||this.strings.emptyTitle;let i=document.createElement("p");i.textContent=this.strings.emptyBody,r.append(a,i);for(let o of this.appearance.starterPrompts){let s=document.createElement("button");s.className="prompt",s.type="button",s.textContent=o,s.addEventListener("click",()=>{t.value=o,this.submit(t,e);}),r.append(s);}e.replaceChildren(r);}renderAway(e){let t=document.createElement("div");t.className="away",t.textContent=this.appearance.awayMessage.trim()||this.strings.awayBody,e.prepend(t);}close(){this.panel&&(this.panel.remove(),this.panel=null,this.lastFocused instanceof HTMLElement?this.lastFocused.focus():this.launcher.focus());}onIncomingTurn(e){if(this.panel){let t=this.panel.querySelector(".log");t instanceof HTMLElement&&!this.hasTurn(t,e.id)&&this.appendTurn(t,e);return}e.authorKind!=="end_user"&&(this.unread+=1,this.renderBadge());}async submit(e,t){let r=e.value.trim();r&&(e.value="",await this.sendBody(t,r));}async sendBody(e,t){var i;(i=e.querySelector(".empty"))==null||i.remove(),this.pendingTurns+=1;let r=this.appendTurn(e,{authorId:null,authorKind:"end_user",body:t,createdAt:new Date().toISOString(),id:`pending-${this.pendingTurns}`});r.setAttribute("data-pending","");let a=await this.client.send(t,je());if(r.removeAttribute("data-pending"),a){r.dataset.turnId=a.id;return}this.markFailed(e,r,t);}markFailed(e,t,r){var i;t.setAttribute("data-failed","");let a=document.createElement("button");a.type="button",a.className="retry",a.textContent=this.strings.retryLabel,a.addEventListener("click",()=>{t.remove(),this.sendBody(e,r);}),((i=t.querySelector(".body"))!=null?i:t).append(a);}hasTurn(e,t){for(let r of e.children)if(r instanceof HTMLElement&&r.dataset.turnId===t)return true;return false}renderThread(e,t){e.replaceChildren();for(let r of t.turns)this.appendTurn(e,r);}appendTurn(e,t){var d;(d=e.querySelector(".empty"))==null||d.remove();let r=We.includes(t.authorKind)?t.authorKind:"agent",a=this.settings,i=document.createElement("div");if(i.className=`turn ${r}`,i.dataset.turnId=t.id,r!=="end_user"&&a.nameAvatar){let c=document.createElement("span");if(c.className=r==="ai"?"av bot":"av",c.setAttribute("aria-hidden","true"),r==="agent"&&t.authorAvatarUrl){let h=document.createElement("img");h.alt="",h.src=this.client.avatarUrl(t.authorAvatarUrl),c.append(h);}else c.textContent=r==="ai"?this.strings.aiLabel:G(this.agentName(t));i.append(c);}let s=document.createElement("div");s.className="body";let p=r!=="end_user"&&a.namePlacement!=="hidden",l=document.createElement("div");if(l.textContent=t.body,p||r==="ai"&&a.namePlacement==="hidden"){let c=document.createElement("div");c.className=r==="ai"?"author ai":"author",c.textContent=r==="ai"?this.strings.aiLabel:this.agentName(t),a.stampPlacement==="beside_name"&&c.append(this.stamp(t)),a.namePlacement==="inline"?(c.classList.add("below"),s.append(l,c)):s.append(c,l);}else s.append(l);return a.stampPlacement==="under_turn"&&s.append(this.stamp(t)),i.append(s),e.append(i),e.scrollTop=e.scrollHeight,i}agentName(e){return e.authorName||this.strings.agentLabel}stamp(e){let t=document.createElement("span");return t.className="stamp",t.textContent=this.strings.timeLabel(e.createdAt),t}onKeydown(e,t,r){if(e.key==="Escape"){e.preventDefault(),this.close();return}if(e.key!=="Tab")return;let a=t.querySelectorAll('button, input, [tabindex]:not([tabindex="-1"])');if(a.length===0)return;let i=a[0],o=a[a.length-1],s=this.root.activeElement;e.shiftKey&&s===i?(e.preventDefault(),o.focus()):!e.shiftKey&&s===o?(e.preventDefault(),i.focus()):s===null&&(e.preventDefault(),r.focus());}renderBadge(){this.unread>0?(this.badge.hidden=false,this.badge.textContent=String(this.unread),this.launcher.setAttribute("aria-label",`${this.strings.launcherLabel}, ${this.strings.unreadLabel(this.unread)}`)):(this.badge.hidden=true,this.badge.textContent="",this.launcher.setAttribute("aria-label",this.strings.launcherLabel));}};function X(n){return `40${JSON.stringify(n)}`}function V(){return "3"}function Q(n){let e=n.charAt(0),t=n.slice(1);if(e==="2")return {kind:"ping"};if(e==="1")return {kind:"disconnect"};if(e==="0"){let o=$(t);return {kind:"open",pingInterval:typeof(o==null?void 0:o.pingInterval)=="number"?o.pingInterval:25e3,pingTimeout:typeof(o==null?void 0:o.pingTimeout)=="number"?o.pingTimeout:2e4}}if(e!=="4")return {kind:"other"};let r=t.charAt(0),a=t.slice(1);if(r==="0")return {kind:"connected"};if(r==="1")return {kind:"disconnect"};if(r==="4"){let o=$(a);return {kind:"connectError",message:typeof(o==null?void 0:o.message)=="string"?o.message:"refused"}}if(r!=="2")return {kind:"other"};let i=$(a);return !Array.isArray(i)||typeof i[0]!="string"?{kind:"other"}:{kind:"event",name:i[0],payload:i[1]}}function $(n){try{return JSON.parse(n)}catch(e){return null}}var Ye="/socket.io/?EIO=4&transport=websocket",H=class{constructor(e){this.options=e;u(this,"socket",null);u(this,"heartbeat",null);u(this,"ready",false);u(this,"closed",false);u(this,"heartbeatWindow",45e3);u(this,"factory");u(this,"setTimer");u(this,"clearTimer");var t,r,a;this.factory=(t=e.socketFactory)!=null?t:Je,this.setTimer=(r=e.setTimer)!=null?r:((i,o)=>setTimeout(i,o)),this.clearTimer=(a=e.clearTimer)!=null?a:(i=>clearTimeout(i));}open(){if(this.socket||this.closed)return;let e=`${this.options.host.replace(/^http/,"ws").replace(/\/+$/,"")}${Ye}`,t;try{t=this.factory(e);}catch(r){this.options.onClosed(false);return}this.socket=t,t.onmessage=r=>this.receive(String(r.data)),t.onerror=()=>t.close(),t.onclose=()=>this.fell();}close(){this.closed=true,this.stopHeartbeat();let e=this.socket;this.socket=null,e==null||e.close();}receive(e){var r,a,i,o;let t=Q(e);if(t.kind==="open"){this.armHeartbeat(t.pingInterval+t.pingTimeout),(r=this.socket)==null||r.send(X(this.options.auth));return}if(t.kind==="ping"){this.armHeartbeat(),(a=this.socket)==null||a.send(V());return}if(t.kind==="connectError"||t.kind==="disconnect"){this.stopHeartbeat(),(i=this.socket)==null||i.close();return}if(t.kind==="event"){if(t.name==="ready"){this.ready=true,this.options.onReady();return}if(t.name==="conversation.turn"){let s=(o=t.payload)==null?void 0:o.turn;s&&this.options.onTurn(s);}}}fell(){this.stopHeartbeat();let e=this.ready;this.socket=null,this.ready=false,this.closed||this.options.onClosed(e);}armHeartbeat(e){e!==void 0&&(this.heartbeatWindow=e),this.stopHeartbeat(),this.heartbeat=this.setTimer(()=>{var t;return (t=this.socket)==null?void 0:t.close()},this.heartbeatWindow);}stopHeartbeat(){this.heartbeat!==null&&this.clearTimer(this.heartbeat),this.heartbeat=null;}};function Je(n){let e=globalThis.WebSocket;if(!e)throw new Error("no WebSocket");return new e(n)}var Xe=6e4;function Z(n){var m,C,k,E;let e=globalThis.document;if(!e)throw new Error("prodantix chat requires a document; mount it in the browser");let t=(m=n.mountPoint)!=null?m:e.createElement("div");n.mountPoint||e.body.append(t);let r=new P(n),a=new M(t,r,n.strings,n.appearance),i=(k=(C=n.appearance)==null?void 0:C.availability)!=null?k:T.availability,o,s=()=>{a.setOpenNow(_(i,new Date)),o=setTimeout(s,Xe);};s();let p=new Set,l,d=null,c=(E=n.pollIntervalMs)!=null?E:15e3,h=f=>{p.has(f.id)||f.authorKind==="end_user"||(p.add(f.id),a.onIncomingTurn(f));},g=async()=>{if(!r.hasThread)return;let f=await r.load();if(f){for(let w of f.turns)h(w);p=new Set(f.turns.map(w=>w.id));}},x=()=>{l||c<=0||(l=setInterval(()=>void g(),c));},v=()=>{l&&clearInterval(l),l=void 0;},b=()=>{if(d||!n.socketHost)return;let f=r.socketAuth;f&&(d=new H({auth:f,host:n.socketHost,onClosed:w=>{d=null,x(),w&&b();},onReady:v,onTurn:h,socketFactory:n.socketFactory}),d.open());};return x(),b(),{close:()=>a.close(),destroy:()=>{v(),clearTimeout(o),d==null||d.close(),d=null,a.close(),t.remove();},identify:f=>r.identify(f),open:()=>{a.open().then(b);}}}var z="prodantix.messenger.config";function ee(n,e){let t=n==null?void 0:n.get(z);if(!t)return null;try{let r=JSON.parse(t);return (r==null?void 0:r.apiKey)===e?r.config:null}catch(r){return null}}async function te(n){var a,i,o,s,p;let e=L(n.fetchImpl);if(!e)return (a=n.onError)==null||a.call(n,new Error("no fetch available for the prodantix messenger")),null;let t=N(n.host),r=n.locale?`?locale=${encodeURIComponent(n.locale)}`:"";try{let l=await e(`${t}/v1/messenger/config${r}`,{headers:{authorization:`Bearer ${n.apiKey}`},method:"GET"});if(!l.ok)return (i=n.onError)==null||i.call(n,new Error(`prodantix messenger config: ${l.status}`)),null;let d=JSON.parse(await l.text());return d.enabled?((s=n.storage)==null||s.set(z,JSON.stringify({apiKey:n.apiKey,config:d})),d):((o=n.storage)==null||o.remove(z),d)}catch(l){return (p=n.onError)==null||p.call(n,l),null}}var Ve=["close","identify","open","shutdown","toggle"],A="[prodantix/messenger]";function Qe(n,e){for(let t of n){let[r,...a]=t!=null?t:[];typeof r!="string"||!Ve.includes(r)||e(r,...a);}}function Ze(n){if(!n)return null;try{return new URL(n).origin}catch(e){return null}}async function re(n,e={}){var h,g,x,v,b;let t=(h=e.warn)!=null?h:(m=>console.warn(m)),r=n.prodantix,a=r==null?void 0:r.k;if(!a)return t(`${A} no project key on the install snippet; nothing will load.`),null;let i=Ze((g=e.scriptSrc)!=null?g:et(n));if(!i)return t(`${A} could not tell which host served this script; nothing will load.`),null;let o=tt(n),s=ee(o,a),p=await te({apiKey:a,host:i,locale:((v=(x=n.document)==null?void 0:x.documentElement)==null?void 0:v.lang)||void 0,onError:m=>t(`${A} settings could not be read: ${String(m)}`),storage:o}),l=p!=null?p:s;if(!l)return t(`${A} no settings available; the messenger will not render.`),null;if(!l.enabled)return null;let d=Z({apiKey:a,appearance:l,distinctId:rt(n,o),host:i,socketHost:l.socketUrl||void 0}),c=(m,...C)=>{if((m==="open"||m==="toggle")&&d.open(),m==="close"&&d.close(),m==="shutdown"&&d.destroy(),m==="identify"){let k=nt(C[0]);if(!k){console.error(`${A} identify needs { userId, userHash }: the hash is HMAC-SHA256 of the user id under the project signing secret, computed on your server. Without it the visitor stays anonymous.`);return}d.identify(k);}};return Qe((b=r==null?void 0:r.q)!=null?b:[],c),n.prodantix=Object.assign((m,...C)=>c(m,...C),{k:a,q:[]}),d}function et(n){var t;let e=(t=n.document)==null?void 0:t.currentScript;return e==null?void 0:e.src}function tt(n){let e=n.localStorage;if(e)return {get:t=>e.getItem(t),remove:t=>e.removeItem(t),set:(t,r)=>e.setItem(t,r)}}function nt(n){if(typeof n!="object"||n===null)return null;let{userHash:e,userId:t}=n;return typeof t!="string"||typeof e!="string"||t.trim()===""||e.trim()===""?null:{userHash:e,userId:t}}var ne="prodantix.messenger.anon";function rt(n,e){var a,i,o;let t=e==null?void 0:e.get(ne);if(t)return t;let r=`anon_${(o=(i=(a=n.crypto)==null?void 0:a.randomUUID)==null?void 0:i.call(a))!=null?o:Math.random().toString(36).slice(2)}`;return e==null||e.set(ne,r),r}re(globalThis);})();//# sourceMappingURL=messenger.iife.js.map
|
|
150
155
|
//# sourceMappingURL=messenger.iife.js.map
|
package/package.json
CHANGED