@brainfish-ai/components 0.35.1 → 0.35.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/chat-search.d.ts +1 -0
- package/dist/esm/chunks/{ChatSearch.D5EABw51.js → ChatSearch.BGtNmt-i.js} +11 -11
- package/dist/esm/chunks/ChatSearch.BGtNmt-i.js.map +1 -0
- package/dist/esm/components/chat-search.js +1 -1
- package/dist/esm/index.js +1 -1
- package/dist/index.d.ts +1 -0
- package/dist/stats.html +1 -1
- package/package.json +1 -1
- package/dist/esm/chunks/ChatSearch.D5EABw51.js.map +0 -1
package/dist/chat-search.d.ts
CHANGED
|
@@ -231,6 +231,7 @@ export declare interface ChatSearchProps {
|
|
|
231
231
|
markConversationCompletedEndpoint?: string;
|
|
232
232
|
reconnectHandoff?: (conversationId: string) => void;
|
|
233
233
|
resetHandoff?: () => void;
|
|
234
|
+
handoffActive?: boolean;
|
|
234
235
|
followUpQuestionsEndpoint?: string;
|
|
235
236
|
autocompleteEndpoint?: string;
|
|
236
237
|
contentTypeEndpoint?: string;
|
|
@@ -79,18 +79,18 @@ return e.createElement("button",{onClick:()=>r({conversationId:t.conversationId,
|
|
|
79
79
|
/* @__PURE__ */e.createElement("div",{className:"flex flex-col min-w-0"},/* @__PURE__ */e.createElement("span",{className:"text-sm font-medium truncate"},t.title),/* @__PURE__ */e.createElement("span",{className:"text-xs text-muted-foreground truncate"},t.subtitle?`${t.subtitle} replied • ${t.timestamp}`:t.timestamp)))}function cn({title:t,items:r,onSelect:n,isReadOnly:a=!1}){return 0===r.length?null:/* @__PURE__ */e.createElement("section",null,/* @__PURE__ */e.createElement("div",{className:"flex items-center gap-2 mb-2"},/* @__PURE__ */e.createElement("p",{className:"text-sm text-muted-foreground"},t),a&&/* @__PURE__ */e.createElement("span",{className:"text-[10px] font-medium px-1.5 py-0.5 rounded bg-muted text-muted-foreground"},"View only")),/* @__PURE__ */e.createElement("div",{className:"flex flex-col gap-2"},r.map(t=>/* @__PURE__ */e.createElement(on,{key:t.conversationId,item:t,onSelect:n}))))}function ln(){/* @__PURE__ */
|
|
80
80
|
return e.createElement("div",{className:"w-full flex items-center gap-3 p-3 rounded-lg bg-card animate-pulse"},/* @__PURE__ */e.createElement("div",{className:"size-8 rounded-full bg-muted shrink-0"}),/* @__PURE__ */e.createElement("div",{className:"flex flex-col gap-2 flex-1 min-w-0"},/* @__PURE__ */e.createElement("div",{className:"h-3.5 bg-muted rounded w-3/4"}),/* @__PURE__ */e.createElement("div",{className:"h-3 bg-muted rounded w-1/2"})))}const dn=()=>{};function un({conversations:t,isLoading:r,onSelectConversation:n}){const a=n??dn,s=t.filter(e=>"active"===e.status),o=t.filter(e=>"completed"===e.status);return r?/* @__PURE__ */e.createElement("div",{className:"flex flex-col gap-2 px-3 py-4 overflow-hidden"},/* @__PURE__ */e.createElement("div",{className:"h-4 w-16 bg-muted rounded animate-pulse mb-2"}),[...Array(3)].map((t,r)=>/* @__PURE__ */e.createElement(ln,{key:r}))):/* @__PURE__ */e.createElement("div",{className:"flex flex-col gap-4 px-3 py-4 min-h-full"},/* @__PURE__ */e.createElement(cn,{title:"Active",items:s,onSelect:a}),/* @__PURE__ */e.createElement(cn,{title:"Previous",items:o,onSelect:a,isReadOnly:!0}),0===t.length&&/* @__PURE__ */e.createElement("div",{className:"flex flex-col items-center justify-center gap-3 mt-16 text-center px-6"},/* @__PURE__ */e.createElement(Se,{size:40,className:"text-muted-foreground opacity-40"}),/* @__PURE__ */e.createElement("p",{className:"text-sm font-medium text-foreground"},"No Threads yet"),/* @__PURE__ */e.createElement("p",{className:"text-xs text-muted-foreground"},"Start a conversation and it will appear here.")))}function mn({onStartNewConversation:t,message:r="This conversation is closed. Messages are read-only."}){/* @__PURE__ */
|
|
81
81
|
return e.createElement(d.div,{initial:{opacity:0,y:20},animate:{opacity:1,y:0},transition:{duration:.5},className:"bg-card shadow-top-soft"},
|
|
82
|
-
/* @__PURE__ */e.createElement("div",{className:"container flex flex-col items-center justify-center p-3 gap-2 text-center"},/* @__PURE__ */e.createElement("span",{className:"text-xs text-muted-foreground"},r),/* @__PURE__ */e.createElement("p",{className:"m-0 text-sm font-medium text-foreground"},"Still need help?"),/* @__PURE__ */e.createElement("button",{type:"button",onClick:t,className:"h-8 rounded-md px-4 text-sm bg-primary text-primary-foreground"},"Start new conversation")))}const pn="enableHistoryTab",hn=[p],fn=[m],gn={p:({children:t})=>/* @__PURE__ */e.createElement("span",null,t)},yn=c(({suggestions:n=[],collections:a=[],selectedCollectionId:s,onCollectionChange:c,selectedRegion:m,onRegionChange:p,apiKey:h,fetchRegionConfig:f,searchEndpoint:g,answerStreamEndpoint:y,uploadEndpoint:v,feedbackEndpoint:w,feedbackReasonEndpoint:b,loadConversationEndpoint:E,autocompleteEndpoint:$,disableFollowUpQuestions:x=!1,enableFileAttachment:_=!1,disableFeedback:k=!1,disclaimer:N,offset:C=0,headers:I,textConfig:S={},followUpQuestionsEndpoint:P,className:T,onToggleSizeButtonClick:A,trackEvent:R,onCloseWidget:j,isWidgetMode:O=!0,nextBestActions:D,bodyActionButtons:z,onNextBestActionClick:L,userData:U,redirectRules:Q,secretAttributes:M,allowedRegions:V,style:q,isSearchWidget:K=!1,isAgentAssist:B=!1,hideCitations:H=!1,conversationInlineSlot:G,liveHumanAgentChatSlot:W,reconnectHandoff:J,resetHandoff:Y,conversationHistoryEndpoint:ee,markConversationReadEndpoint:te,markConversationCompletedEndpoint:re,knowledgeSourceGroups:ne},ae)=>{const{answers:oe,answerListDispatch:ie,query:ce,setQuery:le,followUpQuery:de,setFollowUpQuery:ue,isSearching:me,setIsSearching:pe,showResults:fe,setShowResults:ge,activeAnswerIndex:Ie,setActiveAnswerIndex:Se,conversationId:Ae,setConversationId:Re,clearConversationId:je,isLoadingConversation:Oe,setShowMobileCloseWidgetButton:De}=Nr(),ze={...Yr,...S},Le=he("enableFileAttachment",!1),Fe=_||Le,Ue=he(pn,!1),{toasts:Qe,showToast:Me,dismissToast:Ve}=function(e=3e3){const[n,a]=t([]),s=i(0),o=r(t=>{const r=++s.current;a(e=>[...e,{id:r,message:t}]),setTimeout(()=>{a(e=>e.filter(e=>e.id!==r))},e)},[e]),c=r(e=>{a(t=>t.filter(t=>t.id!==e))},[]);return{toasts:n,showToast:o,dismissToast:c}}(),qe=r(()=>{let e=Ae;return e||(e=ye(),Re(e)),e},[Ae,Re]),{attachedFiles:Ke,isUploading:Be,addFiles:He,removeFile:Ge,clearAttachedFiles:We,getUploadedAttachments:Je}=function({uploadEndpoint:e,headers:n,getConversationId:a,onError:s}){const[o,i]=t([]),c=r(e=>{i(t=>{const r=t.find(t=>t.id===e);return r&&URL.revokeObjectURL(r.preview),t.filter(t=>t.id!==e)})},[]),l=r(t=>{if(0===t.length)return;const r=t.filter(e=>tn[e.type]?!(e.size>10485760&&(s?.(`Image "${e.name}" exceeds the 10MB size limit.`),1)):(s?.("Image type is not supported. Please use JPEG, PNG, GIF, or WebP."),!1)),c=5-o.length;if(0===c)return void s?.("Maximum 5 images reached.");const l=r.slice(0,c);if(0===l.length)return;if(l.length<r.length&&s?.("Maximum 5 images. Some images were not attached."),!e)return console.error("[useFileAttachment] uploadEndpoint is not configured — file attachment is unavailable."),void s?.("Something went wrong. Please try again later.");const d=l.map(e=>({id:"file-"+ ++rn,file:e,preview:URL.createObjectURL(e),status:"uploading",attachmentType:tn[e.type]}));i(e=>[...e,...d]);const u=a();d.forEach(t=>{(async()=>{try{const{publicUrl:r}=await ve({endpoint:e,conversationId:u,file:t.file,headers:n});i(e=>e.map(e=>e.id===t.id?{...e,status:"uploaded",publicUrl:r}:e))}catch(r){console.error("Upload failed:",r),s?.(`Failed to upload "${t.file.name}". Please try again.`),i(e=>{const r=e.find(e=>e.id===t.id);return r&&URL.revokeObjectURL(r.preview),e.filter(e=>e.id!==t.id)})}})()})},[o,e,n,a,s]),d=r(()=>{o.forEach(e=>URL.revokeObjectURL(e.preview)),i([])},[o]),u=r(()=>o.filter(e=>"uploaded"===e.status&&e.publicUrl).map(e=>({type:e.attachmentType,url:e.publicUrl,filename:e.file.name})),[o]),m=o.some(e=>"uploading"===e.status);return{attachedFiles:o,isUploading:m,addFiles:l,removeFile:c,clearAttachedFiles:d,getUploadedAttachments:u}}({uploadEndpoint:v,headers:I,getConversationId:qe,onError:Me}),[Ze,Xe]=t(s),[Ye,et]=t(m),[tt,rt]=t(!0),nt=i(null),at=i(null),st=i(null),ot=i([]),it=i(null),ct=i(null),lt=i(null),dt=i(null),ut=i(null),{suggestions:mt}=$e({query:ce,endpoint:$||"",allowedRegions:V,collectionId:Ze,headers:I,conversationId:Ae,delay:300}),{loadConversationById:pt}=en({loadConversationEndpoint:E,headers:I,mergedTextConfig:ze}),{showHistory:ht,setShowHistory:ft,conversations:gt,isLoadingHistory:yt,hasUnreadConversations:vt,isViewOnly:wt,setIsViewOnly:bt,handleSelectConversation:Et,completeActiveConversations:$t}=function({enabled:e=!1,conversationHistoryEndpoint:n,markConversationReadEndpoint:a,markConversationCompletedEndpoint:s,headers:c,userData:l,currentConversationId:d,loadConversationById:u,reconnectHandoff:m,resetHandoff:p}){const[h,f]=t(!1),[g,y]=t([]),[v,w]=t(!1),[b,E]=t(!1),$=i(null),x=i(c);x.current=c;const _=g.some(e=>e.hasUnread),k=l?.userId,N=c?.["x-bf-fingerprint"],C=!(!k&&!N);o(()=>{if(!e||!n||!C)return;let t=!1;return we({endpoint:n,headers:x.current,externalUserId:k}).then(e=>{t||y(e)}).catch(()=>{t||y([])}),()=>{t=!0}},[n,C,k,N]),o(()=>{if(!(e&&h&&n&&C))return;let t=!1;return w(!0),we({endpoint:n,headers:x.current,externalUserId:k}).then(e=>{t||y(e)}).catch(()=>{t||y([])}).finally(()=>{t||w(!1)}),()=>{t=!0}},[e,h,n,C,k,N]);const I=r(({conversationId:e,isHandoff:t,isCompleted:r})=>{d&&!b&&($.current=d),u(e),E(r),t?m?.(e):p?.(),a&&be({endpoint:a,conversationId:e,headers:x.current}).catch(()=>{}),f(!1)},[e,d,b,u,m,p,a]),S=r(()=>{if(!s)return;const e=g.filter(e=>"active"===e.status).map(e=>e.conversationId),t=new Set([$.current,b?null:d,...e].filter(e=>!!e));y(e=>e.map(e=>t.has(e.conversationId)?{...e,status:"completed"}:e)),t.forEach(e=>{Ee({endpoint:s,conversationId:e,headers:x.current}).catch(()=>{})}),$.current=null},[s,d,b,g]);return{showHistory:h,setShowHistory:f,conversations:g,isLoadingHistory:v,hasUnreadConversations:_,isViewOnly:b,setIsViewOnly:E,handleSelectConversation:I,completeActiveConversations:S}}({enabled:Ue,conversationHistoryEndpoint:ee,markConversationReadEndpoint:te,markConversationCompletedEndpoint:re,headers:I,userData:U??void 0,currentConversationId:Ae,loadConversationById:pt,reconnectHandoff:J,resetHandoff:Y}),{scrollToLastAnswer:xt,scrollToAnswer:_t}=((e,t,r)=>({scrollToLastAnswer:()=>{requestAnimationFrame(()=>{const r=e.current?.[e.current.length-1],n=t.current;if(r&&n){const e=r.getBoundingClientRect(),t=n.getBoundingClientRect(),a=n.scrollTop+(e.top-t.top)-80;n.scrollTo({top:a,behavior:"smooth"})}})},scrollToAnswer:r=>{requestAnimationFrame(()=>{const n=e.current?.[r],a=t.current;if(n&&a){const e=n.getBoundingClientRect(),t=a.getBoundingClientRect(),r=a.scrollTop+(e.top-t.top)-80;a.scrollTo({top:r,behavior:"smooth"})}})},scrollToBottom:()=>{setTimeout(()=>{r?.current&&t.current&&r.current.scrollIntoView({behavior:"smooth",block:"end"})},200)}}))(ot,it,dt),{subscribeToStateChanges:kt}=(()=>{const e=i([]),{showResults:t,answers:r,isLoadingConversation:n,loadError:a}=Nr();return o(()=>{const s={showResults:t,answers:r,isLoading:n,error:a};e.current.forEach(e=>e(s))},[t,r,n,a]),{subscribeToStateChanges:s=>(e.current.push(s),s({showResults:t,answers:r,isLoading:n,error:a}),()=>{e.current=e.current.filter(e=>e!==s)})}})(),{includePageEnabled:Nt,includePageLoading:Ct,includePageDisabled:It,handleIncludePageToggle:St,fetchPageContext:Pt}=(({isAgentAssist:e,apiKey:n,trackEvent:a})=>{const[s,i]=t(!1),[c,l]=t(!1),[d,u]=t(!1),m=r((e,t=5e3)=>new Promise((r,a)=>{const s=ye();let o;const i=e=>{e.data.requestId===s&&(clearTimeout(o),window.removeEventListener("message",i),r(e.data))};o=setTimeout(()=>{window.removeEventListener("message",i),a(new Error("Request timeout"))},t),window.addEventListener("message",i),window.parent.postMessage({...e,requestId:s,widgetKey:n},"*")}),[n]),p=r(async e=>{l(!0);try{if(e){if(!(await m({type:"REQUEST_PAGE_PERMISSION"})).granted)throw a?.("Include Page Permission Denied",{}),new Error("Permission denied");window.parent.postMessage({type:"UPDATE_PAGE_TOGGLE_STATE",enabled:!0,widgetKey:n},"*"),a?.("Include Page Enabled",{}),i(!0)}else window.parent.postMessage({type:"UPDATE_PAGE_TOGGLE_STATE",enabled:!1,widgetKey:n},"*"),a?.("Include Page Disabled",{}),i(!1)}catch(t){console.error("Failed to toggle include page:",t),i(!1)}finally{l(!1)}},[n,m,a]),h=r(async(t,r)=>{if(s&&e&&!d)try{l(!0);const e=await m({type:"REQUEST_PAGE_CONTENT"},5e3);return e.success&&e.content?(a?.("Page Content Included",{conversationId:t,searchQuery:r,contentLength:e.content.length}),[{type:"text",text:`I am currently viewing this web page:\n\n${e.content}`}]):void 0}catch(n){return console.error("Failed to fetch page content:",n),void a?.("Page Content Fetch Failed",{conversationId:t,searchQuery:r})}finally{l(!1)}},[s,e,d,m,a]);return o(()=>{if(!e)return;const t=e=>{const t=e.data;"INCLUDE_PAGE_STATE"===t.type&&(i(t.enabled||!1),u(t.disabled||!1))};return window.addEventListener("message",t),()=>window.removeEventListener("message",t)},[e]),{includePageEnabled:s,includePageLoading:c,includePageDisabled:d,handleIncludePageToggle:p,fetchPageContext:h}})({isAgentAssist:B,apiKey:h??"unknown",trackEvent:R}),Tt=async({reader:e,searchQueryId:t,conversationId:r,onFirstEvent:n})=>{ut.current=e;let a="";try{let s,o,i=!1,c=!0,l=!1;for(;({done:i,value:o}=await e.read()),!i&&ut.current===e;){c&&(c=!1,n?.());const e=(new TextDecoder).decode(o).split(/\n\n/).filter(e=>e.startsWith("data: ")).map(e=>e.replace(/^data: /,"").trim());for(const n of e)try{if("[DONE]"===n)continue;const e=JSON.parse(n);if("status-message"===e.type&&ie(gr({message:e.message})),"answer-text-chunk"===e.type){a+=e.content,ie(dr({text:e.content}));const t=X(a);if(l=t.uncertain,l){const e=ze.uncertaintyFallbackText?.[t.language??"en"]??a??"I don't know.";ie(pr({uncertaintyText:e}))}}"answer-error"===e.type&&ie(ur({error:ze.errorText||e.message})),"action-buttons"===e.type&&(s=e.searchIntentId,ie(vr({searchIntentId:s,actions:e.actions}))),"get-action-inputs"===e.type&&(s=e.searchIntentId,ie(yr({searchIntentId:e.searchIntentId,inputs:e.inputs,actionId:e.actionId,schema:e.schema,initialValues:e.values,onSubmit:async n=>{if("client_execution"===e.actionType){const o=await(a=e.actionKey,s=n,new Promise(e=>{const t=crypto.randomUUID(),r=n=>{n.data.messageId===t&&"CLIENT_EXECUTION_RESULT"===n.data.type&&(window.removeEventListener("message",r),e(n.data.result))};window.addEventListener("message",r),window.parent.postMessage({type:"CLIENT_EXECUTION",messageId:t,actionKey:a,inputs:s},"*"),setTimeout(()=>{window.removeEventListener("message",r),e({success:!1,reason:`Client Action handler with key ${a} timed out`})},5e3)}));return jt({searchQueryId:t,conversationId:r,searchIntentId:e.searchIntentId,actionId:e.actionId,results:o})}var a,s;return"run_workflow"===e.actionType?(ie(hr()),ie(gr({message:ze.loadingAnswerText})),At({searchQueryId:t,conversationId:r,parameters:n})):Rt({searchQueryId:t,conversationId:r,searchIntentId:e.searchIntentId,actionId:e.actionId,parameters:n})}}))),"citations"===e.type&&ie(lr({searchQueryId:t,results:e.data,state:"completed"}))}catch{console.warn("Failed to parse answer stream block")}}return{answer:a,searchIntentId:s,isUncertain:l}}catch(s){if(ut.current!==e)return{answer:"",searchIntentId:void 0,isUncertain:!1};throw s}finally{ut.current===e&&(ut.current=null,e.releaseLock())}},At=async({searchQueryId:e,conversationId:t,context:r,attachments:n,parameters:a})=>{try{const s=(async(e,t)=>{if(P&&!x)try{return await Ce({endpoint:P,searchQueryId:e,headers:I,conversationId:t})}catch(r){return void console.error("Error fetching follow-up questions:",r)}})(e),o=await Ne({endpoint:y,headers:I,body:{type:"generate-for-query",conversationId:t,searchQueryId:e,profileId:U?.userId,...r&&{context:r},...n?.length&&{attachments:n},...a&&{parameters:a}}}),i=o.body?.getReader();if(!i)return;const{answer:c,searchIntentId:l,isUncertain:d}=await Tt({reader:i,searchQueryId:e,conversationId:t,onFirstEvent:()=>{R?.("First Streamed Answer Chunk Received",{conversationId:t,searchQueryId:e})}});if(!c)return;s.then(e=>{e&&e.length>0&&!l&&ie((({questions:e,index:t})=>({type:Wt,payload:{questions:e,index:t}}))({questions:e}))}),R?.(d?"Answer Not Found":"Answer Found",{conversationId:t,searchQueryId:e})}catch(s){console.error("Error generating answer for query:",s),ie(ur({error:ze.errorText||"Sorry, we were unable to process the request right now. Please try again in a moment."}))}finally{ie(mr())}},Rt=async({searchQueryId:e,searchIntentId:t,conversationId:r,actionId:n,parameters:a})=>{ie(hr());try{const s=await Ne({endpoint:y,headers:I,body:{type:"invoke-action",conversationId:r,searchQueryId:e,searchIntentId:t,actionId:n,parameters:a,profileId:U?.userId}}),o=s.body?.getReader();if(!o)return;await Tt({reader:o,searchQueryId:e})}catch(s){console.error("Error generating answer for action:",s),ie(ur({error:ze.errorText||"Sorry, we were unable to process the request right now. Please try again in a moment."}))}finally{ie(mr()),pe(!1)}},jt=async({searchQueryId:e,searchIntentId:t,conversationId:r,actionId:n,results:a})=>{ie(hr());try{const s=await Ne({endpoint:y,headers:I,body:{type:"client-execution-result",conversationId:r,searchQueryId:e,searchIntentId:t,actionId:n,results:a,profileId:U?.userId}}),o=s.body?.getReader();if(!o)return;await Tt({reader:o,searchQueryId:e})}catch(s){console.error("Error generating answer for action:",s),ie(ur({error:ze.errorText||"Sorry, we were unable to process the request right now. Please try again in a moment."}))}finally{ie(mr()),pe(!1)}},Ot=async({searchQuery:e,conversationId:t,attributes:r,secretAttributes:n,allowedRegions:a,knowledgeGroupCollectionIds:s})=>{const o=s??Ze,i=await ke({endpoint:g,query:e,collectionId:o,headers:I,conversationId:t,attributes:r,secretAttributes:n,allowedRegions:a,source:B?"agent_assist":void 0});if(0!==i.results.length||i.isAgenticResponse)return ie(lr({searchQueryId:i.searchQueryId,results:i.results})),i.searchQueryId;R?.("No Articles Found",{conversationId:t,searchQuery:e})},Dt=async({searchQuery:e=ce.trim(),event:t})=>{if(!e)return;const r=Ae||ye();Re(r);const n=Je();We(),pe(!0),ge(!0),Se(oe.length),xt(),ie((({id:e,query:t,attachments:r})=>({type:Kt,payload:{id:e,query:t,attachments:r}}))({query:e,attachments:n})),await Promise.resolve(),lt.current?.focus();const a=await Pt(r,e);if(ne&&ne.length>0&&!nt.current)return at.current={searchQuery:e,conversationId:r,attributes:{...U},secretAttributes:M,allowedRegions:V,pageContext:a??void 0,fileAttachments:n.length>0?n:void 0},ie((({index:e}={})=>({type:sr,payload:{index:e}}))()),void pe(!1);try{const s={...U},o=nt.current?.collectionIds,i=await Ot({searchQuery:e,conversationId:r,attributes:s,secretAttributes:M,allowedRegions:V,knowledgeGroupCollectionIds:o});i?(t&&R?.(t.name,{conversationId:r,searchQuery:e,searchQueryId:i,...t.metaData}),await At({searchQueryId:i,conversationId:r,context:a,attachments:n.length>0?n:void 0})):ie(fr())}catch(s){console.error("Error generating answer:",s),t&&R?.(`${t.name} - Search Error`,{conversationId:r,searchQuery:e,...t.metaData}),ie(ur({error:ze.errorText||"Sorry, we were unable to process the request right now. Please try again in a moment."}))}finally{pe(!1)}},zt=async e=>{nt.current=e;const t=at.current;if(t){at.current=null,ie((({index:e}={})=>({type:or,payload:{index:e}}))()),pe(!0);try{const r=await Ot({searchQuery:t.searchQuery,conversationId:t.conversationId,attributes:t.attributes,secretAttributes:t.secretAttributes,allowedRegions:t.allowedRegions,knowledgeGroupCollectionIds:e.collectionIds});r?(R?.("Knowledge Group Selected",{conversationId:t.conversationId,searchQuery:t.searchQuery,searchQueryId:r,knowledgeGroupId:e.id,knowledgeGroupName:e.name}),await At({searchQueryId:r,conversationId:t.conversationId,context:t.pageContext,attachments:t.fileAttachments})):ie(fr())}catch(r){console.error("Error generating answer after group selection:",r),ie(ur({error:ze.errorText||"Sorry, we were unable to process the request right now. Please try again in a moment."}))}finally{pe(!1)}}},Lt=e=>{if($t(),bt(!1),Y?.(),ut.current){const e=ut.current;ut.current=null,function(e){try{e.cancel().catch(e=>{console.warn("Error cancelling stream reader:",e)});try{e.releaseLock()}catch(t){console.warn("Error releasing stream reader lock:",t)}}catch(r){console.warn("Error cancelling stream reader:",r);try{e.releaseLock()}catch(t){console.warn("Error releasing stream reader lock:",t)}}}(e)}pe(!1),le(""),ue(""),ge(!1),ie(cr()),Se(0),We(),je(),nt.current=null,at.current=null,R?.("New Thread Created",{oldConversationId:Ae}),st.current&&(st.current.style.height="auto"),e&&(le(e),Dt({searchQuery:e,event:{name:"New Thread Created with Query"}}))};l(ae,()=>({createNewThread:Lt,showFollowUpThread:e=>{rt(e)},subscribeToStateChanges:kt,focusSearchField:()=>ct.current?.focus()||lt.current?.focus(),showCloseButton:(e=!0)=>{De(e)},loadConversation:pt})),o(()=>{Xe(s)},[s]),o(()=>{et(m)},[m]);const Ft=async(e,t,r)=>{if(w){ie((({feedback:e,index:t})=>({type:Xt,payload:{feedback:e,index:t}}))({feedback:e,index:r}));try{await _e({endpoint:w,searchQueryId:t,response:e,headers:I,conversationId:Ae}),R?.("accept"===e?"Answer Accepted":"Answer Rejected",{conversationId:Ae,searchQueryId:t})}catch(n){console.error("Error sending feedback:",n),ie((({index:e}={})=>({type:Yt,payload:{index:e}}))({index:r}))}}},Ut=async e=>{const t=void 0!==e?e:de;t.trim()&&(le(t),ue(""),await Dt({searchQuery:t,event:{name:"Follow-up Search Field Submitted"}}))};o(()=>{const e=()=>{new URLSearchParams(window.location.search).get("conversation")||(le(""),ue(""),ge(!1),ie(cr()),Se(0),We(),st.current&&(st.current.style.height="auto"))};return window.addEventListener("popstate",e),()=>window.removeEventListener("popstate",e)},[]);const Mt=e=>{R?.("Follow-up Question Clicked",{conversationId:Ae,question:e}),Dt({searchQuery:e,event:{name:"Follow-up Question Clicked"}})},Vt=({action:e,searchQueryId:t,query:r,answer:n})=>{R?.("Next Best Action Clicked",{conversationId:Ae,searchQueryId:t,action:e.label});const a=((e,t)=>({conversationId:t,messages:e.map(e=>({question:e.question,answer:Qt(e.blocks)}))}))(oe,Ae);L?.({action:e,searchQueryId:t,query:r,answer:n,conversation:a})};return o(()=>{const e=it.current;if(!e||!K)return;let t=0,r=null;const n=()=>{const r=(()=>{const t=e.firstElementChild,r=t?.scrollHeight??e.scrollHeight,n=document.querySelector('[data-name="BrandFooter"]')?.clientHeight??0,a=document.querySelector('[data-name="Header"]')?.clientHeight??0,s=fe&&tt?70:0,o=document.querySelector('[data-name="ChatSearch"]')?.clientHeight??0,i=r+n+s+a+32;return fe?Math.max(i,o):i})();r>0&&r!==t&&(t=r,window.parent.postMessage({type:"RESIZE_IFRAME",height:r,widgetKey:h},"*"))},a=setTimeout(n,100),s=new ResizeObserver(()=>{null!==r&&cancelAnimationFrame(r),r=requestAnimationFrame(()=>{n(),r=null})}),o=e.firstElementChild;return o&&s.observe(o),s.observe(e),()=>{clearTimeout(a),null!==r&&cancelAnimationFrame(r),s.disconnect()}},[K,h,fe,tt]),/* @__PURE__ */e.createElement("div",{className:Z("w-full relative h-dvh flex flex-col justify-between @container","md:h-auto md:p-4 md:bg-dark-100",T),"data-name":"ChatSearch",style:q},
|
|
83
|
-
/* @__PURE__ */e.createElement(nn,{toasts:
|
|
84
|
-
/* @__PURE__ */e.createElement(Pe,{className:"w-full relative h-auto flex-grow [&>[data-radix-scroll-area-viewport]>div:first-child]:!block",ref:
|
|
85
|
-
/* @__PURE__ */e.createElement(u,null,
|
|
86
|
-
/* @__PURE__ */e.createElement(Vr,{index:r,blocks:t.blocks,question:t.question,attachments:t.attachments,state:t.state,searchResults:t.searchResults,searchQueryId:t.searchQueryId,searchIntentId:t.searchIntentId,hideCitations:H,feedback:t.feedback,onFeedback:e=>{
|
|
82
|
+
/* @__PURE__ */e.createElement("div",{className:"container flex flex-col items-center justify-center p-3 gap-2 text-center"},/* @__PURE__ */e.createElement("span",{className:"text-xs text-muted-foreground"},r),/* @__PURE__ */e.createElement("p",{className:"m-0 text-sm font-medium text-foreground"},"Still need help?"),/* @__PURE__ */e.createElement("button",{type:"button",onClick:t,className:"h-8 rounded-md px-4 text-sm bg-primary text-primary-foreground"},"Start new conversation")))}const pn="enableHistoryTab",hn=[p],fn=[m],gn={p:({children:t})=>/* @__PURE__ */e.createElement("span",null,t)},yn=c(({suggestions:n=[],collections:a=[],selectedCollectionId:s,onCollectionChange:c,selectedRegion:m,onRegionChange:p,apiKey:h,fetchRegionConfig:f,searchEndpoint:g,answerStreamEndpoint:y,uploadEndpoint:v,feedbackEndpoint:w,feedbackReasonEndpoint:b,loadConversationEndpoint:E,autocompleteEndpoint:$,disableFollowUpQuestions:x=!1,enableFileAttachment:_=!1,disableFeedback:k=!1,disclaimer:N,offset:C=0,headers:I,textConfig:S={},followUpQuestionsEndpoint:P,className:T,onToggleSizeButtonClick:A,trackEvent:R,onCloseWidget:j,isWidgetMode:O=!0,nextBestActions:D,bodyActionButtons:z,onNextBestActionClick:L,userData:U,redirectRules:Q,secretAttributes:M,allowedRegions:V,style:q,isSearchWidget:K=!1,isAgentAssist:B=!1,hideCitations:H=!1,conversationInlineSlot:G,liveHumanAgentChatSlot:W,reconnectHandoff:J,resetHandoff:Y,handoffActive:ee=!1,conversationHistoryEndpoint:te,markConversationReadEndpoint:re,markConversationCompletedEndpoint:ne,knowledgeSourceGroups:ae},oe)=>{const{answers:ie,answerListDispatch:ce,query:le,setQuery:de,followUpQuery:ue,setFollowUpQuery:me,isSearching:pe,setIsSearching:fe,showResults:ge,setShowResults:Ie,activeAnswerIndex:Se,setActiveAnswerIndex:Ae,conversationId:Re,setConversationId:je,clearConversationId:Oe,isLoadingConversation:De,setShowMobileCloseWidgetButton:ze}=Nr(),Le={...Yr,...S},Fe=he("enableFileAttachment",!1),Ue=_||Fe,Qe=he(pn,!1),{toasts:Me,showToast:Ve,dismissToast:qe}=function(e=3e3){const[n,a]=t([]),s=i(0),o=r(t=>{const r=++s.current;a(e=>[...e,{id:r,message:t}]),setTimeout(()=>{a(e=>e.filter(e=>e.id!==r))},e)},[e]),c=r(e=>{a(t=>t.filter(t=>t.id!==e))},[]);return{toasts:n,showToast:o,dismissToast:c}}(),Ke=r(()=>{let e=Re;return e||(e=ye(),je(e)),e},[Re,je]),{attachedFiles:Be,isUploading:He,addFiles:Ge,removeFile:We,clearAttachedFiles:Je,getUploadedAttachments:Ze}=function({uploadEndpoint:e,headers:n,getConversationId:a,onError:s}){const[o,i]=t([]),c=r(e=>{i(t=>{const r=t.find(t=>t.id===e);return r&&URL.revokeObjectURL(r.preview),t.filter(t=>t.id!==e)})},[]),l=r(t=>{if(0===t.length)return;const r=t.filter(e=>tn[e.type]?!(e.size>10485760&&(s?.(`Image "${e.name}" exceeds the 10MB size limit.`),1)):(s?.("Image type is not supported. Please use JPEG, PNG, GIF, or WebP."),!1)),c=5-o.length;if(0===c)return void s?.("Maximum 5 images reached.");const l=r.slice(0,c);if(0===l.length)return;if(l.length<r.length&&s?.("Maximum 5 images. Some images were not attached."),!e)return console.error("[useFileAttachment] uploadEndpoint is not configured — file attachment is unavailable."),void s?.("Something went wrong. Please try again later.");const d=l.map(e=>({id:"file-"+ ++rn,file:e,preview:URL.createObjectURL(e),status:"uploading",attachmentType:tn[e.type]}));i(e=>[...e,...d]);const u=a();d.forEach(t=>{(async()=>{try{const{publicUrl:r}=await ve({endpoint:e,conversationId:u,file:t.file,headers:n});i(e=>e.map(e=>e.id===t.id?{...e,status:"uploaded",publicUrl:r}:e))}catch(r){console.error("Upload failed:",r),s?.(`Failed to upload "${t.file.name}". Please try again.`),i(e=>{const r=e.find(e=>e.id===t.id);return r&&URL.revokeObjectURL(r.preview),e.filter(e=>e.id!==t.id)})}})()})},[o,e,n,a,s]),d=r(()=>{o.forEach(e=>URL.revokeObjectURL(e.preview)),i([])},[o]),u=r(()=>o.filter(e=>"uploaded"===e.status&&e.publicUrl).map(e=>({type:e.attachmentType,url:e.publicUrl,filename:e.file.name})),[o]),m=o.some(e=>"uploading"===e.status);return{attachedFiles:o,isUploading:m,addFiles:l,removeFile:c,clearAttachedFiles:d,getUploadedAttachments:u}}({uploadEndpoint:v,headers:I,getConversationId:Ke,onError:Ve}),[Xe,Ye]=t(s),[et,tt]=t(m),[rt,nt]=t(!0),at=i(null),st=i(ee);st.current=ee;const ot=i(null),it=i(null),ct=i([]),lt=i(null),dt=i(null),ut=i(null),mt=i(null),pt=i(null),{suggestions:ht}=$e({query:le,endpoint:$||"",allowedRegions:V,collectionId:Xe,headers:I,conversationId:Re,delay:300}),{loadConversationById:ft}=en({loadConversationEndpoint:E,headers:I,mergedTextConfig:Le}),{showHistory:gt,setShowHistory:yt,conversations:vt,isLoadingHistory:wt,hasUnreadConversations:bt,isViewOnly:Et,setIsViewOnly:$t,handleSelectConversation:xt,completeActiveConversations:_t}=function({enabled:e=!1,conversationHistoryEndpoint:n,markConversationReadEndpoint:a,markConversationCompletedEndpoint:s,headers:c,userData:l,currentConversationId:d,loadConversationById:u,reconnectHandoff:m,resetHandoff:p}){const[h,f]=t(!1),[g,y]=t([]),[v,w]=t(!1),[b,E]=t(!1),$=i(null),x=i(c);x.current=c;const _=g.some(e=>e.hasUnread),k=l?.userId,N=c?.["x-bf-fingerprint"],C=!(!k&&!N);o(()=>{if(!e||!n||!C)return;let t=!1;return we({endpoint:n,headers:x.current,externalUserId:k}).then(e=>{t||y(e)}).catch(()=>{t||y([])}),()=>{t=!0}},[n,C,k,N]),o(()=>{if(!(e&&h&&n&&C))return;let t=!1;return w(!0),we({endpoint:n,headers:x.current,externalUserId:k}).then(e=>{t||y(e)}).catch(()=>{t||y([])}).finally(()=>{t||w(!1)}),()=>{t=!0}},[e,h,n,C,k,N]);const I=r(({conversationId:e,isHandoff:t,isCompleted:r})=>{d&&!b&&($.current=d),u(e),E(r),t?m?.(e):p?.(),a&&be({endpoint:a,conversationId:e,headers:x.current}).catch(()=>{}),f(!1)},[e,d,b,u,m,p,a]),S=r(()=>{if(!s)return;const e=g.filter(e=>"active"===e.status).map(e=>e.conversationId),t=new Set([$.current,b?null:d,...e].filter(e=>!!e));y(e=>e.map(e=>t.has(e.conversationId)?{...e,status:"completed"}:e)),t.forEach(e=>{Ee({endpoint:s,conversationId:e,headers:x.current}).catch(()=>{})}),$.current=null},[s,d,b,g]);return{showHistory:h,setShowHistory:f,conversations:g,isLoadingHistory:v,hasUnreadConversations:_,isViewOnly:b,setIsViewOnly:E,handleSelectConversation:I,completeActiveConversations:S}}({enabled:Qe,conversationHistoryEndpoint:te,markConversationReadEndpoint:re,markConversationCompletedEndpoint:ne,headers:I,userData:U??void 0,currentConversationId:Re,loadConversationById:ft,reconnectHandoff:J,resetHandoff:Y}),{scrollToLastAnswer:kt,scrollToAnswer:Nt}=((e,t,r)=>({scrollToLastAnswer:()=>{requestAnimationFrame(()=>{const r=e.current?.[e.current.length-1],n=t.current;if(r&&n){const e=r.getBoundingClientRect(),t=n.getBoundingClientRect(),a=n.scrollTop+(e.top-t.top)-80;n.scrollTo({top:a,behavior:"smooth"})}})},scrollToAnswer:r=>{requestAnimationFrame(()=>{const n=e.current?.[r],a=t.current;if(n&&a){const e=n.getBoundingClientRect(),t=a.getBoundingClientRect(),r=a.scrollTop+(e.top-t.top)-80;a.scrollTo({top:r,behavior:"smooth"})}})},scrollToBottom:()=>{setTimeout(()=>{r?.current&&t.current&&r.current.scrollIntoView({behavior:"smooth",block:"end"})},200)}}))(ct,lt,mt),{subscribeToStateChanges:Ct}=(()=>{const e=i([]),{showResults:t,answers:r,isLoadingConversation:n,loadError:a}=Nr();return o(()=>{const s={showResults:t,answers:r,isLoading:n,error:a};e.current.forEach(e=>e(s))},[t,r,n,a]),{subscribeToStateChanges:s=>(e.current.push(s),s({showResults:t,answers:r,isLoading:n,error:a}),()=>{e.current=e.current.filter(e=>e!==s)})}})(),{includePageEnabled:It,includePageLoading:St,includePageDisabled:Pt,handleIncludePageToggle:Tt,fetchPageContext:At}=(({isAgentAssist:e,apiKey:n,trackEvent:a})=>{const[s,i]=t(!1),[c,l]=t(!1),[d,u]=t(!1),m=r((e,t=5e3)=>new Promise((r,a)=>{const s=ye();let o;const i=e=>{e.data.requestId===s&&(clearTimeout(o),window.removeEventListener("message",i),r(e.data))};o=setTimeout(()=>{window.removeEventListener("message",i),a(new Error("Request timeout"))},t),window.addEventListener("message",i),window.parent.postMessage({...e,requestId:s,widgetKey:n},"*")}),[n]),p=r(async e=>{l(!0);try{if(e){if(!(await m({type:"REQUEST_PAGE_PERMISSION"})).granted)throw a?.("Include Page Permission Denied",{}),new Error("Permission denied");window.parent.postMessage({type:"UPDATE_PAGE_TOGGLE_STATE",enabled:!0,widgetKey:n},"*"),a?.("Include Page Enabled",{}),i(!0)}else window.parent.postMessage({type:"UPDATE_PAGE_TOGGLE_STATE",enabled:!1,widgetKey:n},"*"),a?.("Include Page Disabled",{}),i(!1)}catch(t){console.error("Failed to toggle include page:",t),i(!1)}finally{l(!1)}},[n,m,a]),h=r(async(t,r)=>{if(s&&e&&!d)try{l(!0);const e=await m({type:"REQUEST_PAGE_CONTENT"},5e3);return e.success&&e.content?(a?.("Page Content Included",{conversationId:t,searchQuery:r,contentLength:e.content.length}),[{type:"text",text:`I am currently viewing this web page:\n\n${e.content}`}]):void 0}catch(n){return console.error("Failed to fetch page content:",n),void a?.("Page Content Fetch Failed",{conversationId:t,searchQuery:r})}finally{l(!1)}},[s,e,d,m,a]);return o(()=>{if(!e)return;const t=e=>{const t=e.data;"INCLUDE_PAGE_STATE"===t.type&&(i(t.enabled||!1),u(t.disabled||!1))};return window.addEventListener("message",t),()=>window.removeEventListener("message",t)},[e]),{includePageEnabled:s,includePageLoading:c,includePageDisabled:d,handleIncludePageToggle:p,fetchPageContext:h}})({isAgentAssist:B,apiKey:h??"unknown",trackEvent:R}),Rt=async({reader:e,searchQueryId:t,conversationId:r,onFirstEvent:n})=>{pt.current=e;let a="";try{let s,o,i=!1,c=!0,l=!1;for(;({done:i,value:o}=await e.read()),!i&&pt.current===e;){c&&(c=!1,n?.());const e=(new TextDecoder).decode(o).split(/\n\n/).filter(e=>e.startsWith("data: ")).map(e=>e.replace(/^data: /,"").trim());for(const n of e)try{if("[DONE]"===n)continue;const e=JSON.parse(n);if("status-message"===e.type&&ce(gr({message:e.message})),"answer-text-chunk"===e.type){a+=e.content,ce(dr({text:e.content}));const t=X(a);if(l=t.uncertain,l){const e=Le.uncertaintyFallbackText?.[t.language??"en"]??a??"I don't know.";ce(pr({uncertaintyText:e}))}}"answer-error"===e.type&&ce(ur({error:Le.errorText||e.message})),"action-buttons"===e.type&&(s=e.searchIntentId,ce(vr({searchIntentId:s,actions:e.actions}))),"get-action-inputs"===e.type&&(s=e.searchIntentId,ce(yr({searchIntentId:e.searchIntentId,inputs:e.inputs,actionId:e.actionId,schema:e.schema,initialValues:e.values,onSubmit:async n=>{if("client_execution"===e.actionType){const o=await(a=e.actionKey,s=n,new Promise(e=>{const t=crypto.randomUUID(),r=n=>{n.data.messageId===t&&"CLIENT_EXECUTION_RESULT"===n.data.type&&(window.removeEventListener("message",r),e(n.data.result))};window.addEventListener("message",r),window.parent.postMessage({type:"CLIENT_EXECUTION",messageId:t,actionKey:a,inputs:s},"*"),setTimeout(()=>{window.removeEventListener("message",r),e({success:!1,reason:`Client Action handler with key ${a} timed out`})},5e3)}));return Dt({searchQueryId:t,conversationId:r,searchIntentId:e.searchIntentId,actionId:e.actionId,results:o})}var a,s;return"run_workflow"===e.actionType?(ce(hr()),ce(gr({message:Le.loadingAnswerText})),jt({searchQueryId:t,conversationId:r,parameters:n})):Ot({searchQueryId:t,conversationId:r,searchIntentId:e.searchIntentId,actionId:e.actionId,parameters:n})}}))),"citations"===e.type&&ce(lr({searchQueryId:t,results:e.data,state:"completed"}))}catch{console.warn("Failed to parse answer stream block")}}return{answer:a,searchIntentId:s,isUncertain:l}}catch(s){if(pt.current!==e)return{answer:"",searchIntentId:void 0,isUncertain:!1};throw s}finally{pt.current===e&&(pt.current=null,e.releaseLock())}},jt=async({searchQueryId:e,conversationId:t,context:r,attachments:n,parameters:a})=>{try{const s=(async(e,t)=>{if(P&&!x)try{return await Ce({endpoint:P,searchQueryId:e,headers:I,conversationId:t})}catch(r){return void console.error("Error fetching follow-up questions:",r)}})(e),o=await Ne({endpoint:y,headers:I,body:{type:"generate-for-query",conversationId:t,searchQueryId:e,profileId:U?.userId,...r&&{context:r},...n?.length&&{attachments:n},...a&&{parameters:a}}}),i=o.body?.getReader();if(!i)return;const{answer:c,searchIntentId:l,isUncertain:d}=await Rt({reader:i,searchQueryId:e,conversationId:t,onFirstEvent:()=>{R?.("First Streamed Answer Chunk Received",{conversationId:t,searchQueryId:e})}});if(!c)return;s.then(e=>{e&&e.length>0&&!l&&ce((({questions:e,index:t})=>({type:Wt,payload:{questions:e,index:t}}))({questions:e}))}),R?.(d?"Answer Not Found":"Answer Found",{conversationId:t,searchQueryId:e})}catch(s){console.error("Error generating answer for query:",s),ce(ur({error:Le.errorText||"Sorry, we were unable to process the request right now. Please try again in a moment."}))}finally{ce(mr())}},Ot=async({searchQueryId:e,searchIntentId:t,conversationId:r,actionId:n,parameters:a})=>{ce(hr());try{const s=await Ne({endpoint:y,headers:I,body:{type:"invoke-action",conversationId:r,searchQueryId:e,searchIntentId:t,actionId:n,parameters:a,profileId:U?.userId}}),o=s.body?.getReader();if(!o)return;await Rt({reader:o,searchQueryId:e})}catch(s){console.error("Error generating answer for action:",s),ce(ur({error:Le.errorText||"Sorry, we were unable to process the request right now. Please try again in a moment."}))}finally{ce(mr()),fe(!1)}},Dt=async({searchQueryId:e,searchIntentId:t,conversationId:r,actionId:n,results:a})=>{ce(hr());try{const s=await Ne({endpoint:y,headers:I,body:{type:"client-execution-result",conversationId:r,searchQueryId:e,searchIntentId:t,actionId:n,results:a,profileId:U?.userId}}),o=s.body?.getReader();if(!o)return;await Rt({reader:o,searchQueryId:e})}catch(s){console.error("Error generating answer for action:",s),ce(ur({error:Le.errorText||"Sorry, we were unable to process the request right now. Please try again in a moment."}))}finally{ce(mr()),fe(!1)}},zt=async({searchQuery:e,conversationId:t,attributes:r,secretAttributes:n,allowedRegions:a,knowledgeGroupCollectionIds:s})=>{const o=s??Xe,i=await ke({endpoint:g,query:e,collectionId:o,headers:I,conversationId:t,attributes:r,secretAttributes:n,allowedRegions:a,source:B?"agent_assist":void 0});if(0!==i.results.length||i.isAgenticResponse)return ce(lr({searchQueryId:i.searchQueryId,results:i.results})),i.searchQueryId;R?.("No Articles Found",{conversationId:t,searchQuery:e})},Lt=async({searchQuery:e=le.trim(),event:t})=>{if(!e)return;if(st.current)return;const r=Re||ye();je(r);const n=Ze();Je(),fe(!0),Ie(!0),Ae(ie.length),kt(),ce((({id:e,query:t,attachments:r})=>({type:Kt,payload:{id:e,query:t,attachments:r}}))({query:e,attachments:n})),await Promise.resolve(),ut.current?.focus();const a=await At(r,e);if(ae&&ae.length>0&&!at.current)return ot.current={searchQuery:e,conversationId:r,attributes:{...U},secretAttributes:M,allowedRegions:V,pageContext:a??void 0,fileAttachments:n.length>0?n:void 0},ce((({index:e}={})=>({type:sr,payload:{index:e}}))()),void fe(!1);try{const s={...U},o=at.current?.collectionIds,i=await zt({searchQuery:e,conversationId:r,attributes:s,secretAttributes:M,allowedRegions:V,knowledgeGroupCollectionIds:o});i?(t&&R?.(t.name,{conversationId:r,searchQuery:e,searchQueryId:i,...t.metaData}),await jt({searchQueryId:i,conversationId:r,context:a,attachments:n.length>0?n:void 0})):ce(fr())}catch(s){console.error("Error generating answer:",s),t&&R?.(`${t.name} - Search Error`,{conversationId:r,searchQuery:e,...t.metaData}),ce(ur({error:Le.errorText||"Sorry, we were unable to process the request right now. Please try again in a moment."}))}finally{fe(!1)}},Ft=async e=>{at.current=e;const t=ot.current;if(t){ot.current=null,ce((({index:e}={})=>({type:or,payload:{index:e}}))()),fe(!0);try{const r=await zt({searchQuery:t.searchQuery,conversationId:t.conversationId,attributes:t.attributes,secretAttributes:t.secretAttributes,allowedRegions:t.allowedRegions,knowledgeGroupCollectionIds:e.collectionIds});r?(R?.("Knowledge Group Selected",{conversationId:t.conversationId,searchQuery:t.searchQuery,searchQueryId:r,knowledgeGroupId:e.id,knowledgeGroupName:e.name}),await jt({searchQueryId:r,conversationId:t.conversationId,context:t.pageContext,attachments:t.fileAttachments})):ce(fr())}catch(r){console.error("Error generating answer after group selection:",r),ce(ur({error:Le.errorText||"Sorry, we were unable to process the request right now. Please try again in a moment."}))}finally{fe(!1)}}},Ut=e=>{if(_t(),$t(!1),Y?.(),st.current=!1,pt.current){const e=pt.current;pt.current=null,function(e){try{e.cancel().catch(e=>{console.warn("Error cancelling stream reader:",e)});try{e.releaseLock()}catch(t){console.warn("Error releasing stream reader lock:",t)}}catch(r){console.warn("Error cancelling stream reader:",r);try{e.releaseLock()}catch(t){console.warn("Error releasing stream reader lock:",t)}}}(e)}fe(!1),de(""),me(""),Ie(!1),ce(cr()),Ae(0),Je(),Oe(),at.current=null,ot.current=null,R?.("New Thread Created",{oldConversationId:Re}),it.current&&(it.current.style.height="auto"),e&&(de(e),Lt({searchQuery:e,event:{name:"New Thread Created with Query"}}))};l(oe,()=>({createNewThread:Ut,showFollowUpThread:e=>{nt(e)},subscribeToStateChanges:Ct,focusSearchField:()=>dt.current?.focus()||ut.current?.focus(),showCloseButton:(e=!0)=>{ze(e)},loadConversation:ft})),o(()=>{Ye(s)},[s]),o(()=>{tt(m)},[m]);const Mt=async(e,t,r)=>{if(w){ce((({feedback:e,index:t})=>({type:Xt,payload:{feedback:e,index:t}}))({feedback:e,index:r}));try{await _e({endpoint:w,searchQueryId:t,response:e,headers:I,conversationId:Re}),R?.("accept"===e?"Answer Accepted":"Answer Rejected",{conversationId:Re,searchQueryId:t})}catch(n){console.error("Error sending feedback:",n),ce((({index:e}={})=>({type:Yt,payload:{index:e}}))({index:r}))}}},Vt=async e=>{const t=void 0!==e?e:ue;t.trim()&&(de(t),me(""),await Lt({searchQuery:t,event:{name:"Follow-up Search Field Submitted"}}))};o(()=>{const e=()=>{new URLSearchParams(window.location.search).get("conversation")||(de(""),me(""),Ie(!1),ce(cr()),Ae(0),Je(),it.current&&(it.current.style.height="auto"))};return window.addEventListener("popstate",e),()=>window.removeEventListener("popstate",e)},[]);const qt=e=>{R?.("Follow-up Question Clicked",{conversationId:Re,question:e}),Lt({searchQuery:e,event:{name:"Follow-up Question Clicked"}})},Bt=({action:e,searchQueryId:t,query:r,answer:n})=>{R?.("Next Best Action Clicked",{conversationId:Re,searchQueryId:t,action:e.label});const a=((e,t)=>({conversationId:t,messages:e.map(e=>({question:e.question,answer:Qt(e.blocks)}))}))(ie,Re);L?.({action:e,searchQueryId:t,query:r,answer:n,conversation:a})};return o(()=>{const e=lt.current;if(!e||!K)return;let t=0,r=null;const n=()=>{const r=(()=>{const t=e.firstElementChild,r=t?.scrollHeight??e.scrollHeight,n=document.querySelector('[data-name="BrandFooter"]')?.clientHeight??0,a=document.querySelector('[data-name="Header"]')?.clientHeight??0,s=ge&&rt?70:0,o=document.querySelector('[data-name="ChatSearch"]')?.clientHeight??0,i=r+n+s+a+32;return ge?Math.max(i,o):i})();r>0&&r!==t&&(t=r,window.parent.postMessage({type:"RESIZE_IFRAME",height:r,widgetKey:h},"*"))},a=setTimeout(n,100),s=new ResizeObserver(()=>{null!==r&&cancelAnimationFrame(r),r=requestAnimationFrame(()=>{n(),r=null})}),o=e.firstElementChild;return o&&s.observe(o),s.observe(e),()=>{clearTimeout(a),null!==r&&cancelAnimationFrame(r),s.disconnect()}},[K,h,ge,rt]),/* @__PURE__ */e.createElement("div",{className:Z("w-full relative h-dvh flex flex-col justify-between @container","md:h-auto md:p-4 md:bg-dark-100",T),"data-name":"ChatSearch",style:q},
|
|
83
|
+
/* @__PURE__ */e.createElement(nn,{toasts:Me,onDismiss:qe}),(O||!ge)&&/* @__PURE__ */e.createElement(Xr,{showHistoryButton:Qe,isSearchWidget:K,"data-name":"Header",headerText:Le.headerText,onToggleSizeButtonClick:()=>{A?.()},onBackButtonClick:()=>{Ut()},onCloseWidgetClick:()=>j?.(),showHistory:gt,hasUnreadConversations:bt,onHistoryButtonClick:()=>yt(!0),onHistoryBackClick:()=>yt(!1),className:Z("@3xl:mb-4",{"!block":ge&&K})}),
|
|
84
|
+
/* @__PURE__ */e.createElement(Pe,{className:"w-full relative h-auto flex-grow [&>[data-radix-scroll-area-viewport]>div:first-child]:!block",ref:lt},
|
|
85
|
+
/* @__PURE__ */e.createElement(u,null,gt?/* @__PURE__ */e.createElement(un,{conversations:vt,isLoading:wt,onSelectConversation:xt}):De?/* @__PURE__ */e.createElement(an,null):ge?/* @__PURE__ */e.createElement(e.Fragment,null,/* @__PURE__ */e.createElement(d.div,{key:"results",initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},transition:{duration:.5},className:"w-full max-w-[100vw] space-y-4 p-3 md:p-0"},ie.map((t,r)=>/* @__PURE__ */e.createElement(d.div,{key:r,ref:e=>ct.current[r]=e,initial:{opacity:0,y:20},animate:{opacity:1,y:0},transition:{duration:.5,delay:.1*r},className:"space-y-4 last:!mb-8"},
|
|
86
|
+
/* @__PURE__ */e.createElement(Vr,{index:r,blocks:t.blocks,question:t.question,attachments:t.attachments,state:t.state,searchResults:t.searchResults,searchQueryId:t.searchQueryId,searchIntentId:t.searchIntentId,hideCitations:H,feedback:t.feedback,onFeedback:e=>{Mt(e,t.searchQueryId,r)},disableFeedback:k,textConfig:Le,redirectRules:Q,nextBestActions:D,actions:t.actions,handleActionClick:Bt,isLastAnswer:r===ie.length-1,onFeedbackReasonSubmit:e=>{(async(e,t)=>{if(b)try{await xe({endpoint:b,searchQueryId:t,reason:e,headers:I})}catch(r){console.error("Error sending feedback reason:",r)}})(e,t.searchQueryId)},hasError:t.hasError,statusMessage:t.statusMessage,knowledgeSourceGroups:ae,onKnowledgeGroupSelect:e=>{Ft(e)}}),r===ie.length-1&&!ee&&!x&&t.followUpQuestions&&"completed"===t.state&&!t.hasError&&/* @__PURE__ */e.createElement(Kr,{questions:t.followUpQuestions,onQuestionClick:qt}))))):/* @__PURE__ */e.createElement(e.Fragment,null,/* @__PURE__ */e.createElement(d.div,{key:"search",initial:{opacity:0,y:20},animate:{opacity:1,y:0},transition:{duration:.5},className:"w-full md:space-y-4"},
|
|
87
87
|
/* @__PURE__ */e.createElement("div",{className:Z("pb-4",K?"bg-transparent p-3 md:p-0":"px-3 bg-primary md:p-0 md:bg-transparent")},
|
|
88
88
|
/* @__PURE__ */e.createElement(d.div,{initial:{opacity:0,y:20},animate:{opacity:1,y:0},transition:{duration:.5,delay:.4}},
|
|
89
|
-
/* @__PURE__ */e.createElement(Gr,{ref:
|
|
90
|
-
/* @__PURE__ */e.createElement(Te,{suggestions:n,onQuestionClick:e=>{if(e.conversationId)return R?.("Recent Conversation Clicked",{conversationId:
|
|
89
|
+
/* @__PURE__ */e.createElement(Gr,{ref:dt,query:le,onQueryChange:e=>{var t;de(e),it.current&&((t=it.current).style.height="auto",t.style.height=`${t.scrollHeight}px`)},onSearch:()=>{(async(e=le.trim())=>{await Lt({searchQuery:e,event:{name:"Primary Field Search Submitted"}})})()},textConfig:Le,collections:a,currentCollectionId:Xe,onCollectionChange:e=>{Ye(e),c?.(e)},allowedRegions:V,currentRegion:et,onRegionChange:e=>{tt(e),p?.(e),R?.("Region Changed",{region:e,conversationId:Re})},apiKey:h,fetchRegionConfig:f,enableFileAttachment:Ue,attachedFiles:Be,isUploading:He,onAddFiles:Ge,onRemoveFile:We,isSearching:pe,autocompleteSuggestions:ht,onAutocompleteSuggestionSelect:e=>{Lt({searchQuery:e.question,event:{name:"Autocomplete Suggestion Clicked"}})},isAgentAssist:B,includePageEnabled:It,includePageLoading:St,includePageDisabled:Pt,onIncludePageToggle:Tt}))),
|
|
90
|
+
/* @__PURE__ */e.createElement(Te,{suggestions:n,onQuestionClick:e=>{if(e.conversationId)return R?.("Recent Conversation Clicked",{conversationId:Re,question:e.question}),void ft(e.conversationId);Lt({searchQuery:e.question,event:{name:"Suggested Question Clicked"}})},title:Le.suggestionsTitle}),O&&z&&z.length>0&&/* @__PURE__ */e.createElement("div",{className:"mt-4 mb-4 px-3 @3xl:px-0"},/* @__PURE__ */e.createElement("div",{className:"space-y-3"},/* @__PURE__ */e.createElement(Qr,{nextBestActions:z||[],onActionClick:e=>Bt({action:e,searchQueryId:"",query:"",answer:""})})))))),ge&&ie.length>1&&/* @__PURE__ */e.createElement("div",{className:"hidden lg:block"},/* @__PURE__ */e.createElement(Br,{questions:ie.map(e=>e.question),activeIndex:Se,onNavigate:e=>{Ae(e),Nt(e)},offset:C})),N&&O&&!(ge&&rt)&&/* @__PURE__ */e.createElement("div",{"data-name":"disclaimer",className:Z("mt-2 px-3 @3xl:px-0 text-xs text-dark-500 flex items-center gap-1 justify-center text-center w-full md:static md:mt-4 md:text-left md:flex md:gap-4 leading-5",K?"static mb-2 md:text-left [&>svg]:flex-shrink-0":"absolute bottom-12")},
|
|
91
91
|
/* @__PURE__ */e.createElement(se,{iconName:"Info",className:"size-4"}),
|
|
92
|
-
/* @__PURE__ */e.createElement(F,{className:"[&_a]:underline [&_a:hover]:no-underline",remarkPlugins:hn,rehypePlugins:fn,components:gn},N)),null!=G&&
|
|
93
|
-
/* @__PURE__ */e.createElement("div",{ref:
|
|
94
|
-
return e.createElement(Jr,{ref:
|
|
92
|
+
/* @__PURE__ */e.createElement(F,{className:"[&_a]:underline [&_a:hover]:no-underline",remarkPlugins:hn,rehypePlugins:fn,components:gn},N)),null!=G&&ge&&!gt&&/* @__PURE__ */e.createElement("div",{className:"-mt-6 w-full max-w-[100vw] px-3 pb-0 pt-0 text-foreground md:px-0"},G),
|
|
93
|
+
/* @__PURE__ */e.createElement("div",{ref:mt})),ge&&rt&&!Et&&!W&&!gt&&!ee&&(()=>{const t=ie.some(e=>"awaiting-knowledge-group"===e.state);/* @__PURE__ */
|
|
94
|
+
return e.createElement(Jr,{ref:ut,initialQuery:ue,onQueryChange:me,isSearching:pe,handleFollowUpSearch:Vt,textConfig:Le,enableFileAttachment:Ue,attachedFiles:Be,isUploading:He,onAddFiles:Ge,onRemoveFile:We,disabled:t})})(),ge&&Et&&!W&&!gt&&/* @__PURE__ */e.createElement(mn,{onStartNewConversation:()=>Ut()}),!gt&&W)});yn.displayName="ChatSearch";const vn=c(({featureFlags:t,...r},n)=>/* @__PURE__ */e.createElement(fe,{flags:t},/* @__PURE__ */e.createElement(kr,{searchPath:r.searchPath,contentTypeEndpoint:r.contentTypeEndpoint,widgetKey:r.apiKey},
|
|
95
95
|
/* @__PURE__ */e.createElement(yn,{...r,ref:n}))));vn.displayName="ChatSearch";export{vn as C,Dr as N,mn as R,kr as a,Zr as b,Nr as u,Or as v};
|
|
96
|
-
//# sourceMappingURL=ChatSearch.
|
|
96
|
+
//# sourceMappingURL=ChatSearch.BGtNmt-i.js.map
|