UNPKG

mind-link-ai-widget

Version:

A react widget for React Web and React-Native Mobile integrations.

2 lines (1 loc) 18.7 kB
(function(e,d){typeof exports=="object"&&typeof module<"u"?module.exports=d(require("react")):typeof define=="function"&&define.amd?define(["react"],d):(e=typeof globalThis<"u"?globalThis:e||self,e.MindLinkAIWidget=d(e.React))})(this,(function(e){"use strict";const d=[];for(let n=0;n<256;++n)d.push((n+256).toString(16).slice(1));function oe(n,l=0){return(d[n[l+0]]+d[n[l+1]]+d[n[l+2]]+d[n[l+3]]+"-"+d[n[l+4]]+d[n[l+5]]+"-"+d[n[l+6]]+d[n[l+7]]+"-"+d[n[l+8]]+d[n[l+9]]+"-"+d[n[l+10]]+d[n[l+11]]+d[n[l+12]]+d[n[l+13]]+d[n[l+14]]+d[n[l+15]]).toLowerCase()}let A;const ie=new Uint8Array(16);function re(){if(!A){if(typeof crypto>"u"||!crypto.getRandomValues)throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");A=crypto.getRandomValues.bind(crypto)}return A(ie)}const j={randomUUID:typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto)};function le(n,l,g){if(j.randomUUID&&!n)return j.randomUUID();n=n||{};const m=n.random??n.rng?.()??re();if(m.length<16)throw new Error("Random bytes length must be >= 16");return m[6]=m[6]&15|64,m[8]=m[8]&63|128,oe(m)}const ae=y();function y(){return le()}function se(){const n=new Date().getHours();return n<12?"Good Morning":n<18?"Good Afternoon":"Good Evening"}function O(n,l=1){return n.slice().sort(()=>.5-Math.random()).slice(0,l)}function G(n){return n.replace(/\w\S*/g,l=>l.charAt(0).toUpperCase()+l.slice(1).toLowerCase())}let W=null,H=!1;function ce(n){H=n}function de(n){H&&console.log("[API-RN] setApiConfig:",n),W=n?{...n,apiHost:n.apiHost??"https://uat.api-az.carelonhealth.com/mindlink/api/v1"}:null}const _=()=>W||{apiHost:"",senderApp:"",apiKey:""};async function he(n,l){const g=_(),m=`${g.apiHost}/behive/intents-and-entities`;H&&console.log("[API-RN] fetchIntentsAndEntities - URL:",m,"query:",l,"token:",n,"config:",JSON.stringify(g));const f=await fetch(m,{method:"POST",headers:{Authorization:`Bearer ${n}`,apikey:g.apiKey,"sender-app":g.senderApp,"Content-Type":"application/json",accept:"application/json","x-csid":ae},body:JSON.stringify({query:l})});if(!f.ok){const E=await f.text().catch(()=>"");throw new Error(`fetchIntentsAndEntities failed (${f.status}): ${E}`)}return f.json()}async function q(n,l){const g=_(),m=`${g.apiHost}/behive/crediblemind/suggest`,f=await fetch(m,{method:"POST",headers:{Authorization:`Bearer ${n}`,apikey:g.apiKey,"sender-app":g.senderApp,"Content-Type":"application/json",accept:"application/json"},body:JSON.stringify({query:l})});if(!f.ok){const E=await f.text().catch(()=>"");throw new Error(`fetchCredibleMindSuggestions failed (${f.status}): ${E}`)}return f.json()}async function ue(n,l){const g=_(),m=`${g.apiHost}/behive/providers/search`,f=await fetch(m,{method:"POST",headers:{Authorization:`Bearer ${n}`,apikey:g.apiKey,"sender-app":g.senderApp,"Content-Type":"application/json",accept:"application/json"},body:JSON.stringify(l)});if(!f.ok){const E=await f.text().catch(()=>"");throw new Error(`fetchProviderSearch failed (${f.status}): ${E}`)}return f.json()}const{View:c,Text:r,TextInput:ge,TouchableOpacity:b,ScrollView:v,Linking:z,Image:fe}=(()=>{try{return require("react-native")}catch{return{View:"div",Text:"span",TextInput:"input",TouchableOpacity:"button",ScrollView:"div",Linking:{openURL:n=>window.open(n,"_blank")},Image:"img"}}})(),o={carelonPurple:"#6C47FF",white:"#ffffff",black:"#2f2f2f",borderGrey:"#baadff",lightPurple:"#ececff",textGrey:"#666666",shadowColor:"#000000"};function pe(n){e.useEffect(()=>{n.debug&&ce(!0),n.config&&de(n.config)},[n.debug,n.config]);const{greetingName:l,greetingText:g,greetingSet:m,chips:f}=e.useMemo(()=>{const t=n.user?.fname?`${n.user.fname}!`:"there!",s=O(["Hi","Hey","Hello",se()]),i=O(["How can I help you today?","What can I do for you today?"]),a=O(["I feel stressed","Tips for anxiety","My benefits","Work-life balance advice","Mindfulness techniques","Dealing with burnout","Healthy habits","Managing emotions","Productivity tips","Positive thinking","Social support","Self care routines","Goal setting","Time management","Sleep hygiene","Stress relief","Mental wellness","Emotional balance","Find therapists near me","Find counselors near me"],4);return{greetingName:t,greetingText:s,greetingSet:i,chips:a}},[n.user?.fname]),[E,me]=e.useState(!1),[u,S]=e.useState([]),[p,$]=e.useState([]),[P,F]=e.useState(""),[k,J]=e.useState(!1),[U,K]=e.useState([]),[Y,Q]=e.useState(!0),[X,Z]=e.useState(!1),[L,ye]=e.useState([1,.5,.3]),we=e.useRef(null),R=e.useRef(null),ee=e.useRef(null),N=e.useRef(null),M=e.useRef(null),te=30,be=(t=new Date)=>t.toLocaleTimeString("en-US",{hour:"2-digit",minute:"2-digit",hour12:!1}),Ee=t=>{D(t)},V=t=>{n.onSchemeNavigate?.(t)},D=e.useCallback(async t=>{if(!(t||P.trim())||k)return;E||me(!0);const s=t||P,i={id:y()+"-user",sender:"user",text:s,timestamp:new Date};S(a=>[...a,i]),F(""),J(!0),K([]),Q(!0);try{we.current=R.current,ee.current=N.current;const a=await he(n.token,s);R.current=a.intent,N.current=a.slots.specialty;const w=a?.slots_fulfillment?.status??!0;Q(w);const h=a?.followup?.prompt??null,I=a?.followup?.options??[];K(I);const ne=a.smalltalk,B=a.hybridtalk;if(w&&a.intent!=="provider_search_intent"&&S(x=>[...x,{id:y()+"-bot-smalltalk",sender:"bot",text:ne||B,timestamp:new Date}]),w&&a.intent==="health_content_intent"&&a.slots.content_query){const x=await q(n.token,a.slots.content_query);x?.crediblemind?.length?S(T=>[...T,{id:y()+"-bot-healthcontent-richinfo",sender:"bot",crediblemind:x.crediblemind,timestamp:new Date}]):S(T=>[...T,{id:y()+"-bot-smalltalk",sender:"bot",text:"Sorry! There are no health content suggestions for your query.",timestamp:new Date}])}else if(w&&a.intent==="provider_search_intent"){let x=null;ee.current!==N.current&&(x=await q(n.token,a.query)),x?.crediblemind?.length?S(C=>[...C,{id:y()+"-bot-healthcontent-richinfo-with-text",sender:"bot",text:B,crediblemind:x.crediblemind,timestamp:new Date}]):S(C=>[...C,{id:y()+"-bot-smalltalk",sender:"bot",text:ne||B,timestamp:new Date}]);const T=await ue(n.token,{gender:a.slots.gender,specialty:a.slots.specialty,provider_type:a.slots.provider_type,location:a.slots.location,language:a.slots.language});T?.providers?.length?S(C=>[...C,{id:y()+"-bot-providersearch-richinfo",sender:"bot",providers:T.providers,timestamp:new Date}]):(S(C=>[...C,{id:y()+"-bot-smalltalk",sender:"bot",text:"Sorry! There are no providers available for your search criteria.",timestamp:new Date}]),S(C=>[...C,{id:y()+"-bot-navigation-suggestion",sender:"bot",text:"Would you like to explore more provider options?",showNavigationButton:!0,timestamp:new Date}]))}h&&S(x=>[...x,{id:y()+"-bot-followup",sender:"bot",text:h,timestamp:new Date}])}catch(a){console.error("[BehiveApp] sendMessage error:",a),S(w=>[...w,{id:y()+"-bot-smalltalk",sender:"bot",text:"Sorry! There was a problem interacting with my system. Please try again in a while.",timestamp:new Date}])}finally{J(!1)}},[P,k,E,n.token]);e.useEffect(()=>{if(!X&&E&&u.length>p.length){const t=u[p.length];if(t.sender==="bot"){let s="",i=0;Z(!0);const a=typeof t.text=="string"?t.text:"",w=()=>{a&&i<a.length?(s+=a[i],$(h=>{const I=[...h];return I[I.length-1]={...t,text:s},I}),i++,setTimeout(w,te)):Z(!1)};$(h=>[...h,{...t,text:""}]),setTimeout(w,te)}else $(s=>[...s,t])}},[u,E,p,p.length,X]),e.useEffect(()=>{M.current&&M.current.scrollToEnd({animated:!0})},[p]),e.useEffect(()=>{if(!k)return;const t=setInterval(()=>{ye(s=>[s[2],s[0],s[1]])},400);return()=>clearInterval(t)},[k]);const Se=(()=>{if(!U||U.length===0||p.length===0)return!1;const t=p[p.length-1];return t.sender==="bot"&&t.id.includes("-bot-followup")&&t.text&&u.length===p.length&&u[u.length-1].id===t.id&&u[u.length-1].text===t.text})();return e.createElement(c,{style:{flex:1,backgroundColor:o.white}},e.createElement(v,{ref:M,style:{flex:1},contentContainerStyle:{padding:16}},E?e.createElement(c,{style:{flex:1}},p.map((t,s)=>e.createElement(c,{key:t.id+"-"+s,style:{marginVertical:6}},t.text&&e.createElement(c,{style:{maxWidth:"80%",alignSelf:t.sender==="user"?"flex-end":"flex-start",marginBottom:8}},e.createElement(c,{style:{paddingHorizontal:16,paddingVertical:12,borderRadius:18,backgroundColor:t.sender==="user"?o.carelonPurple:o.white,shadowColor:o.shadowColor,shadowOffset:{width:0,height:1},shadowOpacity:.1,shadowRadius:2,elevation:1}},e.createElement(r,{style:{color:t.sender==="user"?o.white:o.black,fontSize:14,lineHeight:20}},t.text),t.showNavigationButton&&t.sender==="bot"&&e.createElement(b,{style:{marginTop:12,backgroundColor:o.carelonPurple,paddingVertical:10,paddingHorizontal:16,borderRadius:12,alignSelf:"flex-start"},onPress:()=>V("page::counselor-search")},e.createElement(r,{style:{color:o.white,fontSize:13,fontWeight:"600"}},"Explore Provider Options")),t.timestamp&&(!t.id.includes("-bot-")||u.length>s&&p.length>s&&u[s].id===t.id&&u[s].text===t.text&&p[s].text===t.text)&&e.createElement(r,{style:{fontSize:10,color:t.sender==="user"?"rgba(255,255,255,0.7)":o.textGrey,marginTop:4,textAlign:"right"}},be(new Date(t.timestamp))))),Y&&t.crediblemind&&Array.isArray(t.crediblemind)&&t.crediblemind.length>0&&(!t.id.includes("-bot-smalltalk")&&!t.id.includes("-bot-healthcontent-richinfo-with-text")||u.length>s&&p.length>s&&u[s].id===t.id&&u[s].text===t.text&&p[s].text===t.text)&&e.createElement(c,{style:{marginTop:16,marginLeft:-16,marginRight:-16}},e.createElement(r,{style:{fontSize:15,fontWeight:"600",marginBottom:12,marginLeft:16,color:o.carelonPurple}},"📚 Helpful Resources"),e.createElement(v,{horizontal:!0,showsHorizontalScrollIndicator:!1,contentContainerStyle:{paddingHorizontal:16}},t.crediblemind.map(i=>e.createElement(b,{key:i.entry_id,style:{width:280,marginRight:12,backgroundColor:o.white,borderRadius:16,overflow:"hidden",shadowColor:o.shadowColor,shadowOffset:{width:0,height:4},shadowOpacity:.1,shadowRadius:12,elevation:4},onPress:()=>z.openURL(i.content_url)},e.createElement(c,{style:{position:"relative",height:160}},e.createElement(fe,{source:{uri:i.image_url},style:{width:"100%",height:"100%",backgroundColor:"#e0e0e0"}}),e.createElement(c,{style:{position:"absolute",top:12,right:12,backgroundColor:o.carelonPurple,paddingHorizontal:12,paddingVertical:6,borderRadius:20}},e.createElement(r,{style:{color:o.white,fontSize:11,fontWeight:"500"}},i.content_type))),e.createElement(c,{style:{backgroundColor:i.content_type==="Video"?"#6c3eb6":i.content_type==="Article"?"#5a2d9f":i.content_type==="Podcast"?"#7b4bc7":"#8a5dd1",padding:16}},e.createElement(r,{style:{fontSize:16,fontWeight:"600",color:o.white,marginBottom:12,lineHeight:22}},i.title),e.createElement(r,{style:{fontSize:13,color:o.white,fontWeight:"800"}},i.content_type==="Video"?"Watch →":"Read →")))))),Y&&t.providers&&Array.isArray(t.providers)&&t.providers.length>0&&(!t.id.includes("-bot-smalltalk")&&!t.id.includes("-bot-healthcontent-richinfo")&&!t.id.includes("-bot-healthcontent-richinfo-with-text")||u.length>s&&p.length>s&&u[s].id===t.id&&u[s].text===t.text&&p[s].text===t.text)&&e.createElement(c,{style:{marginTop:16,marginLeft:-16,marginRight:-16}},e.createElement(r,{style:{fontSize:15,fontWeight:"600",marginBottom:12,marginLeft:16,color:o.carelonPurple}},"👩 Healthcare Providers"),e.createElement(v,{horizontal:!0,showsHorizontalScrollIndicator:!1,contentContainerStyle:{paddingHorizontal:16}},t.providers.map((i,a)=>{const w=`${i.name.firstName?.[0]||""}${i.name.lastName?.[0]||""}`.toUpperCase();return e.createElement(c,{key:`${t.id}-provider-${i.providerId||a}-${a}`,style:{width:300,marginRight:12,backgroundColor:o.white,borderRadius:16,padding:19,borderWidth:2,borderColor:o.borderGrey,shadowColor:o.shadowColor,shadowOffset:{width:0,height:2},shadowOpacity:.1,shadowRadius:12,elevation:3}},e.createElement(c,{style:{flexDirection:"row",alignItems:"center",marginBottom:12}},e.createElement(c,{style:{width:40,height:40,borderRadius:20,backgroundColor:o.carelonPurple,alignItems:"center",justifyContent:"center",marginRight:12}},e.createElement(r,{style:{color:o.white,fontSize:14,fontWeight:"700"}},w)),e.createElement(c,{style:{flex:1}},e.createElement(r,{style:{fontSize:15,fontWeight:"700",color:o.black,flexWrap:"wrap"}},`${i.name.firstName} ${i.name.lastName}`))),e.createElement(c,{style:{backgroundColor:o.lightPurple,paddingHorizontal:12,paddingVertical:2,borderRadius:12,alignSelf:"flex-start",marginBottom:12}},e.createElement(r,{style:{fontSize:14,fontWeight:"500",color:o.black}},i.title)),i.contact.address&&e.createElement(b,{style:{flexDirection:"row",alignItems:"flex-start",marginBottom:10},onPress:()=>{const h=`${i.contact.address.addr1}, ${i.contact.address.city}, ${i.contact.address.state} ${i.contact.address.zip}`;z.openURL(`https://www.google.com/maps/search/?api=1&query=${encodeURIComponent(h)}`)}},e.createElement(r,{style:{fontSize:16,color:o.carelonPurple,marginRight:8}},"📍"),e.createElement(r,{style:{fontSize:13,color:o.carelonPurple,fontWeight:"500",flex:1}},`${i.contact.address.addr1}, ${i.contact.address.city}, ${i.contact.address.state}`)),i.contact.phone&&i.contact.phone!=="Not Available"&&e.createElement(b,{style:{flexDirection:"row",alignItems:"center",marginBottom:10},onPress:()=>z.openURL(`tel:${i.contact.phone}`)},e.createElement(r,{style:{fontSize:16,color:o.carelonPurple,marginRight:8}},"📞"),e.createElement(r,{style:{fontSize:13,color:o.carelonPurple,fontWeight:"500"}},i.contact.phone)),i.contact.officeEmail&&i.contact.officeEmail!=="Not Available"&&e.createElement(b,{style:{flexDirection:"row",alignItems:"center",marginBottom:10},onPress:()=>z.openURL(`mailto:${i.contact.officeEmail}`)},e.createElement(r,{style:{fontSize:16,color:o.carelonPurple,marginRight:8}},"✉️"),e.createElement(r,{style:{fontSize:13,color:o.black}},i.contact.officeEmail)),i.contact.website&&i.contact.website!=="Not Available"&&e.createElement(b,{style:{flexDirection:"row",alignItems:"center",marginBottom:10},onPress:()=>z.openURL(i.contact.website.startsWith("http")?i.contact.website:`https://${i.contact.website}`)},e.createElement(r,{style:{fontSize:16,color:o.carelonPurple,marginRight:8}},"🌐"),e.createElement(r,{style:{fontSize:13,color:o.black,flex:1},numberOfLines:1},i.contact.website)),i.languages&&i.languages.length>0&&e.createElement(c,{style:{flexDirection:"row",alignItems:"center",marginTop:10}},e.createElement(r,{style:{fontSize:16,color:o.carelonPurple,marginRight:8}},"🗣️"),e.createElement(r,{style:{fontSize:13,color:o.black}},i.languages.map(h=>G(h)).join(", "))),i.yellowLabels&&i.yellowLabels.length>0&&e.createElement(c,{style:{flexDirection:"row",flexWrap:"wrap",marginTop:16,gap:8}},i.yellowLabels.filter(h=>!h.notAvailable).map(h=>e.createElement(c,{key:h.icon,style:{backgroundColor:o.lightPurple,paddingHorizontal:10,paddingVertical:6,borderRadius:10}},e.createElement(r,{style:{fontSize:13,color:o.carelonPurple,fontWeight:"600"}},h.icon==="accepting-new-patients"?"✓ New Patients":h.icon==="public-transportation"?"🚌 Transit":h.icon==="wheelchair-accessible"?"♿ Accessible":h.icon==="telehealth-provider"?"📹 Telehealth":h.icon==="medicaid-provider"?"🏥 Medicaid":G(h.label||h.icon))))),i.onlineAppointmentScheduleFlag==1&&e.createElement(b,{style:{marginTop:19,backgroundColor:o.carelonPurple,paddingVertical:11,paddingHorizontal:35,borderRadius:16,alignSelf:"center",shadowColor:o.carelonPurple,shadowOffset:{width:0,height:2},shadowOpacity:.2,shadowRadius:8,elevation:2},onPress:()=>V("page::counselor-appointments")},e.createElement(r,{style:{color:o.white,fontSize:14,fontWeight:"600"}},"Request an appointment")))})),e.createElement(b,{style:{marginTop:16,marginLeft:16,marginRight:16,backgroundColor:o.white,borderWidth:1.5,borderColor:o.carelonPurple,paddingVertical:12,paddingHorizontal:24,borderRadius:16,alignItems:"center",shadowColor:o.shadowColor,shadowOffset:{width:0,height:2},shadowOpacity:.1,shadowRadius:8,elevation:2},onPress:()=>V("page::counselor-search")},e.createElement(r,{style:{color:o.carelonPurple,fontSize:15,fontWeight:"600"}},"Find More Providers"))))),Se&&e.createElement(c,{style:{flexDirection:"row",flexWrap:"wrap",marginTop:16}},U.map(t=>e.createElement(b,{key:t,style:{backgroundColor:o.white,borderWidth:1,borderColor:o.carelonPurple,paddingHorizontal:12,paddingVertical:8,borderRadius:32,margin:4,shadowColor:o.shadowColor,shadowOffset:{width:0,height:2},shadowOpacity:.1,shadowRadius:8,elevation:1},onPress:()=>D(t)},e.createElement(r,{style:{color:o.black,fontSize:14,fontWeight:"400"}},t)))),k&&e.createElement(c,{style:{alignSelf:"flex-start",paddingHorizontal:16,paddingVertical:12,backgroundColor:o.white,borderRadius:18,marginVertical:8,flexDirection:"row",gap:4}},e.createElement(r,{style:{fontSize:20,color:o.carelonPurple,opacity:L[0]}},"•"),e.createElement(r,{style:{fontSize:20,color:o.carelonPurple,opacity:L[1]}},"•"),e.createElement(r,{style:{fontSize:20,color:o.carelonPurple,opacity:L[2]}},"•"))):e.createElement(c,{style:{flex:1,justifyContent:"center",alignItems:"center",padding:32}},e.createElement(c,{style:{alignItems:"center",marginBottom:32}},e.createElement(r,{style:{fontSize:28,fontWeight:"600",color:o.carelonPurple,textAlign:"center"}},g+", ",e.createElement(r,{style:{fontWeight:"800"}},l)),e.createElement(r,{style:{fontSize:16,color:o.black,marginTop:10,textAlign:"center",fontWeight:"600"}},m)),e.createElement(c,{style:{flexDirection:"row",flexWrap:"wrap",justifyContent:"center"}},f.map(t=>e.createElement(b,{key:t,style:{backgroundColor:o.white,borderWidth:1.5,borderColor:o.carelonPurple,paddingHorizontal:18,paddingVertical:12,borderRadius:32,margin:8,shadowColor:o.shadowColor,shadowOffset:{width:0,height:2},shadowOpacity:.1,shadowRadius:8,elevation:2},onPress:()=>Ee(t)},e.createElement(r,{style:{color:o.black,fontSize:14,fontWeight:"500"}},t)))))),e.createElement(c,{style:{padding:16,borderTopWidth:1,borderTopColor:"#ececff",backgroundColor:o.white,shadowColor:o.shadowColor,shadowOffset:{width:0,height:-2},shadowOpacity:.1,shadowRadius:16,elevation:5}},e.createElement(c,{style:{flexDirection:"row",alignItems:"center"}},e.createElement(ge,{style:{flex:1,borderWidth:1.5,borderColor:"#ececff",borderRadius:32,paddingHorizontal:16,paddingVertical:12,fontSize:14,marginRight:8,backgroundColor:"#fafafd"},placeholder:"Ask anything",value:P,onChangeText:F,onSubmitEditing:()=>D(),editable:!k}),e.createElement(b,{style:{backgroundColor:P.trim()?o.carelonPurple:"#d1caff",width:44,height:44,borderRadius:22,alignItems:"center",justifyContent:"center",shadowColor:o.shadowColor,shadowOffset:{width:0,height:2},shadowOpacity:.3,shadowRadius:8,elevation:3},onPress:()=>D(),disabled:k||!P.trim()},e.createElement(r,{style:{color:o.white,fontSize:18,fontWeight:"600"}},"↑")))))}return pe}));