@hsafa/ui-sdk 0.3.0 → 0.3.1
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.cjs +14 -14
- package/dist/index.cjs.map +1 -1
- package/dist/index.js +14 -14
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -1,16 +1,16 @@
|
|
|
1
|
-
import {jsxs,jsx,Fragment}from'react/jsx-runtime';import nt,{createContext,useRef,useEffect,useState,useCallback,useMemo,useContext}from'react';import {createPortal}from'react-dom';import {useChat}from'@ai-sdk/react';import {DefaultChatTransport,lastAssistantMessageIsCompleteWithToolCalls}from'ai';import {Plus,History,ChevronRight,Trash2,File as File$1,Eye,X,Download}from'lucide-react';import {createRoot}from'react-dom/client';var Se={};var ko=({variant:e="primary",size:t="md",loading:n=false,disabled:o,children:r,className:l,...u})=>{let c=[Se.button,Se[e],Se[t],n&&Se.loading,l].filter(Boolean).join(" ");return jsxs("button",{className:c,disabled:o||n,...u,children:[n&&jsx("span",{className:Se.spinner}),jsx("span",{className:n?Se.hiddenText:void 0,children:r})]})};function Vt({show:e,onClick:t,resolvedColors:n,floatingButtonPosition:o}){if(!e)return null;let r={position:"fixed",bottom:typeof o.bottom=="number"?`${o.bottom}px`:o.bottom,right:o.right?typeof o.right=="number"?`${o.right}px`:o.right:void 0,top:o.top?typeof o.top=="number"?`${o.top}px`:o.top:void 0,left:o.left?typeof o.left=="number"?`${o.left}px`:o.left:void 0,zIndex:1e3};return jsx("button",{"aria-label":"Open chat",onClick:t,style:{...r,borderColor:n.borderColor,backgroundColor:n.accentColor,color:n.textColor,borderRadius:"50%",border:`1px solid ${n.borderColor}`,padding:"12px",boxShadow:"0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06)",transition:"all 0.2s",cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center"},onMouseEnter:l=>{l.currentTarget.style.borderColor=n.primaryColor,l.currentTarget.style.backgroundColor=`${n.accentColor}dd`;},onMouseLeave:l=>{l.currentTarget.style.borderColor=n.borderColor,l.currentTarget.style.backgroundColor=n.accentColor;},children:jsx("svg",{width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:jsx("path",{d:"M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"})})})}function Yt(e=true){let t=useRef(null),n=useRef(e);return useEffect(()=>{n.current=e;},[e]),useEffect(()=>{let o=t.current;if(!o)return;let r=new MutationObserver(()=>{n.current&&(o.scrollTop=o.scrollHeight);});return r.observe(o,{childList:true,subtree:true}),n.current&&(o.scrollTop=o.scrollHeight),()=>r.disconnect()},[]),t}function Jt(e,t){if(!e)return t;let n=e.endsWith("/")?e.slice(0,-1):e,o=t.startsWith("/")?t:`/${t}`;return `${n}${o}`}var St=25*1024*1024;function Qt(e){let[t,n]=useState([]),[o,r]=useState(false),l=useRef(null),u=useCallback(y=>{if(!y||Number.isNaN(y))return "0 B";let x=["B","KB","MB","GB","TB"],g=Math.min(x.length-1,Math.floor(Math.log(y)/Math.log(1024)));return `${(y/Math.pow(1024,g)).toFixed(g===0?0:1)} ${x[g]}`},[]),c=useCallback(async y=>{let x=new FormData;x.append("file",y);let g=await fetch(Jt(e,"/api/uploads"),{method:"POST",body:x});if(!g.ok){let i=await g.text().catch(()=>"");throw new Error(i||`Failed to upload ${y.name}`)}let C=await g.json();return {id:C.id,name:C.name||y.name,url:C.url,mimeType:C.mimeType||y.type||"application/octet-stream",size:typeof C.size=="number"?C.size:y.size}},[e]),w=useCallback(y=>{n(x=>x.filter(g=>g.id!==y));},[]),S=useCallback(async(y,x)=>{if(!y)return;let g=Array.isArray(y)?y:Array.from(y);x(null),r(true);let C=[];try{for(let i of g){if(i.size>St){x(`"${i.name}" exceeds the ${u(St)} limit.`);continue}try{let m=await c(i);C.push(m);}catch(m){console.error("Failed to upload attachment:",m),x(String(m?.message??`Failed to upload ${i.name}`));}}C.length&&n(i=>[...i,...C]);}finally{r(false);}},[c,u]),a=useCallback((y,x)=>{let g=[],C=(y||"").trim();C&&g.push({type:"text",text:C});for(let i of x||[]){let m=i.mimeType||"application/octet-stream";m.startsWith("image/")?g.push({type:"image",image:new URL(i.url),mediaType:m}):g.push({type:"file",data:i.url,mediaType:m,name:i.name});}return g},[]),M=useCallback(()=>{n([]);},[]);return {attachments:t,uploading:o,fileInputRef:l,formatBytes:u,handleRemoveAttachment:w,handleFileSelection:S,buildUserContent:a,clearAttachments:M,MAX_UPLOAD_SIZE:St}}var en=createContext(void 0);function ar({baseUrl:e,dir:t="ltr",theme:n="dark",children:o}){let[r,l]=useState(new Map),[u,c]=useState(new Map),[w,S]=useState(new Map),[a,M]=useState(new Map),y=useCallback((v,b)=>(l(k=>{let p=new Map(k);return p.set(String(v),b),p}),()=>{l(k=>{let p=new Map(k),$=p.get(String(v));return (!b||$===b)&&p.delete(String(v)),p});}),[]),x=useCallback((v,b)=>{l(k=>{let p=new Map(k),$=p.get(String(v));return (!b||$===b)&&p.delete(String(v)),p});},[]),g=useCallback((v,b)=>(c(k=>{let p=new Map(k);return p.set(String(v),b),p}),()=>{c(k=>{let p=new Map(k),$=p.get(String(v));return (!b||$===b)&&p.delete(String(v)),p});}),[]),C=useCallback((v,b)=>{c(k=>{let p=new Map(k),$=p.get(String(v));return (!b||$===b)&&p.delete(String(v)),p});},[]),i=useCallback((v,b)=>{S(k=>{let p=new Map(k);return b?p.set(v,true):p.delete(v),p});},[]),m=useCallback((v,b)=>{M(k=>{let p=new Map(k);return b?p.set(v,true):p.delete(v),p});},[]),f=useMemo(()=>Array.from(w.values()).some(v=>v),[w]),T=useMemo(()=>Array.from(a.values()).some(v=>v),[a]),R=useMemo(()=>({baseUrl:e,dir:t,theme:n,actions:r,components:u,registerAction:y,unregisterAction:x,registerComponent:g,unregisterComponent:C,isAnyStreaming:f,setStreamingState:i,isAnyChatOpen:T,setChatOpenState:m}),[e,t,n,r,u,y,x,g,C,f,i,T,m]);return jsx(en.Provider,{value:R,children:o})}function Le(){let e=useContext(en);return e||{baseUrl:void 0,actions:new Map,components:new Map,registerAction:()=>()=>{},unregisterAction:()=>{},registerComponent:()=>()=>{},unregisterComponent:()=>{},isAnyStreaming:false,setStreamingState:()=>{},isAnyChatOpen:false,setChatOpenState:()=>{}}}function se({IconComponent:e,...t}){return nt.createElement(e,t)}function At({icon:e,onClick:t,ariaLabel:n,resolvedColors:o,disabled:r=false,title:l}){return jsx("button",{"aria-label":n,title:l,disabled:r,style:{backgroundColor:"transparent",color:o.mutedTextColor,border:"none",borderRadius:"8px",padding:"8px",cursor:r?"not-allowed":"pointer",opacity:r?.5:1,transition:"all 0.2s ease-out",display:"flex",alignItems:"center",justifyContent:"center"},onMouseEnter:u=>{r||(u.currentTarget.style.backgroundColor=o.hoverBackground,u.currentTarget.style.color=o.textColor);},onMouseLeave:u=>{u.currentTarget.style.backgroundColor="transparent",u.currentTarget.style.color=o.mutedTextColor;},onClick:t,children:e})}function nn({title:e,alwaysOpen:t,streaming:n,dir:o,resolvedColors:r,onNew:l,onToggleHistory:u,onClose:c,historyBtnRef:w,t:S}){return jsxs("div",{style:{marginBottom:"24px",display:"flex",alignItems:"center",justifyContent:"space-between",direction:o==="rtl"?"rtl":"ltr"},children:[jsx("div",{style:{minWidth:"0"},children:jsx("h1",{title:e,style:{color:r.textColor,fontSize:"18px",fontWeight:"600",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",margin:"0"},children:e})}),jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px",position:"relative",color:r.mutedTextColor},children:[jsx(At,{icon:jsx(se,{IconComponent:Plus,size:"20",strokeWidth:"2"}),onClick:()=>{n||l();},ariaLabel:S("header.new"),resolvedColors:r,disabled:n}),jsx("button",{ref:w,"aria-label":S("header.history"),style:{backgroundColor:"transparent",color:r.mutedTextColor,border:"none",borderRadius:"8px",padding:"8px",cursor:"pointer",transition:"all 0.2s ease-out",display:"flex",alignItems:"center",justifyContent:"center"},onMouseEnter:a=>{a.currentTarget.style.backgroundColor=r.hoverBackground,a.currentTarget.style.color=r.textColor;},onMouseLeave:a=>{a.currentTarget.style.backgroundColor="transparent",a.currentTarget.style.color=r.mutedTextColor;},onClick:u,children:jsx(se,{IconComponent:History,size:"20",strokeWidth:"2"})}),!t&&jsx(At,{icon:jsx(se,{IconComponent:ChevronRight,size:"20",strokeWidth:"2",style:{transform:o==="rtl"?"rotate(180deg)":"none"}}),onClick:c,ariaLabel:S("header.close"),resolvedColors:r})]})]})}function an({chart:e,theme:t}){let n=useRef(null),[o,r]=useState(null),[l,u]=useState(true);useEffect(()=>{let y=true;return (async()=>{try{u(!0),r(null);let g;try{g=await import('mermaid');}catch{throw new Error("Mermaid library not available")}if(!y)return;if(g.default?.initialize({startOnLoad:!1,theme:t==="dark"?"dark":"default",themeVariables:{darkMode:t==="dark",primaryColor:t==="dark"?"#3B82F6":"#1D4ED8",primaryTextColor:t==="dark"?"#F3F4F6":"#1F2937",primaryBorderColor:t==="dark"?"#374151":"#D1D5DB"},flowchart:{useMaxWidth:!0},sequence:{useMaxWidth:!0},gantt:{useMaxWidth:!0}}),n.current&&y){let C=`mermaid-${Date.now()}-${Math.random().toString(36).slice(2)}`,{svg:i}=await g.default.render(C,e);if(n.current&&y){n.current.innerHTML=i;let m=n.current.querySelector("svg");m&&(m.style.maxWidth="100%",m.style.height="auto",m.style.display="block");}}}catch(g){y&&r(g instanceof Error?g.message:"Failed to render diagram");}finally{y&&u(false);}})(),()=>{y=false;}},[e,t]);let c=t==="dark"?"#374151":"#D1D5DB",w=t==="dark"?"#1F2937":"#F9FAFB",S=t==="dark"?"#7F1D1D":"#FEF2F2",a=t==="dark"?"#FCA5A5":"#DC2626",M=t==="dark"?"#9CA3AF":"#6B7280";return o?jsxs("div",{style:{borderRadius:"12px",border:`1px solid ${c}`,backgroundColor:S,padding:"16px",margin:"8px 0"},children:[jsx("div",{style:{fontSize:"14px",color:a,marginBottom:"8px",fontWeight:"500"},children:"Failed to render diagram"}),jsx("div",{style:{fontSize:"12px",color:a,opacity:.8},children:o})]}):jsxs("div",{style:{borderRadius:"12px",border:`1px solid ${c}`,backgroundColor:w,padding:"16px",margin:"8px 0",overflow:"hidden"},children:[l&&jsx("div",{style:{fontSize:"14px",color:M,textAlign:"center",padding:"32px"},children:"Rendering diagram..."}),jsx("div",{ref:n,style:{display:l?"none":"block",textAlign:"center",minHeight:l?"0":"50px"}})]})}function le(e){return e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}function He(e){return e=e.replace(/\[([^\]]+)\]\((https?:\/\/[^\s)]+)\)/g,'<a href="$2" target="_blank" rel="noopener noreferrer" style="text-decoration: underline; color: inherit; opacity: 0.8;">$1</a>'),e=e.replace(/\*\*([^*]+)\*\*/g,"<strong>$1</strong>"),e=e.replace(/\*([^*\n]+)\*/g,"<em>$1</em>"),e=e.replace(/`([^`]+)`/g,'<code style="padding: 2px 4px; border-radius: 4px; background-color: rgba(0,0,0,0.1); font-family: monospace;">$1</code>'),e}function yr(e,t="dark"){let n=(e||"").replace(/\r\n/g,`
|
|
1
|
+
import {jsxs,jsx,Fragment}from'react/jsx-runtime';import ot,{createContext,useRef,useEffect,useState,useCallback,useMemo,useContext}from'react';import {createPortal}from'react-dom';import {useChat}from'@ai-sdk/react';import {DefaultChatTransport,lastAssistantMessageIsCompleteWithToolCalls}from'ai';import {Plus,History,ChevronRight,Trash2,File as File$1,Eye,X,Download}from'lucide-react';import {createRoot}from'react-dom/client';var Me={};var wo=({variant:e="primary",size:t="md",loading:n=false,disabled:o,children:r,className:l,...u})=>{let c=[Me.button,Me[e],Me[t],n&&Me.loading,l].filter(Boolean).join(" ");return jsxs("button",{className:c,disabled:o||n,...u,children:[n&&jsx("span",{className:Me.spinner}),jsx("span",{className:n?Me.hiddenText:void 0,children:r})]})};function Xt({show:e,onClick:t,resolvedColors:n,floatingButtonPosition:o}){if(!e)return null;let r={position:"fixed",bottom:typeof o.bottom=="number"?`${o.bottom}px`:o.bottom,right:o.right?typeof o.right=="number"?`${o.right}px`:o.right:void 0,top:o.top?typeof o.top=="number"?`${o.top}px`:o.top:void 0,left:o.left?typeof o.left=="number"?`${o.left}px`:o.left:void 0,zIndex:1e3};return jsx("button",{"aria-label":"Open chat",onClick:t,style:{...r,borderColor:n.borderColor,backgroundColor:n.accentColor,color:n.textColor,borderRadius:"50%",border:`1px solid ${n.borderColor}`,padding:"12px",boxShadow:"0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06)",transition:"all 0.2s",cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center"},onMouseEnter:l=>{l.currentTarget.style.borderColor=n.primaryColor,l.currentTarget.style.backgroundColor=`${n.accentColor}dd`;},onMouseLeave:l=>{l.currentTarget.style.borderColor=n.borderColor,l.currentTarget.style.backgroundColor=n.accentColor;},children:jsx("svg",{width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:jsx("path",{d:"M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"})})})}function Zt(e=true){let t=useRef(null),n=useRef(e);return useEffect(()=>{n.current=e;},[e]),useEffect(()=>{let o=t.current;if(!o)return;let r=new MutationObserver(()=>{n.current&&(o.scrollTop=o.scrollHeight);});return r.observe(o,{childList:true,subtree:true}),n.current&&(o.scrollTop=o.scrollHeight),()=>r.disconnect()},[]),t}function Qt(e,t){if(!e)return t;let n=e.endsWith("/")?e.slice(0,-1):e,o=t.startsWith("/")?t:`/${t}`;return `${n}${o}`}var At=25*1024*1024;function tn(e){let[t,n]=useState([]),[o,r]=useState(false),l=useRef(null),u=useCallback(f=>{if(!f||Number.isNaN(f))return "0 B";let b=["B","KB","MB","GB","TB"],g=Math.min(b.length-1,Math.floor(Math.log(f)/Math.log(1024)));return `${(f/Math.pow(1024,g)).toFixed(g===0?0:1)} ${b[g]}`},[]),c=useCallback(async f=>{let b=new FormData;b.append("file",f);let g=await fetch(Qt(e,"/api/uploads"),{method:"POST",body:b});if(!g.ok){let i=await g.text().catch(()=>"");throw new Error(i||`Failed to upload ${f.name}`)}let k=await g.json();return {id:k.id,name:k.name||f.name,url:k.url,mimeType:k.mimeType||f.type||"application/octet-stream",size:typeof k.size=="number"?k.size:f.size}},[e]),v=useCallback(f=>{n(b=>b.filter(g=>g.id!==f));},[]),S=useCallback(async(f,b)=>{if(!f)return;let g=Array.isArray(f)?f:Array.from(f);b(null),r(true);let k=[];try{for(let i of g){if(i.size>At){b(`"${i.name}" exceeds the ${u(At)} limit.`);continue}try{let m=await c(i);k.push(m);}catch(m){console.error("Failed to upload attachment:",m),b(String(m?.message??`Failed to upload ${i.name}`));}}k.length&&n(i=>[...i,...k]);}finally{r(false);}},[c,u]),a=useCallback((f,b)=>{let g=[],k=(f||"").trim();k&&g.push({type:"text",text:k});for(let i of b||[]){let m=i.mimeType||"application/octet-stream";m.startsWith("image/")?g.push({type:"image",image:new URL(i.url),mediaType:m}):g.push({type:"file",data:i.url,mediaType:m,name:i.name});}return g},[]),T=useCallback(()=>{n([]);},[]);return {attachments:t,uploading:o,fileInputRef:l,formatBytes:u,handleRemoveAttachment:v,handleFileSelection:S,buildUserContent:a,clearAttachments:T,MAX_UPLOAD_SIZE:At}}var nn=createContext(void 0);function lr({baseUrl:e,dir:t="ltr",theme:n="dark",children:o}){let[r,l]=useState(new Map),[u,c]=useState(new Map),[v,S]=useState(new Map),[a,T]=useState(new Map),f=useCallback((M,w)=>(l(y=>{let p=new Map(y);return p.set(String(M),w),p}),()=>{l(y=>{let p=new Map(y),F=p.get(String(M));return (!w||F===w)&&p.delete(String(M)),p});}),[]),b=useCallback((M,w)=>{l(y=>{let p=new Map(y),F=p.get(String(M));return (!w||F===w)&&p.delete(String(M)),p});},[]),g=useCallback((M,w)=>(c(y=>{let p=new Map(y);return p.set(String(M),w),p}),()=>{c(y=>{let p=new Map(y),F=p.get(String(M));return (!w||F===w)&&p.delete(String(M)),p});}),[]),k=useCallback((M,w)=>{c(y=>{let p=new Map(y),F=p.get(String(M));return (!w||F===w)&&p.delete(String(M)),p});},[]),i=useCallback((M,w)=>{S(y=>{let p=new Map(y);return w?p.set(M,true):p.delete(M),p});},[]),m=useCallback((M,w)=>{T(y=>{let p=new Map(y);return w?p.set(M,true):p.delete(M),p});},[]),h=useMemo(()=>Array.from(v.values()).some(M=>M),[v]),C=useMemo(()=>Array.from(a.values()).some(M=>M),[a]),E=useMemo(()=>({baseUrl:e,dir:t,theme:n,actions:r,components:u,registerAction:f,unregisterAction:b,registerComponent:g,unregisterComponent:k,isAnyStreaming:h,setStreamingState:i,isAnyChatOpen:C,setChatOpenState:m}),[e,t,n,r,u,f,b,g,k,h,i,C,m]);return jsx(nn.Provider,{value:E,children:o})}function Le(){let e=useContext(nn);return e||{baseUrl:void 0,actions:new Map,components:new Map,registerAction:()=>()=>{},unregisterAction:()=>{},registerComponent:()=>()=>{},unregisterComponent:()=>{},isAnyStreaming:false,setStreamingState:()=>{},isAnyChatOpen:false,setChatOpenState:()=>{}}}function se({IconComponent:e,...t}){return ot.createElement(e,t)}function Rt({icon:e,onClick:t,ariaLabel:n,resolvedColors:o,disabled:r=false,title:l}){return jsx("button",{"aria-label":n,title:l,disabled:r,style:{backgroundColor:"transparent",color:o.mutedTextColor,border:"none",borderRadius:"8px",padding:"8px",cursor:r?"not-allowed":"pointer",opacity:r?.5:1,transition:"all 0.2s ease-out",display:"flex",alignItems:"center",justifyContent:"center"},onMouseEnter:u=>{r||(u.currentTarget.style.backgroundColor=o.hoverBackground,u.currentTarget.style.color=o.textColor);},onMouseLeave:u=>{u.currentTarget.style.backgroundColor="transparent",u.currentTarget.style.color=o.mutedTextColor;},onClick:t,children:e})}function on({title:e,alwaysOpen:t,streaming:n,dir:o,resolvedColors:r,onNew:l,onToggleHistory:u,onClose:c,historyBtnRef:v,t:S}){return jsxs("div",{style:{marginBottom:"24px",display:"flex",alignItems:"center",justifyContent:"space-between",direction:o==="rtl"?"rtl":"ltr"},children:[jsx("div",{style:{minWidth:"0"},children:jsx("h1",{title:e,style:{color:r.textColor,fontSize:"18px",fontWeight:"600",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",margin:"0"},children:e})}),jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px",position:"relative",color:r.mutedTextColor},children:[jsx(Rt,{icon:jsx(se,{IconComponent:Plus,size:"20",strokeWidth:"2"}),onClick:()=>{n||l();},ariaLabel:S("header.new"),resolvedColors:r,disabled:n}),jsx("button",{ref:v,"aria-label":S("header.history"),style:{backgroundColor:"transparent",color:r.mutedTextColor,border:"none",borderRadius:"8px",padding:"8px",cursor:"pointer",transition:"all 0.2s ease-out",display:"flex",alignItems:"center",justifyContent:"center"},onMouseEnter:a=>{a.currentTarget.style.backgroundColor=r.hoverBackground,a.currentTarget.style.color=r.textColor;},onMouseLeave:a=>{a.currentTarget.style.backgroundColor="transparent",a.currentTarget.style.color=r.mutedTextColor;},onClick:u,children:jsx(se,{IconComponent:History,size:"20",strokeWidth:"2"})}),!t&&jsx(Rt,{icon:jsx(se,{IconComponent:ChevronRight,size:"20",strokeWidth:"2",style:{transform:o==="rtl"?"rotate(180deg)":"none"}}),onClick:c,ariaLabel:S("header.close"),resolvedColors:r})]})]})}function ln({chart:e,theme:t}){let n=useRef(null),[o,r]=useState(null),[l,u]=useState(true);useEffect(()=>{let f=true;return (async()=>{try{u(!0),r(null);let g;try{g=await import('mermaid');}catch{throw new Error("Mermaid library not available")}if(!f)return;if(g.default?.initialize({startOnLoad:!1,theme:t==="dark"?"dark":"default",themeVariables:{darkMode:t==="dark",primaryColor:t==="dark"?"#3B82F6":"#1D4ED8",primaryTextColor:t==="dark"?"#F3F4F6":"#1F2937",primaryBorderColor:t==="dark"?"#374151":"#D1D5DB"},flowchart:{useMaxWidth:!0},sequence:{useMaxWidth:!0},gantt:{useMaxWidth:!0}}),n.current&&f){let k=`mermaid-${Date.now()}-${Math.random().toString(36).slice(2)}`,{svg:i}=await g.default.render(k,e);if(n.current&&f){n.current.innerHTML=i;let m=n.current.querySelector("svg");m&&(m.style.maxWidth="100%",m.style.height="auto",m.style.display="block");}}}catch(g){f&&r(g instanceof Error?g.message:"Failed to render diagram");}finally{f&&u(false);}})(),()=>{f=false;}},[e,t]);let c=t==="dark"?"#374151":"#D1D5DB",v=t==="dark"?"#1F2937":"#F9FAFB",S=t==="dark"?"#7F1D1D":"#FEF2F2",a=t==="dark"?"#FCA5A5":"#DC2626",T=t==="dark"?"#9CA3AF":"#6B7280";return o?jsxs("div",{style:{borderRadius:"12px",border:`1px solid ${c}`,backgroundColor:S,padding:"16px",margin:"8px 0"},children:[jsx("div",{style:{fontSize:"14px",color:a,marginBottom:"8px",fontWeight:"500"},children:"Failed to render diagram"}),jsx("div",{style:{fontSize:"12px",color:a,opacity:.8},children:o})]}):jsxs("div",{style:{borderRadius:"12px",border:`1px solid ${c}`,backgroundColor:v,padding:"16px",margin:"8px 0",overflow:"hidden"},children:[l&&jsx("div",{style:{fontSize:"14px",color:T,textAlign:"center",padding:"32px"},children:"Rendering diagram..."}),jsx("div",{ref:n,style:{display:l?"none":"block",textAlign:"center",minHeight:l?"0":"50px"}})]})}function le(e){return e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}function He(e){return e=e.replace(/\[([^\]]+)\]\((https?:\/\/[^\s)]+)\)/g,'<a href="$2" target="_blank" rel="noopener noreferrer" style="text-decoration: underline; color: inherit; opacity: 0.8;">$1</a>'),e=e.replace(/\*\*([^*]+)\*\*/g,"<strong>$1</strong>"),e=e.replace(/\*([^*\n]+)\*/g,"<em>$1</em>"),e=e.replace(/`([^`]+)`/g,'<code style="padding: 2px 4px; border-radius: 4px; background-color: rgba(0,0,0,0.1); font-family: monospace;">$1</code>'),e}function xr(e,t="dark"){let n=(e||"").replace(/\r\n/g,`
|
|
2
2
|
`).split(`
|
|
3
|
-
`),o="",r=false,l="",u=[],c=false,
|
|
4
|
-
<table style="width: 100%; min-width: max-content; border-collapse: separate; border-spacing: 0; margin: 0;">`;
|
|
5
|
-
`);o+=`<div class="mermaid-placeholder" data-mermaid="${le(
|
|
6
|
-
`)),
|
|
7
|
-
`);o+=`<div class="mermaid-placeholder" data-mermaid="${le(
|
|
8
|
-
`)),p=l?`language-${l}`:"";o+=`<pre style="border-radius: 8px; padding: 12px; background-color: ${
|
|
3
|
+
`),o="",r=false,l="",u=[],c=false,v=false,S=false,a=t==="dark"?"#374151":"#D1D5DB",f=t==="dark"?"#111827":"#F3F4F6",b=t==="dark"?"#E5E7EB":"#374151",g=t==="dark"?"#374151":"#F3F4F6",k=t==="dark"?"#F9FAFB":"#111827",i=()=>{c&&(o+="</ul>",c=false),v&&(o+="</ol>",v=false);},m=y=>{for(let p=y;p<n.length;p++)if(n[p].trim().length>0)return p;return -1},h=y=>{let p=y.trim(),F=p.startsWith("|")?p.slice(1):p;return (F.endsWith("|")?F.slice(0,-1):F).split("|").map(q=>q.trim())},C=y=>{let p=y.trim();if(!p.startsWith("|"))return false;let F=h(p);return F.length>=2&&F.some(U=>U.length>0)},E=y=>{let p=h(y);return p.length===0?false:p.every(F=>/^:?-{3,}:?$/.test(F))},M=y=>{let p=y.startsWith(":"),F=y.endsWith(":");return p&&F?"center":!p&&F?"right":"left"},w=y=>{let p=y,F=m(p+1);if(F===-1)return {tableHtml:"",endIndex:y};let U=h(n[p]),q=h(n[F]),Z=Math.max(U.length,q.length),z=[];for(let $=0;$<Z;$++){let H=q[$]||"---";z.push(M(H));}let Q=[],V=F+1;for(;V<n.length;){let $=n[V].trim();if($.length===0){V++;continue}if(!$.startsWith("|"))break;let H=h(n[V]),N=[];for(let L=0;L<Z;L++)N.push(H[L]??"");Q.push(N),V++;}let ee=`<div style="overflow: auto; max-width: 100%; max-height: 60vh; border-radius: 10px; margin: 8px 0;">
|
|
4
|
+
<table style="width: 100%; min-width: max-content; border-collapse: separate; border-spacing: 0; margin: 0;">`;ee+="<thead><tr>";for(let $=0;$<Z;$++){let H=He(le(U[$]??"")),N=z[$],L=$===0,ge=$===Z-1;ee+=`<th style="text-align: ${N}; padding: 10px 12px; border-bottom: 1px solid ${a}; background-color: ${g}; color: ${k}; position: sticky; top: 0; z-index: 1; ${`${L?"border-top-left-radius: 10px;":""}${ge?"border-top-right-radius: 10px;":""}`}">${H}</th>`;}ee+="</tr></thead>",ee+="<tbody>";for(let $ of Q){ee+="<tr>";for(let H=0;H<Z;H++){let N=He(le($[H]??"")),L=z[H],ge=H===0;ee+=`<td style="text-align: ${L}; padding: 10px 12px; border-bottom: 1px solid ${a}; ${ge?`border-left: 1px solid ${a};`:""} border-right: 1px solid ${a};">${N}</td>`;}ee+="</tr>";}return ee+="</tbody></table></div>",{tableHtml:ee,endIndex:V-1}};for(let y=0;y<n.length;y++){let p=n[y],F=p.match(/^```\s*(\w+)?\s*$/);if(F){if(!r)i(),r=true,l=F[1]?String(F[1]):"",u=[];else {if(l==="mermaid"){S=true;let z=u.join(`
|
|
5
|
+
`);o+=`<div class="mermaid-placeholder" data-mermaid="${le(z)}"></div>`;}else {let z=le(u.join(`
|
|
6
|
+
`)),Q=l?`language-${l}`:"";o+=`<pre style="border-radius: 8px; padding: 12px; background-color: ${f}; color: ${b}; border: 1px solid ${a}; overflow-x: auto; white-space: pre-wrap; word-break: break-all;"><code class="${Q}">${z}</code></pre>`;}r=false,l="",u=[];}continue}if(r){u.push(p);continue}if(/^\s*(---|\*\*\*|___)\s*$/.test(p)){i(),o+='<hr style="margin: 12px 0; opacity: 0.6; border: none; border-top: 1px solid currentColor;" />';continue}let U=p.match(/^(#{1,6})\s+(.+)$/);if(U){i();let z=U[1].length,Q=He(le(U[2].trim())),V=z<=2?"18px":z===3?"16px":"14px";o+=`<h${z} style="font-size: ${V}; font-weight: 600; margin: 8px 0 4px 0;">${Q}</h${z}>`;continue}if(C(p)){let z=m(y+1);if(z!==-1&&E(n[z])){i();let{tableHtml:Q,endIndex:V}=w(y);if(Q){o+=Q,y=V;continue}}}let q=p.match(/^\s*[-*]\s+(.+)$/),Z=p.match(/^\s*\d+\.\s+(.+)$/);if(q){c||(i(),o+='<ul style="list-style-type: disc; padding-left: 24px; margin: 4px 0;">',c=true);let z=He(le(q[1]));o+=`<li style="margin: 2px 0;">${z}</li>`;continue}if(Z){v||(i(),o+='<ol style="list-style-type: decimal; padding-left: 24px; margin: 4px 0;">',v=true);let z=He(le(Z[1]));o+=`<li style="margin: 2px 0;">${z}</li>`;continue}if(p.trim().length===0)i(),o+='<div style="height: 8px;"></div>';else {i();let z=He(le(p));o+=`<p style="line-height: 1.6; margin: 4px 0; word-break: break-word;">${z}</p>`;}}if(r)if(l==="mermaid"){S=true;let y=u.join(`
|
|
7
|
+
`);o+=`<div class="mermaid-placeholder" data-mermaid="${le(y)}"></div>`;}else {let y=le(u.join(`
|
|
8
|
+
`)),p=l?`language-${l}`:"";o+=`<pre style="border-radius: 8px; padding: 12px; background-color: ${f}; color: ${b}; border: 1px solid ${a}; overflow-x: auto; white-space: pre-wrap; word-break: break-all;"><code class="${p}">${y}</code></pre>`;}return c&&(o+="</ul>"),v&&(o+="</ol>"),{html:o,hasMermaid:S}}function it({content:e,theme:t}){let{html:n,hasMermaid:o}=useMemo(()=>xr(e,t),[e,t]);if(!o)return jsx("div",{style:{fontSize:"14px",lineHeight:"1.6",wordBreak:"break-word",maxWidth:"100%",overflow:"hidden"},dangerouslySetInnerHTML:{__html:n}});let r=n.split(/(<div class="mermaid-placeholder"[^>]*><\/div>)/g),l=[];return r.forEach((u,c)=>{if(u.includes("mermaid-placeholder")){let v=u.match(/data-mermaid="([^"]*)"/);if(v){let S=v[1].replace(/</g,"<").replace(/>/g,">").replace(/&/g,"&").replace(/"/g,'"').replace(/'/g,"'");l.push(ot.createElement(ln,{key:`mermaid-${c}`,chart:S,theme:t}));}}else u.trim()&&l.push(ot.createElement("div",{key:`html-${c}`,style:{fontSize:"14px",lineHeight:"1.6",wordBreak:"break-word",maxWidth:"100%",overflow:"hidden"},dangerouslySetInnerHTML:{__html:u}}));}),ot.createElement(ot.Fragment,{},...l)}var Cr=e=>{let t={"input-streaming":{color:"#eab308",text:"Inputting"},"input-available":{color:"#3b82f6",text:"Running"},error:{color:"#ef4444",text:"Error"},"output-available":{color:"#10b981",text:"Called"},finished:{color:"#10b981",text:"Called"}};return t[e||"output-available"]||t["output-available"]};function cn({parts:e,messageId:t,openReasoningIds:n,toggleReasoning:o,resolvedColors:r}){let l=[],u=[],c,v,S=false;for(let a of Array.isArray(e)?e:[]){if(!a)continue;if(a.type==="reasoning"&&typeof a.text=="string"){u.push(a.text),c||(c=a.startDate),v=a.endDate,a.state==="done"&&(S=true);continue}let T=a.type==="dynamic-tool",f=typeof a.type=="string"&&a.type.startsWith("tool-");if(T||f||a.type==="tool-call"){u.length&&(l.push({type:"reasoning",texts:u,startDate:c,endDate:v,isCompleted:S}),u=[],c=void 0,v=void 0,S=false);let b=String(T?a.toolName||"dynamic-tool":f?a.type?.slice(5)||"tool":a.toolName||"tool");b==="getFromUser"||b==="get_from_user"?l.push({type:"tool",toolName:b,status:a.state||a.status,input:a.input,output:a.output,startDate:a.startDate,endDate:a.endDate,toolCallId:a.toolCallId}):l.push({type:"tool",toolName:b,status:a.state||a.status,input:a.input,output:a.output,startDate:a.startDate,endDate:a.endDate});continue}}return u.length&&l.push({type:"reasoning",texts:u,startDate:c,endDate:v,isCompleted:S}),l.length?jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"8px"},children:[l.map((a,T)=>{let f=`${t}-${T}`,b=n.has(f);if(a.type==="reasoning"){let h=a.isCompleted||typeof a.startDate=="number"&&typeof a.endDate=="number",C=a.texts&&a.texts.length>0&&a.texts.some(M=>M.trim().length>0),E=()=>{C&&o(f);};return h&&!C?null:jsx("div",{onClick:E,style:{cursor:C?"pointer":"default",padding:"0"},children:jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"4px"},children:[jsxs("div",{style:{fontSize:"13px",color:r.mutedTextColor,fontWeight:500,display:"flex",alignItems:"center",gap:"6px",overflow:"hidden",maxWidth:"100%",minWidth:0,width:"100%"},children:[jsxs("span",{style:{display:"inline-flex",alignItems:"center",gap:"6px"},children:[!h&&jsx("span",{style:{display:"inline-block",height:"6px",width:"6px",borderRadius:"50%",backgroundColor:r.mutedTextColor,animation:"pulse 1.5s ease-in-out infinite"}}),jsx("span",{style:{color:r.textColor,fontWeight:600,opacity:.9,background:h?"none":`linear-gradient(90deg, ${r.textColor}, ${r.mutedTextColor}, ${r.mutedTextColor})`,backgroundSize:h?"auto":"200% 100%",backgroundClip:h?"unset":"text",WebkitBackgroundClip:h?"unset":"text",WebkitTextFillColor:h?r.mutedTextColor:"transparent",animation:h?void 0:"shimmer 2s ease-in-out infinite"},children:h?"Finish Thinking":"Thinking"})]}),C&&jsx("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0,transform:b?"rotate(90deg)":"rotate(0deg)",transition:"transform 0.2s ease-out"},children:jsx("polyline",{points:"9 18 15 12 9 6"})})]}),jsx("div",{style:{display:"grid",gridTemplateRows:b||!h?"1fr":"0fr",transition:"grid-template-rows 0.2s ease-out",overflow:"hidden"},children:jsx("div",{style:{minHeight:0},children:a.texts&&a.texts.length>0?jsx("div",{style:{fontSize:"13px",color:r.mutedTextColor,lineHeight:"1.6",maxWidth:"100%"},children:(!h&&b?a.texts:h?b?a.texts:[]:[a.texts[a.texts.length-1]]).map((M,w)=>jsx("div",{style:{marginBottom:"6px"},children:jsx(it,{content:M,theme:"dark"})},`rg-line-${T}-${w}`))}):jsxs("div",{style:{fontSize:"12px",color:r.mutedTextColor,opacity:.7,display:"flex",alignItems:"center",gap:"8px"},children:[jsx("span",{style:{display:"inline-block",height:"6px",width:"6px",borderRadius:"50%",backgroundColor:r.mutedTextColor,animation:"pulse 1.5s ease-in-out infinite"}}),jsx("span",{style:{letterSpacing:"2px",animation:"pulse 2s cubic-bezier(0.4, 0, 0.6, 1) infinite"},children:"..."})]})})})]})},f)}let{color:g,text:k}=Cr(a.status),i=a.status==="input-streaming"||a.status==="input-available",m=a.toolName==="getFromUser"||a.toolName==="get_from_user";return jsx("div",{style:{display:"flex",gap:"12px",position:"relative"},children:jsxs("div",{style:{flex:1,minWidth:0},children:[jsxs("div",{style:{fontSize:"13px",color:r.mutedTextColor,display:"flex",alignItems:"center",gap:"8px",flexWrap:"wrap"},children:[jsxs("span",{style:{fontWeight:600,color:g,display:"flex",alignItems:"center",gap:"6px"},children:[jsx("span",{style:{display:"inline-block",height:"6px",width:"6px",borderRadius:"50%",backgroundColor:g,animation:i?"pulse 1.5s ease-in-out infinite":void 0}}),k]}),jsx("span",{style:{fontWeight:500,color:r.textColor},children:a.toolName||"tool"})]}),m?jsx("div",{style:{marginTop:"8px"},children:jsx("div",{"data-get-from-user-host":a.toolCallId||f,style:{width:"100%"}})}):null]})},f)}),jsx("style",{children:`
|
|
9
9
|
@keyframes shimmer {
|
|
10
10
|
0% { background-position: -200% 0; }
|
|
11
11
|
100% { background-position: 200% 0; }
|
|
12
12
|
}
|
|
13
|
-
`})]}):null}function
|
|
13
|
+
`})]}):null}function dn({items:e,resolvedColors:t,UIComponents:n={}}){return !Array.isArray(e)||e.length===0?null:jsx("div",{style:{},children:jsx("div",{style:{margin:0,color:t.textColor,display:"flex",flexDirection:"column",gap:"12px"},children:e.map((o,r)=>{if(typeof o=="object"&&o!==null&&o.type==="ui"){let{component:u,props:c}=o,v=n[u];return v?jsx("div",{style:{padding:"16px",borderRadius:"12px",backgroundColor:t.cardBackground,border:`1px solid ${t.borderColor}`},children:jsx(v,{props:c,resolvedColors:t})},r):jsx("div",{})}let l=typeof o=="string"?o:JSON.stringify(o);return jsx("div",{style:{whiteSpace:"pre-wrap",lineHeight:1.6},children:jsx(it,{content:l,theme:"dark"})},r)})})})}function un(e){if(!e||Number.isNaN(e))return "0 B";let t=["B","KB","MB","GB","TB"],n=Math.min(t.length-1,Math.floor(Math.log(e)/Math.log(1024)));return `${(e/Math.pow(1024,n)).toFixed(n===0?0:1)} ${t[n]}`}function pn({attachment:e,resolvedColors:t,mode:n,onRemove:o,maxWidth:r="200px"}){let l=e.mimeType?.startsWith("image/"),u=n==="editable"||n==="input",c=n==="viewable",v={display:"flex",alignItems:"center",gap:n==="input"?"8px":"6px",padding:n==="input"?"8px 12px":"6px 10px",backgroundColor:t.inputBackground,borderRadius:n==="input"?"10px":"8px",border:`1px solid ${t.borderColor}`,fontSize:n==="input"?"12px":"11px",color:t.textColor,transition:"all 0.2s ease-out",cursor:c?"pointer":"default",maxWidth:n==="input"?"140px":r,position:"relative"},S=jsxs(Fragment,{children:[jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"center",width:n==="input"?"20px":"16px",height:n==="input"?"20px":"16px",borderRadius:n==="input"?"4px":"3px",backgroundColor:l?"transparent":t.accentColor,flexShrink:0},children:[l?jsx("img",{src:e.url,alt:e.name,style:{width:n==="input"?"20px":"16px",height:n==="input"?"20px":"16px",borderRadius:n==="input"?"4px":"3px",objectFit:"cover"},onError:a=>{a.target.style.display="none";let T=a.target.nextElementSibling;T&&(T.style.display="block");}}):null,jsx(se,{IconComponent:File$1,size:n==="input"?14:10,strokeWidth:"2",style:{display:l?"none":"block",color:t.mutedTextColor}})]}),jsxs("div",{style:{minWidth:"0",flex:"1",display:"flex",flexDirection:"column"},children:[jsx("span",{title:e.name,style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",fontWeight:"500"},children:e.name}),jsx("span",{style:{fontSize:n==="input"?"10px":"9px",color:t.mutedTextColor,marginTop:n==="input"?"2px":"1px"},children:un(e.size)})]}),n==="input"&&l&&jsx("button",{onClick:a=>{a.stopPropagation(),window.open(e.url,"_blank");},style:{background:"none",border:"none",color:t.mutedTextColor,cursor:"pointer",padding:"2px",display:"flex",alignItems:"center",borderRadius:"4px",transition:"all 0.2s"},title:"Preview image",onMouseEnter:a=>{a.currentTarget.style.backgroundColor=t.hoverBackground,a.currentTarget.style.color=t.textColor;},onMouseLeave:a=>{a.currentTarget.style.backgroundColor="transparent",a.currentTarget.style.color=t.mutedTextColor;},children:jsx(se,{IconComponent:Eye,size:"12",strokeWidth:"2"})}),u&&o&&jsx("button",{onClick:a=>{a.stopPropagation(),o(e.id);},style:{display:"flex",alignItems:"center",justifyContent:"center",width:n==="input"?"auto":"16px",height:n==="input"?"auto":"16px",padding:n==="input"?"2px":"0",borderRadius:"4px",border:"none",backgroundColor:"transparent",color:t.mutedTextColor,cursor:"pointer",transition:"all 0.2s",flexShrink:0},onMouseEnter:a=>{a.currentTarget.style.backgroundColor="#ef444420",a.currentTarget.style.color="#ef4444";},onMouseLeave:a=>{a.currentTarget.style.backgroundColor="transparent",a.currentTarget.style.color=t.mutedTextColor;},children:jsx(se,{IconComponent:X,size:"12",strokeWidth:"2"})}),c&&jsx(se,{IconComponent:Download,size:"10",strokeWidth:"2",style:{color:t.mutedTextColor,flexShrink:0}})]});return c?jsx("a",{href:e.url,target:"_blank",rel:"noreferrer",style:{...v,textDecoration:"none"},onMouseEnter:a=>{a.currentTarget.style.backgroundColor=t.hoverBackground,a.currentTarget.style.borderColor=t.primaryColor;},onMouseLeave:a=>{a.currentTarget.style.backgroundColor=t.inputBackground,a.currentTarget.style.borderColor=t.borderColor;},children:S}):jsx("div",{style:v,children:S})}function at({attachments:e,resolvedColors:t,onRemove:n}){if(!Array.isArray(e)||e.length===0)return null;let o=typeof n=="function"?"editable":"viewable";return jsx("div",{style:{marginTop:"12px",display:"flex",flexWrap:"wrap",gap:"8px"},children:e.map(r=>jsx(pn,{attachment:r,resolvedColors:t,mode:o,onRemove:n},r.id))})}function gn({messageId:e,initialText:t,editingText:n,onEditingTextChange:o,onCancel:r,onSave:l,streaming:u,resolvedColors:c,attachments:v,onRemoveAttachment:S,onAddAttachments:a,uploading:T,t:f}){let b=ot.useRef(null),g=i=>{i.key==="Escape"?r():i.key==="Enter"&&!i.shiftKey&&(i.preventDefault(),u||l(e,n||t));},k=i=>{let m=i.target.files;m&&m.length>0&&a&&a(m),b.current&&(b.current.value="");};return jsxs("div",{style:{maxWidth:"720px",borderRadius:"16px",padding:"8px",fontSize:"15px",border:`2px solid ${c.primaryColor}`,backgroundColor:c.accentColor,color:c.textColor,marginBottom:"16px",marginTop:"16px"},children:[jsx("textarea",{autoFocus:true,style:{width:"100%",resize:"none",backgroundColor:"transparent",padding:"8px",lineHeight:"1.6",outline:"none",border:"none",color:"inherit",fontFamily:"inherit",fontSize:"inherit"},rows:Math.max(2,Math.min(10,Math.ceil((n||t).length/60))),value:n,onChange:i=>o(i.target.value),onKeyDown:g}),v&&v.length>0&&jsx("div",{style:{padding:"8px"},children:jsx(at,{attachments:v,resolvedColors:c,onRemove:S})}),T&&jsxs("div",{style:{padding:"8px 16px",display:"flex",alignItems:"center",gap:"8px",fontSize:"13px",color:c.mutedTextColor},children:[jsx("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{animation:"spin 1s linear infinite"},children:jsx("path",{d:"M21 12a9 9 0 1 1-6.219-8.56"})}),jsx("span",{children:f("input.uploadingFiles")})]}),jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:"8px",padding:"8px 8px 8px 0"},children:[a&&jsxs("div",{children:[jsx("input",{ref:b,type:"file",multiple:true,onChange:k,style:{display:"none"}}),jsx("button",{onClick:()=>b.current?.click(),disabled:T||u,title:f(T?"input.uploadingFiles":"input.attachFiles"),style:{display:"flex",margin:"0 10px",alignItems:"center",justifyContent:"center",borderRadius:"50%",width:"28px",height:"28px",transition:"all 0.2s",border:`1px solid ${c.borderColor}`,color:c.mutedTextColor,backgroundColor:"transparent",cursor:T||u?"not-allowed":"pointer",opacity:T||u?.5:1},onMouseEnter:i=>{!T&&!u&&(i.currentTarget.style.backgroundColor=c.inputBackground,i.currentTarget.style.borderColor=c.primaryColor);},onMouseLeave:i=>{i.currentTarget.style.backgroundColor="transparent",i.currentTarget.style.borderColor=c.borderColor;},children:jsx(Plus,{size:16,strokeWidth:2})})]}),jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px"},children:[jsx("button",{style:{borderRadius:"8px",padding:"4px 12px",fontSize:"14px",transition:"background-color 0.2s",border:`1px solid ${c.borderColor}`,color:c.mutedTextColor,backgroundColor:"transparent",cursor:"pointer"},onMouseEnter:i=>i.currentTarget.style.backgroundColor=c.inputBackground,onMouseLeave:i=>i.currentTarget.style.backgroundColor="transparent",onClick:r,children:f("editor.cancel")}),jsx("button",{style:{borderRadius:"8px",padding:"4px 12px",fontSize:"14px",transition:"border-color 0.2s",border:`1px solid ${c.borderColor}`,backgroundColor:c.cardBackground,color:c.textColor,cursor:"pointer"},onMouseEnter:i=>i.currentTarget.style.borderColor=c.primaryColor,onMouseLeave:i=>i.currentTarget.style.borderColor=c.borderColor,onClick:()=>{u||l(e,n||t);},children:f("editor.saveAndRegenerate")})]})]})]})}function fn({chatMessages:e,isLoading:t,openReasoningIds:n,toggleReasoning:o,resolvedColors:r,t:l,onUserMessageClick:u,editingMessageId:c,editingText:v,onEditingTextChange:S,onCancelEdit:a,onSaveEdit:T,editAttachments:f,onRemoveEditAttachment:b,onAddEditAttachments:g,editUploading:k,UIComponents:i={}}){return jsxs(Fragment,{children:[jsx("style",{children:`
|
|
14
14
|
@keyframes jumpingDots {
|
|
15
15
|
0%, 80%, 100% {
|
|
16
16
|
transform: translateY(0);
|
|
@@ -19,8 +19,8 @@ import {jsxs,jsx,Fragment}from'react/jsx-runtime';import nt,{createContext,useRe
|
|
|
19
19
|
transform: translateY(-5px);
|
|
20
20
|
}
|
|
21
21
|
}
|
|
22
|
-
`}),jsxs("div",{style:{display:"flex",flexDirection:"column"},children:[e.map((m,
|
|
23
|
-
`),v=T.filter(b=>b.type==="file"||b.type==="image").map(b=>{if(b.type==="image"){let k=typeof b.image=="string"?b.image:b.image?.toString?.()||"";return {id:k||`${m.id}-img-${Date.now()}`,name:b.name||"image",url:k,mimeType:b.mediaType||"image/jpeg",size:b.size||0}}else return {id:b.url||`${m.id}-file-${Date.now()}`,name:b.name||"file",url:b.url||"",mimeType:b.mediaType||"application/octet-stream",size:b.size||0}});return jsx("div",{style:{padding:"0 4px"},children:m.role==="user"?c===m.id?jsx(pn,{messageId:m.id,initialText:R,editingText:w,onEditingTextChange:S,onCancel:a,onSave:M,streaming:t,resolvedColors:r,attachments:y,onRemoveAttachment:x,onAddAttachments:g,uploading:C,t:l}):jsx("div",{children:jsxs("div",{title:l("editor.clickToEdit"),onClick:()=>u(m.id,R,v),style:{maxWidth:"720px",borderRadius:"16px",padding:"16px",fontSize:"15px",lineHeight:"1.6",whiteSpace:"pre-wrap",cursor:"pointer",transition:"background-color 0.2s",backgroundColor:r.accentColor,color:r.textColor,marginBottom:"16px",marginTop:"16px"},onMouseEnter:b=>b.currentTarget.style.backgroundColor=r.hoverBackground,onMouseLeave:b=>b.currentTarget.style.backgroundColor=r.accentColor,children:[R,v.length>0&&jsx(ot,{attachments:v,resolvedColors:r})]})}):jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"12px"},children:[jsx(sn,{parts:T,messageId:m.id,openReasoningIds:n,toggleReasoning:o,resolvedColors:r}),(()=>{let b=T.find(k=>k.type==="data-final-response"&&k.data&&Array.isArray(k.data.items));return b?jsx(ln,{items:b.data.items,resolvedColors:r,UIComponents:i}):null})()]})},m.id)}),t&&jsxs("div",{style:{display:"flex",alignItems:"center",gap:"4px",padding:"0 4px",height:"20px"},children:[jsx("span",{style:{display:"inline-block",width:"4px",height:"4px",borderRadius:"50%",backgroundColor:r.mutedTextColor,animation:"jumpingDots 1s infinite ease-in-out",animationDelay:"0s"}}),jsx("span",{style:{display:"inline-block",width:"4px",height:"4px",borderRadius:"50%",backgroundColor:r.mutedTextColor,animation:"jumpingDots 1s infinite ease-in-out",animationDelay:"0.2s"}}),jsx("span",{style:{display:"inline-block",width:"4px",height:"4px",borderRadius:"50%",backgroundColor:r.mutedTextColor,animation:"jumpingDots 1s infinite ease-in-out",animationDelay:"0.4s"}})]})]})]})}function gn({input:e,setInput:t,textareaRef:n,fileInputRef:o,isLoading:r,uploading:l,attachments:u,formatBytes:c,handleRemoveAttachment:w,onFileInputChange:S,onSend:a,onStop:M,status:y,t:x,resolvedColors:g}){let C=y==="streaming"||y==="submitted",i=u.length>0||e.trim().length>0;return jsx("div",{style:{position:"sticky",bottom:"0",marginTop:"auto",paddingBottom:"8px",paddingTop:"4px"},children:jsx("div",{style:{position:"relative",flex:1},children:jsxs("div",{style:{position:"relative",width:"100%",borderRadius:"16px",paddingBottom:"48px",paddingTop:"16px",border:`1px solid ${g.borderColor}`,backgroundColor:g.cardBackground},children:[u.length>0&&jsx("div",{style:{padding:"0px 16px 12px 16px",display:"flex",flexWrap:"wrap",gap:"10px"},children:u.map(m=>{let f=m.mimeType.startsWith("image/");return jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px",padding:"8px 12px",backgroundColor:g.inputBackground,borderRadius:"10px",border:`1px solid ${g.borderColor}`,fontSize:"12px",color:g.textColor,position:"relative"},children:[jsx("div",{style:{display:"flex",alignItems:"center",justifyContent:"center",width:"20px",height:"20px",borderRadius:"4px",backgroundColor:f?"transparent":g.cardBackground},children:f?jsx("img",{src:m.url,alt:m.name,style:{width:"20px",height:"20px",borderRadius:"4px",objectFit:"cover"}}):jsx("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:jsx("rect",{x:"4",y:"4",width:"16",height:"20",rx:"2",ry:"2"})})}),jsxs("div",{style:{display:"flex",flexDirection:"column",minWidth:0,flex:1},children:[jsx("span",{title:m.name,style:{maxWidth:"140px",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",fontWeight:500},children:m.name}),jsx("span",{style:{color:g.mutedTextColor,fontSize:"10px",marginTop:"2px"},children:c(m.size)})]}),jsxs("div",{style:{display:"flex",alignItems:"center",gap:"4px",marginLeft:"8px"},children:[f&&jsx("a",{href:m.url,target:"_blank",rel:"noopener noreferrer",style:{background:"none",border:"none",color:g.mutedTextColor,cursor:"pointer",padding:"2px",display:"flex",alignItems:"center",borderRadius:"4px",textDecoration:"none"},title:x("input.previewImage"),children:jsxs("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[jsx("path",{d:"M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"}),jsx("circle",{cx:"12",cy:"12",r:"3"})]})}),jsx("button",{onClick:()=>w(m.id),style:{background:"none",border:"none",color:g.mutedTextColor,cursor:"pointer",padding:"2px",display:"flex",alignItems:"center",borderRadius:"4px"},title:x("input.removeFile"),children:jsxs("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[jsx("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),jsx("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]})})]})]},m.id)})}),l&&jsxs("div",{style:{padding:"0px 16px 12px 16px",display:"flex",alignItems:"center",gap:"8px",fontSize:"13px",color:g.mutedTextColor},children:[jsx("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{animation:"spin 1s linear infinite"},children:jsx("path",{d:"M21 12a9 9 0 1 1-6.219-8.56"})}),jsx("span",{children:x("input.uploadingFiles")})]}),jsx("div",{style:{padding:"0 16px"},children:jsx("textarea",{ref:n,"aria-label":"Prompt",rows:1,placeholder:x("input.placeholder"),value:e,onChange:m=>t(m.target.value),onKeyDown:m=>{m.key==="Enter"&&!m.shiftKey&&(m.preventDefault(),a());},disabled:r||l,style:{height:"24px",maxHeight:"200px",width:"100%",resize:"none",backgroundColor:"transparent",fontSize:"15px",lineHeight:"1.6",outline:"none",border:"none",color:g.textColor,fontFamily:"inherit",overflow:"auto"}})}),jsx("input",{ref:o,type:"file",multiple:true,onChange:S,style:{display:"none"},accept:"*/*"}),jsx("div",{style:{position:"absolute",bottom:"8px",left:"8px",display:"flex",alignItems:"center",gap:"4px",color:g.mutedTextColor},children:jsx("button",{onClick:()=>o.current?.click(),disabled:r||l,style:{borderRadius:"8px",padding:"8px",transition:"all 0.2s",backgroundColor:"transparent",border:"none",cursor:r||l?"not-allowed":"pointer",display:"flex",alignItems:"center",justifyContent:"center",color:"inherit",opacity:r||l?.5:1},"aria-label":x("input.attachFiles"),children:jsx("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:jsx("path",{d:"M21.44 11.05l-9.19 9.19a6 6 0 0 1-8.49-8.49l9.19-9.19a4 4 0 1 1 5.66 5.66l-9.2 9.19a2 2 0 1 1-2.83-2.83l8.49-8.49"})})})}),jsx("div",{style:{position:"absolute",bottom:"8px",right:"8px"},children:r?jsx("button",{onClick:M,disabled:!C,"aria-label":x("input.stop"),title:"Stop generation",style:{borderRadius:"12px",padding:"12px",transition:"all 0.2s ease-out",border:"1px solid #ef4444",backgroundColor:"#ef444420",color:"#ef4444",opacity:C?1:.4,cursor:C?"pointer":"not-allowed",display:"flex",alignItems:"center",justifyContent:"center"},onMouseEnter:m=>{C&&(m.currentTarget.style.backgroundColor="#ef444430",m.currentTarget.style.transform="scale(1.02)");},onMouseLeave:m=>{m.currentTarget.style.backgroundColor="#ef444420",m.currentTarget.style.transform="scale(1)";},children:jsx("svg",{xmlns:"http://www.w3.org/2000/svg",width:"24",height:"24",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:jsx("rect",{width:"18",height:"18",x:"3",y:"3",rx:"2"})})}):jsx("button",{onClick:a,disabled:!i||l,"aria-label":x("input.send"),title:"Send message",style:{borderRadius:"12px",padding:"12px",transition:"all 0.2s ease-out",border:`1px solid ${g.borderColor}`,backgroundColor:g.cardBackground,color:!i||l?g.mutedTextColor:g.primaryColor,cursor:!i||l?"not-allowed":"pointer",display:"flex",alignItems:"center",justifyContent:"center",opacity:!i||l?.5:1},onMouseEnter:m=>{i&&!l&&(m.currentTarget.style.borderColor=g.primaryColor,m.currentTarget.style.transform="scale(1.02)");},onMouseLeave:m=>{m.currentTarget.style.borderColor=g.borderColor,m.currentTarget.style.transform="scale(1)";},children:jsxs("svg",{xmlns:"http://www.w3.org/2000/svg",width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[jsx("path",{d:"m5 12 7-7 7 7"}),jsx("path",{d:"M12 19V5"})]})})})]})})})}function Rt(e){let t=`hsafaChat_${e}`,n=`${t}.chats`,o=T=>`${t}.chat.${T}`,r=`${t}.currentChatId`,l=`${t}.showChat`,u=()=>{try{let T=localStorage.getItem(n);return T?JSON.parse(T):[]}catch{return []}},c=T=>{try{localStorage.setItem(n,JSON.stringify(T));}catch{}},w=T=>{try{let R=localStorage.getItem(o(T));return R?JSON.parse(R):null}catch{return null}},S=T=>{try{localStorage.setItem(o(T.id),JSON.stringify(T));}catch{}},a=T=>{let R=u(),v=R.findIndex(b=>b.id===T.id);v>=0?R[v]=T:R.unshift(T),c(R);},M=T=>{let v=u().filter(b=>b.id!==T);c(v);},y=T=>{try{localStorage.removeItem(o(T));}catch{}};return {loadChatsIndex:u,saveChatsIndex:c,loadChat:w,saveChat:S,upsertChatMeta:a,deleteChatMeta:M,deleteChatData:y,deleteChat:T=>{y(T),M(T);},loadShowChatPreference:T=>{try{let R=localStorage.getItem(l);return R!==null?R==="true":T}catch{return T}},saveShowChatPreference:T=>{try{localStorage.setItem(l,String(T));}catch{}},loadCurrentChatId:()=>{try{return localStorage.getItem(r)}catch{return null}},saveCurrentChatId:T=>{try{localStorage.setItem(r,T);}catch{}},removeCurrentChatId:()=>{try{localStorage.removeItem(r);}catch{}}}}function fn(e){let t=Date.now()-e,n=Math.max(1,Math.floor(t/1e3));if(n<60)return `${n}s`;let o=Math.floor(n/60);if(o<60)return `${o}m`;let r=Math.floor(o/60);if(r<24)return `${r}h`;let l=Math.floor(r/24);if(l<7)return `${l}d`;let u=Math.floor(l/7);if(u<4)return `${u}w`;let c=Math.floor(l/30);return c<12?`${c}mo`:`${Math.floor(c/12)}y`}function yn({historyOpen:e,historySearch:t,currentChatId:n,refreshKey:o,resolvedColors:r,onClose:l,onSearchChange:u,onChatSelect:c,onChatDelete:w,loadChatsIndex:S,historyPopupRef:a}){if(!e)return null;let M=jsxs(Fragment,{children:[jsx("div",{style:{position:"fixed",inset:"0",zIndex:1100,backgroundColor:"rgba(0, 0, 0, 0.4)",backdropFilter:"blur(4px)",WebkitBackdropFilter:"blur(4px)"},onClick:l}),jsxs("div",{ref:a,style:{position:"fixed",left:"50%",top:"64px",transform:"translateX(-50%)",zIndex:1101,width:"680px",maxWidth:"94vw",overflow:"hidden",borderRadius:"16px",border:`1px solid ${r.borderColor}`,backgroundColor:`${r.backgroundColor}f0`,boxShadow:"0 25px 50px -12px rgba(0, 0, 0, 0.25)",backdropFilter:"blur(16px)",WebkitBackdropFilter:"blur(16px)"},children:[jsx("div",{style:{display:"flex",alignItems:"center",gap:"12px",borderBottom:`1px solid ${r.borderColor}`,padding:"12px 16px"},children:jsx("div",{style:{flex:"1"},children:jsx("input",{autoFocus:true,value:t,onChange:y=>u(y.target.value),placeholder:"Search",style:{width:"100%",borderRadius:"8px",backgroundColor:r.inputBackground,padding:"8px 12px",fontSize:"14px",color:r.textColor,border:`1px solid ${r.borderColor}`,outline:"none"},onFocus:y=>y.currentTarget.style.borderColor=r.primaryColor,onBlur:y=>y.currentTarget.style.borderColor=r.borderColor})})}),jsx("div",{style:{maxHeight:"60vh",overflowY:"auto"},children:(()=>{let y=t.toLowerCase().trim(),x=S();return y&&(x=x.filter(g=>(g.title||"").toLowerCase().includes(y))),!x||x.length===0?jsx("div",{style:{padding:"24px",color:r.mutedTextColor,textAlign:"center"},children:"No chats found."}):jsx("div",{children:x.map((g,C)=>jsx("div",{style:{borderTop:C>0?`1px solid ${r.borderColor}`:"none"},children:jsxs("div",{style:{display:"flex",width:"100%",alignItems:"center",justifyContent:"space-between",gap:"12px",padding:"12px",backgroundColor:g.id===n?r.cardBackground:"transparent"},children:[jsx("button",{style:{flex:"1",textAlign:"left",transition:"background-color 0.2s",borderRadius:"8px",padding:"8px",border:"none",backgroundColor:"transparent",cursor:"pointer",color:r.textColor},onMouseEnter:i=>i.currentTarget.style.backgroundColor=r.hoverBackground,onMouseLeave:i=>i.currentTarget.style.backgroundColor="transparent",onClick:()=>c(g.id),children:jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:"12px"},children:[jsx("div",{style:{minWidth:"0",flex:"1"},children:jsx("div",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",fontSize:"14px",color:r.textColor},children:g.title||"Untitled chat"})}),jsx("div",{style:{flexShrink:0,fontSize:"12px",color:r.mutedTextColor},children:fn(g.updatedAt)})]})}),jsx("button",{style:{flexShrink:0,borderRadius:"6px",padding:"8px",color:r.mutedTextColor,border:"1px solid transparent",backgroundColor:"transparent",cursor:"pointer",transition:"all 0.2s"},title:"Delete chat",onMouseEnter:i=>{i.currentTarget.style.color="#ef4444",i.currentTarget.style.backgroundColor="rgba(239, 68, 68, 0.1)",i.currentTarget.style.borderColor="rgba(239, 68, 68, 0.3)";},onMouseLeave:i=>{i.currentTarget.style.color=r.mutedTextColor,i.currentTarget.style.backgroundColor="transparent",i.currentTarget.style.borderColor="transparent";},onClick:i=>{i.stopPropagation(),w(g.id);},children:jsx(se,{IconComponent:Trash2,size:"16",strokeWidth:"2"})})]})},g.id))})})()})]})]});return typeof document<"u"&&document.body?createPortal(M,document.body):M}function Rr(e){if(!(e instanceof HTMLElement))return true;let t=window.getComputedStyle(e);return t.display!=="none"&&t.visibility!=="hidden"&&t.opacity!=="0"&&e.offsetParent!==null}function Fr(e){if(e.id){let n=document.querySelector(`label[for="${e.id}"]`);if(n)return n.textContent?.trim()}let t=e.closest("label");if(t){let n=t.cloneNode(true),o=n.querySelector("input, select, textarea");return o&&o.remove(),n.textContent?.trim()}}function Ft(e){if(e.textContent&&e.textContent.trim())return e.textContent.trim().slice(0,100)}function $t(e){if(e instanceof HTMLInputElement){let t=e.type.toLowerCase();return t==="checkbox"||t==="radio"?e.checked:e.value}if(e instanceof HTMLTextAreaElement)return e.value;if(e instanceof HTMLSelectElement)return e.multiple?Array.from(e.selectedOptions).map(t=>t.value):e.value;if(e instanceof HTMLElement&&e.isContentEditable)return e.textContent||void 0}function $r(e){if(e.id)return `#${e.id}`;let t=[],n=e;for(;n&&n!==document.body;){let o=n.tagName.toLowerCase();if(n.className&&typeof n.className=="string"){let l=n.className.split(" ").filter(u=>u.trim()).slice(0,2);l.length>0&&(o+="."+l.join("."));}let r=n.parentElement;if(r){let l=Array.from(r.children).filter(u=>u.tagName===n.tagName);if(l.length>1){let u=l.indexOf(n)+1;o+=`:nth-child(${u})`;}}t.unshift(o),n=r;}return t.slice(-3).join(" > ")}async function je(e={}){try{let{includeHidden:t=!1,selector:n,what:o="content",limit:r}=e,l=document.querySelector(".hsafa-content-container");if(!l)return {ok:!1,components:[],count:0,total:0,containerFound:!1,error:"ContentContainer not found on page. Make sure you have wrapped your app with <ContentContainer>."};let u=n&&l.querySelector(n)||l,c=[],w=[];o==="inputs"?w=["input","textarea","select",'[contenteditable="true"]','[contenteditable=""]']:w=["header","nav","main","section","article","aside","footer","h1","h2","h3","h4","h5","h6","p","img[alt]","ul","ol","li","table","thead","tbody","tr","td","th","form","label","input","textarea","select",'[contenteditable="true"]','[contenteditable=""]',"a[href]","button",'[role="button"]','[role="link"]',"[onclick]","[tabindex]","div"],u.querySelectorAll(w.join(", ")).forEach(i=>{let m=Rr(i);if(!m&&!t)return;let f={id:i.id||null,tag:i.tagName.toLowerCase(),className:i.className&&typeof i.className=="string"?i.className:void 0,isVisible:m,isInteractive:!0,selector:$r(i)};i instanceof HTMLInputElement?(f.type=i.type,f.name=i.name||void 0,f.placeholder=i.placeholder||void 0,f.value=$t(i),f.checked=i.type==="checkbox"||i.type==="radio"?i.checked:void 0,f.disabled=i.disabled,f.required=i.required):i instanceof HTMLTextAreaElement?(f.name=i.name||void 0,f.placeholder=i.placeholder||void 0,f.value=$t(i),f.disabled=i.disabled,f.required=i.required):i instanceof HTMLSelectElement?(f.name=i.name||void 0,f.value=$t(i),f.disabled=i.disabled,f.required=i.required,f.options=Array.from(i.options).map(T=>({value:T.value,label:T.text,selected:T.selected,disabled:T.disabled}))):i instanceof HTMLButtonElement?(f.type=i.type,f.disabled=i.disabled,f.text=Ft(i)):i instanceof HTMLAnchorElement?(f.href=i.href,f.text=Ft(i)):i instanceof HTMLImageElement?(f.text=i.alt||void 0,f.label=i.alt||f.label):f.text=Ft(i),f.label=Fr(i),f.role=i.getAttribute("role")||void 0,f.ariaLabel=i.getAttribute("aria-label")||void 0,c.push(f);});let a=i=>i.isVisible?o==="inputs"?i.tag==="input"||i.tag==="textarea"||i.tag==="select"||i.role==="textbox"?3:i.tag==="button"||i.tag==="a"?2:1:["header","nav","main","footer"].includes(i.tag)?5:["section","article","aside"].includes(i.tag)||["h1","h2","h3"].includes(i.tag)?4:["h4","h5","h6"].includes(i.tag)?3:i.tag==="form"?4:i.tag==="label"?3:i.tag==="input"||i.tag==="textarea"||i.tag==="select"?4:i.tag==="p"||i.tag==="img"||i.tag==="button"||i.tag==="a"?3:1:0;c.sort((i,m)=>a(m)-a(i));let M=c.length,x=Math.max(1,Math.min(200,typeof r=="number"?Math.floor(r):o==="inputs"?100:150)),g=M>x,C=g?c.slice(0,x):c;return {ok:!0,components:C,count:C.length,total:M,truncated:g,containerFound:!0}}catch(t){return {ok:false,components:[],count:0,total:0,containerFound:false,error:t?.message||String(t)}}}typeof window<"u"&&(window.getDomComponents=je);async function Ae(e,t={}){if(typeof window>"u")return {ok:false,steps:[{ok:false,action:"none",targetKind:"position",durationMs:0,error:"guideCursor only works in browser environment"}]};let n=window.__cursorGuide;if(!n)return {ok:false,steps:[{ok:false,action:"none",targetKind:"position",durationMs:0,error:"CursorController not initialized. Make sure to mount <CursorController /> component."}]};try{return await n(e,t)}catch(o){return {ok:false,steps:[{ok:false,action:t.action||"none",targetKind:"position",durationMs:0,error:o?.message||String(o)}]}}}typeof window<"u"&&(window.guideCursor=Ae);function hn(e){return !!e&&e.nodeType===1}function ue(e,t){e.dispatchEvent(new Event(t,{bubbles:true}));}function xn(e,t){let n=Object.getOwnPropertyDescriptor(Object.getPrototypeOf(e),"value")?.set;n?n.call(e,t):e.value=t,ue(e,"input");}function Lr(e,t){e.checked!==t&&e.click();}function Hr(e,t){if(typeof t=="object"&&t&&"index"in t&&typeof t.index=="number")e.selectedIndex=Math.max(0,Math.min(e.options.length-1,t.index));else if(typeof t=="object"&&t&&"label"in t&&typeof t.label=="string"){let n=Array.from(e.options).findIndex(o=>o.text===t.label);e.selectedIndex=n>=0?n:0;}else e.value=String(t);ue(e,"input"),ue(e,"change");}function Br(e,t){let n=new Set(t.map(String));Array.from(e.options).forEach(o=>{o.selected=n.has(o.value)||n.has(o.text);}),ue(e,"input"),ue(e,"change");}function Dr(e){return e?e instanceof Date?e.toISOString().slice(0,10):String(e):""}function Pr(e,t){let n=Array.isArray(t)?t:[t],o=new DataTransfer;for(let r of n)o.items.add(r);Object.defineProperty(e,"files",{value:o.files,configurable:true}),ue(e,"input"),ue(e,"change");}async function Ue(e,t={}){let n=document.activeElement||null;if(n&&hn(n)){let o=n.closest('[contenteditable="true"], [contenteditable=""]');o&&(n=o);}if(!n||n===document.body)return {ok:false,filled:[{key:"active",status:"skipped",message:"No active input element"}],errors:["No active input element"]};try{let o=n.tagName.toLowerCase();if(o==="input"){let r=n,l=(r.type||"text").toLowerCase();if(l==="checkbox")Lr(r,!!e);else if(l==="radio"){let u=r.name;if(u&&e!=null&&String(r.value)!==String(e)){let c=document.querySelector(`input[type="radio"][name="${CSS.escape(u)}"][value="${CSS.escape(String(e))}"]`);c?c.click():r.click();}else r.click();}else if(l==="file")if(e instanceof File||Array.isArray(e)&&e.every(u=>u instanceof File))Pr(r,e);else return {ok:!1,filled:[{key:"active",status:"skipped",message:"Provide File or File[] for file input"}],errors:["Provide File or File[] for file input"]};else {let u=l==="date"?Dr(e):String(e??"");xn(r,u),ue(r,"change");}return {ok:!0,filled:[{key:"active",status:"ok"}]}}if(o==="textarea"){let r=n,l=String(e??"");return xn(r,l),ue(r,"change"),{ok:!0,filled:[{key:"active",status:"ok"}]}}if(o==="select"){let r=n;return r.multiple?Br(r,Array.isArray(e)?e:[e]):Hr(r,e),{ok:!0,filled:[{key:"active",status:"ok"}]}}if(hn(n)&&n.isContentEditable){let r=n;return r.focus(),r.textContent=String(e??""),ue(r,"input"),ue(r,"change"),r.blur?.(),{ok:!0,filled:[{key:"active",status:"ok"}]}}return {ok:!1,filled:[{key:"active",status:"skipped",message:`Unsupported active element: ${o}`}],errors:[`Unsupported active element: ${o}`]}}catch(o){return {ok:false,filled:[{key:"active",status:"error",message:o?.message??String(o)}],errors:[o?.message??String(o)]}}}typeof window<"u"&&(window.FillActiveInput=Ue);var qe=null,at={},Cn=false,Be=null,lt=false;function Lt(e){e.classList.add("visible");}function Sn(){lt=true,Be!=null&&(clearTimeout(Be),Be=null);}function Wr(e,t=1500){lt||(Be!=null&&clearTimeout(Be),Be=window.setTimeout(()=>{lt||e.classList.remove("visible");},t));}function Or(e,t=1200){lt=false,Wr(e,t);}function Nr(e){let t=[],n=e?.parentElement;for(;n;){let o=getComputedStyle(n),r=o.overflow+o.overflowY+o.overflowX;/(auto|scroll)/.test(r)&&t.push(n),n=n.parentElement;}return t}async function Gr(e,t=1500,n=160){let o=performance.now(),r=e?Nr(e):[],l=()=>{let a=[window.scrollX||document.documentElement.scrollLeft||0,window.scrollY||document.documentElement.scrollTop||0];return r.forEach(M=>{a.push(M.scrollLeft,M.scrollTop);}),a},u=()=>{if(!e)return {x:0,y:0};let a=e.getBoundingClientRect();return {x:a.left,y:a.top}},c=l(),w=u(),S=performance.now();return new Promise(a=>{function M(y){let x=l(),g=u(),C=false;for(let i=0;i<x.length;i++)if(x[i]!==c[i]){C=true;break}if(!C&&e&&(g.x!==w.x||g.y!==w.y)&&(C=true),C&&(c=x,w=g,S=y),y-S>=n||y-o>=t){a();return}requestAnimationFrame(M);}requestAnimationFrame(M);})}var _r='<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 32 32" width="32px" height="32px"><path d="M 7.2304688 4.9863281 C 5.9215232 4.8276681 4.8053213 6.0177722 5.0234375 7.3066406 A 1.0001 1.0001 0 0 0 5.0253906 7.3085938 C 5.9996339 12.981516 7.7205826 18.716222 10 24.515625 A 1.0001 1.0001 0 0 0 10 24.517578 C 10.26886 25.199332 10.914322 25.653844 11.5625 25.738281 C 12.210678 25.822721 12.879213 25.592031 13.359375 25.09375 C 14.505165 23.921134 15.214424 22.695429 15.90625 21.498047 C 17.56565 23.217848 19.256845 24.909775 21.0625 26.484375 L 21.060547 26.480469 C 21.799528 27.12933 22.841378 27.205969 23.673828 26.78125 A 1.0001 1.0001 0 0 0 23.691406 26.771484 C 24.987999 26.077693 26.028685 25.052256 26.71875 23.746094 L 26.71875 23.744141 C 27.174557 22.900924 27.06954 21.854242 26.439453 21.119141 A 1.0001 1.0001 0 0 0 26.433594 21.113281 C 24.867416 19.313474 23.193611 17.633865 21.488281 15.986328 C 22.714141 15.237691 23.933938 14.51508 25.158203 13.414062 A 1.0001 1.0001 0 0 0 25.162109 13.410156 C 26.052979 12.600274 25.977319 11.169141 25.101562 10.404297 A 1.0001 1.0001 0 0 0 24.669922 10.042969 C 18.793373 7.4738953 12.973806 5.6931843 7.2324219 4.9882812 A 1.0001 1.0001 0 0 0 7.2304688 4.9863281 z M 6.9960938 6.9746094 C 12.468883 7.6474978 18.081513 9.3573116 23.796875 11.849609 A 1.0001 1.0001 0 0 0 23.867188 11.884766 C 23.901248 11.899796 23.884276 11.867987 23.816406 11.929688 C 22.403891 13.198979 20.999383 14.076858 19.457031 14.976562 A 1.0001 1.0001 0 0 0 19.275391 16.568359 C 21.250864 18.425305 23.134972 20.36916 24.919922 22.419922 C 25.009402 22.524309 25.024026 22.676488 24.960938 22.792969 A 1.0001 1.0001 0 0 0 24.955078 22.804688 C 24.446951 23.770198 23.730542 24.476149 22.755859 25 C 22.611605 25.06851 22.457885 25.047856 22.378906 24.978516 A 1.0001 1.0001 0 0 0 22.376953 24.976562 C 20.293628 23.159824 18.307991 21.233373 16.419922 19.216797 A 1.0001 1.0001 0 0 0 14.835938 19.378906 C 13.841812 21.004716 13.152668 22.447221 11.925781 23.701172 A 1.0001 1.0001 0 0 0 11.919922 23.707031 C 11.883822 23.744501 11.865156 23.739957 11.847656 23.742188 C 9.6161121 18.057657 7.9395914 12.46667 6.9960938 6.9746094 z"/></svg>',jr='<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 48 48" width="32px" height="32px"><path d="M 22.5 3 C 19.480226 3 17 5.4802259 17 8.5 L 17 23.412109 L 14.871094 22.697266 C 13.308963 22.172461 11.892528 22 10.703125 22 C 9.5908429 22 8.5540295 22.197475 7.640625 22.65625 C 5.2906802 23.831199 3.9427678 26.197397 4.0019531 28.90625 C 4.0019531 28.90625 4.0019531 28.908203 4.0019531 28.908203 C 4.0019531 28.908203 4.0019531 28.910156 4.0019531 28.910156 C 4.0184171 29.660452 4.4596385 30.354695 5.1328125 30.6875 A 1.50015 1.50015 0 0 0 5.1367188 30.689453 C 5.1367188 30.689453 9.4097266 32.789754 11.599609 33.949219 C 12.445613 34.397848 13.696939 34.926046 15.210938 36.09375 C 16.724935 37.261454 18.423179 39.012543 19.826172 41.792969 C 21.023611 44.165544 23.672779 45.195669 26.144531 44.955078 A 1.50015 1.50015 0 0 0 26.146484 44.955078 C 31.427085 44.439215 32.081856 44.381732 35.59375 44.023438 C 37.044229 43.875625 38.276993 43.213524 39.111328 42.289062 C 39.945663 41.364602 40.422895 40.257718 40.798828 39.125 C 41.561218 36.826116 42.933037 33.169846 43.671875 30.599609 C 45.018525 25.913269 41.884024 21.194549 37.246094 19.953125 L 37.242188 19.951172 C 36.99827 19.885452 36.756736 19.832884 36.521484 19.789062 A 1.50015 1.50015 0 0 0 36.513672 19.787109 L 28 18.248047 L 28 8.5 C 28 5.4802259 25.519774 3 22.5 3 z M 22.5 6 C 23.898226 6 25 7.1017741 25 8.5 L 25 19.5 A 1.50015 1.50015 0 0 0 26.232422 20.976562 L 35.980469 22.740234 C 36.14895 22.771804 36.312663 22.808524 36.464844 22.849609 A 1.50015 1.50015 0 0 0 36.46875 22.849609 C 39.614436 23.689967 41.641993 26.803286 40.789062 29.771484 C 40.115901 32.113248 38.752735 35.768572 37.953125 38.179688 C 37.641059 39.119968 37.279727 39.837554 36.882812 40.277344 C 36.485898 40.717133 36.095584 40.956874 35.289062 41.039062 C 31.783676 41.396695 31.135884 41.452908 25.855469 41.96875 C 24.423221 42.108159 23.024467 41.472831 22.503906 40.441406 C 20.887905 37.238832 18.854971 35.116296 17.042969 33.71875 C 15.230967 32.321204 13.560902 31.594199 13.003906 31.298828 C 10.939171 30.205625 7.8041786 28.665144 7.1035156 28.320312 C 7.1954033 26.8809 7.6810328 25.989859 8.9824219 25.339844 A 1.50015 1.50015 0 0 0 8.9863281 25.337891 C 9.3949198 25.132713 9.9434071 25 10.703125 25 C 11.605722 25 12.680146 25.12582 13.916016 25.541016 L 18.021484 26.921875 A 1.50015 1.50015 0 0 0 20 25.5 L 20 8.5 C 20 7.1017741 21.101774 6 22.5 6 z"/></svg>';async function Ur(){if(!at.arrow)try{at.arrow=_r,at.pointer=jr;}catch(e){console.warn("Failed to set cursor SVGs",e);}return at}function kn({arrowSvg:e,pointerSvg:t}){return jsxs(Fragment,{children:[e&&jsx("div",{className:"arrow",dangerouslySetInnerHTML:{__html:e}}),t&&jsx("div",{className:"pointer",dangerouslySetInnerHTML:{__html:t}})]})}async function qr(){let e="demo-fake-cursor",t=document.getElementById(e),n=await Ur();if(!Cn){let o="cursor-controller-styles";if(!document.getElementById(o)){let r=document.createElement("style");r.id=o,r.textContent=`
|
|
22
|
+
`}),jsxs("div",{style:{display:"flex",flexDirection:"column"},children:[e.map((m,h)=>{let C=Array.isArray(m.parts)?m.parts:[],E=C.filter(w=>w.type==="text").map(w=>w&&typeof w.text=="string"?w.text:"").join(`
|
|
23
|
+
`),M=C.filter(w=>w.type==="file"||w.type==="image").map(w=>{if(w.type==="image"){let y=typeof w.image=="string"?w.image:w.image?.toString?.()||"";return {id:y||`${m.id}-img-${Date.now()}`,name:w.name||"image",url:y,mimeType:w.mediaType||"image/jpeg",size:w.size||0}}else return {id:w.url||`${m.id}-file-${Date.now()}`,name:w.name||"file",url:w.url||"",mimeType:w.mediaType||"application/octet-stream",size:w.size||0}});return jsx("div",{style:{padding:"0 4px"},children:m.role==="user"?c===m.id?jsx(gn,{messageId:m.id,initialText:E,editingText:v,onEditingTextChange:S,onCancel:a,onSave:T,streaming:t,resolvedColors:r,attachments:f,onRemoveAttachment:b,onAddAttachments:g,uploading:k,t:l}):jsx("div",{children:jsxs("div",{title:l("editor.clickToEdit"),onClick:()=>u(m.id,E,M),style:{maxWidth:"720px",borderRadius:"16px",padding:"16px",fontSize:"15px",lineHeight:"1.6",whiteSpace:"pre-wrap",cursor:"pointer",transition:"background-color 0.2s",backgroundColor:r.accentColor,color:r.textColor,marginBottom:"16px",marginTop:"16px"},onMouseEnter:w=>w.currentTarget.style.backgroundColor=r.hoverBackground,onMouseLeave:w=>w.currentTarget.style.backgroundColor=r.accentColor,children:[E,M.length>0&&jsx(at,{attachments:M,resolvedColors:r})]})}):jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"12px"},children:[jsx(cn,{parts:C,messageId:m.id,openReasoningIds:n,toggleReasoning:o,resolvedColors:r}),(()=>{let w=C.find(y=>y.type==="data-final-response"&&y.data&&Array.isArray(y.data.items));return w?jsx(dn,{items:w.data.items,resolvedColors:r,UIComponents:i}):null})()]})},m.id)}),t&&jsxs("div",{style:{display:"flex",alignItems:"center",gap:"4px",padding:"0 4px",height:"20px"},children:[jsx("span",{style:{display:"inline-block",width:"4px",height:"4px",borderRadius:"50%",backgroundColor:r.mutedTextColor,animation:"jumpingDots 1s infinite ease-in-out",animationDelay:"0s"}}),jsx("span",{style:{display:"inline-block",width:"4px",height:"4px",borderRadius:"50%",backgroundColor:r.mutedTextColor,animation:"jumpingDots 1s infinite ease-in-out",animationDelay:"0.2s"}}),jsx("span",{style:{display:"inline-block",width:"4px",height:"4px",borderRadius:"50%",backgroundColor:r.mutedTextColor,animation:"jumpingDots 1s infinite ease-in-out",animationDelay:"0.4s"}})]})]})]})}function yn({input:e,setInput:t,textareaRef:n,fileInputRef:o,isLoading:r,uploading:l,attachments:u,formatBytes:c,handleRemoveAttachment:v,onFileInputChange:S,onSend:a,onStop:T,status:f,t:b,resolvedColors:g}){let k=f==="streaming"||f==="submitted",i=u.length>0||e.trim().length>0;return jsx("div",{style:{position:"sticky",bottom:"0",marginTop:"auto",paddingBottom:"8px",paddingTop:"4px"},children:jsx("div",{style:{position:"relative",flex:1},children:jsxs("div",{style:{position:"relative",width:"100%",borderRadius:"16px",paddingBottom:"48px",paddingTop:"16px",border:`1px solid ${g.borderColor}`,backgroundColor:g.cardBackground},children:[u.length>0&&jsx("div",{style:{padding:"0px 16px 12px 16px",display:"flex",flexWrap:"wrap",gap:"10px"},children:u.map(m=>{let h=m.mimeType.startsWith("image/");return jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px",padding:"8px 12px",backgroundColor:g.inputBackground,borderRadius:"10px",border:`1px solid ${g.borderColor}`,fontSize:"12px",color:g.textColor,position:"relative"},children:[jsx("div",{style:{display:"flex",alignItems:"center",justifyContent:"center",width:"20px",height:"20px",borderRadius:"4px",backgroundColor:h?"transparent":g.cardBackground},children:h?jsx("img",{src:m.url,alt:m.name,style:{width:"20px",height:"20px",borderRadius:"4px",objectFit:"cover"}}):jsx("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:jsx("rect",{x:"4",y:"4",width:"16",height:"20",rx:"2",ry:"2"})})}),jsxs("div",{style:{display:"flex",flexDirection:"column",minWidth:0,flex:1},children:[jsx("span",{title:m.name,style:{maxWidth:"140px",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",fontWeight:500},children:m.name}),jsx("span",{style:{color:g.mutedTextColor,fontSize:"10px",marginTop:"2px"},children:c(m.size)})]}),jsxs("div",{style:{display:"flex",alignItems:"center",gap:"4px",marginLeft:"8px"},children:[h&&jsx("a",{href:m.url,target:"_blank",rel:"noopener noreferrer",style:{background:"none",border:"none",color:g.mutedTextColor,cursor:"pointer",padding:"2px",display:"flex",alignItems:"center",borderRadius:"4px",textDecoration:"none"},title:b("input.previewImage"),children:jsxs("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[jsx("path",{d:"M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"}),jsx("circle",{cx:"12",cy:"12",r:"3"})]})}),jsx("button",{onClick:()=>v(m.id),style:{background:"none",border:"none",color:g.mutedTextColor,cursor:"pointer",padding:"2px",display:"flex",alignItems:"center",borderRadius:"4px"},title:b("input.removeFile"),children:jsxs("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[jsx("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),jsx("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]})})]})]},m.id)})}),l&&jsxs("div",{style:{padding:"0px 16px 12px 16px",display:"flex",alignItems:"center",gap:"8px",fontSize:"13px",color:g.mutedTextColor},children:[jsx("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{animation:"spin 1s linear infinite"},children:jsx("path",{d:"M21 12a9 9 0 1 1-6.219-8.56"})}),jsx("span",{children:b("input.uploadingFiles")})]}),jsx("div",{style:{padding:"0 16px"},children:jsx("textarea",{ref:n,"aria-label":"Prompt",rows:1,placeholder:b("input.placeholder"),value:e,onChange:m=>t(m.target.value),onKeyDown:m=>{m.key==="Enter"&&!m.shiftKey&&(m.preventDefault(),a());},disabled:r||l,style:{height:"24px",maxHeight:"200px",width:"100%",resize:"none",backgroundColor:"transparent",fontSize:"15px",lineHeight:"1.6",outline:"none",border:"none",color:g.textColor,fontFamily:"inherit",overflow:"auto"}})}),jsx("input",{ref:o,type:"file",multiple:true,onChange:S,style:{display:"none"},accept:"*/*"}),jsx("div",{style:{position:"absolute",bottom:"8px",left:"8px",display:"flex",alignItems:"center",gap:"4px",color:g.mutedTextColor},children:jsx("button",{onClick:()=>o.current?.click(),disabled:r||l,style:{borderRadius:"8px",padding:"8px",transition:"all 0.2s",backgroundColor:"transparent",border:"none",cursor:r||l?"not-allowed":"pointer",display:"flex",alignItems:"center",justifyContent:"center",color:"inherit",opacity:r||l?.5:1},"aria-label":b("input.attachFiles"),children:jsx("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:jsx("path",{d:"M21.44 11.05l-9.19 9.19a6 6 0 0 1-8.49-8.49l9.19-9.19a4 4 0 1 1 5.66 5.66l-9.2 9.19a2 2 0 1 1-2.83-2.83l8.49-8.49"})})})}),jsx("div",{style:{position:"absolute",bottom:"8px",right:"8px"},children:r?jsx("button",{onClick:T,disabled:!k,"aria-label":b("input.stop"),title:"Stop generation",style:{borderRadius:"12px",padding:"12px",transition:"all 0.2s ease-out",border:"1px solid #ef4444",backgroundColor:"#ef444420",color:"#ef4444",opacity:k?1:.4,cursor:k?"pointer":"not-allowed",display:"flex",alignItems:"center",justifyContent:"center"},onMouseEnter:m=>{k&&(m.currentTarget.style.backgroundColor="#ef444430",m.currentTarget.style.transform="scale(1.02)");},onMouseLeave:m=>{m.currentTarget.style.backgroundColor="#ef444420",m.currentTarget.style.transform="scale(1)";},children:jsx("svg",{xmlns:"http://www.w3.org/2000/svg",width:"24",height:"24",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:jsx("rect",{width:"18",height:"18",x:"3",y:"3",rx:"2"})})}):jsx("button",{onClick:a,disabled:!i||l,"aria-label":b("input.send"),title:"Send message",style:{borderRadius:"12px",padding:"12px",transition:"all 0.2s ease-out",border:`1px solid ${g.borderColor}`,backgroundColor:g.cardBackground,color:!i||l?g.mutedTextColor:g.primaryColor,cursor:!i||l?"not-allowed":"pointer",display:"flex",alignItems:"center",justifyContent:"center",opacity:!i||l?.5:1},onMouseEnter:m=>{i&&!l&&(m.currentTarget.style.borderColor=g.primaryColor,m.currentTarget.style.transform="scale(1.02)");},onMouseLeave:m=>{m.currentTarget.style.borderColor=g.borderColor,m.currentTarget.style.transform="scale(1)";},children:jsxs("svg",{xmlns:"http://www.w3.org/2000/svg",width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[jsx("path",{d:"m5 12 7-7 7 7"}),jsx("path",{d:"M12 19V5"})]})})})]})})})}function $t(e){let t=`hsafaChat_${e}`,n=`${t}.chats`,o=C=>`${t}.chat.${C}`,r=`${t}.currentChatId`,l=`${t}.showChat`,u=()=>{try{let C=localStorage.getItem(n);return C?JSON.parse(C):[]}catch{return []}},c=C=>{try{localStorage.setItem(n,JSON.stringify(C));}catch{}},v=C=>{try{let E=localStorage.getItem(o(C));return E?JSON.parse(E):null}catch{return null}},S=C=>{try{localStorage.setItem(o(C.id),JSON.stringify(C));}catch{}},a=C=>{let E=u(),M=E.findIndex(w=>w.id===C.id);M>=0?E[M]=C:E.unshift(C),c(E);},T=C=>{let M=u().filter(w=>w.id!==C);c(M);},f=C=>{try{localStorage.removeItem(o(C));}catch{}};return {loadChatsIndex:u,saveChatsIndex:c,loadChat:v,saveChat:S,upsertChatMeta:a,deleteChatMeta:T,deleteChatData:f,deleteChat:C=>{f(C),T(C);},loadShowChatPreference:C=>{try{let E=localStorage.getItem(l);return E!==null?E==="true":C}catch{return C}},saveShowChatPreference:C=>{try{localStorage.setItem(l,String(C));}catch{}},loadCurrentChatId:()=>{try{return localStorage.getItem(r)}catch{return null}},saveCurrentChatId:C=>{try{localStorage.setItem(r,C);}catch{}},removeCurrentChatId:()=>{try{localStorage.removeItem(r);}catch{}}}}function hn(e){let t=Date.now()-e,n=Math.max(1,Math.floor(t/1e3));if(n<60)return `${n}s`;let o=Math.floor(n/60);if(o<60)return `${o}m`;let r=Math.floor(o/60);if(r<24)return `${r}h`;let l=Math.floor(r/24);if(l<7)return `${l}d`;let u=Math.floor(l/7);if(u<4)return `${u}w`;let c=Math.floor(l/30);return c<12?`${c}mo`:`${Math.floor(c/12)}y`}function xn({historyOpen:e,historySearch:t,currentChatId:n,refreshKey:o,resolvedColors:r,onClose:l,onSearchChange:u,onChatSelect:c,onChatDelete:v,loadChatsIndex:S,historyPopupRef:a}){if(!e)return null;let T=jsxs(Fragment,{children:[jsx("div",{style:{position:"fixed",inset:"0",zIndex:1100,backgroundColor:"rgba(0, 0, 0, 0.4)",backdropFilter:"blur(4px)",WebkitBackdropFilter:"blur(4px)"},onClick:l}),jsxs("div",{ref:a,style:{position:"fixed",left:"50%",top:"64px",transform:"translateX(-50%)",zIndex:1101,width:"680px",maxWidth:"94vw",overflow:"hidden",borderRadius:"16px",border:`1px solid ${r.borderColor}`,backgroundColor:`${r.backgroundColor}f0`,boxShadow:"0 25px 50px -12px rgba(0, 0, 0, 0.25)",backdropFilter:"blur(16px)",WebkitBackdropFilter:"blur(16px)"},children:[jsx("div",{style:{display:"flex",alignItems:"center",gap:"12px",borderBottom:`1px solid ${r.borderColor}`,padding:"12px 16px"},children:jsx("div",{style:{flex:"1"},children:jsx("input",{autoFocus:true,value:t,onChange:f=>u(f.target.value),placeholder:"Search",style:{width:"100%",borderRadius:"8px",backgroundColor:r.inputBackground,padding:"8px 12px",fontSize:"14px",color:r.textColor,border:`1px solid ${r.borderColor}`,outline:"none"},onFocus:f=>f.currentTarget.style.borderColor=r.primaryColor,onBlur:f=>f.currentTarget.style.borderColor=r.borderColor})})}),jsx("div",{style:{maxHeight:"60vh",overflowY:"auto"},children:(()=>{let f=t.toLowerCase().trim(),b=S();return f&&(b=b.filter(g=>(g.title||"").toLowerCase().includes(f))),!b||b.length===0?jsx("div",{style:{padding:"24px",color:r.mutedTextColor,textAlign:"center"},children:"No chats found."}):jsx("div",{children:b.map((g,k)=>jsx("div",{style:{borderTop:k>0?`1px solid ${r.borderColor}`:"none"},children:jsxs("div",{style:{display:"flex",width:"100%",alignItems:"center",justifyContent:"space-between",gap:"12px",padding:"12px",backgroundColor:g.id===n?r.cardBackground:"transparent"},children:[jsx("button",{style:{flex:"1",textAlign:"left",transition:"background-color 0.2s",borderRadius:"8px",padding:"8px",border:"none",backgroundColor:"transparent",cursor:"pointer",color:r.textColor},onMouseEnter:i=>i.currentTarget.style.backgroundColor=r.hoverBackground,onMouseLeave:i=>i.currentTarget.style.backgroundColor="transparent",onClick:()=>c(g.id),children:jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:"12px"},children:[jsx("div",{style:{minWidth:"0",flex:"1"},children:jsx("div",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",fontSize:"14px",color:r.textColor},children:g.title||"Untitled chat"})}),jsx("div",{style:{flexShrink:0,fontSize:"12px",color:r.mutedTextColor},children:hn(g.updatedAt)})]})}),jsx("button",{style:{flexShrink:0,borderRadius:"6px",padding:"8px",color:r.mutedTextColor,border:"1px solid transparent",backgroundColor:"transparent",cursor:"pointer",transition:"all 0.2s"},title:"Delete chat",onMouseEnter:i=>{i.currentTarget.style.color="#ef4444",i.currentTarget.style.backgroundColor="rgba(239, 68, 68, 0.1)",i.currentTarget.style.borderColor="rgba(239, 68, 68, 0.3)";},onMouseLeave:i=>{i.currentTarget.style.color=r.mutedTextColor,i.currentTarget.style.backgroundColor="transparent",i.currentTarget.style.borderColor="transparent";},onClick:i=>{i.stopPropagation(),v(g.id);},children:jsx(se,{IconComponent:Trash2,size:"16",strokeWidth:"2"})})]})},g.id))})})()})]})]});return typeof document<"u"&&document.body?createPortal(T,document.body):T}function $r(e){if(!(e instanceof HTMLElement))return true;let t=window.getComputedStyle(e);return t.display!=="none"&&t.visibility!=="hidden"&&t.opacity!=="0"&&e.offsetParent!==null}function Lr(e){if(e.id){let n=document.querySelector(`label[for="${e.id}"]`);if(n)return n.textContent?.trim()}let t=e.closest("label");if(t){let n=t.cloneNode(true),o=n.querySelector("input, select, textarea");return o&&o.remove(),n.textContent?.trim()}}function Lt(e){if(e.textContent&&e.textContent.trim())return e.textContent.trim().slice(0,100)}function Ht(e){if(e instanceof HTMLInputElement){let t=e.type.toLowerCase();return t==="checkbox"||t==="radio"?e.checked:e.value}if(e instanceof HTMLTextAreaElement)return e.value;if(e instanceof HTMLSelectElement)return e.multiple?Array.from(e.selectedOptions).map(t=>t.value):e.value;if(e instanceof HTMLElement&&e.isContentEditable)return e.textContent||void 0}function Hr(e){if(e.id)return `#${e.id}`;let t=[],n=e;for(;n&&n!==document.body;){let o=n.tagName.toLowerCase();if(n.className&&typeof n.className=="string"){let l=n.className.split(" ").filter(u=>u.trim()).slice(0,2);l.length>0&&(o+="."+l.join("."));}let r=n.parentElement;if(r){let l=Array.from(r.children).filter(u=>u.tagName===n.tagName);if(l.length>1){let u=l.indexOf(n)+1;o+=`:nth-child(${u})`;}}t.unshift(o),n=r;}return t.slice(-3).join(" > ")}async function je(e={}){try{let{includeHidden:t=!1,selector:n,what:o="content",limit:r}=e,l=document.querySelector(".hsafa-content-container");if(!l)return {ok:!1,components:[],count:0,total:0,containerFound:!1,error:"ContentContainer not found on page. Make sure you have wrapped your app with <ContentContainer>."};let u=n&&l.querySelector(n)||l,c=[],v=[];o==="inputs"?v=["input","textarea","select",'[contenteditable="true"]','[contenteditable=""]']:v=["header","nav","main","section","article","aside","footer","h1","h2","h3","h4","h5","h6","p","img[alt]","ul","ol","li","table","thead","tbody","tr","td","th","form","label","input","textarea","select",'[contenteditable="true"]','[contenteditable=""]',"a[href]","button",'[role="button"]','[role="link"]',"[onclick]","[tabindex]","div"],u.querySelectorAll(v.join(", ")).forEach(i=>{let m=$r(i);if(!m&&!t)return;let h={id:i.id||null,tag:i.tagName.toLowerCase(),className:i.className&&typeof i.className=="string"?i.className:void 0,isVisible:m,isInteractive:!0,selector:Hr(i)};i instanceof HTMLInputElement?(h.type=i.type,h.name=i.name||void 0,h.placeholder=i.placeholder||void 0,h.value=Ht(i),h.checked=i.type==="checkbox"||i.type==="radio"?i.checked:void 0,h.disabled=i.disabled,h.required=i.required):i instanceof HTMLTextAreaElement?(h.name=i.name||void 0,h.placeholder=i.placeholder||void 0,h.value=Ht(i),h.disabled=i.disabled,h.required=i.required):i instanceof HTMLSelectElement?(h.name=i.name||void 0,h.value=Ht(i),h.disabled=i.disabled,h.required=i.required,h.options=Array.from(i.options).map(C=>({value:C.value,label:C.text,selected:C.selected,disabled:C.disabled}))):i instanceof HTMLButtonElement?(h.type=i.type,h.disabled=i.disabled,h.text=Lt(i)):i instanceof HTMLAnchorElement?(h.href=i.href,h.text=Lt(i)):i instanceof HTMLImageElement?(h.text=i.alt||void 0,h.label=i.alt||h.label):h.text=Lt(i),h.label=Lr(i),h.role=i.getAttribute("role")||void 0,h.ariaLabel=i.getAttribute("aria-label")||void 0,c.push(h);});let a=i=>i.isVisible?o==="inputs"?i.tag==="input"||i.tag==="textarea"||i.tag==="select"||i.role==="textbox"?3:i.tag==="button"||i.tag==="a"?2:1:["header","nav","main","footer"].includes(i.tag)?5:["section","article","aside"].includes(i.tag)||["h1","h2","h3"].includes(i.tag)?4:["h4","h5","h6"].includes(i.tag)?3:i.tag==="form"?4:i.tag==="label"?3:i.tag==="input"||i.tag==="textarea"||i.tag==="select"?4:i.tag==="p"||i.tag==="img"||i.tag==="button"||i.tag==="a"?3:1:0;c.sort((i,m)=>a(m)-a(i));let T=c.length,b=Math.max(1,Math.min(200,typeof r=="number"?Math.floor(r):o==="inputs"?100:150)),g=T>b,k=g?c.slice(0,b):c;return {ok:!0,components:k,count:k.length,total:T,truncated:g,containerFound:!0}}catch(t){return {ok:false,components:[],count:0,total:0,containerFound:false,error:t?.message||String(t)}}}typeof window<"u"&&(window.getDomComponents=je);async function Ee(e,t={}){if(typeof window>"u")return {ok:false,steps:[{ok:false,action:"none",targetKind:"position",durationMs:0,error:"guideCursor only works in browser environment"}]};let n=window.__cursorGuide;if(!n)return {ok:false,steps:[{ok:false,action:"none",targetKind:"position",durationMs:0,error:"CursorController not initialized. Make sure to mount <CursorController /> component."}]};try{return await n(e,t)}catch(o){return {ok:false,steps:[{ok:false,action:t.action||"none",targetKind:"position",durationMs:0,error:o?.message||String(o)}]}}}typeof window<"u"&&(window.guideCursor=Ee);function bn(e){return !!e&&e.nodeType===1}function ue(e,t){e.dispatchEvent(new Event(t,{bubbles:true}));}function Cn(e,t){let n=Object.getOwnPropertyDescriptor(Object.getPrototypeOf(e),"value")?.set;n?n.call(e,t):e.value=t,ue(e,"input");}function Br(e,t){e.checked!==t&&e.click();}function Dr(e,t){if(typeof t=="object"&&t&&"index"in t&&typeof t.index=="number")e.selectedIndex=Math.max(0,Math.min(e.options.length-1,t.index));else if(typeof t=="object"&&t&&"label"in t&&typeof t.label=="string"){let n=Array.from(e.options).findIndex(o=>o.text===t.label);e.selectedIndex=n>=0?n:0;}else e.value=String(t);ue(e,"input"),ue(e,"change");}function Pr(e,t){let n=new Set(t.map(String));Array.from(e.options).forEach(o=>{o.selected=n.has(o.value)||n.has(o.text);}),ue(e,"input"),ue(e,"change");}function zr(e){return e?e instanceof Date?e.toISOString().slice(0,10):String(e):""}function Wr(e,t){let n=Array.isArray(t)?t:[t],o=new DataTransfer;for(let r of n)o.items.add(r);Object.defineProperty(e,"files",{value:o.files,configurable:true}),ue(e,"input"),ue(e,"change");}async function Ue(e,t={}){let n=document.activeElement||null;if(n&&bn(n)){let o=n.closest('[contenteditable="true"], [contenteditable=""]');o&&(n=o);}if(!n||n===document.body)return {ok:false,filled:[{key:"active",status:"skipped",message:"No active input element"}],errors:["No active input element"]};try{let o=n.tagName.toLowerCase();if(o==="input"){let r=n,l=(r.type||"text").toLowerCase();if(l==="checkbox")Br(r,!!e);else if(l==="radio"){let u=r.name;if(u&&e!=null&&String(r.value)!==String(e)){let c=document.querySelector(`input[type="radio"][name="${CSS.escape(u)}"][value="${CSS.escape(String(e))}"]`);c?c.click():r.click();}else r.click();}else if(l==="file")if(e instanceof File||Array.isArray(e)&&e.every(u=>u instanceof File))Wr(r,e);else return {ok:!1,filled:[{key:"active",status:"skipped",message:"Provide File or File[] for file input"}],errors:["Provide File or File[] for file input"]};else {let u=l==="date"?zr(e):String(e??"");Cn(r,u),ue(r,"change");}return {ok:!0,filled:[{key:"active",status:"ok"}]}}if(o==="textarea"){let r=n,l=String(e??"");return Cn(r,l),ue(r,"change"),{ok:!0,filled:[{key:"active",status:"ok"}]}}if(o==="select"){let r=n;return r.multiple?Pr(r,Array.isArray(e)?e:[e]):Dr(r,e),{ok:!0,filled:[{key:"active",status:"ok"}]}}if(bn(n)&&n.isContentEditable){let r=n;return r.focus(),r.textContent=String(e??""),ue(r,"input"),ue(r,"change"),r.blur?.(),{ok:!0,filled:[{key:"active",status:"ok"}]}}return {ok:!1,filled:[{key:"active",status:"skipped",message:`Unsupported active element: ${o}`}],errors:[`Unsupported active element: ${o}`]}}catch(o){return {ok:false,filled:[{key:"active",status:"error",message:o?.message??String(o)}],errors:[o?.message??String(o)]}}}typeof window<"u"&&(window.FillActiveInput=Ue);var qe=null,lt={},vn=false,Be=null,dt=false;function Bt(e){e.classList.add("visible");}function An(){dt=true,Be!=null&&(clearTimeout(Be),Be=null);}function Nr(e,t=1500){dt||(Be!=null&&clearTimeout(Be),Be=window.setTimeout(()=>{dt||e.classList.remove("visible");},t));}function Gr(e,t=1200){dt=false,Nr(e,t);}function _r(e){let t=[],n=e?.parentElement;for(;n;){let o=getComputedStyle(n),r=o.overflow+o.overflowY+o.overflowX;/(auto|scroll)/.test(r)&&t.push(n),n=n.parentElement;}return t}async function jr(e,t=1500,n=160){let o=performance.now(),r=e?_r(e):[],l=()=>{let a=[window.scrollX||document.documentElement.scrollLeft||0,window.scrollY||document.documentElement.scrollTop||0];return r.forEach(T=>{a.push(T.scrollLeft,T.scrollTop);}),a},u=()=>{if(!e)return {x:0,y:0};let a=e.getBoundingClientRect();return {x:a.left,y:a.top}},c=l(),v=u(),S=performance.now();return new Promise(a=>{function T(f){let b=l(),g=u(),k=false;for(let i=0;i<b.length;i++)if(b[i]!==c[i]){k=true;break}if(!k&&e&&(g.x!==v.x||g.y!==v.y)&&(k=true),k&&(c=b,v=g,S=f),f-S>=n||f-o>=t){a();return}requestAnimationFrame(T);}requestAnimationFrame(T);})}var Ur='<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 32 32" width="32px" height="32px"><path d="M 7.2304688 4.9863281 C 5.9215232 4.8276681 4.8053213 6.0177722 5.0234375 7.3066406 A 1.0001 1.0001 0 0 0 5.0253906 7.3085938 C 5.9996339 12.981516 7.7205826 18.716222 10 24.515625 A 1.0001 1.0001 0 0 0 10 24.517578 C 10.26886 25.199332 10.914322 25.653844 11.5625 25.738281 C 12.210678 25.822721 12.879213 25.592031 13.359375 25.09375 C 14.505165 23.921134 15.214424 22.695429 15.90625 21.498047 C 17.56565 23.217848 19.256845 24.909775 21.0625 26.484375 L 21.060547 26.480469 C 21.799528 27.12933 22.841378 27.205969 23.673828 26.78125 A 1.0001 1.0001 0 0 0 23.691406 26.771484 C 24.987999 26.077693 26.028685 25.052256 26.71875 23.746094 L 26.71875 23.744141 C 27.174557 22.900924 27.06954 21.854242 26.439453 21.119141 A 1.0001 1.0001 0 0 0 26.433594 21.113281 C 24.867416 19.313474 23.193611 17.633865 21.488281 15.986328 C 22.714141 15.237691 23.933938 14.51508 25.158203 13.414062 A 1.0001 1.0001 0 0 0 25.162109 13.410156 C 26.052979 12.600274 25.977319 11.169141 25.101562 10.404297 A 1.0001 1.0001 0 0 0 24.669922 10.042969 C 18.793373 7.4738953 12.973806 5.6931843 7.2324219 4.9882812 A 1.0001 1.0001 0 0 0 7.2304688 4.9863281 z M 6.9960938 6.9746094 C 12.468883 7.6474978 18.081513 9.3573116 23.796875 11.849609 A 1.0001 1.0001 0 0 0 23.867188 11.884766 C 23.901248 11.899796 23.884276 11.867987 23.816406 11.929688 C 22.403891 13.198979 20.999383 14.076858 19.457031 14.976562 A 1.0001 1.0001 0 0 0 19.275391 16.568359 C 21.250864 18.425305 23.134972 20.36916 24.919922 22.419922 C 25.009402 22.524309 25.024026 22.676488 24.960938 22.792969 A 1.0001 1.0001 0 0 0 24.955078 22.804688 C 24.446951 23.770198 23.730542 24.476149 22.755859 25 C 22.611605 25.06851 22.457885 25.047856 22.378906 24.978516 A 1.0001 1.0001 0 0 0 22.376953 24.976562 C 20.293628 23.159824 18.307991 21.233373 16.419922 19.216797 A 1.0001 1.0001 0 0 0 14.835938 19.378906 C 13.841812 21.004716 13.152668 22.447221 11.925781 23.701172 A 1.0001 1.0001 0 0 0 11.919922 23.707031 C 11.883822 23.744501 11.865156 23.739957 11.847656 23.742188 C 9.6161121 18.057657 7.9395914 12.46667 6.9960938 6.9746094 z"/></svg>',qr='<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 48 48" width="32px" height="32px"><path d="M 22.5 3 C 19.480226 3 17 5.4802259 17 8.5 L 17 23.412109 L 14.871094 22.697266 C 13.308963 22.172461 11.892528 22 10.703125 22 C 9.5908429 22 8.5540295 22.197475 7.640625 22.65625 C 5.2906802 23.831199 3.9427678 26.197397 4.0019531 28.90625 C 4.0019531 28.90625 4.0019531 28.908203 4.0019531 28.908203 C 4.0019531 28.908203 4.0019531 28.910156 4.0019531 28.910156 C 4.0184171 29.660452 4.4596385 30.354695 5.1328125 30.6875 A 1.50015 1.50015 0 0 0 5.1367188 30.689453 C 5.1367188 30.689453 9.4097266 32.789754 11.599609 33.949219 C 12.445613 34.397848 13.696939 34.926046 15.210938 36.09375 C 16.724935 37.261454 18.423179 39.012543 19.826172 41.792969 C 21.023611 44.165544 23.672779 45.195669 26.144531 44.955078 A 1.50015 1.50015 0 0 0 26.146484 44.955078 C 31.427085 44.439215 32.081856 44.381732 35.59375 44.023438 C 37.044229 43.875625 38.276993 43.213524 39.111328 42.289062 C 39.945663 41.364602 40.422895 40.257718 40.798828 39.125 C 41.561218 36.826116 42.933037 33.169846 43.671875 30.599609 C 45.018525 25.913269 41.884024 21.194549 37.246094 19.953125 L 37.242188 19.951172 C 36.99827 19.885452 36.756736 19.832884 36.521484 19.789062 A 1.50015 1.50015 0 0 0 36.513672 19.787109 L 28 18.248047 L 28 8.5 C 28 5.4802259 25.519774 3 22.5 3 z M 22.5 6 C 23.898226 6 25 7.1017741 25 8.5 L 25 19.5 A 1.50015 1.50015 0 0 0 26.232422 20.976562 L 35.980469 22.740234 C 36.14895 22.771804 36.312663 22.808524 36.464844 22.849609 A 1.50015 1.50015 0 0 0 36.46875 22.849609 C 39.614436 23.689967 41.641993 26.803286 40.789062 29.771484 C 40.115901 32.113248 38.752735 35.768572 37.953125 38.179688 C 37.641059 39.119968 37.279727 39.837554 36.882812 40.277344 C 36.485898 40.717133 36.095584 40.956874 35.289062 41.039062 C 31.783676 41.396695 31.135884 41.452908 25.855469 41.96875 C 24.423221 42.108159 23.024467 41.472831 22.503906 40.441406 C 20.887905 37.238832 18.854971 35.116296 17.042969 33.71875 C 15.230967 32.321204 13.560902 31.594199 13.003906 31.298828 C 10.939171 30.205625 7.8041786 28.665144 7.1035156 28.320312 C 7.1954033 26.8809 7.6810328 25.989859 8.9824219 25.339844 A 1.50015 1.50015 0 0 0 8.9863281 25.337891 C 9.3949198 25.132713 9.9434071 25 10.703125 25 C 11.605722 25 12.680146 25.12582 13.916016 25.541016 L 18.021484 26.921875 A 1.50015 1.50015 0 0 0 20 25.5 L 20 8.5 C 20 7.1017741 21.101774 6 22.5 6 z"/></svg>';async function Vr(){if(!lt.arrow)try{lt.arrow=Ur,lt.pointer=qr;}catch(e){console.warn("Failed to set cursor SVGs",e);}return lt}function wn({arrowSvg:e,pointerSvg:t}){return jsxs(Fragment,{children:[e&&jsx("div",{className:"arrow",dangerouslySetInnerHTML:{__html:e}}),t&&jsx("div",{className:"pointer",dangerouslySetInnerHTML:{__html:t}})]})}async function Kr(){let e="demo-fake-cursor",t=document.getElementById(e),n=await Vr();if(!vn){let o="cursor-controller-styles";if(!document.getElementById(o)){let r=document.createElement("style");r.id=o,r.textContent=`
|
|
24
24
|
.fake-cursor { pointer-events: none; opacity: 0; transition: opacity 0.2s ease; z-index: 2147483647; }
|
|
25
25
|
.fake-cursor.visible { opacity: 1; }
|
|
26
26
|
.fake-cursor .arrow { display: none; }
|
|
@@ -30,14 +30,14 @@ import {jsxs,jsx,Fragment}from'react/jsx-runtime';import nt,{createContext,useRe
|
|
|
30
30
|
.fake-cursor.as-pointer .arrow { display: none; }
|
|
31
31
|
.fake-cursor.as-pointer .pointer { display: block; }
|
|
32
32
|
.fake-cursor.pressing .pointer svg path { filter: brightness(0.9); }
|
|
33
|
-
`,document.head.appendChild(r);}Cn=true;}return t?(t.classList.add("as-arrow"),qe||(qe=createRoot(t),qe.render(jsx(kn,{arrowSvg:n.arrow,pointerSvg:n.pointer})))):(t=document.createElement("div"),t.id=e,t.className="fake-cursor as-arrow",t.style.position="fixed",t.style.left="20px",t.style.top="20px",document.body.appendChild(t),qe=createRoot(t),qe.render(jsx(kn,{arrowSvg:n.arrow,pointerSvg:n.pointer}))),t}function De(e,t,n){return Math.max(t,Math.min(n,e))}function Vr(e){return e<.5?4*e*e*e:1-Math.pow(-2*e+2,3)/2}function En(e){if(!e)return null;let t=document.createElement("canvas").getContext("2d");if(!t)return null;t.fillStyle="#000",t.fillStyle=e;let o=t.fillStyle.match(/rgba?\(([^)]+)\)/i);if(!o)return null;let r=o[1].split(/\s*,\s*/).map(Number),[l,u,c,w=1]=r;return {r:l,g:u,b:c,a:w}}function Kr({r:e,g:t,b:n}){let o=[e,t,n].map(r=>r/255).map(r=>r<=.03928?r/12.92:Math.pow((r+.055)/1.055,2.4));return .2126*o[0]+.7152*o[1]+.0722*o[2]}function Xr(e){let t=e?En(e):null;return !t||t.a===0?false:Kr(t)<.5}function Yr(e,t){let n=document.elementFromPoint(e,t),o=new Set;for(;n&&!o.has(n);){o.add(n);let u=getComputedStyle(n).backgroundColor,c=En(u);if(c&&c.a>0)return u;n=n.parentElement;}return getComputedStyle(document.body).backgroundColor||"rgb(255,255,255)"}function Ht(e,t,n){let o=Yr(t,n),r=Xr(o),l=r?"#ffffff":"#000000";e.querySelectorAll("svg path").forEach(c=>{c.style.fill="white",c.style.stroke=l,c.style.strokeWidth="1";}),e.style.filter=r?"drop-shadow(0 1px 2px rgba(0,0,0,0.8))":"drop-shadow(0 1px 2px rgba(255,255,255,0.9))";}async function st(e,t,n,o,r="ease-in-out",l="curve",u=.25,c="auto",w){Sn(),Lt(e);let S=performance.now(),a=r==="linear"?x=>x:Vr,M=l!=="straight",y={x:0,y:0};if(M){let x=n.x-t.x,g=n.y-t.y,C=Math.hypot(x,g)||1,i=(t.x+n.x)/2,m=(t.y+n.y)/2,f=-g/C,T=x/C,R=1;c==="left"?R=-1:c==="right"?R=1:R=Math.random()<.5?-1:1;let v=De(u,0,1)*C;y={x:i+R*f*v,y:m+R*T*v};}return new Promise(x=>{function g(C){let i=De((C-S)/o,0,1),m=a(i),f,T;if(M){let p=1-m;f=p*p*t.x+2*p*m*y.x+m*m*n.x,T=p*p*t.y+2*p*m*y.y+m*m*n.y;}else f=t.x+(n.x-t.x)*m,T=t.y+(n.y-t.y)*m;let v=.35*(1-m),b=Math.sin(C*.02)*v,k=Math.cos(C*.018)*v;e.style.left=`${f+b}px`,e.style.top=`${T+k}px`,Ht(e,f+b,T+k),w&&w({x:f+b,y:T+k,t:i,now:C}),i<1?requestAnimationFrame(g):x();}requestAnimationFrame(g);})}function vn(e,t){return {x:e.x+(t?.x??0),y:e.y+(t?.y??0)}}function he(e,t,n,o){let r={bubbles:true,cancelable:true,view:window,clientX:n.x,clientY:n.y,...o};try{let l=t==="pointerdown"||t==="mousedown",u=t==="pointerup"||t==="mouseup",c={button:0,buttons:l?1:0,isPrimary:!0,...r};if("PointerEvent"in window){let w=new PointerEvent(t,{pointerId:1,pointerType:"mouse",...c});e.dispatchEvent(w);}else {let w=new MouseEvent(t,c);e.dispatchEvent(w);}}catch{let l=new MouseEvent(t,r);e.dispatchEvent(l);}}function An(e){return e&&typeof e=="object"&&e.nodeType===1}function Jr(e){if(!e)return document;if(An(e))return e;if(typeof e=="string"){let t=document.getElementById(e);if(t)return t;let n=document.querySelector(e);if(n)return n}return document}function wn(e){if(An(e))return {kind:"element",element:e};if(typeof e=="string"){let t=document.getElementById(e);if(t)return {kind:"element",element:t};let n=document.querySelector(e);return {kind:n?"element":"position",element:n??null}}if(typeof e=="object"&&"position"in e)return {kind:"position",point:e.position};if(typeof e=="object"&&"selector"in e){let n=Jr(e.within??null).querySelectorAll(e.selector),o=Math.max(0,Math.min(n.length-1,e.nth??0)),r=n[o]??null;return {kind:r?"element":"position",element:r}}return {kind:"position",point:{x:0,y:0}}}function Tn(e,t){let n=e.getBoundingClientRect();if(!t||t==="center")return {x:n.left+n.width/2,y:n.top+n.height/2};if(t==="top-left")return {x:n.left,y:n.top};if(t==="bottom-right")return {x:n.right,y:n.bottom};let o=De(t.x,0,1),r=De(t.y,0,1);return {x:n.left+n.width*o,y:n.top+n.height*r}}function Mn(e){return {x:De(e.x,0,window.innerWidth),y:De(e.y,0,window.innerHeight)}}function Zr(){return useEffect(()=>(window.__cursorGuide=async(e,t={})=>{let n=Array.isArray(e)?e:[{target:e,action:t.action??"none",options:t}],o=[],r=await qr();r.classList.add("visible","as-arrow"),r.classList.remove("as-pointer","pressing"),Lt(r),Sn();let l=parseFloat(r.style.left||"20")||20,u=parseFloat(r.style.top||"20")||20;Ht(r,l,u);for(let c of n){let{durationMs:w=800,easing:S="ease-in-out",offset:a,highlight:M=true,path:y="curve",curveStrength:x=.25,curveDirection:g="auto",anchor:C,cursorHotspot:i,dragTo:m}=c.options??{},f=c.action??c.options?.action??"none",T=performance.now(),R=wn(c.target),v=null,b=null;if(R.kind==="element"&&R.element?(b=R.element,r.classList.remove("visible"),b.scrollIntoView({behavior:"smooth",block:"center",inline:"center"}),await Gr(b,1500,180),Lt(r),v=Tn(b,C)):R.kind==="position"&&R.point&&(v=R.point),!v){o.push({ok:false,action:f,targetKind:R.kind,durationMs:Math.round(performance.now()-T),error:"Target not found"});continue}let k={x:parseFloat(r.style.left||"20")||20,y:parseFloat(r.style.top||"20")||20},p=Mn(vn(v,a));await st(r,k,p,w,S,y,x,g);let $=p.x-k.x,U=p.y-k.y,Q=Math.hypot($,U)||1,J=$/Q,D=U/Q,ee=Math.min(6,Math.max(3,Q*.02)),G={x:p.x+J*ee,y:p.y+D*ee};await st(r,p,G,Math.max(70,w*.1),"ease-out","straight",0,"right"),await st(r,G,p,120,"ease-out","straight",0,"left"),M&&(r.classList?.add("click"),setTimeout(()=>r.classList?.remove("click"),180));let V=null;try{if(f==="click"){r.classList.remove("as-arrow"),r.classList.add("as-pointer","pressing");let L={x:i?.x??0,y:i?.y??0},E={x:p.x+L.x,y:p.y+L.y};r.style.left=`${E.x}px`,r.style.top=`${E.y}px`,Ht(r,E.x,E.y);let O=b??document.elementFromPoint(E.x,E.y)??document.body;he(O,"pointerdown",E),he(O,"mousedown",E),await new Promise(K=>setTimeout(K,90)),r.classList.remove("pressing"),he(O,"mouseup",E),he(O,"click",E),setTimeout(()=>{r.classList.remove("as-pointer"),r.classList.add("as-arrow");},140),O instanceof HTMLElement&&O.focus?.(),V=O?.id??null;}else if(f==="drag"){if(!m)throw new Error("dragTo is required for action 'drag'");let L=wn(m),E=null;if(L.kind==="element"&&L.element&&(E=Tn(L.element,C)),L.kind==="position"&&L.point&&(E=L.point),!E)throw new Error("dragTo target not found");let O=Mn(vn(E,a)),K={x:p.x,y:p.y},be=b??document.elementFromPoint(K.x,K.y)??document.body;r.classList.remove("as-arrow"),r.classList.add("as-pointer","pressing"),he(be,"pointerdown",K),he(be,"mousedown",K),await st(r,K,O,Math.max(200,w),S,y,x,g,({x:ze,y:we})=>{let ge=document.elementFromPoint(ze,we)??document.body,xe={x:ze,y:we};he(ge,"pointermove",xe),he(ge,"mousemove",xe);});let Ie=document.elementFromPoint(O.x,O.y)??document.body;r.classList.remove("pressing"),he(Ie,"pointerup",O),he(Ie,"mouseup",O);}o.push({ok:!0,action:f,targetKind:R.kind,durationMs:Math.round(performance.now()-T),clickedElementId:V});}catch(L){o.push({ok:false,action:f,targetKind:R.kind,durationMs:Math.round(performance.now()-T),error:L?.message??String(L)});}}return Or(r,2e3),{ok:o.every(c=>c.ok),steps:o}},()=>{try{delete window.__cursorGuide;}catch{window.__cursorGuide=void 0;}}),[]),null}var In=Zr;function ao({agentId:e,theme:t,primaryColor:n,primaryColorDark:o,primaryColorLight:r,backgroundColor:l,borderColor:u,textColor:c,accentColor:w,baseUrl:S="",initialMessages:a=[],onMessagesChange:M,defaultOpen:y=true,floatingButtonPosition:x={bottom:24,right:24},UIComponents:g={},HsafaTools:C={}}){let{dir:i,theme:m}=Le(),f=t||m||"dark",v={primaryColor:f==="dark"?o||n||"#ffffff":r||n||"#000000",backgroundColor:l||(f==="dark"?"#0B0B0F":"#FFFFFF"),borderColor:u||(f==="dark"?"#2A2C33":"#E5E7EB"),textColor:c||(f==="dark"?"#EDEEF0":"#111827"),accentColor:w||(f==="dark"?"#17181C":"#F9FAFB"),mutedTextColor:f==="dark"?"#9AA0A6":"#6B7280",inputBackground:f==="dark"?"#17181C":"#F3F4F6",cardBackground:f==="dark"?"#121318":"#FFFFFF",hoverBackground:f==="dark"?"#1c1e25":"#F3F4F6"},b=s=>({"header.new":"New","header.history":"History","header.close":"Close chat","input.placeholder":"Ask your question...","input.attachFiles":"Attach files","input.insertLink":"Insert link","input.send":"Send","input.stop":"Stop","input.uploadingFiles":"Uploading files...","input.previewImage":"Preview image","input.removeFile":"Remove file","messages.empty":"Start by sending a message to the agent.","general.agent":"Agent","editor.cancel":"Cancel","editor.saveAndRegenerate":"Save & Regenerate","editor.clickToEdit":"Click to edit"})[s]||s,{attachments:k,uploading:p,fileInputRef:$,formatBytes:U,handleRemoveAttachment:Q,handleFileSelection:J,clearAttachments:D}=Qt(S),[ee,G]=useState(null),[V,L]=useState(""),[E,O]=useState(()=>`chat_${Date.now()}_${Math.random().toString(36).slice(2)}`),K=useMemo(()=>new DefaultChatTransport({api:`${S}/api/run/${e}`,fetch:async(s,d)=>{let F={...d?.body?JSON.parse(d.body):{},chatId:E};return fetch(s,{...d,body:JSON.stringify(F)})}}),[S,e,E]),be=useCallback(s=>{console.log("Message finished:",s);},[]),Ie=useCallback(s=>{console.error("Chat error:",s);},[]),ze=useMemo(()=>({getDomComponents:{tool:async({includeHidden:s,selector:d})=>await je({includeHidden:s,selector:d}),executeEachToken:false},controlCursor:{tool:async({target:s,action:d,anchor:h,durationMs:F,dragTo:H})=>{let W=await Ae(s,{action:d,anchor:h,durationMs:F,dragTo:H});if(W&&W.ok){let te=Array.isArray(W.steps)&&W.steps.length?W.steps[W.steps.length-1]:void 0,Te=te?.clickedElementId?` (clicked element id: ${te.clickedElementId})`:"",ne=d||te?.action||"none";return {success:true,message:ne==="click"?`Cursor moved and clicked successfully${Te}`:ne==="drag"?"Cursor dragged successfully":"Cursor moved successfully",details:W}}return {success:false,message:"Cursor action failed",details:W}},executeEachToken:false},fillActiveInput:{tool:async({value:s})=>{let d=await Ue(s);return {success:!!d?.ok,message:d?.ok?"Active input filled successfully":d?.errors?.[0]||"Failed to fill active input",details:d}},executeEachToken:true},getFromUser:{tool:async s=>({ok:true}),executeEachToken:true}}),[]),we=useMemo(()=>({...ze,...C}),[ze,C]),ge=useRef(new Map),xe=useRef(new Map),pt=useCallback(()=>{try{ge.current.forEach(s=>{try{s.remove();}catch{}}),ge.current.clear(),xe.current.clear();}catch{}},[]),Ve=useCallback((s,d)=>{let h=ge.current.get(d);if(h){let A=h.parentElement,P=document.querySelector(`[data-get-from-user-host="${d}"]`);if(P&&A!==P){try{A?.removeChild(h);}catch{}P.innerHTML="",P.appendChild(h);}}else {h=document.createElement("div"),h.className="hsafa-inline-form";let A=document.querySelector(`[data-get-from-user-host="${d}"]`);A?(A.innerHTML="",A.appendChild(h)):(document.querySelector(".chat-scroll-container")||document.body).appendChild(h),ge.current.set(d,h);}let F=s?.title||"Provide input",H=s?.description||"",W=s?.submitLabel||"Submit",te=s?.skipLabel||"Skip",Te=Array.isArray(s?.fields)?s.fields:s?.label||s?.placeholder?[{id:"value",label:s?.label||"Value",type:"text",placeholder:s?.placeholder||""}]:[],ne=xe.current.get(d)||{submitted:false,skipped:false,values:void 0};h.innerHTML="";let X=document.createElement("form");X.style.margin="12px 0",X.style.padding="14px",X.style.border="1px solid var(--hsafa-border, #2A2C33)",X.style.borderRadius="12px",X.style.background="var(--hsafa-card, #121318)",X.style.color="var(--hsafa-text, #EDEEF0)",X.style.boxShadow="0 6px 20px rgba(0,0,0,0.25)";let Je=document.createElement("div");if(Je.style.fontWeight="600",Je.style.marginBottom="6px",Je.textContent=F,X.appendChild(Je),H){let A=document.createElement("div");A.style.fontSize="12px",A.style.opacity="0.8",A.style.marginBottom="10px",A.textContent=H,X.appendChild(A);}Te.forEach(A=>{let P=document.createElement("div");if(P.style.margin="10px 0",A.label){let I=document.createElement("label");I.style.display="block",I.style.fontSize="12px",I.style.marginBottom="6px",I.style.opacity="0.9",I.textContent=A.label,P.appendChild(I);}let j,Me=(A.type||"text").toLowerCase();if(Me==="textarea"){let I=document.createElement("textarea");I.placeholder=A.placeholder||"",I.value=A.value??"",I.style.width="100%",I.style.minHeight="72px",I.style.padding="10px 12px",I.style.border="1px solid var(--hsafa-border, #2A2C33)",I.style.borderRadius="10px",I.style.background="var(--hsafa-input-bg, #17181C)",I.style.color="inherit",j=I;}else if(Me==="select"&&Array.isArray(A.options)){let I=document.createElement("select");I.style.width="100%",I.style.padding="10px 12px",I.style.border="1px solid var(--hsafa-border, #2A2C33)",I.style.borderRadius="10px",I.style.background="var(--hsafa-input-bg, #17181C)",I.style.color="inherit",A.options.forEach(wt=>{let Tt=document.createElement("option");Tt.value=String(wt.value),Tt.text=String(wt.label??wt.value),I.appendChild(Tt);}),I.value=A.value??"",j=I;}else if(Me==="checkbox"){let I=document.createElement("input");I.type="checkbox",I.checked=!!A.value,I.style.transform="scale(1.1)",j=I;}else {let I=document.createElement("input");I.type=Me,I.placeholder=A.placeholder||"",I.value=A.value??"",I.style.width="100%",I.style.padding="10px 12px",I.style.border="1px solid var(--hsafa-border, #2A2C33)",I.style.borderRadius="10px",I.style.background="var(--hsafa-input-bg, #17181C)",I.style.color="inherit",j=I;}let kt=A.id||"value";j.dataset.fieldId=kt;let vt=ne.values&&Object.prototype.hasOwnProperty.call(ne.values,kt)?ne.values[kt]:void 0;typeof vt<"u"&&(j.type==="checkbox"?j.checked=!!vt:j.value=String(vt)),(ne.submitted||ne.skipped)&&(j.setAttribute("disabled","true"),j.style.opacity="0.7"),P.appendChild(j),X.appendChild(P);});let Ze=String(W).trim(),Qe=String(te).trim(),er=!!(Ze||Qe),Y=null,_=null;if(er){let A=document.createElement("div");A.style.display="flex",A.style.gap="8px",A.style.marginTop="10px",Y=document.createElement("button"),Y.type="submit",Y.textContent=Ze||"Submit",Y.style.padding="6px 10px",Y.style.borderRadius="8px",Y.style.background="var(--hsafa-button-bg, var(--hsafa-primary, #2563eb))",Y.style.color="#000000",_=document.createElement("button"),_.type="button",_.textContent=Qe||"Skip",_.style.padding="6px 10px",_.style.borderRadius="8px",_.style.background="transparent",_.style.border="1px solid var(--hsafa-border, #2A2C33)",_.style.color="inherit",ne.submitted&&(Y.textContent=`${Ze||"Submit"} \u2713`,Y.style.opacity="0.8",Y.disabled=true),ne.skipped&&(_.textContent=`${Qe||"Skip"} \u2713`,_.style.opacity="0.8",_.disabled=true),A.appendChild(Y),A.appendChild(_),X.appendChild(A);}if(X.onsubmit=A=>{A.preventDefault();let P={};X.querySelectorAll("[data-field-id]").forEach(j=>{let Me=j.dataset.fieldId||"value";j.type==="checkbox"?P[Me]=j.checked:P[Me]=j.value??"";}),xe.current.set(d,{submitted:true,skipped:false,values:P}),mt.current.addToolResult({tool:"getFromUser",toolCallId:d,output:{success:true,submitted:true,values:P}}),X.querySelectorAll("[data-field-id]").forEach(j=>{j.disabled=true,j.style.opacity="0.7";}),Y&&(Y.textContent=`${Ze||"Submit"} \u2713`,Y.style.opacity="0.8",Y.disabled=true),_&&(_.disabled=true);},_&&(_.onclick=()=>{xe.current.set(d,{submitted:false,skipped:true,values:void 0}),mt.current.addToolResult({tool:"getFromUser",toolCallId:d,output:{success:true,submitted:false,skipped:true}}),X.querySelectorAll("[data-field-id]").forEach(A=>{A.disabled=true,A.style.opacity="0.7";}),_&&(_.textContent=`${Qe||"Skip"} \u2713`,_.style.opacity="0.8",_.disabled=true),Y&&(Y.disabled=true);}),ne.submitted||ne.skipped){let A=document.createElement("div");A.style.marginTop="10px",A.style.fontSize="12px",A.style.display="flex",A.style.alignItems="center",A.style.gap="8px";let P=document.createElement("span");P.style.display="inline-flex",P.style.alignItems="center",P.style.padding="2px 8px",P.style.borderRadius="999px",P.style.fontWeight="600",P.style.fontSize="11px",ne.submitted?(P.style.background="rgba(16,185,129,0.15)",P.style.color="#10b981",P.textContent="Submitted"):(P.style.background="rgba(234,179,8,0.15)",P.style.color="#eab308",P.textContent="Skipped"),A.appendChild(P),X.appendChild(A);}h.appendChild(X);},[]),mt=useRef(null),Fn=useCallback(s=>{let d=we[s];return d?typeof d=="object"&&"tool"in d?d.tool:typeof d=="function"?d:null:null},[we]),fe=useChat({transport:K,onFinish:be,onError:Ie,experimental_throttle:10,sendAutomaticallyWhen:lastAssistantMessageIsCompleteWithToolCalls,async onToolCall({toolCall:s}){let d=Fn(s.toolName);if(s.toolName==="getFromUser"||s.toolName==="get_from_user"){try{Ve(s.input,s.toolCallId);}catch(h){console.error("get_from_user render error",h);}return}if(d)try{let h=await d(s.input);fe.addToolResult({tool:s.toolName,toolCallId:s.toolCallId,output:h});}catch(h){fe.addToolResult({tool:s.toolName,toolCallId:s.toolCallId,state:"output-error",errorText:h?.message||String(h)});}}}),{messages:z,sendMessage:Ke,status:gt,stop:$n,error:Dt}=fe;mt.current=fe;let Pt=useRef(new Map);useEffect(()=>{z.forEach(s=>{s.role==="assistant"&&s.parts?.forEach(d=>{if(!d.toolCallId)return;let h=d.toolName;if(!h&&d.type?.startsWith("tool-")&&(h=d.type.replace(/^tool-/,"")),!h)return;let F=we[h];if(F&&typeof F=="object"&&F.executeEachToken&&F.tool){let H=d.input||d.args||{},W=JSON.stringify(H),te=Pt.current.get(d.toolCallId);if(W!==te&&W!=="{}"){Pt.current.set(d.toolCallId,W);try{h==="getFromUser"||h==="get_from_user"?Ve(H,d.toolCallId):F.tool(H);}catch(Te){console.error(`Error executing streaming tool ${h}:`,Te);}}}});});},[z,we]),useEffect(()=>{try{let s=new Set,d=[];if(z.forEach(h=>{h.role==="assistant"&&(h.parts||[]).forEach(F=>{let H=F?.toolName||(typeof F?.type=="string"&&F.type.startsWith("tool-")?String(F.type.replace(/^tool-/,"")):void 0);if(H!=="getFromUser"&&H!=="get_from_user")return;let W=F?.toolCallId||"";if(!W)return;s.add(W);let te=F?.output;if(te&&(te.submitted||te.skipped||te.values)){let ne={submitted:!!te.submitted,skipped:!!te.skipped,values:te.values||void 0};xe.current.set(W,ne);}let Te=F?.input||F?.args||{};d.push({input:Te,toolCallId:W});});}),ge.current.forEach((h,F)=>{if(!s.has(F)){let H=ge.current.get(F);try{H?.remove();}catch{}ge.current.delete(F),xe.current.delete(F);}}),d.length>0){let h=requestAnimationFrame(()=>{d.forEach(({input:F,toolCallId:H})=>{try{Ve(F,H);}catch{}});});return ()=>cancelAnimationFrame(h)}}catch{}},[z,Ve]),useEffect(()=>{a&&a.length>0&&z.length===0&&console.log("Initial messages:",a);},[a,z.length]);let ft=useRef(M);useEffect(()=>{ft.current=M;},[M]);let We=useRef([]);useEffect(()=>{(z.length!==We.current.length||z.length>0&&We.current.length>0&&z[z.length-1]?.id!==We.current[We.current.length-1]?.id)&&ft.current&&(We.current=z,ft.current(z));},[z]);let Z=gt==="submitted"||gt==="streaming",{setStreamingState:yt,setChatOpenState:ht}=Le(),[Xe,zt]=useState(()=>{try{return Rt(e).loadShowChatPreference(!!y)}catch{return !!y}}),[Ln,xt]=useState(false),[Hn,Bn]=useState(""),[Dn,Pn]=useState(0),zn=useRef(null),Wn=useRef(null),[On,Wt]=useState(new Set),[Nn,Ye]=useState(null),[Ot,Oe]=useState(""),[bt,Re]=useState([]),[Gn,Nt]=useState(false),Gt=useRef(null),_n=useRef(null),jn=Yt(Z),N=useMemo(()=>Rt(e),[e]),Ne=useRef(false),_t=useRef(false);useEffect(()=>{if(!_t.current){try{let s=N.loadCurrentChatId();if(s){Ne.current=!0,O(s);let d=N.loadChat(s),h=d&&Array.isArray(d.messages)?d.messages:[];try{fe?.setMessages?.(h);}catch{}}}catch{}_t.current=true;}},[N]),useEffect(()=>{if(z.length!==0)if(Ne.current){if(!Z){let s=Date.now();N.saveChat({id:E,messages:z,agentId:e});let h=N.loadChatsIndex().find(F=>F.id===E);h&&N.upsertChatMeta({...h,updatedAt:s});}}else {let s=z.find(d=>d.role==="user");if(s){let d="";if(Array.isArray(s.parts)){let H=s.parts.find(W=>W&&W.type==="text");d=H&&typeof H.text=="string"?H.text:"";}let h=(d||"New chat").slice(0,80),F=Date.now();N.upsertChatMeta({id:E,title:h,createdAt:F,updatedAt:F}),N.saveChat({id:E,messages:z,agentId:e}),N.saveCurrentChatId(E),Ne.current=true;}}},[z,e,E,N,Z]);let Ct=useRef(false);useEffect(()=>{if(Z){Ct.current=true;return}if(Ct.current){Ct.current=false;try{let s=Date.now();N.saveChat({id:E,messages:z,agentId:e});let h=N.loadChatsIndex().find(F=>F.id===E);h&&N.upsertChatMeta({...h,updatedAt:s});}catch{}}},[Z,z,E,e,N]),useEffect(()=>{try{yt(E,Z);}catch{}return ()=>{try{yt(E,!1);}catch{}}},[E,Z,yt]),useEffect(()=>{try{ht(E,Xe);}catch{}return ()=>{try{ht(E,!1);}catch{}}},[E,Xe,ht]);let Un=useCallback(async()=>{let s=V.trim();if(!(!s&&k.length===0)&&!Z)try{await Ke({text:s,files:k.map(d=>({type:"file",url:d.url,mediaType:d.mimeType||"application/octet-stream",...d.name?{name:d.name}:{},...d.size?{size:d.size}:{}}))}),L(""),D(),G(null);}catch(d){console.error("Failed to send message:",d),G("Failed to send message. Please try again.");}},[V,k,Z,Ke,D]),jt=useCallback(()=>{if(Z)return;pt(),L(""),D(),G(null),Ye(null),Oe(""),Re([]);try{fe?.setMessages?.([]);}catch{}Ne.current=false;let s=`chat_${Date.now()}_${Math.random().toString(36).slice(2)}`;O(s);try{N.saveCurrentChatId(s);}catch{}},[Z,D,N,fe,pt]),qn=useCallback(()=>{xt(s=>!s);},[]),Vn=useCallback(()=>{zt(false);try{N.saveShowChatPreference(!1);}catch{}},[N]),Kn=useCallback(async s=>{let d=s.target.files;d&&await J(d,G),$.current&&($.current.value="");},[J,$]);useEffect(()=>{let s=Gt.current;if(!s)return;s.style.height="24px",s.offsetHeight,s.style.height="auto";let d=Math.min(s.scrollHeight,200);s.style.height=`${d}px`;},[V]),nt.useEffect(()=>{let s=_n.current;if(!s)return;s.style.height="auto",s.offsetHeight;let d=Math.min(Math.max(s.scrollHeight,48),300);s.style.height=`${d}px`;},[Ot]);let Xn=useCallback(async s=>{Nt(true);try{let d=await Promise.all(Array.from(s).map(async h=>{let F=new FormData;F.append("file",h);let H=await fetch(`${S}/api/upload`,{method:"POST",body:F});if(!H.ok)throw new Error(`Upload failed: ${H.statusText}`);let W=await H.json();return {id:W.url||`${Date.now()}-${Math.random()}`,name:h.name,url:W.url,mimeType:h.type,size:h.size}}));Re(h=>[...h,...d]);}catch(d){console.error("Failed to upload files:",d),G("Failed to upload files. Please try again.");}finally{Nt(false);}},[S]),Yn=useCallback(s=>{Re(d=>d.filter(h=>h.id!==s));},[]),Jn=useCallback((s,d,h)=>{Ye(s),Oe(d),Re(h||[]);},[]),Zn=useCallback(()=>{Ye(null),Oe(""),Re([]);},[]),Qn=useCallback(async(s,d)=>{if(!Z)try{let h=z.findIndex(H=>H.id===s);if(h===-1)return;let F=z.slice(0,h);try{fe?.setMessages?.(F);}catch{}await Ke({text:d.trim(),files:bt.map(H=>({type:"file",url:H.url,mediaType:H.mimeType||"application/octet-stream",...H.name?{name:H.name}:{},...H.size?{size:H.size}:{}}))}),Ye(null),Oe(""),Re([]);}catch(h){console.error("Failed to save edit:",h),G("Failed to save message. Please try again.");}},[Z,z,Ke,fe,bt]),Ut=jsxs("div",{style:{position:"fixed",right:0,top:0,bottom:0,width:"420px",display:"flex",flexDirection:"column",padding:"24px 16px",color:v.textColor,gap:"16px",zIndex:1e3,transform:Xe?"translateX(0)":"translateX(100%)",transition:"transform 0.25s ease-out, width 0.2s ease-out"},children:[jsx(nn,{title:b("general.agent"),alwaysOpen:false,streaming:Z,dir:i||"ltr",resolvedColors:v,onNew:jt,onToggleHistory:qn,onClose:Vn,historyBtnRef:zn,t:b}),jsx("div",{ref:jn,className:"chat-scroll-container",style:{flex:"1",overflowY:"auto",overflowX:"hidden",padding:"16px 4px 16px 4px",display:"flex",flexDirection:"column",gap:"16px",scrollBehavior:"smooth","--hsafa-primary":v.primaryColor,"--hsafa-border":v.borderColor,"--hsafa-card":v.cardBackground,"--hsafa-text":v.textColor,"--hsafa-muted":v.mutedTextColor,"--hsafa-bg":v.backgroundColor,"--hsafa-hover":v.hoverBackground,"--hsafa-input-bg":v.inputBackground,"--hsafa-accent":v.accentColor},children:z.length===0?jsx("div",{style:{padding:"32px",textAlign:"center",color:v.mutedTextColor,fontSize:"14px"},children:b("messages.empty")}):jsx(mn,{chatMessages:z,isLoading:Z,openReasoningIds:On,toggleReasoning:s=>Wt(d=>{let h=new Set(d);return h.has(s)?h.delete(s):h.add(s),h}),resolvedColors:v,t:b,onUserMessageClick:Jn,editingMessageId:Nn,editingText:Ot,onEditingTextChange:Oe,onCancelEdit:Zn,onSaveEdit:Qn,editAttachments:bt,onRemoveEditAttachment:Yn,onAddEditAttachments:Xn,editUploading:Gn,UIComponents:g})}),jsxs("div",{style:{position:"sticky",bottom:"0",marginTop:"auto",paddingBottom:"8px"},children:[ee&&jsxs("div",{style:{padding:"8px 12px",marginBottom:"8px",backgroundColor:"#ef4444",color:"#fff",borderRadius:"8px",fontSize:"13px",display:"flex",alignItems:"center",justifyContent:"space-between"},children:[jsx("span",{children:ee}),jsx("button",{onClick:()=>G(null),style:{background:"none",border:"none",color:"#fff",cursor:"pointer",padding:"2px"},children:"\xD7"})]}),Dt&&jsxs("div",{style:{padding:"8px 12px",marginBottom:"8px",backgroundColor:"#ef4444",color:"#fff",borderRadius:"8px",fontSize:"13px",display:"flex",alignItems:"center",justifyContent:"space-between"},children:[jsxs("span",{children:["An error occurred: ",Dt.message||"Please try again."]}),jsx("button",{onClick:()=>window.location.reload(),style:{background:"none",border:"1px solid #fff",color:"#fff",cursor:"pointer",padding:"4px 8px",borderRadius:"4px",fontSize:"12px"},children:"Refresh"})]}),jsx(gn,{input:V,setInput:L,textareaRef:Gt,fileInputRef:$,isLoading:Z,uploading:p,attachments:k,formatBytes:U,handleRemoveAttachment:Q,onFileInputChange:Kn,onSend:Un,onStop:()=>$n(),status:gt,t:b,resolvedColors:v})]}),jsx(yn,{historyOpen:Ln,historySearch:Hn,currentChatId:E,refreshKey:Dn,resolvedColors:v,onClose:()=>xt(false),onSearchChange:Bn,onChatSelect:s=>{if(xt(false),s&&s!==E){Ne.current=true,pt(),O(s);try{N.saveCurrentChatId(s);}catch{}try{let d=N.loadChat(s),h=d&&Array.isArray(d.messages)?d.messages:[];try{fe?.setMessages?.(h);}catch{}}catch{}}},onChatDelete:s=>{try{N.deleteChat(s),Pn(d=>d+1),s===E&&jt();}catch{}},loadChatsIndex:()=>N.loadChatsIndex(),historyPopupRef:Wn}),jsx("style",{children:`
|
|
33
|
+
`,document.head.appendChild(r);}vn=true;}return t?(t.classList.add("as-arrow"),qe||(qe=createRoot(t),qe.render(jsx(wn,{arrowSvg:n.arrow,pointerSvg:n.pointer})))):(t=document.createElement("div"),t.id=e,t.className="fake-cursor as-arrow",t.style.position="fixed",t.style.left="20px",t.style.top="20px",document.body.appendChild(t),qe=createRoot(t),qe.render(jsx(wn,{arrowSvg:n.arrow,pointerSvg:n.pointer}))),t}function De(e,t,n){return Math.max(t,Math.min(n,e))}function Xr(e){return e<.5?4*e*e*e:1-Math.pow(-2*e+2,3)/2}function In(e){if(!e)return null;let t=document.createElement("canvas").getContext("2d");if(!t)return null;t.fillStyle="#000",t.fillStyle=e;let o=t.fillStyle.match(/rgba?\(([^)]+)\)/i);if(!o)return null;let r=o[1].split(/\s*,\s*/).map(Number),[l,u,c,v=1]=r;return {r:l,g:u,b:c,a:v}}function Yr({r:e,g:t,b:n}){let o=[e,t,n].map(r=>r/255).map(r=>r<=.03928?r/12.92:Math.pow((r+.055)/1.055,2.4));return .2126*o[0]+.7152*o[1]+.0722*o[2]}function Jr(e){let t=e?In(e):null;return !t||t.a===0?false:Yr(t)<.5}function Zr(e,t){let n=document.elementFromPoint(e,t),o=new Set;for(;n&&!o.has(n);){o.add(n);let u=getComputedStyle(n).backgroundColor,c=In(u);if(c&&c.a>0)return u;n=n.parentElement;}return getComputedStyle(document.body).backgroundColor||"rgb(255,255,255)"}function Dt(e,t,n){let o=Zr(t,n),r=Jr(o),l=r?"#ffffff":"#000000";e.querySelectorAll("svg path").forEach(c=>{c.style.fill="white",c.style.stroke=l,c.style.strokeWidth="1";}),e.style.filter=r?"drop-shadow(0 1px 2px rgba(0,0,0,0.8))":"drop-shadow(0 1px 2px rgba(255,255,255,0.9))";}async function ct(e,t,n,o,r="ease-in-out",l="curve",u=.25,c="auto",v){An(),Bt(e);let S=performance.now(),a=r==="linear"?b=>b:Xr,T=l!=="straight",f={x:0,y:0};if(T){let b=n.x-t.x,g=n.y-t.y,k=Math.hypot(b,g)||1,i=(t.x+n.x)/2,m=(t.y+n.y)/2,h=-g/k,C=b/k,E=1;c==="left"?E=-1:c==="right"?E=1:E=Math.random()<.5?-1:1;let M=De(u,0,1)*k;f={x:i+E*h*M,y:m+E*C*M};}return new Promise(b=>{function g(k){let i=De((k-S)/o,0,1),m=a(i),h,C;if(T){let p=1-m;h=p*p*t.x+2*p*m*f.x+m*m*n.x,C=p*p*t.y+2*p*m*f.y+m*m*n.y;}else h=t.x+(n.x-t.x)*m,C=t.y+(n.y-t.y)*m;let M=.35*(1-m),w=Math.sin(k*.02)*M,y=Math.cos(k*.018)*M;e.style.left=`${h+w}px`,e.style.top=`${C+y}px`,Dt(e,h+w,C+y),v&&v({x:h+w,y:C+y,t:i,now:k}),i<1?requestAnimationFrame(g):b();}requestAnimationFrame(g);})}function Tn(e,t){return {x:e.x+(t?.x??0),y:e.y+(t?.y??0)}}function he(e,t,n,o){let r={bubbles:true,cancelable:true,view:window,clientX:n.x,clientY:n.y,...o};try{let l=t==="pointerdown"||t==="mousedown",u=t==="pointerup"||t==="mouseup",c={button:0,buttons:l?1:0,isPrimary:!0,...r};if("PointerEvent"in window){let v=new PointerEvent(t,{pointerId:1,pointerType:"mouse",...c});e.dispatchEvent(v);}else {let v=new MouseEvent(t,c);e.dispatchEvent(v);}}catch{let l=new MouseEvent(t,r);e.dispatchEvent(l);}}function Rn(e){return e&&typeof e=="object"&&e.nodeType===1}function Qr(e){if(!e)return document;if(Rn(e))return e;if(typeof e=="string"){let t=document.getElementById(e);if(t)return t;let n=document.querySelector(e);if(n)return n}return document}function Mn(e){if(Rn(e))return {kind:"element",element:e};if(typeof e=="string"){let t=document.getElementById(e);if(t)return {kind:"element",element:t};let n=document.querySelector(e);return {kind:n?"element":"position",element:n??null}}if(typeof e=="object"&&"position"in e)return {kind:"position",point:e.position};if(typeof e=="object"&&"selector"in e){let n=Qr(e.within??null).querySelectorAll(e.selector),o=Math.max(0,Math.min(n.length-1,e.nth??0)),r=n[o]??null;return {kind:r?"element":"position",element:r}}return {kind:"position",point:{x:0,y:0}}}function Sn(e,t){let n=e.getBoundingClientRect();if(!t||t==="center")return {x:n.left+n.width/2,y:n.top+n.height/2};if(t==="top-left")return {x:n.left,y:n.top};if(t==="bottom-right")return {x:n.right,y:n.bottom};let o=De(t.x,0,1),r=De(t.y,0,1);return {x:n.left+n.width*o,y:n.top+n.height*r}}function En(e){return {x:De(e.x,0,window.innerWidth),y:De(e.y,0,window.innerHeight)}}function eo(){return useEffect(()=>(window.__cursorGuide=async(e,t={})=>{let n=Array.isArray(e)?e:[{target:e,action:t.action??"none",options:t}],o=[],r=await Kr();r.classList.add("visible","as-arrow"),r.classList.remove("as-pointer","pressing"),Bt(r),An();let l=parseFloat(r.style.left||"20")||20,u=parseFloat(r.style.top||"20")||20;Dt(r,l,u);for(let c of n){let{durationMs:v=800,easing:S="ease-in-out",offset:a,highlight:T=true,path:f="curve",curveStrength:b=.25,curveDirection:g="auto",anchor:k,cursorHotspot:i,dragTo:m}=c.options??{},h=c.action??c.options?.action??"none",C=performance.now(),E=Mn(c.target),M=null,w=null;if(E.kind==="element"&&E.element?(w=E.element,r.classList.remove("visible"),w.scrollIntoView({behavior:"smooth",block:"center",inline:"center"}),await jr(w,1500,180),Bt(r),M=Sn(w,k)):E.kind==="position"&&E.point&&(M=E.point),!M){o.push({ok:false,action:h,targetKind:E.kind,durationMs:Math.round(performance.now()-C),error:"Target not found"});continue}let y={x:parseFloat(r.style.left||"20")||20,y:parseFloat(r.style.top||"20")||20},p=En(Tn(M,a));await ct(r,y,p,v,S,f,b,g);let F=p.x-y.x,U=p.y-y.y,q=Math.hypot(F,U)||1,Z=F/q,z=U/q,Q=Math.min(6,Math.max(3,q*.02)),V={x:p.x+Z*Q,y:p.y+z*Q};await ct(r,p,V,Math.max(70,v*.1),"ease-out","straight",0,"right"),await ct(r,V,p,120,"ease-out","straight",0,"left"),T&&(r.classList?.add("click"),setTimeout(()=>r.classList?.remove("click"),180));let ee=null;try{if(h==="click"){r.classList.remove("as-arrow"),r.classList.add("as-pointer","pressing");let $={x:i?.x??0,y:i?.y??0},H={x:p.x+$.x,y:p.y+$.y};r.style.left=`${H.x}px`,r.style.top=`${H.y}px`,Dt(r,H.x,H.y);let N=w??document.elementFromPoint(H.x,H.y)??document.body;he(N,"pointerdown",H),he(N,"mousedown",H),await new Promise(L=>setTimeout(L,90)),r.classList.remove("pressing"),he(N,"mouseup",H),he(N,"click",H),setTimeout(()=>{r.classList.remove("as-pointer"),r.classList.add("as-arrow");},140),N instanceof HTMLElement&&N.focus?.(),ee=N?.id??null;}else if(h==="drag"){if(!m)throw new Error("dragTo is required for action 'drag'");let $=Mn(m),H=null;if($.kind==="element"&&$.element&&(H=Sn($.element,k)),$.kind==="position"&&$.point&&(H=$.point),!H)throw new Error("dragTo target not found");let N=En(Tn(H,a)),L={x:p.x,y:p.y},ge=w??document.elementFromPoint(L.x,L.y)??document.body;r.classList.remove("as-arrow"),r.classList.add("as-pointer","pressing"),he(ge,"pointerdown",L),he(ge,"mousedown",L),await ct(r,L,N,Math.max(200,v),S,f,b,g,({x:Ve,y:Ke})=>{let ze=document.elementFromPoint(Ve,Ke)??document.body,ke={x:Ve,y:Ke};he(ze,"pointermove",ke),he(ze,"mousemove",ke);});let Ae=document.elementFromPoint(N.x,N.y)??document.body;r.classList.remove("pressing"),he(Ae,"pointerup",N),he(Ae,"mouseup",N);}o.push({ok:!0,action:h,targetKind:E.kind,durationMs:Math.round(performance.now()-C),clickedElementId:ee});}catch($){o.push({ok:false,action:h,targetKind:E.kind,durationMs:Math.round(performance.now()-C),error:$?.message??String($)});}}return Gr(r,2e3),{ok:o.every(c=>c.ok),steps:o}},()=>{try{delete window.__cursorGuide;}catch{window.__cursorGuide=void 0;}}),[]),null}var Fn=eo;function lo({agentId:e,theme:t,primaryColor:n,primaryColorDark:o,primaryColorLight:r,backgroundColor:l,borderColor:u,textColor:c,accentColor:v,baseUrl:S="",initialMessages:a=[],onMessagesChange:T,defaultOpen:f=true,floatingButtonPosition:b={bottom:24,right:24},UIComponents:g={},HsafaTools:k={}}){let{dir:i,theme:m,baseUrl:h}=Le(),C=t||m||"dark",E=S&&S.length>0?S:h||"",y={primaryColor:C==="dark"?o||n||"#ffffff":r||n||"#000000",backgroundColor:l||(C==="dark"?"#0B0B0F":"#FFFFFF"),borderColor:u||(C==="dark"?"#2A2C33":"#E5E7EB"),textColor:c||(C==="dark"?"#EDEEF0":"#111827"),accentColor:v||(C==="dark"?"#17181C":"#F9FAFB"),mutedTextColor:C==="dark"?"#9AA0A6":"#6B7280",inputBackground:C==="dark"?"#17181C":"#F3F4F6",cardBackground:C==="dark"?"#121318":"#FFFFFF",hoverBackground:C==="dark"?"#1c1e25":"#F3F4F6"},p=s=>({"header.new":"New","header.history":"History","header.close":"Close chat","input.placeholder":"Ask your question...","input.attachFiles":"Attach files","input.insertLink":"Insert link","input.send":"Send","input.stop":"Stop","input.uploadingFiles":"Uploading files...","input.previewImage":"Preview image","input.removeFile":"Remove file","messages.empty":"Start by sending a message to the agent.","general.agent":"Agent","editor.cancel":"Cancel","editor.saveAndRegenerate":"Save & Regenerate","editor.clickToEdit":"Click to edit"})[s]||s,{attachments:F,uploading:U,fileInputRef:q,formatBytes:Z,handleRemoveAttachment:z,handleFileSelection:Q,clearAttachments:V}=tn(E),[ee,$]=useState(null),[H,N]=useState(""),[L,ge]=useState(()=>`chat_${Date.now()}_${Math.random().toString(36).slice(2)}`),Ae=useMemo(()=>new DefaultChatTransport({api:`${E}/api/run/${e}`,fetch:async(s,d)=>{let R={...d?.body?JSON.parse(d.body):{},chatId:L};return fetch(s,{...d,body:JSON.stringify(R)})}}),[h,S,e,L]),Ve=useCallback(s=>{console.log("Message finished:",s);},[]),Ke=useCallback(s=>{console.error("Chat error:",s);},[]),ze=useMemo(()=>({getDomComponents:{tool:async({includeHidden:s,selector:d})=>await je({includeHidden:s,selector:d}),executeEachToken:false},controlCursor:{tool:async({target:s,action:d,anchor:x,durationMs:R,dragTo:B})=>{let O=await Ee(s,{action:d,anchor:x,durationMs:R,dragTo:B});if(O&&O.ok){let te=Array.isArray(O.steps)&&O.steps.length?O.steps[O.steps.length-1]:void 0,we=te?.clickedElementId?` (clicked element id: ${te.clickedElementId})`:"",ne=d||te?.action||"none";return {success:true,message:ne==="click"?`Cursor moved and clicked successfully${we}`:ne==="drag"?"Cursor dragged successfully":"Cursor moved successfully",details:O}}return {success:false,message:"Cursor action failed",details:O}},executeEachToken:false},fillActiveInput:{tool:async({value:s})=>{let d=await Ue(s);return {success:!!d?.ok,message:d?.ok?"Active input filled successfully":d?.errors?.[0]||"Failed to fill active input",details:d}},executeEachToken:true},getFromUser:{tool:async s=>({ok:true}),executeEachToken:true}}),[]),ke=useMemo(()=>({...ze,...k}),[ze,k]),ve=useRef(new Map),Ie=useRef(new Map),gt=useCallback(()=>{try{ve.current.forEach(s=>{try{s.remove();}catch{}}),ve.current.clear(),Ie.current.clear();}catch{}},[]),Xe=useCallback((s,d)=>{let x=ve.current.get(d);if(x){let A=x.parentElement,P=document.querySelector(`[data-get-from-user-host="${d}"]`);if(P&&A!==P){try{A?.removeChild(x);}catch{}P.innerHTML="",P.appendChild(x);}}else {x=document.createElement("div"),x.className="hsafa-inline-form";let A=document.querySelector(`[data-get-from-user-host="${d}"]`);A?(A.innerHTML="",A.appendChild(x)):(document.querySelector(".chat-scroll-container")||document.body).appendChild(x),ve.current.set(d,x);}let R=s?.title||"Provide input",B=s?.description||"",O=s?.submitLabel||"Submit",te=s?.skipLabel||"Skip",we=Array.isArray(s?.fields)?s.fields:s?.label||s?.placeholder?[{id:"value",label:s?.label||"Value",type:"text",placeholder:s?.placeholder||""}]:[],ne=Ie.current.get(d)||{submitted:false,skipped:false,values:void 0};x.innerHTML="";let X=document.createElement("form");X.style.margin="12px 0",X.style.padding="14px",X.style.border="1px solid var(--hsafa-border, #2A2C33)",X.style.borderRadius="12px",X.style.background="var(--hsafa-card, #121318)",X.style.color="var(--hsafa-text, #EDEEF0)",X.style.boxShadow="0 6px 20px rgba(0,0,0,0.25)";let Qe=document.createElement("div");if(Qe.style.fontWeight="600",Qe.style.marginBottom="6px",Qe.textContent=R,X.appendChild(Qe),B){let A=document.createElement("div");A.style.fontSize="12px",A.style.opacity="0.8",A.style.marginBottom="10px",A.textContent=B,X.appendChild(A);}we.forEach(A=>{let P=document.createElement("div");if(P.style.margin="10px 0",A.label){let I=document.createElement("label");I.style.display="block",I.style.fontSize="12px",I.style.marginBottom="6px",I.style.opacity="0.9",I.textContent=A.label,P.appendChild(I);}let j,Te=(A.type||"text").toLowerCase();if(Te==="textarea"){let I=document.createElement("textarea");I.placeholder=A.placeholder||"",I.value=A.value??"",I.style.width="100%",I.style.minHeight="72px",I.style.padding="10px 12px",I.style.border="1px solid var(--hsafa-border, #2A2C33)",I.style.borderRadius="10px",I.style.background="var(--hsafa-input-bg, #17181C)",I.style.color="inherit",j=I;}else if(Te==="select"&&Array.isArray(A.options)){let I=document.createElement("select");I.style.width="100%",I.style.padding="10px 12px",I.style.border="1px solid var(--hsafa-border, #2A2C33)",I.style.borderRadius="10px",I.style.background="var(--hsafa-input-bg, #17181C)",I.style.color="inherit",A.options.forEach(Mt=>{let St=document.createElement("option");St.value=String(Mt.value),St.text=String(Mt.label??Mt.value),I.appendChild(St);}),I.value=A.value??"",j=I;}else if(Te==="checkbox"){let I=document.createElement("input");I.type="checkbox",I.checked=!!A.value,I.style.transform="scale(1.1)",j=I;}else {let I=document.createElement("input");I.type=Te,I.placeholder=A.placeholder||"",I.value=A.value??"",I.style.width="100%",I.style.padding="10px 12px",I.style.border="1px solid var(--hsafa-border, #2A2C33)",I.style.borderRadius="10px",I.style.background="var(--hsafa-input-bg, #17181C)",I.style.color="inherit",j=I;}let wt=A.id||"value";j.dataset.fieldId=wt;let Tt=ne.values&&Object.prototype.hasOwnProperty.call(ne.values,wt)?ne.values[wt]:void 0;typeof Tt<"u"&&(j.type==="checkbox"?j.checked=!!Tt:j.value=String(Tt)),(ne.submitted||ne.skipped)&&(j.setAttribute("disabled","true"),j.style.opacity="0.7"),P.appendChild(j),X.appendChild(P);});let et=String(O).trim(),tt=String(te).trim(),nr=!!(et||tt),Y=null,_=null;if(nr){let A=document.createElement("div");A.style.display="flex",A.style.gap="8px",A.style.marginTop="10px",Y=document.createElement("button"),Y.type="submit",Y.textContent=et||"Submit",Y.style.padding="6px 10px",Y.style.borderRadius="8px",Y.style.background="var(--hsafa-button-bg, var(--hsafa-primary, #2563eb))",Y.style.color="#000000",_=document.createElement("button"),_.type="button",_.textContent=tt||"Skip",_.style.padding="6px 10px",_.style.borderRadius="8px",_.style.background="transparent",_.style.border="1px solid var(--hsafa-border, #2A2C33)",_.style.color="inherit",ne.submitted&&(Y.textContent=`${et||"Submit"} \u2713`,Y.style.opacity="0.8",Y.disabled=true),ne.skipped&&(_.textContent=`${tt||"Skip"} \u2713`,_.style.opacity="0.8",_.disabled=true),A.appendChild(Y),A.appendChild(_),X.appendChild(A);}if(X.onsubmit=A=>{A.preventDefault();let P={};X.querySelectorAll("[data-field-id]").forEach(j=>{let Te=j.dataset.fieldId||"value";j.type==="checkbox"?P[Te]=j.checked:P[Te]=j.value??"";}),Ie.current.set(d,{submitted:true,skipped:false,values:P}),ft.current.addToolResult({tool:"getFromUser",toolCallId:d,output:{success:true,submitted:true,values:P}}),X.querySelectorAll("[data-field-id]").forEach(j=>{j.disabled=true,j.style.opacity="0.7";}),Y&&(Y.textContent=`${et||"Submit"} \u2713`,Y.style.opacity="0.8",Y.disabled=true),_&&(_.disabled=true);},_&&(_.onclick=()=>{Ie.current.set(d,{submitted:false,skipped:true,values:void 0}),ft.current.addToolResult({tool:"getFromUser",toolCallId:d,output:{success:true,submitted:false,skipped:true}}),X.querySelectorAll("[data-field-id]").forEach(A=>{A.disabled=true,A.style.opacity="0.7";}),_&&(_.textContent=`${tt||"Skip"} \u2713`,_.style.opacity="0.8",_.disabled=true),Y&&(Y.disabled=true);}),ne.submitted||ne.skipped){let A=document.createElement("div");A.style.marginTop="10px",A.style.fontSize="12px",A.style.display="flex",A.style.alignItems="center",A.style.gap="8px";let P=document.createElement("span");P.style.display="inline-flex",P.style.alignItems="center",P.style.padding="2px 8px",P.style.borderRadius="999px",P.style.fontWeight="600",P.style.fontSize="11px",ne.submitted?(P.style.background="rgba(16,185,129,0.15)",P.style.color="#10b981",P.textContent="Submitted"):(P.style.background="rgba(234,179,8,0.15)",P.style.color="#eab308",P.textContent="Skipped"),A.appendChild(P),X.appendChild(A);}x.appendChild(X);},[]),ft=useRef(null),Ln=useCallback(s=>{let d=ke[s];return d?typeof d=="object"&&"tool"in d?d.tool:typeof d=="function"?d:null:null},[ke]),fe=useChat({transport:Ae,onFinish:Ve,onError:Ke,experimental_throttle:10,sendAutomaticallyWhen:lastAssistantMessageIsCompleteWithToolCalls,async onToolCall({toolCall:s}){let d=Ln(s.toolName);if(s.toolName==="getFromUser"||s.toolName==="get_from_user"){try{Xe(s.input,s.toolCallId);}catch(x){console.error("get_from_user render error",x);}return}if(d)try{let x=await d(s.input);fe.addToolResult({tool:s.toolName,toolCallId:s.toolCallId,output:x});}catch(x){fe.addToolResult({tool:s.toolName,toolCallId:s.toolCallId,state:"output-error",errorText:x?.message||String(x)});}}}),{messages:W,sendMessage:Ye,status:yt,stop:Hn,error:zt}=fe;ft.current=fe;let Wt=useRef(new Map);useEffect(()=>{W.forEach(s=>{s.role==="assistant"&&s.parts?.forEach(d=>{if(!d.toolCallId)return;let x=d.toolName;if(!x&&d.type?.startsWith("tool-")&&(x=d.type.replace(/^tool-/,"")),!x)return;let R=ke[x];if(R&&typeof R=="object"&&R.executeEachToken&&R.tool){let B=d.input||d.args||{},O=JSON.stringify(B),te=Wt.current.get(d.toolCallId);if(O!==te&&O!=="{}"){Wt.current.set(d.toolCallId,O);try{x==="getFromUser"||x==="get_from_user"?Xe(B,d.toolCallId):R.tool(B);}catch(we){console.error(`Error executing streaming tool ${x}:`,we);}}}});});},[W,ke]),useEffect(()=>{try{let s=new Set,d=[];if(W.forEach(x=>{x.role==="assistant"&&(x.parts||[]).forEach(R=>{let B=R?.toolName||(typeof R?.type=="string"&&R.type.startsWith("tool-")?String(R.type.replace(/^tool-/,"")):void 0);if(B!=="getFromUser"&&B!=="get_from_user")return;let O=R?.toolCallId||"";if(!O)return;s.add(O);let te=R?.output;if(te&&(te.submitted||te.skipped||te.values)){let ne={submitted:!!te.submitted,skipped:!!te.skipped,values:te.values||void 0};Ie.current.set(O,ne);}let we=R?.input||R?.args||{};d.push({input:we,toolCallId:O});});}),ve.current.forEach((x,R)=>{if(!s.has(R)){let B=ve.current.get(R);try{B?.remove();}catch{}ve.current.delete(R),Ie.current.delete(R);}}),d.length>0){let x=requestAnimationFrame(()=>{d.forEach(({input:R,toolCallId:B})=>{try{Xe(R,B);}catch{}});});return ()=>cancelAnimationFrame(x)}}catch{}},[W,Xe]),useEffect(()=>{a&&a.length>0&&W.length===0&&console.log("Initial messages:",a);},[a,W.length]);let ht=useRef(T);useEffect(()=>{ht.current=T;},[T]);let We=useRef([]);useEffect(()=>{(W.length!==We.current.length||W.length>0&&We.current.length>0&&W[W.length-1]?.id!==We.current[We.current.length-1]?.id)&&ht.current&&(We.current=W,ht.current(W));},[W]);let J=yt==="submitted"||yt==="streaming",{setStreamingState:xt,setChatOpenState:bt}=Le(),[Je,Ot]=useState(()=>{try{return $t(e).loadShowChatPreference(!!f)}catch{return !!f}}),[Bn,Ct]=useState(false),[Dn,Pn]=useState(""),[zn,Wn]=useState(0),On=useRef(null),Nn=useRef(null),[Gn,Nt]=useState(new Set),[_n,Ze]=useState(null),[Gt,Oe]=useState(""),[kt,Re]=useState([]),[jn,_t]=useState(false),jt=useRef(null),Un=useRef(null),qn=Zt(J),G=useMemo(()=>$t(e),[e]),Ne=useRef(false),Ut=useRef(false);useEffect(()=>{if(!Ut.current){try{let s=G.loadCurrentChatId();if(s){Ne.current=!0,ge(s);let d=G.loadChat(s),x=d&&Array.isArray(d.messages)?d.messages:[];try{fe?.setMessages?.(x);}catch{}}}catch{}Ut.current=true;}},[G]),useEffect(()=>{if(W.length!==0)if(Ne.current){if(!J){let s=Date.now();G.saveChat({id:L,messages:W,agentId:e});let x=G.loadChatsIndex().find(R=>R.id===L);x&&G.upsertChatMeta({...x,updatedAt:s});}}else {let s=W.find(d=>d.role==="user");if(s){let d="";if(Array.isArray(s.parts)){let B=s.parts.find(O=>O&&O.type==="text");d=B&&typeof B.text=="string"?B.text:"";}let x=(d||"New chat").slice(0,80),R=Date.now();G.upsertChatMeta({id:L,title:x,createdAt:R,updatedAt:R}),G.saveChat({id:L,messages:W,agentId:e}),G.saveCurrentChatId(L),Ne.current=true;}}},[W,e,L,G,J]);let vt=useRef(false);useEffect(()=>{if(J){vt.current=true;return}if(vt.current){vt.current=false;try{let s=Date.now();G.saveChat({id:L,messages:W,agentId:e});let x=G.loadChatsIndex().find(R=>R.id===L);x&&G.upsertChatMeta({...x,updatedAt:s});}catch{}}},[J,W,L,e,G]),useEffect(()=>{try{xt(L,J);}catch{}return ()=>{try{xt(L,!1);}catch{}}},[L,J,xt]),useEffect(()=>{try{bt(L,Je);}catch{}return ()=>{try{bt(L,!1);}catch{}}},[L,Je,bt]);let Vn=useCallback(async()=>{let s=H.trim();if(!(!s&&F.length===0)&&!J)try{await Ye({text:s,files:F.map(d=>({type:"file",url:d.url,mediaType:d.mimeType||"application/octet-stream",...d.name?{name:d.name}:{},...d.size?{size:d.size}:{}}))}),N(""),V(),$(null);}catch(d){console.error("Failed to send message:",d),$("Failed to send message. Please try again.");}},[H,F,J,Ye,V]),qt=useCallback(()=>{if(J)return;gt(),N(""),V(),$(null),Ze(null),Oe(""),Re([]);try{fe?.setMessages?.([]);}catch{}Ne.current=false;let s=`chat_${Date.now()}_${Math.random().toString(36).slice(2)}`;ge(s);try{G.saveCurrentChatId(s);}catch{}},[J,V,G,fe,gt]),Kn=useCallback(()=>{Ct(s=>!s);},[]),Xn=useCallback(()=>{Ot(false);try{G.saveShowChatPreference(!1);}catch{}},[G]),Yn=useCallback(async s=>{let d=s.target.files;d&&await Q(d,$),q.current&&(q.current.value="");},[Q,q]);useEffect(()=>{let s=jt.current;if(!s)return;s.style.height="24px",s.offsetHeight,s.style.height="auto";let d=Math.min(s.scrollHeight,200);s.style.height=`${d}px`;},[H]),ot.useEffect(()=>{let s=Un.current;if(!s)return;s.style.height="auto",s.offsetHeight;let d=Math.min(Math.max(s.scrollHeight,48),300);s.style.height=`${d}px`;},[Gt]);let Jn=useCallback(async s=>{_t(true);try{let d=await Promise.all(Array.from(s).map(async x=>{let R=new FormData;R.append("file",x);let B=await fetch(`${E}/api/upload`,{method:"POST",body:R});if(!B.ok)throw new Error(`Upload failed: ${B.statusText}`);let O=await B.json();return {id:O.url||`${Date.now()}-${Math.random()}`,name:x.name,url:O.url,mimeType:x.type,size:x.size}}));Re(x=>[...x,...d]);}catch(d){console.error("Failed to upload files:",d),$("Failed to upload files. Please try again.");}finally{_t(false);}},[E]),Zn=useCallback(s=>{Re(d=>d.filter(x=>x.id!==s));},[]),Qn=useCallback((s,d,x)=>{Ze(s),Oe(d),Re(x||[]);},[]),er=useCallback(()=>{Ze(null),Oe(""),Re([]);},[]),tr=useCallback(async(s,d)=>{if(!J)try{let x=W.findIndex(B=>B.id===s);if(x===-1)return;let R=W.slice(0,x);try{fe?.setMessages?.(R);}catch{}await Ye({text:d.trim(),files:kt.map(B=>({type:"file",url:B.url,mediaType:B.mimeType||"application/octet-stream",...B.name?{name:B.name}:{},...B.size?{size:B.size}:{}}))}),Ze(null),Oe(""),Re([]);}catch(x){console.error("Failed to save edit:",x),$("Failed to save message. Please try again.");}},[J,W,Ye,fe,kt]),Vt=jsxs("div",{style:{position:"fixed",right:0,top:0,bottom:0,width:"420px",display:"flex",flexDirection:"column",padding:"24px 16px",color:y.textColor,gap:"16px",zIndex:1e3,transform:Je?"translateX(0)":"translateX(100%)",transition:"transform 0.25s ease-out, width 0.2s ease-out"},children:[jsx(on,{title:p("general.agent"),alwaysOpen:false,streaming:J,dir:i||"ltr",resolvedColors:y,onNew:qt,onToggleHistory:Kn,onClose:Xn,historyBtnRef:On,t:p}),jsx("div",{ref:qn,className:"chat-scroll-container",style:{flex:"1",overflowY:"auto",overflowX:"hidden",padding:"16px 4px 16px 4px",display:"flex",flexDirection:"column",gap:"16px",scrollBehavior:"smooth","--hsafa-primary":y.primaryColor,"--hsafa-border":y.borderColor,"--hsafa-card":y.cardBackground,"--hsafa-text":y.textColor,"--hsafa-muted":y.mutedTextColor,"--hsafa-bg":y.backgroundColor,"--hsafa-hover":y.hoverBackground,"--hsafa-input-bg":y.inputBackground,"--hsafa-accent":y.accentColor},children:W.length===0?jsx("div",{style:{padding:"32px",textAlign:"center",color:y.mutedTextColor,fontSize:"14px"},children:p("messages.empty")}):jsx(fn,{chatMessages:W,isLoading:J,openReasoningIds:Gn,toggleReasoning:s=>Nt(d=>{let x=new Set(d);return x.has(s)?x.delete(s):x.add(s),x}),resolvedColors:y,t:p,onUserMessageClick:Qn,editingMessageId:_n,editingText:Gt,onEditingTextChange:Oe,onCancelEdit:er,onSaveEdit:tr,editAttachments:kt,onRemoveEditAttachment:Zn,onAddEditAttachments:Jn,editUploading:jn,UIComponents:g})}),jsxs("div",{style:{position:"sticky",bottom:"0",marginTop:"auto",paddingBottom:"8px"},children:[ee&&jsxs("div",{style:{padding:"8px 12px",marginBottom:"8px",backgroundColor:"#ef4444",color:"#fff",borderRadius:"8px",fontSize:"13px",display:"flex",alignItems:"center",justifyContent:"space-between"},children:[jsx("span",{children:ee}),jsx("button",{onClick:()=>$(null),style:{background:"none",border:"none",color:"#fff",cursor:"pointer",padding:"2px"},children:"\xD7"})]}),zt&&jsxs("div",{style:{padding:"8px 12px",marginBottom:"8px",backgroundColor:"#ef4444",color:"#fff",borderRadius:"8px",fontSize:"13px",display:"flex",alignItems:"center",justifyContent:"space-between"},children:[jsxs("span",{children:["An error occurred: ",zt.message||"Please try again."]}),jsx("button",{onClick:()=>window.location.reload(),style:{background:"none",border:"1px solid #fff",color:"#fff",cursor:"pointer",padding:"4px 8px",borderRadius:"4px",fontSize:"12px"},children:"Refresh"})]}),jsx(yn,{input:H,setInput:N,textareaRef:jt,fileInputRef:q,isLoading:J,uploading:U,attachments:F,formatBytes:Z,handleRemoveAttachment:z,onFileInputChange:Yn,onSend:Vn,onStop:()=>Hn(),status:yt,t:p,resolvedColors:y})]}),jsx(xn,{historyOpen:Bn,historySearch:Dn,currentChatId:L,refreshKey:zn,resolvedColors:y,onClose:()=>Ct(false),onSearchChange:Pn,onChatSelect:s=>{if(Ct(false),s&&s!==L){Ne.current=true,gt(),ge(s);try{G.saveCurrentChatId(s);}catch{}try{let d=G.loadChat(s),x=d&&Array.isArray(d.messages)?d.messages:[];try{fe?.setMessages?.(x);}catch{}}catch{}}},onChatDelete:s=>{try{G.deleteChat(s),Wn(d=>d+1),s===L&&qt();}catch{}},loadChatsIndex:()=>G.loadChatsIndex(),historyPopupRef:Nn}),jsx("style",{children:`
|
|
34
34
|
@keyframes pulse { 0%, 100% { opacity: 1; } 50% { opacity: 0.5; } }
|
|
35
35
|
@keyframes spin { from { transform: rotate(0deg); } to { transform: rotate(360deg); } }
|
|
36
|
-
`})]});return typeof document<"u"&&document.body?jsxs(Fragment,{children:[createPortal(
|
|
37
|
-
@keyframes ${
|
|
36
|
+
`})]});return typeof document<"u"&&document.body?jsxs(Fragment,{children:[createPortal(Vt,document.body),jsx(Xt,{show:!Je,onClick:()=>{Ot(true);try{G.saveShowChatPreference(!0);}catch{}},resolvedColors:y,floatingButtonPosition:b})]}):Vt}var $n={dark:{primaryColor:"#4D78FF",backgroundColor:"#0B0B0F",borderColor:"#2A2C33",textColor:"#EDEEF0",accentColor:"#17181C",mutedTextColor:"#9AA0A6",inputBackground:"#17181C",cardBackground:"#121318",hoverBackground:"#1c1e25"},light:{primaryColor:"#2563EB",backgroundColor:"#FFFFFF",borderColor:"#E5E7EB",textColor:"#111827",accentColor:"#F9FAFB",mutedTextColor:"#6B7280",inputBackground:"#F9FAFB",cardBackground:"#F3F4F6",hoverBackground:"#F3F4F6"}};function go({children:e,theme:t="dark",primaryColor:n,backgroundColor:o,borderColor:r,textColor:l,mutedTextColor:u,enableBorderAnimation:c=true,borderRadius:v=16,enableContentBorder:S=true,className:a="",enableMargin:T=true,chatWidth:f=420,dir:b="ltr"}){let{isAnyStreaming:g,isAnyChatOpen:k,dir:i,theme:m}=Le(),h=(b??i)||"ltr",C=(t??m)||"dark",E=useRef(`content-container-${Date.now()}-${Math.random().toString(36).slice(2,8)}`),[M,w]=useState(false);useEffect(()=>{let z=setTimeout(()=>w(true),50);return ()=>clearTimeout(z)},[]);let y=$n[C],p={primaryColor:n||y.primaryColor,backgroundColor:o||y.backgroundColor,borderColor:r||y.borderColor,textColor:l||y.textColor,accentColor:y.accentColor,mutedTextColor:u||y.mutedTextColor,inputBackground:y.inputBackground,cardBackground:y.cardBackground,hoverBackground:y.hoverBackground},F=typeof v=="number"?`${v}px`:v,U=typeof f=="number"?`${f}px`:f,q=T&&k?h==="rtl"?{marginLeft:U}:{marginRight:U}:{},Z=T&&k?`calc(100% - ${U})`:"100%";return jsxs(Fragment,{children:[jsx("div",{className:a,style:{width:Z,height:"100%",transition:M?"all 0.2s ease-out":"none",padding:k&&S?"16px":"0",...q},children:jsx("div",{style:{position:"relative",width:"100%",height:"100%",transition:M?"all 0.2s ease-out":"none",borderRadius:k?F:"0",border:k&&g&&c?"none":k?`1px solid ${p.borderColor}`:"none",padding:k&&g&&c?"1.5px":"0",background:k&&g&&c?`linear-gradient(120deg, ${p.primaryColor}dd 0%, ${p.primaryColor}88 25%, ${p.primaryColor}00 50%, ${p.primaryColor}88 75%, ${p.primaryColor}dd 100%)`:"transparent",backgroundSize:k&&g&&c?"300% 300%":"auto",animation:k&&g&&c?`${E.current}-border-flow 3s ease-in-out infinite`:"none",filter:k&&g&&c?`drop-shadow(0 0 10px ${p.primaryColor}40)`:"none"},children:jsx("div",{className:"hsafa-content-container",style:{width:"100%",height:"100%",borderRadius:k&&S?F:"0",backgroundColor:k&&S?p.backgroundColor:"transparent",overflow:"auto",position:"relative",isolation:"isolate",contain:"layout style paint",transform:"translateZ(0)",scrollbarWidth:"thin",scrollbarColor:`${p.mutedTextColor}40 transparent`},children:e})})}),jsx("style",{children:`
|
|
37
|
+
@keyframes ${E.current}-border-flow {
|
|
38
38
|
0% { background-position: 0% 50%; }
|
|
39
39
|
50% { background-position: 100% 50%; }
|
|
40
40
|
100% { background-position: 0% 50%; }
|
|
41
41
|
}
|
|
42
|
-
`})," "]})}var
|
|
42
|
+
`})," "]})}var Pt=class{constructor(){this.components=new Map;}register(t,n){this.components.set(t,n);}unregister(t){this.components.delete(t);}get(t){return this.components.get(t)}has(t){return this.components.has(t)}clear(){this.components.clear();}getRegisteredNames(){return Array.from(this.components.keys())}},ho=new Pt;export{wo as Button,go as ContentContainer,Fn as CursorController,Ue as FillActiveInput,Xt as FloatingChatButton,lo as HsafaChat,lr as HsafaProvider,ho as componentRegistry,Ee as controlCursor,je as getDomComponents,Ee as guideCursor,Zt as useAutoScroll,tn as useFileUpload,Le as useHsafa};//# sourceMappingURL=index.js.map
|
|
43
43
|
//# sourceMappingURL=index.js.map
|