@eka-care/medassist-widget-embed 0.2.94 → 0.2.95
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/index.d.ts +8 -0
- package/dist/index.js +39 -7
- package/package.json +1 -1
package/dist/index.d.ts
CHANGED
|
@@ -185,6 +185,14 @@ declare class MedAssistWidgetLoader extends HTMLElement {
|
|
|
185
185
|
private displayMode;
|
|
186
186
|
private reactRoot;
|
|
187
187
|
private agentConfigPromise;
|
|
188
|
+
private loading;
|
|
189
|
+
/**
|
|
190
|
+
* Launcher visual state:
|
|
191
|
+
* - "idle" → icon, clickable
|
|
192
|
+
* - "loading" → spinner in the launcher's place, clicks ignored
|
|
193
|
+
* - "open" → hidden (widget is mounted)
|
|
194
|
+
*/
|
|
195
|
+
private setLauncherState;
|
|
188
196
|
private getAgentConfig;
|
|
189
197
|
constructor();
|
|
190
198
|
static get observedAttributes(): string[];
|
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:e}=document;if(e instanceof HTMLScriptElement)return e;const t=document.getElementsByTagName("script");return t.length?t[t.length-1]:null},getEnvironment=e=>{if(e==="production"||e==="development"||e==="staging")return e},scriptEl=getCurrentScript(),DEFAULT_WIDGET_ASSET_BASE=(()=>{var e;return!((e=scriptEl==null?void 0:scriptEl.src)===null||e===void 0)&&e.includes("@dev"),"https://cdn.jsdelivr.net/npm/@eka-care/medassist-widget@0.1.118/dist/"})();var FeedbackTypeEnum;(function(e){e.DEFAULT="default",e.NPS="nps"})(FeedbackTypeEnum||(FeedbackTypeEnum={}));function mapAgentConfigThemeToWidgetTheme(e){if(!e)return;const t=e.mode==="dark"?"white":e.mode==="light"?"black":void 0;return{...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.hide_watermark&&{hideWatermark:e.hide_watermark},...e.explicit_disclaimer&&{explicitDisclaimer:e.explicit_disclaimer}}}function preloadImage(e){if(!(!e||typeof document=="undefined"))try{const t=document.createElement("link");t.rel="preload",t.as="image",t.href=e,document.head.appendChild(t)}catch{const t=new Image;t.src=e}}async function fetchAgentConfig(e,t){const n=`${e.replace(/\/$/,"")}/med-assist/agent-config/${t}`,i=await fetch(n,{headers:{"ngrok-skip-browser-warning":"69420"}});if(!i.ok)return;const o=await i.json();if(o!=null&&o.success&&(o!=null&&o.data))return o.data}const NUDGE_STORAGE_KEY="eka-medassist-nudges",AGENT_CONFIG_CACHE_KEY="eka-medassist-agent-config";function readAgentConfigCache(e){try{const t=localStorage.getItem(AGENT_CONFIG_CACHE_KEY);return(t?JSON.parse(t):{})[e]}catch{return}}function writeAgentConfigCache(e,t){try{const n=localStorage.getItem(AGENT_CONFIG_CACHE_KEY),i=n?JSON.parse(n):{};i[e]={...i[e]||{},...t},localStorage.setItem(AGENT_CONFIG_CACHE_KEY,JSON.stringify(i))}catch{}}function getNudgeStore(){try{const e=localStorage.getItem(NUDGE_STORAGE_KEY);return e?JSON.parse(e):{}}catch{return{}}}function setNudgeStore(e){try{localStorage.setItem(NUDGE_STORAGE_KEY,JSON.stringify(e))}catch{}}function normalizePath(e){let t=e.replace(/\/+$/,"");return t.startsWith("/")||(t="/"+t),t||"/"}function getNudgePathCandidates(e){const t=e.split("/").filter(Boolean),n=[];for(let i=t.length;i>=0;i--)n.push(i===0?"/":"/"+t.slice(0,i).join("/"));return n}function findCachedNudgeForCandidates(e,t,n){const o=getNudgeStore()[e];if(!o)return null;const s=t.host,r=o[s];if(!r)return null;for(const d of n){if(r[d]!==void 0)return{domain:s,path:d,data:r[d]};const a=d==="/"?"/*":d+"/*";if(r[a]!==void 0)return{domain:s,path:a,data:r[a]}}return null}function findFreshCachedNudge(e,t,n){const i=findCachedNudgeForCandidates(e,t,n);if(!i)return null;const o=Math.floor(Date.now()/1e3);return i.data.expiry<=o?(clearNudgeForPath(e,i.domain,i.path),null):i}function clearNudgeForPath(e,t,n){const i=getNudgeStore(),o=i[e];!o||!o[t]||(delete o[t][n],setNudgeStore(i))}function storeNudgeResponse(e,t){var n,i,o,s;const r=(n=t==null?void 0:t.url_pattern)===null||n===void 0?void 0:n.domain,d=(i=t==null?void 0:t.url_pattern)===null||i===void 0?void 0:i.path;if(!(!((o=t.nudges)===null||o===void 0)&&o.length)||!t.expiry||!r||!d)return;const a=getNudgeStore();a[e]||(a[e]={}),a[e][r]||(a[e][r]={}),a[e][r][d]={nudges:t.nudges,expiry:t.expiry,delay:(s=t.delay)!==null&&s!==void 0?s:5},setNudgeStore(a)}const NUDGE_COOKIE_PREFIX="eka-nudge";function setNudgeCookie(e,t){const n=new Date(Date.now()+864e5).toUTCString();document.cookie=`${NUDGE_COOKIE_PREFIX}-${e}=${t}; expires=${n}; path=/; SameSite=Lax`}function getNudgeCookie(e){const t=document.cookie.split(";").map(i=>i.trim()).find(i=>i.startsWith(`${NUDGE_COOKIE_PREFIX}-${e}=`));if(!t)return null;const n=t.split("=")[1];return n==="open"||n==="closed"?n:null}async function fetchNudgeData(e,t){const n=`${t}/med-assist/user-nudge`,i=[];typeof document!="undefined"&&document.querySelectorAll("meta").forEach(o=>{var s,r,d;const a=(s=o.getAttribute("name"))!==null&&s!==void 0?s:void 0,g=(r=o.getAttribute("property"))!==null&&r!==void 0?r:void 0,c=(d=o.getAttribute("content"))!==null&&d!==void 0?d:void 0;(a||g)&&i.push({name:a,property:g,content:c})});try{const o=await fetch(n,{method:"POST",headers:{"Content-Type":"application/json","x-agent-id":e,referer:typeof window!="undefined"?window.location.href:""},body:JSON.stringify({meta_tags:i,url:typeof window!="undefined"?window.location.href:""})});return o.ok?await o.json():void 0}catch{return}}const globalMedAssistConfig={},getWidgetElement=()=>typeof document=="undefined"?null:document.querySelector("eka-medassist-widget");if(typeof window!="undefined"){const e=window;e.__ekaMedAssistConfig__=globalMedAssistConfig,e.EkaMedAssist={init(t){var n,i,o;Object.assign(globalMedAssistConfig,t);const s=getWidgetElement();if(s){if(t.agentId&&s.setAttribute("agent-id",t.agentId),t.authToken&&s.setAttribute("auth-token",t.authToken),t.title&&s.setAttribute("title",t.title),t.iconUrl&&s.setAttribute("icon-url",t.iconUrl),t.baseUrl&&s.setAttribute("base-url",t.baseUrl),t.resize!==void 0&&s.setAttribute("resize",String(t.resize)),(t.displayMode==="full"||t.displayMode==="widget")&&s.setAttribute("display-mode",t.displayMode),t.context)try{s.setAttribute("context",JSON.stringify(t.context))}catch{console.warn("Failed to stringify context passed to init")}typeof t.customLauncherStyles=="string"&&s.setAttribute("custom-launcher-styles",t.customLauncherStyles),t.redirectUrl&&s.setAttribute("redirect-url",t.redirectUrl),!((n=t.theme)===null||n===void 0)&&n.backgroundImage&&preloadImage(t.theme.backgroundImage),(o=(i=s).openFromBridge)===null||o===void 0||o.call(i)}}}}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 e=scriptEl.dataset.widgetAssets;if(e==="local")return`${scriptBaseUrl}src/`;if(e&&e.length>0)try{return new URL(e,scriptBaseUrl).href}catch{return e.endsWith("/")?e:`${e}/`}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(e=>{if(!e.ok)throw new Error(`Unable to fetch widget styles from ${WIDGET_CSS_URL}`);return e.text()})),widgetCssTextPromise}class MedAssistWidgetLoader extends HTMLElement{getAgentConfig(){if(!this.agentConfigPromise){const t=(typeof window!="undefined"?window.__ekaMedAssistConfig__:void 0)||{},n=t.baseUrl||this.getAttribute("base-url")||"https://matrix.eka.care/reloaded",i=t.agentId||this.getAttribute("agent-id")||"";if(!i)return Promise.resolve(void 0);this.agentConfigPromise=fetchAgentConfig(n,i).catch(()=>{})}return this.agentConfigPromise}constructor(){super(),this.reactRoot=null,this.agentConfigPromise=null,this.authPrefetchStarted=!1,this.attachShadow({mode:"open"}),this.defaultIconUrl="https://cdn.eka.care/bot-icon.svg",this.widgetLoaded=!1,this.displayMode=this.getAttribute("display-mode")==="full"?"full":"widget",this.setupAuthExpirationListener()}static get observedAttributes(){return["icon-url","display-mode","custom-launcher-styles","redirect-url"]}connectedCallback(){this.displayMode==="full"?(this.initializeFullMode(),this.loadAndRender().catch(t=>{console.error("Failed to load MedAssist widget in full mode",t)})):(this.renderButton(),this.scheduleIdle(()=>{this.preloadWidgetAssets(),this.prefetchAuthTokens(),this.initNudge()}))}scheduleIdle(t){if(typeof window=="undefined"){t();return}const n=window.requestIdleCallback;typeof n=="function"?n(t,{timeout:3e3}):setTimeout(t,200)}attributeChangedCallback(t){if(t==="icon-url"&&this.displayMode==="widget"&&this.renderButton(),t==="display-mode"){const n=this.getAttribute("display-mode")==="full"?"full":"widget";n!==this.displayMode&&(this.displayMode=n,n==="full"?this.initializeFullMode():this.renderButton())}t==="custom-launcher-styles"&&this.applyCustomLauncherStyles()}preloadWidgetAssets(){getWidgetCssTextPromise(),this.loadWidgetModule(),this.preloadBackgroundImage()}prefetchAuthTokens(){var t;if(this.authPrefetchStarted)return;const n=(typeof window!="undefined"?window.__ekaMedAssistConfig__:void 0)||{},i=n.agentId||this.getAttribute("agent-id")||"";if(!i)return;this.authPrefetchStarted=!0;const o=n.authToken||this.getAttribute("auth-token")||void 0,s=n.baseUrl||this.getAttribute("base-url")||"https://matrix.eka.care/reloaded",r=(t=getEnvironment(this.getAttribute("environment")))!==null&&t!==void 0?t:"production";this.loadWidgetModule().then(d=>{var a;return(a=d.prefetchAuth)===null||a===void 0?void 0:a.call(d,{agentId:i,authToken:o,serverUrl:s,environment:r})}).catch(()=>{this.authPrefetchStarted=!1})}preloadBackgroundImage(){var t;const n=typeof window!="undefined"?window.__ekaMedAssistConfig__:void 0,i=this.getAttribute("theme")?(()=>{try{return JSON.parse(this.getAttribute("theme")||"{}")}catch{return}})():void 0,o=(t=n==null?void 0:n.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(r=>{var d;const a=(d=r==null?void 0:r.theme)===null||d===void 0?void 0:d.background_img;a&&preloadImage(a)}).catch(()=>{})}setupAuthExpirationListener(){if(typeof window=="undefined")return;const t=n=>{var i;((i=n.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(){this.displayMode=this.getAttribute("display-mode")==="full"?"full":"widget",this.displayMode==="full"?this.initializeFullMode():this.renderButton(),this.loadAndRender().catch(t=>{console.error("Failed to open MedAssist widget from bridge",t)})}async initNudge(){var t,n,i,o;const s=typeof window!="undefined"?window.__ekaMedAssistConfig__:void 0,r=(s==null?void 0:s.agentId)||this.getAttribute("agent-id")||"";if(!r)return;const d=await this.getAgentConfig();if(!(d!=null&&d.nudge))return;const a=(n=(t=d==null?void 0:d.theme)===null||t===void 0?void 0:t.nudge_color)!==null&&n!==void 0?n:"#ffffff",g=typeof window!="undefined"?window.location.href:"";let c;try{c=new URL(g)}catch{return}const f=getNudgePathCandidates(c.pathname),m=f.slice(0,1),v=f.slice(1);let h=findFreshCachedNudge(r,c,m);if(!h){const b=(s==null?void 0:s.baseUrl)||this.getAttribute("base-url")||"https://matrix.eka.care/reloaded",u=await fetchNudgeData(r,b).catch(()=>{});!((i=u==null?void 0:u.nudges)===null||i===void 0)&&i.length&&(storeNudgeResponse(r,u),h=findFreshCachedNudge(r,c,f))}if(h||(h=findFreshCachedNudge(r,c,v)),!h)return;const x=h.data.nudges[Math.floor(Math.random()*h.data.nudges.length)],w=(o=h.data.delay)!==null&&o!==void 0?o:5;setTimeout(()=>{this.showNudgePopup(x,a)},w*1e3)}showNudgePopup(t,n){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 g=s.getElementById("medassist-open-btn"),c=g==null?void 0:g.getBoundingClientRect(),f=272,m=12,v=8,h=16,x=16;let w=window.innerWidth-f-m,b=76,u=f-h-v*2;if(c&&c.width>0){const A=c.left+c.width/2,p=A-f/2,_=window.innerWidth-f-m;w=Math.max(m,Math.min(p,_)),b=window.innerHeight-c.top+x,u=Math.max(h,Math.min(A-w-v,f-h-v*2))}const y=document.createElement("div");y.id="medassist-nudge-popup",y.innerHTML=`
|
|
1
|
+
"use strict";const getCurrentScript=()=>{if(typeof document=="undefined")return console.error("document is not defined"),null;const{currentScript:e}=document;if(e instanceof HTMLScriptElement)return e;const t=document.getElementsByTagName("script");return t.length?t[t.length-1]:null},getEnvironment=e=>{if(e==="production"||e==="development"||e==="staging")return e},scriptEl=getCurrentScript(),DEFAULT_WIDGET_ASSET_BASE=(()=>{var e;return!((e=scriptEl==null?void 0:scriptEl.src)===null||e===void 0)&&e.includes("@dev"),"https://cdn.jsdelivr.net/npm/@eka-care/medassist-widget@0.1.118/dist/"})();var FeedbackTypeEnum;(function(e){e.DEFAULT="default",e.NPS="nps"})(FeedbackTypeEnum||(FeedbackTypeEnum={}));function mapAgentConfigThemeToWidgetTheme(e){if(!e)return;const t=e.mode==="dark"?"white":e.mode==="light"?"black":void 0;return{...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.hide_watermark&&{hideWatermark:e.hide_watermark},...e.explicit_disclaimer&&{explicitDisclaimer:e.explicit_disclaimer}}}function preloadImage(e){if(!(!e||typeof document=="undefined"))try{const t=document.createElement("link");t.rel="preload",t.as="image",t.href=e,document.head.appendChild(t)}catch{const t=new Image;t.src=e}}async function fetchAgentConfig(e,t){const n=`${e.replace(/\/$/,"")}/med-assist/agent-config/${t}`,i=await fetch(n,{headers:{"ngrok-skip-browser-warning":"69420"}});if(!i.ok)return;const o=await i.json();if(o!=null&&o.success&&(o!=null&&o.data))return o.data}const NUDGE_STORAGE_KEY="eka-medassist-nudges",AGENT_CONFIG_CACHE_KEY="eka-medassist-agent-config";function readAgentConfigCache(e){try{const t=localStorage.getItem(AGENT_CONFIG_CACHE_KEY);return(t?JSON.parse(t):{})[e]}catch{return}}function writeAgentConfigCache(e,t){try{const n=localStorage.getItem(AGENT_CONFIG_CACHE_KEY),i=n?JSON.parse(n):{};i[e]={...i[e]||{},...t},localStorage.setItem(AGENT_CONFIG_CACHE_KEY,JSON.stringify(i))}catch{}}function getNudgeStore(){try{const e=localStorage.getItem(NUDGE_STORAGE_KEY);return e?JSON.parse(e):{}}catch{return{}}}function setNudgeStore(e){try{localStorage.setItem(NUDGE_STORAGE_KEY,JSON.stringify(e))}catch{}}function normalizePath(e){let t=e.replace(/\/+$/,"");return t.startsWith("/")||(t="/"+t),t||"/"}function getNudgePathCandidates(e){const t=e.split("/").filter(Boolean),n=[];for(let i=t.length;i>=0;i--)n.push(i===0?"/":"/"+t.slice(0,i).join("/"));return n}function findCachedNudgeForCandidates(e,t,n){const o=getNudgeStore()[e];if(!o)return null;const s=t.host,r=o[s];if(!r)return null;for(const d of n){if(r[d]!==void 0)return{domain:s,path:d,data:r[d]};const a=d==="/"?"/*":d+"/*";if(r[a]!==void 0)return{domain:s,path:a,data:r[a]}}return null}function findFreshCachedNudge(e,t,n){const i=findCachedNudgeForCandidates(e,t,n);if(!i)return null;const o=Math.floor(Date.now()/1e3);return i.data.expiry<=o?(clearNudgeForPath(e,i.domain,i.path),null):i}function clearNudgeForPath(e,t,n){const i=getNudgeStore(),o=i[e];!o||!o[t]||(delete o[t][n],setNudgeStore(i))}function storeNudgeResponse(e,t){var n,i,o,s;const r=(n=t==null?void 0:t.url_pattern)===null||n===void 0?void 0:n.domain,d=(i=t==null?void 0:t.url_pattern)===null||i===void 0?void 0:i.path;if(!(!((o=t.nudges)===null||o===void 0)&&o.length)||!t.expiry||!r||!d)return;const a=getNudgeStore();a[e]||(a[e]={}),a[e][r]||(a[e][r]={}),a[e][r][d]={nudges:t.nudges,expiry:t.expiry,delay:(s=t.delay)!==null&&s!==void 0?s:5},setNudgeStore(a)}const NUDGE_COOKIE_PREFIX="eka-nudge";function setNudgeCookie(e,t){const n=new Date(Date.now()+864e5).toUTCString();document.cookie=`${NUDGE_COOKIE_PREFIX}-${e}=${t}; expires=${n}; path=/; SameSite=Lax`}function getNudgeCookie(e){const t=document.cookie.split(";").map(i=>i.trim()).find(i=>i.startsWith(`${NUDGE_COOKIE_PREFIX}-${e}=`));if(!t)return null;const n=t.split("=")[1];return n==="open"||n==="closed"?n:null}async function fetchNudgeData(e,t){const n=`${t}/med-assist/user-nudge`,i=[];typeof document!="undefined"&&document.querySelectorAll("meta").forEach(o=>{var s,r,d;const a=(s=o.getAttribute("name"))!==null&&s!==void 0?s:void 0,p=(r=o.getAttribute("property"))!==null&&r!==void 0?r:void 0,u=(d=o.getAttribute("content"))!==null&&d!==void 0?d:void 0;(a||p)&&i.push({name:a,property:p,content:u})});try{const o=await fetch(n,{method:"POST",headers:{"Content-Type":"application/json","x-agent-id":e,referer:typeof window!="undefined"?window.location.href:""},body:JSON.stringify({meta_tags:i,url:typeof window!="undefined"?window.location.href:""})});return o.ok?await o.json():void 0}catch{return}}const globalMedAssistConfig={},getWidgetElement=()=>typeof document=="undefined"?null:document.querySelector("eka-medassist-widget");if(typeof window!="undefined"){const e=window;e.__ekaMedAssistConfig__=globalMedAssistConfig,e.EkaMedAssist={init(t){var n,i,o;Object.assign(globalMedAssistConfig,t);const s=getWidgetElement();if(s){if(t.agentId&&s.setAttribute("agent-id",t.agentId),t.authToken&&s.setAttribute("auth-token",t.authToken),t.title&&s.setAttribute("title",t.title),t.iconUrl&&s.setAttribute("icon-url",t.iconUrl),t.baseUrl&&s.setAttribute("base-url",t.baseUrl),t.resize!==void 0&&s.setAttribute("resize",String(t.resize)),(t.displayMode==="full"||t.displayMode==="widget")&&s.setAttribute("display-mode",t.displayMode),t.context)try{s.setAttribute("context",JSON.stringify(t.context))}catch{console.warn("Failed to stringify context passed to init")}typeof t.customLauncherStyles=="string"&&s.setAttribute("custom-launcher-styles",t.customLauncherStyles),t.redirectUrl&&s.setAttribute("redirect-url",t.redirectUrl),!((n=t.theme)===null||n===void 0)&&n.backgroundImage&&preloadImage(t.theme.backgroundImage),(o=(i=s).openFromBridge)===null||o===void 0||o.call(i)}}}}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 e=scriptEl.dataset.widgetAssets;if(e==="local")return`${scriptBaseUrl}src/`;if(e&&e.length>0)try{return new URL(e,scriptBaseUrl).href}catch{return e.endsWith("/")?e:`${e}/`}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(e=>{if(!e.ok)throw new Error(`Unable to fetch widget styles from ${WIDGET_CSS_URL}`);return e.text()})),widgetCssTextPromise}class MedAssistWidgetLoader extends HTMLElement{setLauncherState(t){var n;const i=(n=this.shadowRoot)===null||n===void 0?void 0:n.getElementById("medassist-open-btn");i&&(i.classList.toggle("loading",t==="loading"),i.classList.toggle("hidden",t==="open"),t==="loading"?i.setAttribute("aria-busy","true"):i.removeAttribute("aria-busy"))}getAgentConfig(){if(!this.agentConfigPromise){const t=(typeof window!="undefined"?window.__ekaMedAssistConfig__:void 0)||{},n=t.baseUrl||this.getAttribute("base-url")||"https://matrix.eka.care/reloaded",i=t.agentId||this.getAttribute("agent-id")||"";if(!i)return Promise.resolve(void 0);this.agentConfigPromise=fetchAgentConfig(n,i).catch(()=>{})}return this.agentConfigPromise}constructor(){super(),this.reactRoot=null,this.agentConfigPromise=null,this.loading=!1,this.authPrefetchStarted=!1,this.attachShadow({mode:"open"}),this.defaultIconUrl="https://cdn.eka.care/bot-icon.svg",this.widgetLoaded=!1,this.displayMode=this.getAttribute("display-mode")==="full"?"full":"widget",this.setupAuthExpirationListener()}static get observedAttributes(){return["icon-url","display-mode","custom-launcher-styles","redirect-url"]}connectedCallback(){this.displayMode==="full"?(this.initializeFullMode(),this.loadAndRender().catch(t=>{console.error("Failed to load MedAssist widget in full mode",t)})):(this.renderButton(),this.scheduleIdle(()=>{this.preloadWidgetAssets(),this.prefetchAuthTokens(),this.initNudge()}))}scheduleIdle(t){if(typeof window=="undefined"){t();return}const n=window.requestIdleCallback;typeof n=="function"?n(t,{timeout:3e3}):setTimeout(t,200)}attributeChangedCallback(t){if(t==="icon-url"&&this.displayMode==="widget"&&this.renderButton(),t==="display-mode"){const n=this.getAttribute("display-mode")==="full"?"full":"widget";n!==this.displayMode&&(this.displayMode=n,n==="full"?this.initializeFullMode():this.renderButton())}t==="custom-launcher-styles"&&this.applyCustomLauncherStyles()}preloadWidgetAssets(){getWidgetCssTextPromise(),this.loadWidgetModule(),this.preloadBackgroundImage()}prefetchAuthTokens(){var t;if(this.authPrefetchStarted)return;const n=(typeof window!="undefined"?window.__ekaMedAssistConfig__:void 0)||{},i=n.agentId||this.getAttribute("agent-id")||"";if(!i)return;this.authPrefetchStarted=!0;const o=n.authToken||this.getAttribute("auth-token")||void 0,s=n.baseUrl||this.getAttribute("base-url")||"https://matrix.eka.care/reloaded",r=(t=getEnvironment(this.getAttribute("environment")))!==null&&t!==void 0?t:"production";this.loadWidgetModule().then(d=>{var a;return(a=d.prefetchAuth)===null||a===void 0?void 0:a.call(d,{agentId:i,authToken:o,serverUrl:s,environment:r})}).catch(()=>{this.authPrefetchStarted=!1})}preloadBackgroundImage(){var t;const n=typeof window!="undefined"?window.__ekaMedAssistConfig__:void 0,i=this.getAttribute("theme")?(()=>{try{return JSON.parse(this.getAttribute("theme")||"{}")}catch{return}})():void 0,o=(t=n==null?void 0:n.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(r=>{var d;const a=(d=r==null?void 0:r.theme)===null||d===void 0?void 0:d.background_img;a&&preloadImage(a)}).catch(()=>{})}setupAuthExpirationListener(){if(typeof window=="undefined")return;const t=n=>{var i;((i=n.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(){this.displayMode=this.getAttribute("display-mode")==="full"?"full":"widget",this.displayMode==="full"?this.initializeFullMode():this.renderButton(),this.loadAndRender().catch(t=>{console.error("Failed to open MedAssist widget from bridge",t)})}async initNudge(){var t,n,i,o;const s=typeof window!="undefined"?window.__ekaMedAssistConfig__:void 0,r=(s==null?void 0:s.agentId)||this.getAttribute("agent-id")||"";if(!r)return;const d=await this.getAgentConfig();if(!(d!=null&&d.nudge))return;const a=(n=(t=d==null?void 0:d.theme)===null||t===void 0?void 0:t.nudge_color)!==null&&n!==void 0?n:"#ffffff",p=typeof window!="undefined"?window.location.href:"";let u;try{u=new URL(p)}catch{return}const g=getNudgePathCandidates(u.pathname),v=g.slice(0,1),w=g.slice(1);let h=findFreshCachedNudge(r,u,v);if(!h){const c=(s==null?void 0:s.baseUrl)||this.getAttribute("base-url")||"https://matrix.eka.care/reloaded",m=await fetchNudgeData(r,c).catch(()=>{});!((i=m==null?void 0:m.nudges)===null||i===void 0)&&i.length&&(storeNudgeResponse(r,m),h=findFreshCachedNudge(r,u,g))}if(h||(h=findFreshCachedNudge(r,u,w)),!h)return;const A=h.data.nudges[Math.floor(Math.random()*h.data.nudges.length)],b=(o=h.data.delay)!==null&&o!==void 0?o:5;setTimeout(()=>{this.showNudgePopup(A,a)},b*1e3)}showNudgePopup(t,n){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 p=s.getElementById("medassist-open-btn"),u=p==null?void 0:p.getBoundingClientRect(),g=272,v=12,w=8,h=16,A=16;let b=window.innerWidth-g-v,c=76,m=g-h-w*2;if(u&&u.width>0){const f=u.left+u.width/2,_=f-g/2,x=window.innerWidth-g-v;b=Math.max(v,Math.min(_,x)),c=window.innerHeight-u.top+A,m=Math.max(h,Math.min(f-b-w,g-h-w*2))}const y=document.createElement("div");y.id="medassist-nudge-popup",y.innerHTML=`
|
|
2
2
|
<style>
|
|
3
3
|
@keyframes nudge-slide-up {
|
|
4
4
|
from { opacity: 0; transform: translateY(12px) scale(0.97); }
|
|
@@ -6,9 +6,9 @@
|
|
|
6
6
|
}
|
|
7
7
|
#medassist-nudge-popup {
|
|
8
8
|
position: fixed;
|
|
9
|
-
bottom: ${
|
|
10
|
-
left: ${
|
|
11
|
-
width: ${
|
|
9
|
+
bottom: ${c}px;
|
|
10
|
+
left: ${b}px;
|
|
11
|
+
width: ${g}px;
|
|
12
12
|
background: ${n};
|
|
13
13
|
border-radius: 16px;
|
|
14
14
|
box-shadow: 0 8px 32px rgba(0,0,0,0.14), 0 2px 8px rgba(0,0,0,0.08);
|
|
@@ -26,7 +26,7 @@
|
|
|
26
26
|
content: '';
|
|
27
27
|
position: absolute;
|
|
28
28
|
bottom: -8px;
|
|
29
|
-
left: ${
|
|
29
|
+
left: ${m}px;
|
|
30
30
|
width: 16px;
|
|
31
31
|
height: 10px;
|
|
32
32
|
background: ${n};
|
|
@@ -79,7 +79,7 @@
|
|
|
79
79
|
<p class="nudge-text">${t.replace(/</g,"<").replace(/>/g,">")}</p>
|
|
80
80
|
<button class="nudge-close" aria-label="Dismiss">✕</button>
|
|
81
81
|
</div>
|
|
82
|
-
`,(o=y.querySelector(".nudge-close"))===null||o===void 0||o.addEventListener("click",
|
|
82
|
+
`,(o=y.querySelector(".nudge-close"))===null||o===void 0||o.addEventListener("click",f=>{f.stopPropagation(),d&&setNudgeCookie(d,"closed"),this.dismissNudgePopup()}),y.addEventListener("click",()=>{d&&setNudgeCookie(d,"closed"),this.dismissNudgePopup(),this.loadAndRender()}),s.appendChild(y)}dismissNudgePopup(){var t;const n=(t=this.shadowRoot)===null||t===void 0?void 0:t.getElementById("medassist-nudge-popup");n==null||n.remove()}applyCustomLauncherStyles(){var t;const n=this.shadowRoot;if(!n||this.displayMode!=="widget")return;const i=n.querySelector('style[data-medassist-custom-launcher="true"]'),o=(t=this.getAttribute("custom-launcher-styles"))!==null&&t!==void 0?t:"";if(!o){i==null||i.remove();return}if(i){i.textContent=o;return}const s=document.createElement("style");s.setAttribute("data-medassist-custom-launcher","true"),s.textContent=o,n.appendChild(s)}renderButton(){var t;const n=this.getAttribute("icon-url")||this.defaultIconUrl,i=this.shadowRoot;if(!i){console.error("Shadow root was not created");return}if(!i.querySelector("button"))i.innerHTML=`
|
|
83
83
|
<style>
|
|
84
84
|
#medassist-open-btn {
|
|
85
85
|
width: 60px;
|
|
@@ -115,10 +115,42 @@
|
|
|
115
115
|
#medassist-open-btn.hidden {
|
|
116
116
|
display: none !important;
|
|
117
117
|
}
|
|
118
|
+
/* Loading state: the launcher stays exactly where it is (so custom
|
|
119
|
+
launcher styles still apply) and swaps its icon for a spinner
|
|
120
|
+
while the widget bundle + config are fetched. */
|
|
121
|
+
#medassist-open-btn.loading {
|
|
122
|
+
cursor: default;
|
|
123
|
+
pointer-events: none;
|
|
124
|
+
}
|
|
125
|
+
#medassist-open-btn.loading img {
|
|
126
|
+
display: none;
|
|
127
|
+
}
|
|
128
|
+
#medassist-loader {
|
|
129
|
+
display: none;
|
|
130
|
+
width: 26px;
|
|
131
|
+
height: 26px;
|
|
132
|
+
box-sizing: border-box;
|
|
133
|
+
border-radius: 50%;
|
|
134
|
+
border: 3px solid rgba(0, 0, 0, 0.12);
|
|
135
|
+
border-top-color: rgba(0, 0, 0, 0.45);
|
|
136
|
+
animation: medassist-spin 0.7s linear infinite;
|
|
137
|
+
}
|
|
138
|
+
#medassist-open-btn.loading #medassist-loader {
|
|
139
|
+
display: block;
|
|
140
|
+
}
|
|
141
|
+
@keyframes medassist-spin {
|
|
142
|
+
to { transform: rotate(360deg); }
|
|
143
|
+
}
|
|
144
|
+
@media (prefers-reduced-motion: reduce) {
|
|
145
|
+
#medassist-loader {
|
|
146
|
+
animation-duration: 1.8s;
|
|
147
|
+
}
|
|
148
|
+
}
|
|
118
149
|
</style>
|
|
119
150
|
|
|
120
151
|
<button id="medassist-open-btn">
|
|
121
152
|
<img src="${n}" alt="MedAssist Icon">
|
|
153
|
+
<span id="medassist-loader" aria-hidden="true"></span>
|
|
122
154
|
</button>
|
|
123
155
|
<div id="medassist-widget-root" class="hidden"></div>
|
|
124
156
|
`,(t=i.getElementById("medassist-open-btn"))===null||t===void 0||t.addEventListener("click",()=>{const s=((typeof window!="undefined"?window.__ekaMedAssistConfig__:void 0)||{}).agentId||this.getAttribute("agent-id")||"";s&&setNudgeCookie(s,"closed"),this.dismissNudgePopup(),this.loadAndRender()});else{const o=i.querySelector("#medassist-open-btn img");o&&(o.src=n)}this.applyCustomLauncherStyles()}initializeFullMode(){const t=this.shadowRoot;if(!t){console.error("Shadow root is not available");return}t.getElementById("medassist-widget-root")||(t.innerHTML=`
|
|
@@ -138,4 +170,4 @@
|
|
|
138
170
|
}
|
|
139
171
|
</style>
|
|
140
172
|
<div id="medassist-widget-root"></div>
|
|
141
|
-
`)}async loadAndRender(){var t,n;const i=this.shadowRoot;if(!i){console.error("Shadow root is not available");return}this.prefetchAuthTokens(),this.style.display="";const o=i.getElementById("medassist-
|
|
173
|
+
`)}async loadAndRender(){var t,n;const i=this.shadowRoot;if(!i){console.error("Shadow root is not available");return}if(this.loading)return;this.prefetchAuthTokens(),this.style.display="";const o=i.getElementById("medassist-widget-root"),s=this.getAttribute("agent-id");let r=this.getAttribute("icon-url")||this.defaultIconUrl;const d=(t=getEnvironment(this.getAttribute("environment")))!==null&&t!==void 0?t:"production",a=this.getAttribute("connectivity"),p=a==="http_stream"||a==="socket"?a:void 0;let u=this.getAttribute("title")||"Medi Clinic";const g=this.getAttribute("base-url")||"https://matrix.eka.care/reloaded",w=this.getAttribute("display-mode")==="full"?"full":"widget",h=this.getAttribute("context")?JSON.parse(this.getAttribute("context")||"{}"):void 0,A=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,c=(typeof window!="undefined"?window.__ekaMedAssistConfig__:void 0)||{},m={...h||{},...c.context||{}},y=c.authToken||this.getAttribute("auth-token")||void 0,f=c.agentId||s,_=c.baseUrl||g,x=typeof window!="undefined"?(n=window.EkaMedAssist)===null||n===void 0?void 0:n.onClose:void 0,$=this.getAttribute("redirect-url")||void 0,k=c.redirectUrl||$,z=!!k||c.showCloseButton===!0;if(!f){console.error("Agent ID is required");return}if(!o){console.error("Widget root element is missing");return}this.loading=!0,this.setLauncherState("loading"),o.classList.remove("hidden");let I,L,U,N=!1,R,P=!1,C;const B=l=>{var S,M,E;u=l.name||u,r=((S=l.theme)===null||S===void 0?void 0:S.icon_img)||r,I=mapAgentConfigThemeToWidgetTheme(l.theme||void 0),L=l.allowed,U=l.connectivity,N=l.resize||(c==null?void 0:c.resize)||!1,R=l.initial_message,P=(E=(M=l.theme)===null||M===void 0?void 0:M.hide_watermark)!==null&&E!==void 0?E:!1,C=l.feedback},T=readAgentConfigCache(f);if(T)B(T),this.getAgentConfig().then(l=>{l&&writeAgentConfigCache(f,l)}).catch(()=>{});else try{const l=await this.getAgentConfig();l&&(writeAgentConfigCache(f,l),B(l))}catch{}const F=p||U||"socket",W={title:c.title||u,iconUrl:r||c.iconUrl,showCloseButton:z,allowed:L,environment:d,connectionType:F,onClose:()=>{var l;if((l=this.reactRoot)===null||l===void 0||l.unmount(),this.reactRoot=null,x&&typeof x=="function"&&x(),k){window.location.href=k;return}w==="full"?this.style.display="none":(this.setLauncherState("idle"),o.classList.add("hidden"))},baseUrl:_,context:m,displayMode:w,resize:N||this.getAttribute("resize")==="true",authToken:y,initialMessage:R,hideWatermark:P,...(b||C)&&{feedback:b||C},theme:{...I||{},...A||{},...c.theme||{}}},O=window;if(this.widgetLoaded){this.reactRoot=O.renderMedAssist(o,f,W),this.setLauncherState("open"),this.loading=!1;return}try{const[,l]=await Promise.all([this.loadWidgetCss(),this.loadWidgetModule()]);this.reactRoot=l.renderMedAssist(o,f,W),this.widgetLoaded=!0,this.setLauncherState("open")}catch(l){console.error("Failed to load MedAssist widget",l),this.setLauncherState("idle"),o.classList.add("hidden")}finally{this.loading=!1}}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 n=await getWidgetCssTextPromise(),i=document.createElement("style");i.setAttribute("data-medassist-style","true"),i.textContent=n,t.appendChild(i)}loadWidgetModule(){return widgetModulePromise||(widgetModulePromise=import(WIDGET_JS_URL)),widgetModulePromise}}customElements.define("eka-medassist-widget",MedAssistWidgetLoader);
|