UNPKG

mind-link-ai-widget

Version:

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

2 lines (1 loc) 18.5 kB
"use strict";const e=require("react"),u=[];for(let n=0;n<256;++n)u.push((n+256).toString(16).slice(1));function ce(n,i=0){return(u[n[i+0]]+u[n[i+1]]+u[n[i+2]]+u[n[i+3]]+"-"+u[n[i+4]]+u[n[i+5]]+"-"+u[n[i+6]]+u[n[i+7]]+"-"+u[n[i+8]]+u[n[i+9]]+"-"+u[n[i+10]]+u[n[i+11]]+u[n[i+12]]+u[n[i+13]]+u[n[i+14]]+u[n[i+15]]).toLowerCase()}let $;const de=new Uint8Array(16);function he(){if(!$){if(typeof crypto>"u"||!crypto.getRandomValues)throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");$=crypto.getRandomValues.bind(crypto)}return $(de)}const ue=typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto),ee={randomUUID:ue};function ge(n,i,g){if(ee.randomUUID&&!n)return ee.randomUUID();n=n||{};const m=n.random??n.rng?.()??he();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,ce(m)}const fe=w();function w(){return ge()}function pe(){const n=new Date().getHours();return n<12?"Good Morning":n<18?"Good Afternoon":"Good Evening"}function L(n,i=1){return n.slice().sort(()=>.5-Math.random()).slice(0,i)}function te(n){return n.replace(/\w\S*/g,i=>i.charAt(0).toUpperCase()+i.slice(1).toLowerCase())}let U=null,V=!1;function me(n){V=n}function ye(n){V&&console.log("[API-RN] setApiConfig:",n),U=n?{...n,apiHost:n.apiHost??"https://uat.api-az.carelonhealth.com/mindlink/api/v1"}:null}const M=()=>U||{apiHost:"",senderApp:"",apiKey:""};async function we(n,i){const g=M(),m=`${g.apiHost}/behive/intents-and-entities`;V&&console.log("[API-RN] fetchIntentsAndEntities - URL:",m,"query:",i,"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":fe},body:JSON.stringify({query:i})});if(!f.ok){const b=await f.text().catch(()=>"");throw new Error(`fetchIntentsAndEntities failed (${f.status}): ${b}`)}return f.json()}async function ne(n,i){const g=M(),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:i})});if(!f.ok){const b=await f.text().catch(()=>"");throw new Error(`fetchCredibleMindSuggestions failed (${f.status}): ${b}`)}return f.json()}async function be(n,i){const g=M(),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(i)});if(!f.ok){const b=await f.text().catch(()=>"");throw new Error(`fetchProviderSearch failed (${f.status}): ${b}`)}return f.json()}const{View:c,Text:r,TextInput:Ee,TouchableOpacity:S,ScrollView:N,Linking:z,Image:Se}=(()=>{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 xe(n){e.useEffect(()=>{n.debug&&me(!0),n.config&&ye(n.config)},[n.debug,n.config]);const{greetingName:i,greetingText:g,greetingSet:m,chips:f}=e.useMemo(()=>{const t=n.user?.fname?`${n.user.fname}!`:"there!",s=L(["Hi","Hey","Hello",pe()]),a=L(["How can I help you today?","What can I do for you today?"]),l=L(["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:a,chips:l}},[n.user?.fname]),[b,oe]=e.useState(!1),[h,E]=e.useState([]),[p,D]=e.useState([]),[k,B]=e.useState(""),[R,j]=e.useState(!1),[A,G]=e.useState([]),[q,F]=e.useState(!0),[J,K]=e.useState(!1),[O,ae]=e.useState([1,.5,.3]),re=e.useRef(null),Y=e.useRef(null),Q=e.useRef(null),W=e.useRef(null),H=e.useRef(null),X=30,ie=(t=new Date)=>t.toLocaleTimeString("en-US",{hour:"2-digit",minute:"2-digit",hour12:!1}),le=t=>{I(t)},_=t=>{n.onSchemeNavigate?.(t)},I=e.useCallback(async t=>{if(!(t||k.trim())||R)return;b||oe(!0);const s=t||k,a={id:w()+"-user",sender:"user",text:s,timestamp:new Date};E(l=>[...l,a]),B(""),j(!0),G([]),F(!0);try{re.current=Y.current,Q.current=W.current;const l=await we(n.token,s);Y.current=l.intent,W.current=l.slots.specialty;const y=l?.slots_fulfillment?.status??!0;F(y);const d=l?.followup?.prompt??null,T=l?.followup?.options??[];G(T);const Z=l.smalltalk,v=l.hybridtalk;if(y&&l.intent!=="provider_search_intent"&&E(x=>[...x,{id:w()+"-bot-smalltalk",sender:"bot",text:Z||v,timestamp:new Date}]),y&&l.intent==="health_content_intent"&&l.slots.content_query){const x=await ne(n.token,l.slots.content_query);x?.crediblemind?.length?E(P=>[...P,{id:w()+"-bot-healthcontent-richinfo",sender:"bot",crediblemind:x.crediblemind,timestamp:new Date}]):E(P=>[...P,{id:w()+"-bot-smalltalk",sender:"bot",text:"Sorry! There are no health content suggestions for your query.",timestamp:new Date}])}else if(y&&l.intent==="provider_search_intent"){let x=null;Q.current!==W.current&&(x=await ne(n.token,l.query)),x?.crediblemind?.length?E(C=>[...C,{id:w()+"-bot-healthcontent-richinfo-with-text",sender:"bot",text:v,crediblemind:x.crediblemind,timestamp:new Date}]):E(C=>[...C,{id:w()+"-bot-smalltalk",sender:"bot",text:Z||v,timestamp:new Date}]);const P=await be(n.token,{gender:l.slots.gender,specialty:l.slots.specialty,provider_type:l.slots.provider_type,location:l.slots.location,language:l.slots.language});P?.providers?.length?E(C=>[...C,{id:w()+"-bot-providersearch-richinfo",sender:"bot",providers:P.providers,timestamp:new Date}]):(E(C=>[...C,{id:w()+"-bot-smalltalk",sender:"bot",text:"Sorry! There are no providers available for your search criteria.",timestamp:new Date}]),E(C=>[...C,{id:w()+"-bot-navigation-suggestion",sender:"bot",text:"Would you like to explore more provider options?",showNavigationButton:!0,timestamp:new Date}]))}d&&E(x=>[...x,{id:w()+"-bot-followup",sender:"bot",text:d,timestamp:new Date}])}catch(l){console.error("[BehiveApp] sendMessage error:",l),E(y=>[...y,{id:w()+"-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)}},[k,R,b,n.token]);e.useEffect(()=>{if(!J&&b&&h.length>p.length){const t=h[p.length];if(t.sender==="bot"){let s="",a=0;K(!0);const l=typeof t.text=="string"?t.text:"",y=()=>{l&&a<l.length?(s+=l[a],D(d=>{const T=[...d];return T[T.length-1]={...t,text:s},T}),a++,setTimeout(y,X)):K(!1)};D(d=>[...d,{...t,text:""}]),setTimeout(y,X)}else D(s=>[...s,t])}},[h,b,p,p.length,J]),e.useEffect(()=>{H.current&&H.current.scrollToEnd({animated:!0})},[p]),e.useEffect(()=>{if(!R)return;const t=setInterval(()=>{ae(s=>[s[2],s[0],s[1]])},400);return()=>clearInterval(t)},[R]);const se=(()=>{if(!A||A.length===0||p.length===0)return!1;const t=p[p.length-1];return t.sender==="bot"&&t.id.includes("-bot-followup")&&t.text&&h.length===p.length&&h[h.length-1].id===t.id&&h[h.length-1].text===t.text})();return e.createElement(c,{style:{flex:1,backgroundColor:o.white}},e.createElement(N,{ref:H,style:{flex:1},contentContainerStyle:{padding:16}},b?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(S,{style:{marginTop:12,backgroundColor:o.carelonPurple,paddingVertical:10,paddingHorizontal:16,borderRadius:12,alignSelf:"flex-start"},onPress:()=>_("page::counselor-search")},e.createElement(r,{style:{color:o.white,fontSize:13,fontWeight:"600"}},"Explore Provider Options")),t.timestamp&&(!t.id.includes("-bot-")||h.length>s&&p.length>s&&h[s].id===t.id&&h[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"}},ie(new Date(t.timestamp))))),q&&t.crediblemind&&Array.isArray(t.crediblemind)&&t.crediblemind.length>0&&(!t.id.includes("-bot-smalltalk")&&!t.id.includes("-bot-healthcontent-richinfo-with-text")||h.length>s&&p.length>s&&h[s].id===t.id&&h[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(N,{horizontal:!0,showsHorizontalScrollIndicator:!1,contentContainerStyle:{paddingHorizontal:16}},t.crediblemind.map(a=>e.createElement(S,{key:a.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(a.content_url)},e.createElement(c,{style:{position:"relative",height:160}},e.createElement(Se,{source:{uri:a.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"}},a.content_type))),e.createElement(c,{style:{backgroundColor:a.content_type==="Video"?"#6c3eb6":a.content_type==="Article"?"#5a2d9f":a.content_type==="Podcast"?"#7b4bc7":"#8a5dd1",padding:16}},e.createElement(r,{style:{fontSize:16,fontWeight:"600",color:o.white,marginBottom:12,lineHeight:22}},a.title),e.createElement(r,{style:{fontSize:13,color:o.white,fontWeight:"800"}},a.content_type==="Video"?"Watch →":"Read →")))))),q&&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")||h.length>s&&p.length>s&&h[s].id===t.id&&h[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(N,{horizontal:!0,showsHorizontalScrollIndicator:!1,contentContainerStyle:{paddingHorizontal:16}},t.providers.map((a,l)=>{const y=`${a.name.firstName?.[0]||""}${a.name.lastName?.[0]||""}`.toUpperCase();return e.createElement(c,{key:`${t.id}-provider-${a.providerId||l}-${l}`,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"}},y)),e.createElement(c,{style:{flex:1}},e.createElement(r,{style:{fontSize:15,fontWeight:"700",color:o.black,flexWrap:"wrap"}},`${a.name.firstName} ${a.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}},a.title)),a.contact.address&&e.createElement(S,{style:{flexDirection:"row",alignItems:"flex-start",marginBottom:10},onPress:()=>{const d=`${a.contact.address.addr1}, ${a.contact.address.city}, ${a.contact.address.state} ${a.contact.address.zip}`;z.openURL(`https://www.google.com/maps/search/?api=1&query=${encodeURIComponent(d)}`)}},e.createElement(r,{style:{fontSize:16,color:o.carelonPurple,marginRight:8}},"📍"),e.createElement(r,{style:{fontSize:13,color:o.carelonPurple,fontWeight:"500",flex:1}},`${a.contact.address.addr1}, ${a.contact.address.city}, ${a.contact.address.state}`)),a.contact.phone&&a.contact.phone!=="Not Available"&&e.createElement(S,{style:{flexDirection:"row",alignItems:"center",marginBottom:10},onPress:()=>z.openURL(`tel:${a.contact.phone}`)},e.createElement(r,{style:{fontSize:16,color:o.carelonPurple,marginRight:8}},"📞"),e.createElement(r,{style:{fontSize:13,color:o.carelonPurple,fontWeight:"500"}},a.contact.phone)),a.contact.officeEmail&&a.contact.officeEmail!=="Not Available"&&e.createElement(S,{style:{flexDirection:"row",alignItems:"center",marginBottom:10},onPress:()=>z.openURL(`mailto:${a.contact.officeEmail}`)},e.createElement(r,{style:{fontSize:16,color:o.carelonPurple,marginRight:8}},"✉️"),e.createElement(r,{style:{fontSize:13,color:o.black}},a.contact.officeEmail)),a.contact.website&&a.contact.website!=="Not Available"&&e.createElement(S,{style:{flexDirection:"row",alignItems:"center",marginBottom:10},onPress:()=>z.openURL(a.contact.website.startsWith("http")?a.contact.website:`https://${a.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},a.contact.website)),a.languages&&a.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}},a.languages.map(d=>te(d)).join(", "))),a.yellowLabels&&a.yellowLabels.length>0&&e.createElement(c,{style:{flexDirection:"row",flexWrap:"wrap",marginTop:16,gap:8}},a.yellowLabels.filter(d=>!d.notAvailable).map(d=>e.createElement(c,{key:d.icon,style:{backgroundColor:o.lightPurple,paddingHorizontal:10,paddingVertical:6,borderRadius:10}},e.createElement(r,{style:{fontSize:13,color:o.carelonPurple,fontWeight:"600"}},d.icon==="accepting-new-patients"?"✓ New Patients":d.icon==="public-transportation"?"🚌 Transit":d.icon==="wheelchair-accessible"?"♿ Accessible":d.icon==="telehealth-provider"?"📹 Telehealth":d.icon==="medicaid-provider"?"🏥 Medicaid":te(d.label||d.icon))))),a.onlineAppointmentScheduleFlag==1&&e.createElement(S,{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:()=>_("page::counselor-appointments")},e.createElement(r,{style:{color:o.white,fontSize:14,fontWeight:"600"}},"Request an appointment")))})),e.createElement(S,{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:()=>_("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}},A.map(t=>e.createElement(S,{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:()=>I(t)},e.createElement(r,{style:{color:o.black,fontSize:14,fontWeight:"400"}},t)))),R&&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:O[0]}},"•"),e.createElement(r,{style:{fontSize:20,color:o.carelonPurple,opacity:O[1]}},"•"),e.createElement(r,{style:{fontSize:20,color:o.carelonPurple,opacity:O[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"}},i)),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(S,{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:()=>le(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(Ee,{style:{flex:1,borderWidth:1.5,borderColor:"#ececff",borderRadius:32,paddingHorizontal:16,paddingVertical:12,fontSize:14,marginRight:8,backgroundColor:"#fafafd"},placeholder:"Ask anything",value:k,onChangeText:B,onSubmitEditing:()=>I(),editable:!R}),e.createElement(S,{style:{backgroundColor:k.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:()=>I(),disabled:R||!k.trim()},e.createElement(r,{style:{color:o.white,fontSize:18,fontWeight:"600"}},"↑")))))}module.exports=xe;