@eka-care/medassist-widget-embed 0.2.120-dev.0 → 0.2.120-dev.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/eka-agents.html +4 -4
- package/dist/iframe.js +1 -1
- package/dist/index.d.ts +17 -0
- package/dist/index.js +11 -9
- package/package.json +1 -1
package/dist/eka-agents.html
CHANGED
|
@@ -18,7 +18,7 @@
|
|
|
18
18
|
CORS mode — the browser would download it twice. -->
|
|
19
19
|
<link
|
|
20
20
|
rel="modulepreload"
|
|
21
|
-
href="https://cdn.jsdelivr.net/npm/@eka-care/medassist-widget@0.2.0-dev.
|
|
21
|
+
href="https://cdn.jsdelivr.net/npm/@eka-care/medassist-widget@0.2.0-dev.3/dist/medassist-widget.js"
|
|
22
22
|
fetchpriority="high"
|
|
23
23
|
crossorigin
|
|
24
24
|
/>
|
|
@@ -27,14 +27,14 @@
|
|
|
27
27
|
<link
|
|
28
28
|
rel="preload"
|
|
29
29
|
as="style"
|
|
30
|
-
href="https://cdn.jsdelivr.net/npm/@eka-care/medassist-widget@0.2.0-dev.
|
|
30
|
+
href="https://cdn.jsdelivr.net/npm/@eka-care/medassist-widget@0.2.0-dev.3/dist/medassist-widget.css"
|
|
31
31
|
onload="this.rel='stylesheet'"
|
|
32
32
|
crossorigin
|
|
33
33
|
/>
|
|
34
34
|
<noscript>
|
|
35
35
|
<link
|
|
36
36
|
rel="stylesheet"
|
|
37
|
-
href="https://cdn.jsdelivr.net/npm/@eka-care/medassist-widget@0.2.0-dev.
|
|
37
|
+
href="https://cdn.jsdelivr.net/npm/@eka-care/medassist-widget@0.2.0-dev.3/dist/medassist-widget.css"
|
|
38
38
|
/>
|
|
39
39
|
</noscript>
|
|
40
40
|
|
|
@@ -149,7 +149,7 @@
|
|
|
149
149
|
window.renderMedAssist would never be set. -->
|
|
150
150
|
<script
|
|
151
151
|
type="module"
|
|
152
|
-
src="https://cdn.jsdelivr.net/npm/@eka-care/medassist-widget@0.2.0-dev.
|
|
152
|
+
src="https://cdn.jsdelivr.net/npm/@eka-care/medassist-widget@0.2.0-dev.3/dist/medassist-widget.js"
|
|
153
153
|
onload="init()"
|
|
154
154
|
fetchpriority="high"
|
|
155
155
|
crossorigin
|
package/dist/iframe.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";(function(){const $=()=>{if(typeof document=="undefined")return null;const{currentScript:e}=document;if(e instanceof HTMLScriptElement)return e;const
|
|
1
|
+
"use strict";(function(){const $=()=>{if(typeof document=="undefined")return null;const{currentScript:e}=document;if(e instanceof HTMLScriptElement)return e;const n=document.getElementsByTagName("script");return n.length?n[n.length-1]:null},C=e=>{if(e==="production"||e==="development"||e==="staging")return e};function z(e){var n,r;if(!e)return;const t=e.mode==="dark"?"white":e.mode==="light"?"black":void 0;return{...e.background&&{background:e.background},...e.background_img&&{backgroundImage:e.background_img},...e.accent&&{primary:e.accent},...t&&{textColor:t},...e.mode&&{mode:e.mode},...e.header_tinted!==void 0&&{headerTinted:e.header_tinted},...e.title_img&&{titleImg:e.title_img},...e.tagline&&{tagline:e.tagline},...e.consent_content&&{consentContent:e.consent_content},...((n=e.tips)===null||n===void 0?void 0:n.length)&&{tips:e.tips},...((r=e.banner)===null||r===void 0?void 0:r.trim())&&{banner:e.banner},...e.feature!==void 0&&{feature:e.feature}}}function b(e){if(!(!e||typeof document=="undefined"))try{const n=document.createElement("link");n.rel="preload",n.as="image",n.href=e,document.head.appendChild(n)}catch{const n=new Image;n.src=e}}async function F(e,n,r){var t;try{return await v(),await((t=window.fetchAgentConfig)===null||t===void 0?void 0:t.call(window,{agentId:n,serverUrl:e,environment:r,channel:"web"}))}catch{return}}const S="https://cdn.jsdelivr.net/npm/@eka-care/medassist-widget@0.2.0-dev.3/dist/",s=$(),U=(()=>{if(!s)return"";try{return new URL(".",s.src||window.location.href).href}catch{return""}})(),u=(()=>{if(!s)return S;const e=s.dataset.widgetAssets;if(e==="local")return`${U}src/`;if(e&&e.length>0)try{return new URL(e,U).href}catch{return e.endsWith("/")?e:`${e}/`}return S})(),a=`${u}medassist-widget.js`,g=`${u}medassist-widget.css`;let f=null,m=null;const i=new URLSearchParams(typeof window!="undefined"?window.location.search:""),A=i.get("agentId"),w=i.get("baseUrl")||"https://matrix.eka.care/reloaded";if(typeof document!="undefined"&&document.head){try{const e=new URL(u).origin,n=new URL(w).origin,r=document.createElement("link");if(r.rel="preconnect",r.href=e,r.crossOrigin="anonymous",document.head.appendChild(r),e!==n){const c=document.createElement("link");c.rel="preconnect",c.href=n,c.crossOrigin="anonymous",document.head.appendChild(c)}const t=document.createElement("link");t.rel="modulepreload",t.href=a,document.head.appendChild(t);const d=document.createElement("link");d.rel="preload",d.as="style",d.href=g,document.head.appendChild(d)}catch{}M(),v()}const L=A&&w?F(w,A,C(i.get("environment"))):Promise.resolve(void 0);if(typeof document!="undefined"&&document.head){const e=i.get("theme");if(e)try{const n=JSON.parse(e);n.backgroundImage&&b(n.backgroundImage)}catch{}L.then(n=>{var r;const t=(r=n==null?void 0:n.theme)===null||r===void 0?void 0:r.background_img;t&&b(t)})}const I=async()=>{var e,n,r,t,d,c,h;const P=i.get("agentId");if(!P){console.error("Agent ID is required in URL parameters");return}let p=i.get("title")||"Medi Clinic",y=i.get("iconUrl")||void 0;const x=i.get("context"),G=i.get("baseUrl")||"https://matrix.eka.care/reloaded",O=i.get("auth-token")||void 0;let k=i.get("resize")==="true"?!0:void 0;const J=(e=C(i.get("environment")))!==null&&e!==void 0?e:"production",_=i.get("connectivity"),N=_==="http_stream"||_==="socket"?_:void 0,E=i.get("theme")?(()=>{try{return JSON.parse(i.get("theme")||"{}")}catch{return}})():void 0,q=document.getElementById("root")||document.body;try{const[,,o]=await Promise.all([M(),v(),L]);if(!(window!=null&&window.renderMedAssist)||typeof(window==null?void 0:window.renderMedAssist)!="function")throw new Error("renderMedAssist is not available on window");let l,W,R,B,D=!1;o&&(p=(n=o==null?void 0:o.name)!==null&&n!==void 0?n:p,y=(t=(r=o==null?void 0:o.theme)===null||r===void 0?void 0:r.icon_img)!==null&&t!==void 0?t:y,l=z((d=o==null?void 0:o.theme)!==null&&d!==void 0?d:void 0),W=o==null?void 0:o.allowed,R=o==null?void 0:o.connectivity,B=o==null?void 0:o.initial_message,D=(h=(c=o==null?void 0:o.theme)===null||c===void 0?void 0:c.hide_watermark)!==null&&h!==void 0?h:!1,k=k||(o==null?void 0:o.resize)||void 0);const H={title:p,iconUrl:y,environment:J,connectionType:R||N||"socket",onClose:()=>{window.parent!==window&&window.parent.postMessage({type:"WIDGET_CLOSE"},"*")},context:x?JSON.parse(x):void 0,baseUrl:G,displayMode:"full",allowed:W,showCloseButton:!1,resize:k,initialMessage:B,hideWatermark:D,...O&&{authToken:O},theme:{...l!=null?l:{},...E!=null?E:{}}};window.renderMedAssist(q,P,H)}catch(o){throw console.error("Failed to initialize MedAssist widget",o),o}};async function M(){document.querySelector("link[data-medassist-style='true']")||(m||(m=new Promise((n,r)=>{const t=document.createElement("link");t.rel="stylesheet",t.href=g,t.setAttribute("data-medassist-style","true"),t.onload=()=>{n("")},t.onerror=()=>{r(new Error(`Failed to load ${g}`))},document.head.appendChild(t)})),await m)}function v(){return f||(f=new Promise((e,n)=>{const r=document.querySelector(`script[src="${a}"]`);if(r){if(r.dataset.loaded==="true"){e();return}r.addEventListener("load",()=>e()),r.addEventListener("error",d=>n(d.error||new Error("Unknown script loading error")));return}const t=document.createElement("script");t.src=a,t.type="module",t.async=!0,t.dataset.widget="medassist",t.onload=()=>{t.dataset.loaded="true",e()},t.onerror=d=>{if(d instanceof ErrorEvent&&d.error){n(d.error);return}n(new Error(`Failed to load ${a}`))},document.head.appendChild(t)})),f}if(typeof document!="undefined")if(document.readyState==="loading")document.addEventListener("DOMContentLoaded",I);else try{I()}catch(e){console.error("Failed to initialize MedAssist widget",e)}})();
|
package/dist/index.d.ts
CHANGED
|
@@ -36,6 +36,8 @@ type AgentConfig = {
|
|
|
36
36
|
upfront_consent?: boolean;
|
|
37
37
|
/** Tips shown while the bot works on a reply. Absent or empty -> the widget's built-in tips. */
|
|
38
38
|
tips?: string[];
|
|
39
|
+
/** Short inline markdown shown in a dismissible strip under the widget header. */
|
|
40
|
+
banner?: string;
|
|
39
41
|
/** Feature flag — currently gates the chat-history UI (session drawer + fullscreen sidebar). */
|
|
40
42
|
feature?: boolean;
|
|
41
43
|
/** Floating-widget width in px (desktop "widget" mode only). Clamped by the widget. */
|
|
@@ -133,6 +135,7 @@ type MedAssistInitConfig = {
|
|
|
133
135
|
consentContent?: string | string[];
|
|
134
136
|
upfrontConsent?: boolean;
|
|
135
137
|
tips?: string[];
|
|
138
|
+
banner?: string;
|
|
136
139
|
feature?: boolean;
|
|
137
140
|
/** Floating-widget size (px) from the agent config. Overridden by the `override…` keys below. */
|
|
138
141
|
widgetWidth?: number;
|
|
@@ -156,6 +159,13 @@ declare function preloadImage(url: string): void;
|
|
|
156
159
|
type SynapseChannel = "widget" | "web" | "side_panel";
|
|
157
160
|
declare function channelFromDisplayMode(displayMode: string | null | undefined): SynapseChannel;
|
|
158
161
|
declare function prefersReducedMotion(): boolean;
|
|
162
|
+
/**
|
|
163
|
+
* Same rule as the widget's useIsMobile (packages/widget/src/hooks/useResolvedMode.ts),
|
|
164
|
+
* so the loader and the widget agree on "mobile": narrow or touch viewport, or a mobile UA.
|
|
165
|
+
*/
|
|
166
|
+
declare const MOBILE_QUERY = "(max-width: 768px), (pointer: coarse)";
|
|
167
|
+
declare const MOBILE_UA_REGEX: RegExp;
|
|
168
|
+
declare function isMobileViewport(): boolean;
|
|
159
169
|
declare function nextFrame(): Promise<void>;
|
|
160
170
|
/**
|
|
161
171
|
* Icon colour on the accent: near-black on light accents, near-white on dark
|
|
@@ -346,6 +356,13 @@ declare class MedAssistWidgetLoader extends HTMLElement {
|
|
|
346
356
|
* - "open" → both hidden (widget is mounted)
|
|
347
357
|
*/
|
|
348
358
|
private updateLauncherView;
|
|
359
|
+
/**
|
|
360
|
+
* Whether a tap on the chatbox opens the widget straight away instead of
|
|
361
|
+
* waiting for a typed message: always on mobile (the widget opens full
|
|
362
|
+
* screen there, so typing into the small bar first is a wasted step), and
|
|
363
|
+
* on any device once a chat is in progress ("Continue your chat…").
|
|
364
|
+
*/
|
|
365
|
+
private chatboxOpensOnTap;
|
|
349
366
|
/**
|
|
350
367
|
* `x-channel` for every request this loader makes, from how the widget is set
|
|
351
368
|
* to open. The attribute wins; `init({ displayMode })` covers calls made
|
package/dist/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
"use strict";const getCurrentScript=()=>{if(typeof document=="undefined")return console.error("document is not defined"),null;const{currentScript:n}=document;if(n instanceof HTMLScriptElement)return n;const t=Array.from(document.getElementsByTagName("script")),e=t.find(s=>s.hasAttribute("data-widget-assets"));if(e)return e;const i=t.filter(s=>/(^|\/)index\.js(\?.*)?$/.test(s.src));return i.length?i[i.length-1]:t.length?t[t.length-1]:null},getEnvironment=n=>{if(n==="production"||n==="development"||n==="staging")return n},scriptEl=getCurrentScript(),DEFAULT_WIDGET_ASSET_BASE=(()=>{var n;return!((n=scriptEl==null?void 0:scriptEl.src)===null||n===void 0)&&n.includes("@dev"),"https://cdn.jsdelivr.net/npm/@eka-care/medassist-widget@0.2.0-dev.1/dist/"})();var FeedbackTypeEnum;(function(n){n.DEFAULT="default",n.NPS="nps"})(FeedbackTypeEnum||(FeedbackTypeEnum={}));function mapAgentConfigThemeToWidgetTheme(n){var t;if(!n)return;const e=n.mode==="dark"?"white":n.mode==="light"?"black":void 0;return{...n.background_img&&{backgroundImage:n.background_img},...n.accent&&{primary:n.accent},...e&&{textColor:e},...n.mode&&{mode:n.mode},...n.header_tinted!==void 0&&{headerTinted:n.header_tinted},...n.title_img&&{titleImg:n.title_img},...n.tagline&&{tagline:n.tagline},...n.hide_watermark&&{hideWatermark:n.hide_watermark},...n.explicit_disclaimer&&{explicitDisclaimer:n.explicit_disclaimer},...n.consent_content&&{consentContent:n.consent_content},...n.upfront_consent&&{upfrontConsent:n.upfront_consent},...((t=n.tips)===null||t===void 0?void 0:t.length)&&{tips:n.tips},...n.feature!==void 0&&{feature:n.feature},...typeof n.widget_width=="number"&&{widgetWidth:n.widget_width},...typeof n.widget_height=="number"&&{widgetHeight:n.widget_height}}}function preloadImage(n){if(!(!n||typeof document=="undefined"))try{const t=document.createElement("link");t.rel="preload",t.as="image",t.href=n,document.head.appendChild(t)}catch{const t=new Image;t.src=n}}function channelFromDisplayMode(n){return n==="full"?"web":n==="side_panel"?"side_panel":"widget"}function prefersReducedMotion(){var n;return typeof window!="undefined"&&!!(!((n=window.matchMedia)===null||n===void 0)&&n.call(window,"(prefers-reduced-motion: reduce)").matches)}function nextFrame(){return new Promise(n=>requestAnimationFrame(()=>n()))}function colorOnAccent(n){const t=n.trim().replace("#",""),e=t.length===3?t.split("").map(o=>o+o).join(""):t;if(!/^[0-9a-f]{6}$/i.test(e))return"#fafafa";const i=[0,2,4].map(o=>parseInt(e.slice(o,o+2),16)/255);return(Math.max(...i)+Math.min(...i))/2>.5?"#171717":"#fafafa"}function normalizeDisplayMode(n){return n==="full"?"full":n==="side_panel"?"side_panel":"widget"}const NUDGE_STORAGE_KEY="eka-medassist-nudges",AGENT_CONFIG_CACHE_KEY="eka-medassist-agent-config";function readAgentConfigCache(n){try{const t=localStorage.getItem(AGENT_CONFIG_CACHE_KEY);return(t?JSON.parse(t):{})[n]}catch{return}}function writeAgentConfigCache(n,t){try{const e=localStorage.getItem(AGENT_CONFIG_CACHE_KEY),i=e?JSON.parse(e):{};i[n]={...i[n]||{},...t},localStorage.setItem(AGENT_CONFIG_CACHE_KEY,JSON.stringify(i))}catch{}}function getNudgeStore(){try{const n=localStorage.getItem(NUDGE_STORAGE_KEY);return n?JSON.parse(n):{}}catch{return{}}}function setNudgeStore(n){try{localStorage.setItem(NUDGE_STORAGE_KEY,JSON.stringify(n))}catch{}}function normalizePath(n){let t=n.replace(/\/+$/,"");return t.startsWith("/")||(t="/"+t),t||"/"}function getNudgePathCandidates(n){const t=n.split("/").filter(Boolean),e=[];for(let i=t.length;i>=0;i--)e.push(i===0?"/":"/"+t.slice(0,i).join("/"));return e}function findCachedNudgeForCandidates(n,t,e){const s=getNudgeStore()[n];if(!s)return null;const o=t.host,a=s[o];if(!a)return null;for(const d of e){if(a[d]!==void 0)return{domain:o,path:d,data:a[d]};const r=d==="/"?"/*":d+"/*";if(a[r]!==void 0)return{domain:o,path:r,data:a[r]}}return null}function findFreshCachedNudge(n,t,e){const i=findCachedNudgeForCandidates(n,t,e);if(!i)return null;const s=Math.floor(Date.now()/1e3);return i.data.expiry<=s?(clearNudgeForPath(n,i.domain,i.path),null):i}function clearNudgeForPath(n,t,e){const i=getNudgeStore(),s=i[n];!s||!s[t]||(delete s[t][e],setNudgeStore(i))}function storeNudgeResponse(n,t,e){var i,s,o,a;const d=(i=t==null?void 0:t.url_pattern)===null||i===void 0?void 0:i.domain,r=(s=t==null?void 0:t.url_pattern)===null||s===void 0?void 0:s.path;if(!(!((o=t.nudges)===null||o===void 0)&&o.length)||!t.expiry||!d||!r)return;const l=getNudgeStore();l[n]||(l[n]={}),l[n][d]||(l[n][d]={});const c={nudges:t.nudges,expiry:t.expiry,delay:(a=t.delay)!==null&&a!==void 0?a:5};l[n][d][r]=c,e&&e!==r&&(l[n][d][e]=c),setNudgeStore(l)}const NUDGE_COOKIE_PREFIX="eka-nudge";function setNudgeCookie(n,t){const e=new Date(Date.now()+864e5).toUTCString();document.cookie=`${NUDGE_COOKIE_PREFIX}-${n}=${t}; expires=${e}; path=/; SameSite=Lax`}function getNudgeCookie(n){const t=document.cookie.split(";").map(i=>i.trim()).find(i=>i.startsWith(`${NUDGE_COOKIE_PREFIX}-${n}=`));if(!t)return null;const e=t.split("=")[1];return e==="open"||e==="closed"?e:null}const WIDGET_STORE_KEY_PREFIX="med-assist-store-";function readPersistedSessToken(n){var t,e;try{const i=sessionStorage.getItem(`${WIDGET_STORE_KEY_PREFIX}${n}`),s=i?(e=(t=JSON.parse(i))===null||t===void 0?void 0:t.state)===null||e===void 0?void 0:e.sessToken:void 0;return typeof s=="string"&&s?s:void 0}catch{return}}async function fetchNudgeData(n,t,e,i="widget"){const s=`${e}/med-assist/user-nudge`,o=[];typeof document!="undefined"&&document.querySelectorAll("meta").forEach(a=>{var d,r,l;const c=(d=a.getAttribute("name"))!==null&&d!==void 0?d:void 0,h=(r=a.getAttribute("property"))!==null&&r!==void 0?r:void 0,m=(l=a.getAttribute("content"))!==null&&l!==void 0?l:void 0;(c||h)&&o.push({name:c,property:h,content:m})});try{const a=await fetch(s,{method:"POST",headers:{"Content-Type":"application/json","x-agent-id":n,"x-channel":i,referer:typeof window!="undefined"?window.location.href:"",Authorization:`Bearer ${t}`},body:JSON.stringify({meta_tags:o,url:typeof window!="undefined"?window.location.href:""})});return a.ok?await a.json():void 0}catch{return}}function withTrailingEllipsis(n){const t=n.trim();return/[…?!]$/.test(t)?t:`${t.replace(/\.+$/,"")}\u2026`}const SIDE_PANEL_PUSH_EVENT="eka-medassist:side-panel-push",globalMedAssistConfig={},getWidgetElement=()=>typeof document=="undefined"?null:document.querySelector("eka-medassist-widget");if(typeof window!="undefined"){const n=window;n.__ekaMedAssistConfig__=globalMedAssistConfig,n.EkaMedAssist={registerTools(t){var e;globalMedAssistConfig.tools=t,(e=n.registerMedAssistTools)===null||e===void 0||e.call(n,t)},init(t){var e,i,s,o;Object.assign(globalMedAssistConfig,t),t.tools&&((e=n.registerMedAssistTools)===null||e===void 0||e.call(n,t.tools));const a=getWidgetElement();if(a){if(t.agentId&&a.setAttribute("agent-id",t.agentId),t.authToken&&a.setAttribute("auth-token",t.authToken),t.title&&a.setAttribute("title",t.title),t.iconUrl&&a.setAttribute("icon-url",t.iconUrl),t.baseUrl&&a.setAttribute("base-url",t.baseUrl),t.resize!==void 0&&a.setAttribute("resize",String(t.resize)),(t.displayMode==="full"||t.displayMode==="widget"||t.displayMode==="side_panel")&&a.setAttribute("display-mode",t.displayMode),t.sidePanelMode&&a.setAttribute("side-panel-mode",t.sidePanelMode),t.sidePanelWidth!==void 0&&a.setAttribute("side-panel-width",String(t.sidePanelWidth)),t.side&&a.setAttribute("side",t.side),t.context)try{a.setAttribute("context",JSON.stringify(t.context))}catch{console.warn("Failed to stringify context passed to init")}typeof t.customLauncherStyles=="string"&&a.setAttribute("custom-launcher-styles",t.customLauncherStyles),t.launcherType&&a.setAttribute("launcher-type",t.launcherType),t.redirectUrl&&a.setAttribute("redirect-url",t.redirectUrl),!((i=t.theme)===null||i===void 0)&&i.backgroundImage&&preloadImage(t.theme.backgroundImage),(o=(s=a).openFromBridge)===null||o===void 0||o.call(s)}}}}const scriptBaseUrl=(()=>{if(!scriptEl)return"";try{return new URL(".",scriptEl.src||window.location.href).href}catch{return""}})(),widgetAssetBaseUrl=(()=>{if(!scriptEl)return DEFAULT_WIDGET_ASSET_BASE;const n=scriptEl.dataset.widgetAssets;if(n==="local")return`${scriptBaseUrl}src/`;if(n&&n.length>0)try{return new URL(n,scriptBaseUrl).href}catch{return n.endsWith("/")?n:`${n}/`}return DEFAULT_WIDGET_ASSET_BASE})(),WIDGET_JS_URL=`${widgetAssetBaseUrl}medassist-widget.js`,WIDGET_CSS_URL=`${widgetAssetBaseUrl}medassist-widget.css`;let widgetModulePromise=null,widgetCssTextPromise=null;function getWidgetCssTextPromise(){return widgetCssTextPromise||(widgetCssTextPromise=fetch(WIDGET_CSS_URL).then(n=>{if(!n.ok)throw new Error(`Unable to fetch widget styles from ${WIDGET_CSS_URL}`);return n.text()})),widgetCssTextPromise}class MedAssistWidgetLoader extends HTMLElement{setLauncherState(t){this.launcherState=t,this.updateLauncherView()}getLauncherType(){var t,e;if(this.displayMode!=="widget")return"button";const i=(typeof window!="undefined"?window.__ekaMedAssistConfig__:void 0)||{},s=this.getAgentId();return(this.getAttribute("launcher-type")||i.launcherType||(s?(e=(t=readAgentConfigCache(s))===null||t===void 0?void 0:t.theme)===null||e===void 0?void 0:e.launcher_type:void 0))==="chatbox"?"chatbox":"button"}isChatboxShown(){return this.getLauncherType()==="chatbox"}updateLauncherView(){const t=this.shadowRoot;if(!t)return;this.applyCustomLauncherStyles();const e=this.launcherState,i=this.isChatboxShown(),s=t.getElementById("medassist-open-btn");if(s){const a=e==="loading"&&!i;s.classList.toggle("loading",a),s.classList.toggle("hidden",e==="open"||i),a?s.setAttribute("aria-busy","true"):s.removeAttribute("aria-busy")}const o=t.getElementById("medassist-chatbox");if(o){this.applyChatboxTheme(o);const a=e==="loading"&&i;o.classList.toggle("hidden",e==="open"||!i),o.classList.toggle("sending",a);const d=this.chatStarted&&e==="idle";o.classList.toggle("continuing",d),this.syncChatboxPlaceholder(),this.syncChatboxPulse();const r=t.getElementById("medassist-chatbox-input");if(r){r.readOnly=a||d,e==="open"&&(r.value="",this.autosizeChatbox());const l=o.querySelector(".medassist-chatbox-send");l&&(l.disabled=!r.value.trim())}}}getChannel(){const t=this.getAttribute("display-mode");if(t)return channelFromDisplayMode(t);const e=typeof window!="undefined"?window.__ekaMedAssistConfig__:void 0;return channelFromDisplayMode(e==null?void 0:e.displayMode)}getAgentConfig(){var t;if(!this.agentConfigPromise){const e=(typeof window!="undefined"?window.__ekaMedAssistConfig__:void 0)||{},i=e.baseUrl||this.getAttribute("base-url")||"https://matrix.eka.care/reloaded",s=e.agentId||this.getAttribute("agent-id")||"";if(!s)return Promise.resolve(void 0);const o=(t=getEnvironment(this.getAttribute("environment")))!==null&&t!==void 0?t:"production";this.agentConfigPromise=this.loadWidgetModule().then(a=>{var d;return(d=a.fetchAgentConfig)===null||d===void 0?void 0:d.call(a,{agentId:s,serverUrl:i,environment:o,channel:this.getChannel()})}).catch(()=>{this.agentConfigPromise=null})}return this.agentConfigPromise}constructor(){super(),this.hostPushStyleEl=null,this.hostPushState=null,this.reactRoot=null,this.agentConfigPromise=null,this.loading=!1,this.chatStarted=!1,this.placeholderTimer=null,this.placeholderIndex=0,this.launcherState="idle",this.authPrefetchPromise=null,this.launcherRenderSeq=0,this.attachShadow({mode:"open"}),this.widgetLoaded=!1,this.displayMode=normalizeDisplayMode(this.getAttribute("display-mode")),this.setupAuthExpirationListener()}static get observedAttributes(){return["icon-url","display-mode","custom-launcher-styles","redirect-url","side-panel-mode","side-panel-width","side","override-widget-width","override-widget-height","launcher-type"]}connectedCallback(){this.displayMode==="full"?(this.initializeFullMode(),this.loadAndRender().catch(t=>{console.error("Failed to load MedAssist widget in full mode",t)})):(this.renderLauncher(),this.scheduleIdle(()=>{this.preloadWidgetAssets(),this.prefetchAuthTokens(),this.initNudge()}))}disconnectedCallback(){var t,e,i,s,o;this.placeholderTimer&&clearInterval(this.placeholderTimer),this.placeholderTimer=null,(t=this.reactRoot)===null||t===void 0||t.unmount(),this.reactRoot=null,(e=document.body)===null||e===void 0||e.classList.remove("eka-medassist-pushed"),(i=document.documentElement)===null||i===void 0||i.style.removeProperty("--eka-medassist-panel-width"),(s=document.documentElement)===null||s===void 0||s.style.removeProperty("--eka-medassist-panel-side"),(o=this.hostPushStyleEl)===null||o===void 0||o.remove(),this.hostPushStyleEl=null,this.hostPushState=null}applyHostPush(t,e,i){var s;if(typeof document=="undefined")return;const o=t?{width:e,side:i}:null,a=this.hostPushState;if(a===o||a&&o&&a.width===o.width&&a.side===o.side)return;this.hostPushState=o,this.hostPushStyleEl||(this.hostPushStyleEl=document.createElement("style"),this.hostPushStyleEl.setAttribute("data-medassist-side-panel-push","true"),document.head.appendChild(this.hostPushStyleEl));const d=i==="left"?"margin-left":"margin-right";this.hostPushStyleEl.textContent=`
|
|
1
|
+
"use strict";const getCurrentScript=()=>{if(typeof document=="undefined")return console.error("document is not defined"),null;const{currentScript:n}=document;if(n instanceof HTMLScriptElement)return n;const t=Array.from(document.getElementsByTagName("script")),e=t.find(o=>o.hasAttribute("data-widget-assets"));if(e)return e;const i=t.filter(o=>/(^|\/)index\.js(\?.*)?$/.test(o.src));return i.length?i[i.length-1]:t.length?t[t.length-1]:null},getEnvironment=n=>{if(n==="production"||n==="development"||n==="staging")return n},scriptEl=getCurrentScript(),DEFAULT_WIDGET_ASSET_BASE=(()=>{var n;return!((n=scriptEl==null?void 0:scriptEl.src)===null||n===void 0)&&n.includes("@dev"),"https://cdn.jsdelivr.net/npm/@eka-care/medassist-widget@0.2.0-dev.3/dist/"})();var FeedbackTypeEnum;(function(n){n.DEFAULT="default",n.NPS="nps"})(FeedbackTypeEnum||(FeedbackTypeEnum={}));function mapAgentConfigThemeToWidgetTheme(n){var t,e;if(!n)return;const i=n.mode==="dark"?"white":n.mode==="light"?"black":void 0;return{...n.background_img&&{backgroundImage:n.background_img},...n.accent&&{primary:n.accent},...i&&{textColor:i},...n.mode&&{mode:n.mode},...n.header_tinted!==void 0&&{headerTinted:n.header_tinted},...n.title_img&&{titleImg:n.title_img},...n.tagline&&{tagline:n.tagline},...n.hide_watermark&&{hideWatermark:n.hide_watermark},...n.explicit_disclaimer&&{explicitDisclaimer:n.explicit_disclaimer},...n.consent_content&&{consentContent:n.consent_content},...n.upfront_consent&&{upfrontConsent:n.upfront_consent},...((t=n.tips)===null||t===void 0?void 0:t.length)&&{tips:n.tips},...((e=n.banner)===null||e===void 0?void 0:e.trim())&&{banner:n.banner},...n.feature!==void 0&&{feature:n.feature},...typeof n.widget_width=="number"&&{widgetWidth:n.widget_width},...typeof n.widget_height=="number"&&{widgetHeight:n.widget_height}}}function preloadImage(n){if(!(!n||typeof document=="undefined"))try{const t=document.createElement("link");t.rel="preload",t.as="image",t.href=n,document.head.appendChild(t)}catch{const t=new Image;t.src=n}}function channelFromDisplayMode(n){return n==="full"?"web":n==="side_panel"?"side_panel":"widget"}function prefersReducedMotion(){var n;return typeof window!="undefined"&&!!(!((n=window.matchMedia)===null||n===void 0)&&n.call(window,"(prefers-reduced-motion: reduce)").matches)}const MOBILE_QUERY="(max-width: 768px), (pointer: coarse)",MOBILE_UA_REGEX=/android|webos|iphone|ipad|ipod|blackberry|iemobile|opera mini/i;function isMobileViewport(){var n,t,e;return typeof window=="undefined"?!1:!!(!((t=(n=window.matchMedia)===null||n===void 0?void 0:n.call(window,MOBILE_QUERY))===null||t===void 0)&&t.matches)||MOBILE_UA_REGEX.test((e=navigator==null?void 0:navigator.userAgent)!==null&&e!==void 0?e:"")}function nextFrame(){return new Promise(n=>requestAnimationFrame(()=>n()))}function colorOnAccent(n){const t=n.trim().replace("#",""),e=t.length===3?t.split("").map(s=>s+s).join(""):t;if(!/^[0-9a-f]{6}$/i.test(e))return"#fafafa";const i=[0,2,4].map(s=>parseInt(e.slice(s,s+2),16)/255);return(Math.max(...i)+Math.min(...i))/2>.5?"#171717":"#fafafa"}function normalizeDisplayMode(n){return n==="full"?"full":n==="side_panel"?"side_panel":"widget"}const NUDGE_STORAGE_KEY="eka-medassist-nudges",AGENT_CONFIG_CACHE_KEY="eka-medassist-agent-config";function readAgentConfigCache(n){try{const t=localStorage.getItem(AGENT_CONFIG_CACHE_KEY);return(t?JSON.parse(t):{})[n]}catch{return}}function writeAgentConfigCache(n,t){try{const e=localStorage.getItem(AGENT_CONFIG_CACHE_KEY),i=e?JSON.parse(e):{};i[n]={...i[n]||{},...t},localStorage.setItem(AGENT_CONFIG_CACHE_KEY,JSON.stringify(i))}catch{}}function getNudgeStore(){try{const n=localStorage.getItem(NUDGE_STORAGE_KEY);return n?JSON.parse(n):{}}catch{return{}}}function setNudgeStore(n){try{localStorage.setItem(NUDGE_STORAGE_KEY,JSON.stringify(n))}catch{}}function normalizePath(n){let t=n.replace(/\/+$/,"");return t.startsWith("/")||(t="/"+t),t||"/"}function getNudgePathCandidates(n){const t=n.split("/").filter(Boolean),e=[];for(let i=t.length;i>=0;i--)e.push(i===0?"/":"/"+t.slice(0,i).join("/"));return e}function findCachedNudgeForCandidates(n,t,e){const o=getNudgeStore()[n];if(!o)return null;const s=t.host,a=o[s];if(!a)return null;for(const d of e){if(a[d]!==void 0)return{domain:s,path:d,data:a[d]};const l=d==="/"?"/*":d+"/*";if(a[l]!==void 0)return{domain:s,path:l,data:a[l]}}return null}function findFreshCachedNudge(n,t,e){const i=findCachedNudgeForCandidates(n,t,e);if(!i)return null;const o=Math.floor(Date.now()/1e3);return i.data.expiry<=o?(clearNudgeForPath(n,i.domain,i.path),null):i}function clearNudgeForPath(n,t,e){const i=getNudgeStore(),o=i[n];!o||!o[t]||(delete o[t][e],setNudgeStore(i))}function storeNudgeResponse(n,t,e){var i,o,s,a;const d=(i=t==null?void 0:t.url_pattern)===null||i===void 0?void 0:i.domain,l=(o=t==null?void 0:t.url_pattern)===null||o===void 0?void 0:o.path;if(!(!((s=t.nudges)===null||s===void 0)&&s.length)||!t.expiry||!d||!l)return;const r=getNudgeStore();r[n]||(r[n]={}),r[n][d]||(r[n][d]={});const c={nudges:t.nudges,expiry:t.expiry,delay:(a=t.delay)!==null&&a!==void 0?a:5};r[n][d][l]=c,e&&e!==l&&(r[n][d][e]=c),setNudgeStore(r)}const NUDGE_COOKIE_PREFIX="eka-nudge";function setNudgeCookie(n,t){const e=new Date(Date.now()+864e5).toUTCString();document.cookie=`${NUDGE_COOKIE_PREFIX}-${n}=${t}; expires=${e}; path=/; SameSite=Lax`}function getNudgeCookie(n){const t=document.cookie.split(";").map(i=>i.trim()).find(i=>i.startsWith(`${NUDGE_COOKIE_PREFIX}-${n}=`));if(!t)return null;const e=t.split("=")[1];return e==="open"||e==="closed"?e:null}const WIDGET_STORE_KEY_PREFIX="med-assist-store-";function readPersistedSessToken(n){var t,e;try{const i=sessionStorage.getItem(`${WIDGET_STORE_KEY_PREFIX}${n}`),o=i?(e=(t=JSON.parse(i))===null||t===void 0?void 0:t.state)===null||e===void 0?void 0:e.sessToken:void 0;return typeof o=="string"&&o?o:void 0}catch{return}}async function fetchNudgeData(n,t,e,i="widget"){const o=`${e}/med-assist/user-nudge`,s=[];typeof document!="undefined"&&document.querySelectorAll("meta").forEach(a=>{var d,l,r;const c=(d=a.getAttribute("name"))!==null&&d!==void 0?d:void 0,u=(l=a.getAttribute("property"))!==null&&l!==void 0?l:void 0,m=(r=a.getAttribute("content"))!==null&&r!==void 0?r:void 0;(c||u)&&s.push({name:c,property:u,content:m})});try{const a=await fetch(o,{method:"POST",headers:{"Content-Type":"application/json","x-agent-id":n,"x-channel":i,referer:typeof window!="undefined"?window.location.href:"",Authorization:`Bearer ${t}`},body:JSON.stringify({meta_tags:s,url:typeof window!="undefined"?window.location.href:""})});return a.ok?await a.json():void 0}catch{return}}function withTrailingEllipsis(n){const t=n.trim();return/[…?!]$/.test(t)?t:`${t.replace(/\.+$/,"")}\u2026`}const SIDE_PANEL_PUSH_EVENT="eka-medassist:side-panel-push",globalMedAssistConfig={},getWidgetElement=()=>typeof document=="undefined"?null:document.querySelector("eka-medassist-widget");if(typeof window!="undefined"){const n=window;n.__ekaMedAssistConfig__=globalMedAssistConfig,n.EkaMedAssist={registerTools(t){var e;globalMedAssistConfig.tools=t,(e=n.registerMedAssistTools)===null||e===void 0||e.call(n,t)},init(t){var e,i,o,s;Object.assign(globalMedAssistConfig,t),t.tools&&((e=n.registerMedAssistTools)===null||e===void 0||e.call(n,t.tools));const a=getWidgetElement();if(a){if(t.agentId&&a.setAttribute("agent-id",t.agentId),t.authToken&&a.setAttribute("auth-token",t.authToken),t.title&&a.setAttribute("title",t.title),t.iconUrl&&a.setAttribute("icon-url",t.iconUrl),t.baseUrl&&a.setAttribute("base-url",t.baseUrl),t.resize!==void 0&&a.setAttribute("resize",String(t.resize)),(t.displayMode==="full"||t.displayMode==="widget"||t.displayMode==="side_panel")&&a.setAttribute("display-mode",t.displayMode),t.sidePanelMode&&a.setAttribute("side-panel-mode",t.sidePanelMode),t.sidePanelWidth!==void 0&&a.setAttribute("side-panel-width",String(t.sidePanelWidth)),t.side&&a.setAttribute("side",t.side),t.context)try{a.setAttribute("context",JSON.stringify(t.context))}catch{console.warn("Failed to stringify context passed to init")}typeof t.customLauncherStyles=="string"&&a.setAttribute("custom-launcher-styles",t.customLauncherStyles),t.launcherType&&a.setAttribute("launcher-type",t.launcherType),t.redirectUrl&&a.setAttribute("redirect-url",t.redirectUrl),!((i=t.theme)===null||i===void 0)&&i.backgroundImage&&preloadImage(t.theme.backgroundImage),(s=(o=a).openFromBridge)===null||s===void 0||s.call(o)}}}}const scriptBaseUrl=(()=>{if(!scriptEl)return"";try{return new URL(".",scriptEl.src||window.location.href).href}catch{return""}})(),widgetAssetBaseUrl=(()=>{if(!scriptEl)return DEFAULT_WIDGET_ASSET_BASE;const n=scriptEl.dataset.widgetAssets;if(n==="local")return`${scriptBaseUrl}src/`;if(n&&n.length>0)try{return new URL(n,scriptBaseUrl).href}catch{return n.endsWith("/")?n:`${n}/`}return DEFAULT_WIDGET_ASSET_BASE})(),WIDGET_JS_URL=`${widgetAssetBaseUrl}medassist-widget.js`,WIDGET_CSS_URL=`${widgetAssetBaseUrl}medassist-widget.css`;let widgetModulePromise=null,widgetCssTextPromise=null;function getWidgetCssTextPromise(){return widgetCssTextPromise||(widgetCssTextPromise=fetch(WIDGET_CSS_URL).then(n=>{if(!n.ok)throw new Error(`Unable to fetch widget styles from ${WIDGET_CSS_URL}`);return n.text()})),widgetCssTextPromise}class MedAssistWidgetLoader extends HTMLElement{setLauncherState(t){this.launcherState=t,this.updateLauncherView()}getLauncherType(){var t,e;if(this.displayMode!=="widget")return"button";const i=(typeof window!="undefined"?window.__ekaMedAssistConfig__:void 0)||{},o=this.getAgentId();return(this.getAttribute("launcher-type")||i.launcherType||(o?(e=(t=readAgentConfigCache(o))===null||t===void 0?void 0:t.theme)===null||e===void 0?void 0:e.launcher_type:void 0))==="chatbox"?"chatbox":"button"}isChatboxShown(){return this.getLauncherType()==="chatbox"}updateLauncherView(){const t=this.shadowRoot;if(!t)return;this.applyCustomLauncherStyles();const e=this.launcherState,i=this.isChatboxShown(),o=t.getElementById("medassist-open-btn");if(o){const a=e==="loading"&&!i;o.classList.toggle("loading",a),o.classList.toggle("hidden",e==="open"||i),a?o.setAttribute("aria-busy","true"):o.removeAttribute("aria-busy")}const s=t.getElementById("medassist-chatbox");if(s){this.applyChatboxTheme(s);const a=e==="loading"&&i;s.classList.toggle("hidden",e==="open"||!i),s.classList.toggle("sending",a);const d=this.chatStarted&&e==="idle";s.classList.toggle("continuing",d);const l=e==="idle"&&this.chatboxOpensOnTap();s.classList.toggle("tap-open",l),this.syncChatboxPlaceholder(),this.syncChatboxPulse();const r=t.getElementById("medassist-chatbox-input");if(r){r.readOnly=a||d||l,e==="open"&&(r.value="",this.autosizeChatbox());const c=s.querySelector(".medassist-chatbox-send");c&&(c.disabled=!r.value.trim()&&!l)}}}chatboxOpensOnTap(){return this.chatStarted||isMobileViewport()}getChannel(){const t=this.getAttribute("display-mode");if(t)return channelFromDisplayMode(t);const e=typeof window!="undefined"?window.__ekaMedAssistConfig__:void 0;return channelFromDisplayMode(e==null?void 0:e.displayMode)}getAgentConfig(){var t;if(!this.agentConfigPromise){const e=(typeof window!="undefined"?window.__ekaMedAssistConfig__:void 0)||{},i=e.baseUrl||this.getAttribute("base-url")||"https://matrix.eka.care/reloaded",o=e.agentId||this.getAttribute("agent-id")||"";if(!o)return Promise.resolve(void 0);const s=(t=getEnvironment(this.getAttribute("environment")))!==null&&t!==void 0?t:"production";this.agentConfigPromise=this.loadWidgetModule().then(a=>{var d;return(d=a.fetchAgentConfig)===null||d===void 0?void 0:d.call(a,{agentId:o,serverUrl:i,environment:s,channel:this.getChannel()})}).catch(()=>{this.agentConfigPromise=null})}return this.agentConfigPromise}constructor(){super(),this.hostPushStyleEl=null,this.hostPushState=null,this.reactRoot=null,this.agentConfigPromise=null,this.loading=!1,this.chatStarted=!1,this.placeholderTimer=null,this.placeholderIndex=0,this.launcherState="idle",this.authPrefetchPromise=null,this.launcherRenderSeq=0,this.attachShadow({mode:"open"}),this.widgetLoaded=!1,this.displayMode=normalizeDisplayMode(this.getAttribute("display-mode")),this.setupAuthExpirationListener()}static get observedAttributes(){return["icon-url","display-mode","custom-launcher-styles","redirect-url","side-panel-mode","side-panel-width","side","override-widget-width","override-widget-height","launcher-type"]}connectedCallback(){this.displayMode==="full"?(this.initializeFullMode(),this.loadAndRender().catch(t=>{console.error("Failed to load MedAssist widget in full mode",t)})):(this.renderLauncher(),this.scheduleIdle(()=>{this.preloadWidgetAssets(),this.prefetchAuthTokens(),this.initNudge()}))}disconnectedCallback(){var t,e,i,o,s;this.placeholderTimer&&clearInterval(this.placeholderTimer),this.placeholderTimer=null,(t=this.reactRoot)===null||t===void 0||t.unmount(),this.reactRoot=null,(e=document.body)===null||e===void 0||e.classList.remove("eka-medassist-pushed"),(i=document.documentElement)===null||i===void 0||i.style.removeProperty("--eka-medassist-panel-width"),(o=document.documentElement)===null||o===void 0||o.style.removeProperty("--eka-medassist-panel-side"),(s=this.hostPushStyleEl)===null||s===void 0||s.remove(),this.hostPushStyleEl=null,this.hostPushState=null}applyHostPush(t,e,i){var o;if(typeof document=="undefined")return;const s=t?{width:e,side:i}:null,a=this.hostPushState;if(a===s||a&&s&&a.width===s.width&&a.side===s.side)return;this.hostPushState=s,this.hostPushStyleEl||(this.hostPushStyleEl=document.createElement("style"),this.hostPushStyleEl.setAttribute("data-medassist-side-panel-push","true"),document.head.appendChild(this.hostPushStyleEl));const d=i==="left"?"margin-left":"margin-right";this.hostPushStyleEl.textContent=`
|
|
2
2
|
body.eka-medassist-pushed {
|
|
3
3
|
${d}: ${e}px;
|
|
4
4
|
transition: margin 300ms ease;
|
|
@@ -9,7 +9,7 @@
|
|
|
9
9
|
@media (prefers-reduced-motion: reduce) {
|
|
10
10
|
body.eka-medassist-pushed { transition: none !important; }
|
|
11
11
|
}
|
|
12
|
-
`;const
|
|
12
|
+
`;const l=document.documentElement.style;t?(l.setProperty("--eka-medassist-panel-width",`${e}px`),l.setProperty("--eka-medassist-panel-side",i),document.body.classList.add("eka-medassist-pushed")):(document.body.classList.remove("eka-medassist-pushed"),l.removeProperty("--eka-medassist-panel-width"),l.removeProperty("--eka-medassist-panel-side"),this.hostPushStyleEl.remove(),this.hostPushStyleEl=null);const r={pushed:t,width:e,side:i};if(typeof window!="undefined"){try{window.dispatchEvent(new CustomEvent(SIDE_PANEL_PUSH_EVENT,{detail:r}))}catch{}const c=(o=window.EkaMedAssist)===null||o===void 0?void 0:o.onSidePanelPushChange;if(typeof c=="function")try{c(t,e,i)}catch(u){console.error("EkaMedAssist.onSidePanelPushChange threw",u)}}}scheduleIdle(t){if(typeof window=="undefined"){t();return}const e=window.requestIdleCallback;typeof e=="function"?e(t,{timeout:3e3}):setTimeout(t,200)}attributeChangedCallback(t){if(t==="icon-url"&&this.displayMode!=="full"&&this.renderLauncher(),t==="display-mode"){const e=normalizeDisplayMode(this.getAttribute("display-mode"));e!==this.displayMode&&(this.displayMode=e,e==="full"?this.initializeFullMode():this.renderLauncher())}t==="custom-launcher-styles"&&this.applyCustomLauncherStyles(),t==="launcher-type"&&this.updateLauncherView()}preloadWidgetAssets(){getWidgetCssTextPromise(),this.loadWidgetModule(),this.preloadBackgroundImage()}prefetchAuthTokens(){var t;if(this.authPrefetchPromise)return this.authPrefetchPromise;const e=(typeof window!="undefined"?window.__ekaMedAssistConfig__:void 0)||{},i=e.agentId||this.getAttribute("agent-id")||"";if(!i)return Promise.resolve(void 0);const o=e.authToken||this.getAttribute("auth-token")||void 0,s=e.baseUrl||this.getAttribute("base-url")||"https://matrix.eka.care/reloaded",a=(t=getEnvironment(this.getAttribute("environment")))!==null&&t!==void 0?t:"production";return this.authPrefetchPromise=this.loadWidgetModule().then(d=>{var l;return(l=d.prefetchAuth)===null||l===void 0?void 0:l.call(d,{agentId:i,authToken:o,serverUrl:s,environment:a,channel:this.getChannel()})}).catch(()=>{this.authPrefetchPromise=null}),this.authPrefetchPromise}async resolveSessToken(t){const e=readPersistedSessToken(t);if(e)return e;const i=await this.prefetchAuthTokens();return(i==null?void 0:i.sess_token)||readPersistedSessToken(t)}preloadBackgroundImage(){var t;const e=typeof window!="undefined"?window.__ekaMedAssistConfig__:void 0,i=this.getAttribute("theme")?(()=>{try{return JSON.parse(this.getAttribute("theme")||"{}")}catch{return}})():void 0,o=(t=e==null?void 0:e.theme)===null||t===void 0?void 0:t.backgroundImage,s=i==null?void 0:i.backgroundImage;o&&preloadImage(o),s&&s!==o&&preloadImage(s),this.getAgentConfig().then(a=>{var d;const l=(d=a==null?void 0:a.theme)===null||d===void 0?void 0:d.background_img;l&&preloadImage(l)}).catch(()=>{})}setupAuthExpirationListener(){if(typeof window=="undefined")return;const t=e=>{var i;((i=e.data)===null||i===void 0?void 0:i.type)==="AUTH_EXPIRED"&&window.parent!==window&&window.parent.postMessage({type:"AUTH_EXPIRED",message:"Authentication expired"},"*")};window.addEventListener("message",t)}openFromBridge(){if(this.displayMode=normalizeDisplayMode(this.getAttribute("display-mode")),this.displayMode==="full")this.initializeFullMode();else if(this.renderLauncher(),this.getLauncherType()==="chatbox")return;this.loadAndRender().catch(t=>{console.error("Failed to open MedAssist widget from bridge",t)})}async initNudge(){var t,e,i,o;const s=typeof window!="undefined"?window.__ekaMedAssistConfig__:void 0,a=(s==null?void 0:s.agentId)||this.getAttribute("agent-id")||"";if(!a)return;const d=await this.getAgentConfig();if(!(d!=null&&d.nudge))return;const l=(e=(t=d==null?void 0:d.theme)===null||t===void 0?void 0:t.nudge_color)!==null&&e!==void 0?e:"#ffffff",r=typeof window!="undefined"?window.location.href:"";let c;try{c=new URL(r)}catch{return}const u=getNudgePathCandidates(c.pathname),m=u.slice(0,1),x=u.slice(1);let g=findFreshCachedNudge(a,c,m);if(!g){const y=(s==null?void 0:s.baseUrl)||this.getAttribute("base-url")||"https://matrix.eka.care/reloaded",_=await this.resolveSessToken(a).catch(()=>{});if(_){const f=await fetchNudgeData(a,_,y,this.getChannel()).catch(()=>{});!((i=f==null?void 0:f.nudges)===null||i===void 0)&&i.length&&(storeNudgeResponse(a,f,normalizePath(c.pathname)),g=findFreshCachedNudge(a,c,u))}}if(g||(g=findFreshCachedNudge(a,c,x)),!g)return;const C=g.data.nudges[Math.floor(Math.random()*g.data.nudges.length)],w=(o=g.data.delay)!==null&&o!==void 0?o:5;setTimeout(()=>{this.showNudgePopup(C,l)},w*1e3)}showNudgePopup(t,e){var i,o;const s=this.shadowRoot;if(!s||!(!((i=s.getElementById("medassist-widget-root"))===null||i===void 0)&&i.classList.contains("hidden")))return;const d=((typeof window!="undefined"?window.__ekaMedAssistConfig__:void 0)||{}).agentId||this.getAttribute("agent-id")||"";if(d&&getNudgeCookie(d)!==null||s.getElementById("medassist-nudge-popup"))return;const r=this.isChatboxShown()?s.getElementById("medassist-chatbox"):s.getElementById("medassist-open-btn"),c=r==null?void 0:r.getBoundingClientRect(),u=272,m=12,x=8,g=16,C=16;let w=window.innerWidth-u-m,y=76,_=u-g-x*2;if(c&&c.width>0){const b=c.left+c.width/2,p=b-u/2,E=window.innerWidth-u-m;w=Math.max(m,Math.min(p,E)),y=window.innerHeight-c.top+C,_=Math.max(g,Math.min(b-w-x,u-g-x*2))}const f=document.createElement("div");f.id="medassist-nudge-popup",f.innerHTML=`
|
|
13
13
|
<style>
|
|
14
14
|
@keyframes nudge-slide-up {
|
|
15
15
|
from { opacity: 0; transform: translateY(12px) scale(0.97); }
|
|
@@ -19,7 +19,7 @@
|
|
|
19
19
|
position: fixed;
|
|
20
20
|
bottom: ${y}px;
|
|
21
21
|
left: ${w}px;
|
|
22
|
-
width: ${
|
|
22
|
+
width: ${u}px;
|
|
23
23
|
background: ${e};
|
|
24
24
|
border-radius: 16px;
|
|
25
25
|
box-shadow: 0 8px 32px rgba(0,0,0,0.14), 0 2px 8px rgba(0,0,0,0.08);
|
|
@@ -37,7 +37,7 @@
|
|
|
37
37
|
content: '';
|
|
38
38
|
position: absolute;
|
|
39
39
|
bottom: -8px;
|
|
40
|
-
left: ${
|
|
40
|
+
left: ${_}px;
|
|
41
41
|
width: 16px;
|
|
42
42
|
height: 10px;
|
|
43
43
|
background: ${e};
|
|
@@ -90,7 +90,7 @@
|
|
|
90
90
|
<p class="nudge-text">${t.replace(/</g,"<").replace(/>/g,">")}</p>
|
|
91
91
|
<button class="nudge-close" aria-label="Dismiss">✕</button>
|
|
92
92
|
</div>
|
|
93
|
-
`,(
|
|
93
|
+
`,(o=f.querySelector(".nudge-close"))===null||o===void 0||o.addEventListener("click",b=>{b.stopPropagation(),d&&setNudgeCookie(d,"closed"),this.dismissNudgePopup()}),f.addEventListener("click",()=>{var b;if(d&&setNudgeCookie(d,"closed"),this.dismissNudgePopup(),this.isChatboxShown()){(b=s.getElementById("medassist-chatbox-input"))===null||b===void 0||b.focus();return}this.loadAndRender()}),s.appendChild(f)}dismissNudgePopup(){var t;const e=(t=this.shadowRoot)===null||t===void 0?void 0:t.getElementById("medassist-nudge-popup");e==null||e.remove()}applyCustomLauncherStyles(){var t,e,i,o;const s=this.shadowRoot;if(!s||this.displayMode==="full")return;const a=this.getAgentId(),d=(i=a?(e=(t=readAgentConfigCache(a))===null||t===void 0?void 0:t.theme)===null||e===void 0?void 0:e.launcher_styles:void 0)!==null&&i!==void 0?i:"";this.setLauncherStyleTag("data-medassist-config-launcher",d);const l=s.querySelector('style[data-medassist-custom-launcher="true"]'),r=(o=this.getAttribute("custom-launcher-styles"))!==null&&o!==void 0?o:"";if(!r){l==null||l.remove();return}if(l){l.textContent=r;return}const c=document.createElement("style");c.setAttribute("data-medassist-custom-launcher","true"),c.textContent=r,s.appendChild(c)}setLauncherStyleTag(t,e){const i=this.shadowRoot;if(!i)return;const o=i.querySelector(`style[${t}="true"]`);if(!e){o==null||o.remove();return}if(o){o.textContent=e;return}const s=document.createElement("style");s.setAttribute(t,"true"),s.textContent=e;const a=i.querySelector('style[data-medassist-custom-launcher="true"]');i.insertBefore(s,a)}getAgentId(){return((typeof window!="undefined"?window.__ekaMedAssistConfig__:void 0)||{}).agentId||this.getAttribute("agent-id")||""}async renderLauncher(){var t,e;if(this.displayMode==="full")return;const i=++this.launcherRenderSeq;this.renderButton();const o=this.getAttribute("icon-url");if(o){this.setLauncherIcon(o);const l=this.getAgentId();l&&this.scheduleIdle(()=>{this.getAgentConfig().then(r=>{!r||i!==this.launcherRenderSeq||(writeAgentConfigCache(l,r),this.updateLauncherView())})});return}const s=this.getAgentId();if(!s)return;const a=(e=(t=readAgentConfigCache(s))===null||t===void 0?void 0:t.theme)===null||e===void 0?void 0:e.icon_img;a&&this.setLauncherIcon(a);const d=async()=>{var l;const r=await this.getAgentConfig().catch(()=>{});i===this.launcherRenderSeq&&(r&&writeAgentConfigCache(s,r),this.setLauncherIcon(((l=r==null?void 0:r.theme)===null||l===void 0?void 0:l.icon_img)||a))};a?this.scheduleIdle(()=>{d()}):await d()}setLauncherIcon(t){var e,i;const o=this.shadowRoot;if(!o)return;const s=o.querySelector("#medassist-open-btn img");s&&(t?s.src=t:s.removeAttribute("src")),(e=o.getElementById("medassist-open-btn"))===null||e===void 0||e.classList.remove("pending"),(i=o.getElementById("medassist-chatbox"))===null||i===void 0||i.classList.remove("pending"),this.updateLauncherView()}applyChatboxTheme(t){var e;const i=((typeof window!="undefined"?window.__ekaMedAssistConfig__:void 0)||{}).theme;let o;try{o=JSON.parse(this.getAttribute("theme")||"{}")}catch{o=void 0}const s=this.getAgentId(),a=s?(e=readAgentConfigCache(s))===null||e===void 0?void 0:e.theme:void 0,d=(i==null?void 0:i.primary)||(o==null?void 0:o.primary)||(a==null?void 0:a.accent);d&&(t.style.setProperty("--medassist-chatbox-accent",d),t.style.setProperty("--medassist-chatbox-on-accent",colorOnAccent(d))),((i==null?void 0:i.mode)||(o==null?void 0:o.mode)||(a==null?void 0:a.mode))==="dark"?t.setAttribute("data-mode","dark"):t.removeAttribute("data-mode")}renderButton(){var t;const e=this.shadowRoot;if(!e){console.error("Shadow root was not created");return}if(!e.querySelector("button")){e.innerHTML=`
|
|
94
94
|
<style>
|
|
95
95
|
#medassist-open-btn {
|
|
96
96
|
width: 60px;
|
|
@@ -390,8 +390,10 @@
|
|
|
390
390
|
#medassist-chatbox-ph.in { opacity: 0; transform: translateY(8px); transition: none; }
|
|
391
391
|
#medassist-chatbox-ph.gone { display: none; }
|
|
392
392
|
/* Widget closed with a chat in progress: any click reopens it. */
|
|
393
|
-
#medassist-chatbox.continuing
|
|
394
|
-
#medassist-chatbox.
|
|
393
|
+
#medassist-chatbox.continuing,
|
|
394
|
+
#medassist-chatbox.tap-open { cursor: pointer; }
|
|
395
|
+
#medassist-chatbox.continuing #medassist-chatbox-input,
|
|
396
|
+
#medassist-chatbox.tap-open #medassist-chatbox-input { cursor: pointer; }
|
|
395
397
|
@media (prefers-reduced-motion: reduce) {
|
|
396
398
|
#medassist-chatbox, #medassist-chatbox-ph { transition: none; }
|
|
397
399
|
}
|
|
@@ -443,7 +445,7 @@
|
|
|
443
445
|
</button>
|
|
444
446
|
</form>
|
|
445
447
|
<div id="medassist-widget-root" class="hidden"></div>
|
|
446
|
-
`,(t=e.getElementById("medassist-open-btn"))===null||t===void 0||t.addEventListener("click",()=>{const r=this.getAgentId();r&&setNudgeCookie(r,"closed"),this.dismissNudgePopup(),this.loadAndRender()});const i=e.getElementById("medassist-chatbox-input");let
|
|
448
|
+
`,(t=e.getElementById("medassist-open-btn"))===null||t===void 0||t.addEventListener("click",()=>{const r=this.getAgentId();r&&setNudgeCookie(r,"closed"),this.dismissNudgePopup(),this.loadAndRender()});const i=e.getElementById("medassist-chatbox-input");let o=!1;const s=e.querySelector(".medassist-chatbox-send"),a=()=>{o||(o=!0,this.preloadWidgetAssets(),this.prefetchAuthTokens())};i==null||i.addEventListener("input",()=>{s&&(s.disabled=!i.value.trim()),this.syncChatboxPlaceholder(),this.syncChatboxPulse(),this.autosizeChatbox(),a()});const d=e.getElementById("medassist-chatbox"),l=()=>{if(!this.chatboxOpensOnTap()||this.loading||this.launcherState!=="idle")return!1;const r=this.getAgentId();return r&&setNudgeCookie(r,"closed"),this.dismissNudgePopup(),this.loadAndRender(),!0};d==null||d.addEventListener("pointerdown",()=>{this.chatboxOpensOnTap()&&a()}),d==null||d.addEventListener("click",r=>{l()&&r.preventDefault()}),i==null||i.addEventListener("scroll",()=>this.updateChatboxFades()),i==null||i.addEventListener("keydown",r=>{r.key!=="Enter"||r.shiftKey||r.isComposing||(r.preventDefault(),!l()&&i.value.trim()&&(d==null||d.requestSubmit()))}),this.startPlaceholderRotation(),d==null||d.addEventListener("submit",r=>{r.preventDefault();const c=i==null?void 0:i.value.trim();if(!c&&l()||!c||this.loading)return;const u=this.getAgentId();u&&setNudgeCookie(u,"closed"),this.dismissNudgePopup(),this.loadAndRender(c)})}this.applyCustomLauncherStyles()}initializeFullMode(){const t=this.shadowRoot;if(!t){console.error("Shadow root is not available");return}t.getElementById("medassist-widget-root")||(t.innerHTML=`
|
|
447
449
|
<style>
|
|
448
450
|
:host {
|
|
449
451
|
display: block;
|
|
@@ -460,4 +462,4 @@
|
|
|
460
462
|
}
|
|
461
463
|
</style>
|
|
462
464
|
<div id="medassist-widget-root"></div>
|
|
463
|
-
`)}async loadAndRender(t){var e,i,s,o;const a=this.shadowRoot;if(!a){console.error("Shadow root is not available");return}if(this.loading)return;this.prefetchAuthTokens(),this.style.display="";const d=a.getElementById("medassist-widget-root"),r=this.getAttribute("agent-id");let l=this.getAttribute("icon-url")||void 0;const c=(e=getEnvironment(this.getAttribute("environment")))!==null&&e!==void 0?e:"production",h=this.getAttribute("connectivity"),m=h==="http_stream"||h==="socket"?h:void 0,x=this.getAttribute("force-start")==="true";let g=this.getAttribute("title")||"Medi Clinic";const C=this.getAttribute("base-url")||"https://matrix.eka.care/reloaded",w=this.getAttribute("display-mode"),y=normalizeDisplayMode(w),A=this.getAttribute("context")?JSON.parse(this.getAttribute("context")||"{}"):void 0,f=this.getAttribute("theme")?(()=>{try{return JSON.parse(this.getAttribute("theme")||"{}")}catch{return}})():void 0,b=this.getAttribute("feedback")?(()=>{try{return JSON.parse(this.getAttribute("feedback")||"{}")}catch{return}})():void 0,p=(typeof window!="undefined"?window.__ekaMedAssistConfig__:void 0)||{},E=this.getAttribute("side-panel-mode"),J=p.sidePanelMode||(E==="overlay"?"overlay":"push"),R=this.getAttribute("side-panel-width"),Y=(i=p.sidePanelWidth)!==null&&i!==void 0?i:R?Number(R):void 0,j=p.side||this.getAttribute("side")||(typeof document!="undefined"&&document.dir==="rtl"?"left":"right"),T=u=>{const v=Number(this.getAttribute(u));return Number.isFinite(v)&&v>0?v:void 0},N=T("override-widget-width"),B=T("override-widget-height"),G={...N!==void 0&&{overrideWidgetWidth:N},...B!==void 0&&{overrideWidgetHeight:B}},V={...A||{},...p.context||{}},K=p.authToken||this.getAttribute("auth-token")||void 0,_=p.agentId||r,X=p.baseUrl||C,P=typeof window!="undefined"?(s=window.EkaMedAssist)===null||s===void 0?void 0:s.onClose:void 0,Z=this.getAttribute("redirect-url")||void 0,I=p.redirectUrl||Z,Q=!!I||p.showCloseButton===!0;if(!_){console.error("Agent ID is required");return}if(!d){console.error("Widget root element is missing");return}this.loading=!0,this.setLauncherState("loading"),d.classList.remove("hidden");let W,$,z,U=!1,F,O=!1,L;const D=u=>{var v,k,M;g=u.name||g,l=((v=u.theme)===null||v===void 0?void 0:v.icon_img)||l,W=mapAgentConfigThemeToWidgetTheme(u.theme||void 0),$=u.allowed,z=u.connectivity,U=u.resize||(p==null?void 0:p.resize)||!1,F=u.initial_message,O=(M=(k=u.theme)===null||k===void 0?void 0:k.hide_watermark)!==null&&M!==void 0?M:!1,L=u.feedback},H=readAgentConfigCache(_);if(H)D(H),this.getAgentConfig().then(u=>{u&&writeAgentConfigCache(_,u)}).catch(()=>{});else try{const u=await this.getAgentConfig();u&&(writeAgentConfigCache(_,u),D(u))}catch{}const tt=m||z||"socket",q={title:p.title||g,iconUrl:l||p.iconUrl,showCloseButton:Q,allowed:$,environment:c,connectionType:tt,onClose:()=>{var u;if((u=this.reactRoot)===null||u===void 0||u.unmount(),this.reactRoot=null,P&&typeof P=="function"&&P(),I){window.location.href=I;return}y==="full"?this.style.display="none":(this.setLauncherState("idle"),d.classList.add("hidden"))},baseUrl:X,context:V,...p.tools&&{tools:p.tools},displayMode:y,sidePanelMode:J,sidePanelWidth:Y,side:j,onSidePanelPushChange:(u,v,k)=>this.applyHostPush(u,v,k),resize:U||this.getAttribute("resize")==="true",authToken:K,force:x,initialMessage:F,hideWatermark:O,...(b||L)&&{feedback:b||L},...t&&{firstUserMessage:t},theme:{...this.isChatboxShown()&&{widgetWidth:520},...W||{},...f||{},...G,...p.theme||{},...this.isChatboxShown()&&{openFrom:"bottom-center"}}},et=window,S=this.isChatboxShown()?(o=a.getElementById("medassist-chatbox"))===null||o===void 0?void 0:o.getBoundingClientRect():void 0;if(this.widgetLoaded){this.reactRoot=et.renderMedAssist(d,_,q),this.chatStarted=!0,S&&await this.growWidgetFromChatbox(S),this.setLauncherState("open"),this.loading=!1;return}try{const[,u]=await Promise.all([this.loadWidgetCss(),this.loadWidgetModule()]);this.reactRoot=u.renderMedAssist(d,_,q),this.widgetLoaded=!0,this.chatStarted=!0,S&&await this.growWidgetFromChatbox(S),this.setLauncherState("open")}catch(u){console.error("Failed to load MedAssist widget",u),this.setLauncherState("idle"),d.classList.add("hidden")}finally{this.loading=!1}}getOpenAnimation(){const t=(typeof window!="undefined"?window.__ekaMedAssistConfig__:void 0)||{},e=this.getAttribute("open-animation")||t.openAnimation;return e==="unfold"||e==="pop"||e==="curtain"||e==="fade"||e==="none"?e:"rise"}async growWidgetFromChatbox(t){var e;try{const i=this.getOpenAnimation();if(i==="none"||prefersReducedMotion())return;const s=this.shadowRoot;let o=null;for(let c=0;c<30&&!o;c++)await nextFrame(),o=(e=s==null?void 0:s.querySelector(".synapse-chat-widget-container"))!==null&&e!==void 0?e:null;if(!o||typeof o.animate!="function")return;const a=o.getBoundingClientRect();if(!a.width||!a.height||!t.width)return;const d=a.width>=window.innerWidth-1?0:24,r="50% 100%";if(i==="rise")o.animate([{transform:"translateY(56px) scale(0.96)",opacity:0,transformOrigin:r},{transform:"translateY(0px) scale(1)",opacity:1,transformOrigin:r}],{duration:520,easing:"cubic-bezier(0.22, 1, 0.36, 1)"});else if(i==="pop")o.animate([{transform:"scale(0.4)",opacity:0,transformOrigin:r},{transform:"scale(1.04)",opacity:1,transformOrigin:r,offset:.6},{transform:"scale(1)",opacity:1,transformOrigin:r}],{duration:560,easing:"cubic-bezier(0.34, 1.2, 0.64, 1)"});else if(i==="curtain")o.animate([{transform:"translateY(20px)",clipPath:`inset(100% 0px 0px 0px round ${d}px)`},{transform:"translateY(0px)",clipPath:`inset(0px 0px 0px 0px round ${d}px)`}],{duration:560,easing:"cubic-bezier(0.65, 0, 0.35, 1)"});else if(i==="fade"){o.animate([{transform:"scale(0.97)",opacity:0,transformOrigin:r},{transform:"scale(1)",opacity:1,transformOrigin:r}],{duration:280,easing:"ease-out"});return}else{const c=t.left+t.width/2-(a.left+a.width/2),h=t.bottom-a.bottom,m=Math.max(0,a.height-t.height),x=Math.max(0,(a.width-t.width)/2),g=Math.min(t.height/2,28);o.animate([{transform:`translate(${c}px, ${h}px)`,clipPath:`inset(${m}px ${x}px 0px ${x}px round ${g}px)`},{transform:"translate(0px, 0px)",clipPath:`inset(0px 0px 0px 0px round ${d}px)`}],{duration:620,easing:"cubic-bezier(0.22, 1, 0.36, 1)"})}const l=Array.from(o.children).find(c=>c.tagName!=="STYLE");l==null||l.animate([{opacity:0,transform:"translateY(14px)"},{opacity:1,transform:"translateY(0px)"}],{duration:420,delay:140,easing:"cubic-bezier(0.22, 1, 0.36, 1)",fill:"backwards"})}catch{}}getChatboxPlaceholders(){return this.collectChatboxPlaceholders().map(withTrailingEllipsis)}collectChatboxPlaceholders(){var t,e,i;const s=(typeof window!="undefined"?window.__ekaMedAssistConfig__:void 0)||{};let o=s.chatboxPlaceholders;if(!Array.isArray(o))try{o=JSON.parse(this.getAttribute("chatbox-placeholders")||"null")}catch{o=null}const a=Array.isArray(o)?o.filter(l=>typeof l=="string"&&!!l.trim()):[];if(a.length)return a;const d=s.agentId||this.getAttribute("agent-id")||"",r=l=>Array.isArray(l)?l.filter(c=>typeof c=="string"&&!!c.trim()):[];if(d){try{const c=new URL(window.location.href),h=findFreshCachedNudge(d,c,getNudgePathCandidates(c.pathname)),m=r(h==null?void 0:h.data.nudges);if(m.length)return m}catch{}const l=r((i=(e=(t=readAgentConfigCache(d))===null||t===void 0?void 0:t.initial_message)===null||e===void 0?void 0:e.suggestions)===null||i===void 0?void 0:i.map(c=>c.label||c.value));if(l.length)return l}return["Ask me anything\u2026","Not sure what to ask? Just say hi\u2026","You can type in any language\u2026"]}autosizeChatbox(){var t;const e=(t=this.shadowRoot)===null||t===void 0?void 0:t.getElementById("medassist-chatbox-input");if(!e)return;e.style.height="auto";const i=parseFloat(getComputedStyle(e).maxHeight)||92;e.style.height=`${Math.min(e.scrollHeight,i)}px`,e.style.overflowY=e.scrollHeight>i?"auto":"hidden",this.updateChatboxFades()}updateChatboxFades(){var t;const e=(t=this.shadowRoot)===null||t===void 0?void 0:t.getElementById("medassist-chatbox-input");e&&(e.classList.toggle("fade-t",e.scrollTop>1),e.classList.toggle("fade-b",e.scrollHeight-e.clientHeight-e.scrollTop>1))}syncChatboxPulse(){const t=this.shadowRoot,e=t==null?void 0:t.getElementById("medassist-chatbox"),i=t==null?void 0:t.getElementById("medassist-chatbox-input");if(!e)return;const s=this.launcherState==="idle"&&!this.chatStarted&&!(i!=null&&i.value)&&!prefersReducedMotion();e.classList.toggle("pulse",s)}syncChatboxPlaceholder(){const t=this.shadowRoot,e=t==null?void 0:t.getElementById("medassist-chatbox-ph");if(!t||!e)return;const i=t.getElementById("medassist-chatbox-input"),s=this.chatStarted&&this.launcherState==="idle";e.classList.toggle("gone",!!(i!=null&&i.value));const o=s?"Continue your chat\u2026":this.getChatboxPlaceholders()[this.placeholderIndex%this.getChatboxPlaceholders().length];e.textContent!==o&&(e.textContent=o)}startPlaceholderRotation(){this.placeholderTimer||(this.syncChatboxPlaceholder(),!prefersReducedMotion()&&(this.placeholderTimer=setInterval(()=>{const t=this.shadowRoot,e=t==null?void 0:t.getElementById("medassist-chatbox-ph"),i=t==null?void 0:t.getElementById("medassist-chatbox-input");if(!t||!e||!i)return;const s=this.getChatboxPlaceholders();s.length<2||document.hidden||this.chatStarted||this.launcherState!=="idle"||i.value||t.activeElement===i||(e.classList.add("out"),setTimeout(()=>{this.placeholderIndex=(this.placeholderIndex+1)%s.length,e.classList.remove("out"),e.classList.add("in"),this.syncChatboxPlaceholder(),e.offsetWidth,e.classList.remove("in")},220))},3500)))}async loadWidgetCss(){const t=this.shadowRoot;if(!t)throw new Error("Shadow root is not available");if(t.querySelector("[data-medassist-style='true']"))return;const e=await getWidgetCssTextPromise(),i=document.createElement("style");i.setAttribute("data-medassist-style","true"),i.textContent=e,t.appendChild(i)}loadWidgetModule(){return widgetModulePromise||(widgetModulePromise=import(WIDGET_JS_URL)),widgetModulePromise}}customElements.define("eka-medassist-widget",MedAssistWidgetLoader);
|
|
465
|
+
`)}async loadAndRender(t){var e,i,o,s;const a=this.shadowRoot;if(!a){console.error("Shadow root is not available");return}if(this.loading)return;this.prefetchAuthTokens(),this.style.display="";const d=a.getElementById("medassist-widget-root"),l=this.getAttribute("agent-id");let r=this.getAttribute("icon-url")||void 0;const c=(e=getEnvironment(this.getAttribute("environment")))!==null&&e!==void 0?e:"production",u=this.getAttribute("connectivity"),m=u==="http_stream"||u==="socket"?u:void 0,x=this.getAttribute("force-start")==="true";let g=this.getAttribute("title")||"Medi Clinic";const C=this.getAttribute("base-url")||"https://matrix.eka.care/reloaded",w=this.getAttribute("display-mode"),y=normalizeDisplayMode(w),_=this.getAttribute("context")?JSON.parse(this.getAttribute("context")||"{}"):void 0,f=this.getAttribute("theme")?(()=>{try{return JSON.parse(this.getAttribute("theme")||"{}")}catch{return}})():void 0,b=this.getAttribute("feedback")?(()=>{try{return JSON.parse(this.getAttribute("feedback")||"{}")}catch{return}})():void 0,p=(typeof window!="undefined"?window.__ekaMedAssistConfig__:void 0)||{},E=this.getAttribute("side-panel-mode"),J=p.sidePanelMode||(E==="overlay"?"overlay":"push"),R=this.getAttribute("side-panel-width"),Y=(i=p.sidePanelWidth)!==null&&i!==void 0?i:R?Number(R):void 0,j=p.side||this.getAttribute("side")||(typeof document!="undefined"&&document.dir==="rtl"?"left":"right"),T=h=>{const v=Number(this.getAttribute(h));return Number.isFinite(v)&&v>0?v:void 0},B=T("override-widget-width"),N=T("override-widget-height"),G={...B!==void 0&&{overrideWidgetWidth:B},...N!==void 0&&{overrideWidgetHeight:N}},V={..._||{},...p.context||{}},X=p.authToken||this.getAttribute("auth-token")||void 0,A=p.agentId||l,K=p.baseUrl||C,I=typeof window!="undefined"?(o=window.EkaMedAssist)===null||o===void 0?void 0:o.onClose:void 0,Q=this.getAttribute("redirect-url")||void 0,P=p.redirectUrl||Q,Z=!!P||p.showCloseButton===!0;if(!A){console.error("Agent ID is required");return}if(!d){console.error("Widget root element is missing");return}this.loading=!0,this.setLauncherState("loading"),d.classList.remove("hidden");let O,W,U,$=!1,z,F=!1,L;const D=h=>{var v,k,M;g=h.name||g,r=((v=h.theme)===null||v===void 0?void 0:v.icon_img)||r,O=mapAgentConfigThemeToWidgetTheme(h.theme||void 0),W=h.allowed,U=h.connectivity,$=h.resize||(p==null?void 0:p.resize)||!1,z=h.initial_message,F=(M=(k=h.theme)===null||k===void 0?void 0:k.hide_watermark)!==null&&M!==void 0?M:!1,L=h.feedback},q=readAgentConfigCache(A);if(q)D(q),this.getAgentConfig().then(h=>{h&&writeAgentConfigCache(A,h)}).catch(()=>{});else try{const h=await this.getAgentConfig();h&&(writeAgentConfigCache(A,h),D(h))}catch{}const tt=m||U||"socket",H={title:p.title||g,iconUrl:r||p.iconUrl,showCloseButton:Z,allowed:W,environment:c,connectionType:tt,onClose:()=>{var h;if((h=this.reactRoot)===null||h===void 0||h.unmount(),this.reactRoot=null,I&&typeof I=="function"&&I(),P){window.location.href=P;return}y==="full"?this.style.display="none":(this.setLauncherState("idle"),d.classList.add("hidden"))},baseUrl:K,context:V,...p.tools&&{tools:p.tools},displayMode:y,sidePanelMode:J,sidePanelWidth:Y,side:j,onSidePanelPushChange:(h,v,k)=>this.applyHostPush(h,v,k),resize:$||this.getAttribute("resize")==="true",authToken:X,force:x,initialMessage:z,hideWatermark:F,...(b||L)&&{feedback:b||L},...t&&{firstUserMessage:t},theme:{...this.isChatboxShown()&&{widgetWidth:520},...O||{},...f||{},...G,...p.theme||{},...this.isChatboxShown()&&{openFrom:"bottom-center"}}},et=window,S=this.isChatboxShown()?(s=a.getElementById("medassist-chatbox"))===null||s===void 0?void 0:s.getBoundingClientRect():void 0;if(this.widgetLoaded){this.reactRoot=et.renderMedAssist(d,A,H),this.chatStarted=!0,S&&await this.growWidgetFromChatbox(S),this.setLauncherState("open"),this.loading=!1;return}try{const[,h]=await Promise.all([this.loadWidgetCss(),this.loadWidgetModule()]);this.reactRoot=h.renderMedAssist(d,A,H),this.widgetLoaded=!0,this.chatStarted=!0,S&&await this.growWidgetFromChatbox(S),this.setLauncherState("open")}catch(h){console.error("Failed to load MedAssist widget",h),this.setLauncherState("idle"),d.classList.add("hidden")}finally{this.loading=!1}}getOpenAnimation(){const t=(typeof window!="undefined"?window.__ekaMedAssistConfig__:void 0)||{},e=this.getAttribute("open-animation")||t.openAnimation;return e==="unfold"||e==="pop"||e==="curtain"||e==="fade"||e==="none"?e:"rise"}async growWidgetFromChatbox(t){var e;try{const i=this.getOpenAnimation();if(i==="none"||prefersReducedMotion())return;const o=this.shadowRoot;let s=null;for(let c=0;c<30&&!s;c++)await nextFrame(),s=(e=o==null?void 0:o.querySelector(".synapse-chat-widget-container"))!==null&&e!==void 0?e:null;if(!s||typeof s.animate!="function")return;const a=s.getBoundingClientRect();if(!a.width||!a.height||!t.width)return;const d=a.width>=window.innerWidth-1?0:24,l="50% 100%";if(i==="rise")s.animate([{transform:"translateY(56px) scale(0.96)",opacity:0,transformOrigin:l},{transform:"translateY(0px) scale(1)",opacity:1,transformOrigin:l}],{duration:520,easing:"cubic-bezier(0.22, 1, 0.36, 1)"});else if(i==="pop")s.animate([{transform:"scale(0.4)",opacity:0,transformOrigin:l},{transform:"scale(1.04)",opacity:1,transformOrigin:l,offset:.6},{transform:"scale(1)",opacity:1,transformOrigin:l}],{duration:560,easing:"cubic-bezier(0.34, 1.2, 0.64, 1)"});else if(i==="curtain")s.animate([{transform:"translateY(20px)",clipPath:`inset(100% 0px 0px 0px round ${d}px)`},{transform:"translateY(0px)",clipPath:`inset(0px 0px 0px 0px round ${d}px)`}],{duration:560,easing:"cubic-bezier(0.65, 0, 0.35, 1)"});else if(i==="fade"){s.animate([{transform:"scale(0.97)",opacity:0,transformOrigin:l},{transform:"scale(1)",opacity:1,transformOrigin:l}],{duration:280,easing:"ease-out"});return}else{const c=t.left+t.width/2-(a.left+a.width/2),u=t.bottom-a.bottom,m=Math.max(0,a.height-t.height),x=Math.max(0,(a.width-t.width)/2),g=Math.min(t.height/2,28);s.animate([{transform:`translate(${c}px, ${u}px)`,clipPath:`inset(${m}px ${x}px 0px ${x}px round ${g}px)`},{transform:"translate(0px, 0px)",clipPath:`inset(0px 0px 0px 0px round ${d}px)`}],{duration:620,easing:"cubic-bezier(0.22, 1, 0.36, 1)"})}const r=Array.from(s.children).find(c=>c.tagName!=="STYLE");r==null||r.animate([{opacity:0,transform:"translateY(14px)"},{opacity:1,transform:"translateY(0px)"}],{duration:420,delay:140,easing:"cubic-bezier(0.22, 1, 0.36, 1)",fill:"backwards"})}catch{}}getChatboxPlaceholders(){return this.collectChatboxPlaceholders().map(withTrailingEllipsis)}collectChatboxPlaceholders(){var t,e,i;const o=(typeof window!="undefined"?window.__ekaMedAssistConfig__:void 0)||{};let s=o.chatboxPlaceholders;if(!Array.isArray(s))try{s=JSON.parse(this.getAttribute("chatbox-placeholders")||"null")}catch{s=null}const a=Array.isArray(s)?s.filter(r=>typeof r=="string"&&!!r.trim()):[];if(a.length)return a;const d=o.agentId||this.getAttribute("agent-id")||"",l=r=>Array.isArray(r)?r.filter(c=>typeof c=="string"&&!!c.trim()):[];if(d){try{const c=new URL(window.location.href),u=findFreshCachedNudge(d,c,getNudgePathCandidates(c.pathname)),m=l(u==null?void 0:u.data.nudges);if(m.length)return m}catch{}const r=l((i=(e=(t=readAgentConfigCache(d))===null||t===void 0?void 0:t.initial_message)===null||e===void 0?void 0:e.suggestions)===null||i===void 0?void 0:i.map(c=>c.label||c.value));if(r.length)return r}return["Ask me anything\u2026","Not sure what to ask? Just say hi\u2026","You can type in any language\u2026"]}autosizeChatbox(){var t;const e=(t=this.shadowRoot)===null||t===void 0?void 0:t.getElementById("medassist-chatbox-input");if(!e)return;e.style.height="auto";const i=parseFloat(getComputedStyle(e).maxHeight)||92;e.style.height=`${Math.min(e.scrollHeight,i)}px`,e.style.overflowY=e.scrollHeight>i?"auto":"hidden",this.updateChatboxFades()}updateChatboxFades(){var t;const e=(t=this.shadowRoot)===null||t===void 0?void 0:t.getElementById("medassist-chatbox-input");e&&(e.classList.toggle("fade-t",e.scrollTop>1),e.classList.toggle("fade-b",e.scrollHeight-e.clientHeight-e.scrollTop>1))}syncChatboxPulse(){const t=this.shadowRoot,e=t==null?void 0:t.getElementById("medassist-chatbox"),i=t==null?void 0:t.getElementById("medassist-chatbox-input");if(!e)return;const o=this.launcherState==="idle"&&!this.chatStarted&&!(i!=null&&i.value)&&!prefersReducedMotion();e.classList.toggle("pulse",o)}syncChatboxPlaceholder(){const t=this.shadowRoot,e=t==null?void 0:t.getElementById("medassist-chatbox-ph");if(!t||!e)return;const i=t.getElementById("medassist-chatbox-input"),o=this.chatStarted&&this.launcherState==="idle";e.classList.toggle("gone",!!(i!=null&&i.value));const s=o?"Continue your chat\u2026":this.getChatboxPlaceholders()[this.placeholderIndex%this.getChatboxPlaceholders().length];e.textContent!==s&&(e.textContent=s)}startPlaceholderRotation(){this.placeholderTimer||(this.syncChatboxPlaceholder(),!prefersReducedMotion()&&(this.placeholderTimer=setInterval(()=>{const t=this.shadowRoot,e=t==null?void 0:t.getElementById("medassist-chatbox-ph"),i=t==null?void 0:t.getElementById("medassist-chatbox-input");if(!t||!e||!i)return;const o=this.getChatboxPlaceholders();o.length<2||document.hidden||this.chatStarted||this.launcherState!=="idle"||i.value||t.activeElement===i||(e.classList.add("out"),setTimeout(()=>{this.placeholderIndex=(this.placeholderIndex+1)%o.length,e.classList.remove("out"),e.classList.add("in"),this.syncChatboxPlaceholder(),e.offsetWidth,e.classList.remove("in")},220))},3500)))}async loadWidgetCss(){const t=this.shadowRoot;if(!t)throw new Error("Shadow root is not available");if(t.querySelector("[data-medassist-style='true']"))return;const e=await getWidgetCssTextPromise(),i=document.createElement("style");i.setAttribute("data-medassist-style","true"),i.textContent=e,t.appendChild(i)}loadWidgetModule(){return widgetModulePromise||(widgetModulePromise=import(WIDGET_JS_URL)),widgetModulePromise}}customElements.define("eka-medassist-widget",MedAssistWidgetLoader);
|