@pickaxeproject/react 6.3.4 → 6.4.0
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.
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("../../../_virtual/_tslib.js"),t=require("react/jsx-runtime"),s=require("react"),n=require("../../../hooks/pickaxe/usePickaxeContext.js"),i=require("../../../hooks/pickaxe/useResponseContext.js"),o=require("../../../hooks/studio/useStyleInput.js"),r=require("../../../hooks/studio/useStyleFontSize.js"),a=require("../../../hooks/pickaxe/useConversation.js"),l=require("../../../hooks/pickaxe/useDimensionContext.js"),c=require("../Addons/Auth/hooks/useAuthContext.js"),d=require("../Addons/Document/hooks/useDocument.js"),u=require("../Addons/Scroll/hooks/useScroll.js"),p=require("../Addons/Artifact/hooks/useArtifactContext.js"),f=require("../../../hooks/core/useHover.js"),g=require("../../../hooks/core/useMediaQuery.js"),h=require("../../../common/documents.js"),m=require("eventsource-parser"),v=require("../../Icons/attach-vertical.svg.js"),b=require("../../Icons/arrow-right.svg.js"),x=require("../../Icons/microphone.svg.js"),y=require("../../Icons/stop.svg.js"),j=require("../Addons/Document/List.js"),w=require("../../Core/Textarea.js"),O=require("../../Core/ErrorAlert.js"),S=require("../../../common/error.js"),k=require("../../../common/validation.js"),C=require("../../../common/cn.js"),N=require("../../../common/utils.js"),I=require("../../../hooks/studio/useStudio.js"),_=require("../../../hooks/pickaxe/useSpeech.js");const E=s.forwardRef((({resubmitPrompt:E,onFocus:T,onBlur:A,onInputHeightChange:P,initSmitheryAuthData:q},R)=>{var U,D,L;const{origin:M,pickaxeId:F,sessionId:$,sender:B,senderType:H,portalId:V,deploymentId:X,deploymentType:K,pickaxe:W,styles:J,colors:z,translations:G,locale:Q,forceMobile:Y,isNewChat:Z,isRtl:ee,isShowFeedbackMessage:te,accessGroup:se,setIsNewChat:ne,setIsShowIceBreaker:ie,setValidationStatus:oe,setValidationUpgradeGroups:re,setValidationUpgradeUrl:ae,onGenerateComplete:le}=n.usePickaxeContext(),{token:ce,isLoggedOut:de,isSent:ue,isPricingAuth:pe}=c.useAuthContext(),{messages:fe,isGenerating:ge,setMessages:he,setStatus:me,setLimitData:ve,setError:be}=i.useResponseContext(),{documents:xe,isUploading:ye,documentError:je,onFileUpload:we,setDocuments:Oe,setDocumentError:Se}=d.useDocument(),{studio:ke}=I.useStudio(),{scrollStartSession:Ce,scrollEndSession:Ne,scrollToBottom:Ie}=u.useScroll({auto:!0}),{artifacts:_e,currentPopupType:Ee,setArtifacts:Te,setCurrentArtifact:Ae}=p.useArtifactContext(),{height:Pe}=l.useDimensionContext(),qe=a.useConversation(),[Re,Ue]=s.useState(""),[De,Le]=s.useState(!1),[Me,Fe]=s.useState(!1),[$e,Be]=s.useState(null),[He,Ve]=s.useState(null),[Xe,Ke]=s.useState(!1),We=s.useRef(null),Je=s.useRef(""),ze=s.useRef(null),Ge=s.useRef(null),Qe=s.useRef(null),Ye=s.useRef(null),Ze=s.useRef(null),et=Math.max(.4*Pe,100),{speechTranscript:tt,isSpeechListening:st,isSpeechProcessing:nt,isSpeechSupported:it,onStartListening:ot,onStopListening:rt}=_.useSpeech(),[at]=g.useMediaQuery("(max-width: 480px)"),lt=f.useHover(),{isHover:ct}=lt,dt=e.__rest(lt,["isHover"]),ut=f.useHover(),{isHover:pt}=ut,ft=e.__rest(ut,["isHover"]),gt=f.useHover(),{isHover:ht}=gt,mt=e.__rest(gt,["isHover"]),vt=r.useStyleFontSize(),bt=o.useStyleInput(),xt="undefined"!=typeof window?window.location.hostname:"",yt="undefined"!=typeof window?window.location.href:"",jt="undefined"!=typeof window&&window.self!==window.top,wt=xt.includes("pickaxe.co")&&!yt.includes("https://studio.pickaxe.co/_embed")&&!jt,Ot=null===(U=null==W?void 0:W.documentuploadtype)||void 0===U?void 0:U.startsWith("enduserupload"),St=it&&(null==W?void 0:W.enablevoicetotext),kt="chat-input"===K&&Z&&!ue,Ct="chat-input"===K&&pe&&de&&ue,Nt=s.useCallback((e=>{const t=k.getValidationFailure(e);return!!t&&(be(""),ve(null),oe(t.status),re(t.upgradeGroups),ae(t.upgradeUrl),!0)}),[be,ve,oe,re,ae]),It=null!==(D=null==W?void 0:W.placeholdertext)&&void 0!==D?D:ee?"بماذا تريد أن تتحدث؟":(null==G?void 0:G["what-do-you-want-to-talk-about"])||"What do you want to talk about?",_t=De||Me,Et=s.useCallback((()=>e.__awaiter(void 0,void 0,void 0,(function*(){try{const e=yield fetch(`${process.env.NEXT_PUBLIC_PICKAXE_API_URL}/get_user`,Object.assign(Object.assign({method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(Object.assign(Object.assign(Object.assign({studioId:null==W?void 0:W.studioid},B&&{sender:B}),ce&&{studioSessionToken:ce}),!ce&&!B&&{sender:N.initializeEmbedUserId()}))},(!process.env.NODE_ENV||"development"===process.env.NODE_ENV)&&Object.assign({},process.env.NEXT_PUBLIC_PICKAXE_SESSION_TOKEN&&{headers:{"Content-Type":"application/json","x-pickaxe-session-token":process.env.NEXT_PUBLIC_PICKAXE_SESSION_TOKEN}})),wt&&{credentials:"include"})),t=yield e.json();(null==t?void 0:t.studioUser)&&(Be(t.studioUser),Ve(t.url))}catch(e){console.error("Failed to fetch studio user:",e)}}))),[M,F,$,H,B,ce,V,X,wt]);s.useEffect((()=>{Et()}),[Et]);const Tt=(null==se?void 0:se.limit)||0,At=(null==$e?void 0:$e.currentUses)||0,Pt=(null==$e?void 0:$e.extraUses)||0,qt=!!(null==ke?void 0:ke.data.usage)&&ke.data.usage.isCredits,Rt=Tt>At?Tt-At+Pt:Pt,Ut=s.useMemo((()=>!!$e&&(!Xe&&(!(Tt<=0)&&Rt<=.05*Tt))),[$e,Xe,Rt,Tt]),Dt=s.useMemo((()=>{var e,t,s;return!!Z&&(!!W&&(!qe.isLoading&&(!((null!==(t=null===(e=qe.data)||void 0===e?void 0:e.messages.length)&&void 0!==t?t:0)>1)&&(!!(null===(s=W.icebreakers)||void 0===s?void 0:s.length)&&(!te&&!kt)))))}),[W,Z,te,kt,qe.data,qe.isLoading]),Lt=s.useMemo((()=>{if(ge||ye)return!1;const e=xe.length>0&&xe.every((e=>"finished"===e.status));return!(!Re.trim()&&!e)&&xe.every((e=>"finished"===e.status||e.isInsertedAsRaw))}),[ge,ye,Re,xe]);s.useImperativeHandle(R,(()=>({onSubmit:Mt}))),s.useEffect((()=>{ie(Dt)}),[Dt]),s.useEffect((()=>{var e;if(E){const t=Array.from(fe),s=null===(e=t[t.length-2].parts.find((e=>"text"===e.type)))||void 0===e?void 0:e.content;Mt(s,!0)}}),[E]),s.useEffect((()=>{if(!Ye.current||!P)return;const e=new ResizeObserver((e=>{for(const t of e)P(t.contentRect.height)}));return e.observe(Ye.current),()=>{e.disconnect()}}),[P]),s.useEffect((()=>{if(!st)return;const e=Je.current?`${Je.current} `:"";Ue(`${e}${tt}`)}),[tt,st]),s.useEffect((()=>{if(!Ge.current)return;(()=>{if(!Ge.current)return;let e=Ge.current.scrollHeight>52;Re.includes("\n")||xe.length?e=!0:Re.trim()||(e=!1),Le(e)})()}),[Re,xe]),s.useEffect((()=>{const e=Ge.current,t=Qe.current;if(!e||!t||De||Re.includes("\n"))return void Fe(!1);const s=window.getComputedStyle(e),n=`${s.fontStyle} ${s.fontVariant} ${s.fontWeight} ${s.fontSize} / ${s.lineHeight} ${s.fontFamily}`,i=document.createElement("span");Object.assign(i.style,{font:n,letterSpacing:s.letterSpacing,position:"absolute",visibility:"hidden",whiteSpace:"nowrap",top:"0",left:"0"}),i.textContent=Re||It,document.body.appendChild(i);const o=i.offsetWidth;i.remove();const r=parseFloat(s.paddingLeft)||0,a=parseFloat(s.paddingRight)||0,l=e.clientWidth-r-a-t.offsetWidth;Fe(o>l)}),[Re,De,It]);const Mt=(t,s=!1)=>e.__awaiter(void 0,void 0,void 0,(function*(){var e,n,i;try{if(ge||ye)return;const o=xe.filter((e=>"finished"===e.status&&!e.isInsertedAsRaw)),r=o.map((e=>e.documentId)).filter(Boolean),a=o.filter((e=>"image"===e.type)).map((e=>{const t=e.name.split(".").pop()||"";return{documentId:e.documentId,extension:t}})),l=r.length>0,c=null!=t?t:Re;if(!c&&!l)return;be(""),Se(""),ve(null),Ue(""),ne(!1),me("fetching"),Ce(),Ie();const d=null!==(n=null===(e=null==W?void 0:W.documentuploadtype)||void 0===e?void 0:e.startsWith("enduserupload"))&&void 0!==n&&n&&r.length>0,u=[...s?Array.from(fe.slice(0,fe.length-1)):Array.from(fe),...s?[]:[{id:fe.length+1,role:"user",parts:[{type:"text",content:c,isVisible:!0}],documentIds:d?r:[]}],{id:fe.length+(s?0:2),role:"assistant",parts:[],documentIds:[]}];he(u),Ie(),d&&Oe([]);const p=yield fetch(`${process.env.NEXT_PUBLIC_PICKAXE_API_URL}/submit`,Object.assign({method:"POST",body:JSON.stringify(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({origin:M,pickaxeId:F,sessionId:$,senderType:H,value:c},d&&{documentIds:r}),B&&{sender:B}),ce&&{studioSessionToken:ce}),!ce&&!B&&{sender:N.initializeEmbedUserId()}),V&&{portalId:V}),X&&{deploymentId:X}),a.length>0&&{uploadedModelImages:a})),headers:Object.assign(Object.assign({},(!process.env.NODE_ENV||"development"===process.env.NODE_ENV)&&Object.assign({},process.env.NEXT_PUBLIC_PICKAXE_SESSION_TOKEN&&{"x-pickaxe-session-token":process.env.NEXT_PUBLIC_PICKAXE_SESSION_TOKEN})),{"x-request-sent-at":(new Date).toISOString()})},wt&&{credentials:"include"})),f=yield p.json();if(!f.success){if(Nt(f))return;const e=new Error(f.error||f.message||(null==G?void 0:G["failed-to-start-generation"])||"Failed to start generation");throw f.limitData&&(e.limitData=f.limitData),e}const g=f.submissionId;me("streaming"),Ze.current=new AbortController;const h=u.length-1,v=[];let b=[...null!=_e?_e:[]],x=0,y=!1,j="";for(;!y;)try{const e=yield fetch(`${process.env.NEXT_PUBLIC_PICKAXE_API_URL}/stream/${g}?index=${x}`,{signal:null===(i=Ze.current)||void 0===i?void 0:i.signal,headers:{"Cache-Control":"no-cache",Connection:"keep-alive"}});if(!e.body)throw new Error("No response body");const t=e.body.getReader();ze.current=t;const s=new TextDecoder,n=m.createParser({onEvent:e=>{var t,s;if(e.event&&"ping"!==e.event&&x++,"stop"!==e.event){if("error"===e.event){const t=JSON.parse(e.data),s=t.error||t.message||(null==G?void 0:G["something-went-wrong"])||"Something went wrong.";return Nt(t)||be(s),void(y=!0)}if("delta"===e.event){const n=JSON.parse(e.data);if("data-error"===n.type&&q){const e=n.data.error;if("string"==typeof e){if(/['"]type['"]\s*:\s*['"]unauthorized_smithery['"]/.test(e)){const t=e.match(/['"]qualifiedName['"]\s*:\s*['"]([^'"]+)['"]/),s=e.match(/['"]serverId['"]\s*:\s*['"]([^'"]+)['"]/),n=e.match(/['"]name['"]\s*:\s*['"]([^'"]+)['"]/);if(t&&t[1]&&s&&s[1]&&n&&n[1])throw y=!0,q({smitheryId:t[1],serverId:s[1],name:n[1]}),new Error("STOP_STREAM")}}else if("object"==typeof e&&null!==e){const t=e;if("unauthorized_smithery"===t.type&&t.qualifiedName&&t.serverId&&t.name)throw y=!0,q({smitheryId:t.qualifiedName,serverId:t.serverId,name:t.name}),new Error("STOP_STREAM")}}else if("text-start"===n.type)j="",v.push({type:"text",content:"",isVisible:null===(t=n.isVisible)||void 0===t||t});else if("text-delta"===n.type)j+=n.delta,v[v.length-1].content=j;else if("text-end"===n.type)j="";else if("reasoning-start"===n.type)j="",v.push({type:"reasoning",content:"",isVisible:null===(s=n.isVisible)||void 0===s||s});else if("reasoning-delta"===n.type)j+=n.delta,v[v.length-1].content=j;else if("reasoning-end"===n.type)j="";else if(n.type.startsWith("data-")){const e=n;v.push({type:e.type,content:JSON.stringify(e.data),isVisible:!0})}he([...u.slice(0,h),Object.assign(Object.assign({},u[u.length-1]),{id:fe.length+1,role:"assistant",parts:v})])}else if("artifact_created"===e.event){const t=JSON.parse(e.data);b=b.filter((e=>!(e.id===t.id&&e.version===t.version))),b.push(Object.assign(Object.assign({},t),{content:"",status:"streaming"})),Te([...b]),Ee.startsWith("inline")||Ae({id:t.id,version:t.version})}else if("artifact_updated"===e.event){const t=JSON.parse(e.data);b=b.filter((e=>!(e.id===t.id&&e.version===t.version))),b.push(Object.assign(Object.assign({},t),{content:"",status:"updating"})),Te(b),Ee.startsWith("inline")||Ae({id:t.id,version:t.version})}else if("artifact_rewrite"===e.event){const t=JSON.parse(e.data);b=b.filter((e=>!(e.id===t.id&&e.version===t.version))),b.push(Object.assign(Object.assign({},t),{content:"",status:"streaming"})),Te(b),Ee.startsWith("inline")||Ae({id:t.id,version:t.version})}else if("artifact_content"===e.event){const t=JSON.parse(e.data),s=t.token.replace(/\u200B/g,"");b=b.map((e=>e.id===t.id&&e.version===t.version?Object.assign(Object.assign({},e),{content:e.content+s,status:"streaming"}):e)),Te(b)}else if("artifact_finished"===e.event){const t=JSON.parse(e.data);Te(b.map((e=>e.id===t.id?Object.assign(Object.assign({},e),{status:"finished"}):e)))}else if("error"===e.event){const t=JSON.parse(e.data),s=t.error||t.message||(null==G?void 0:G["something-went-wrong-try-again"])||"Something went wrong, please try again.";if(Nt(t))return void(y=!0);be(s)}else"stop"===e.event&&(y=!0)}else y=!0}});for(;;){const{value:e,done:i}=yield t.read();if(i)break;n.feed(s.decode(e))}y||(yield new Promise((e=>setTimeout(e,1e3))))}catch(e){if("STOP_STREAM"===e.message||"AbortError"===e.name)return void(y=!0);console.warn("Stream connection lost, retrying...",e),yield new Promise((e=>setTimeout(e,1e3)))}null==le||le($)}catch(e){if(e.limitData)ve(e.limitData),be("");else{let t=S.default(e)||"";t&&!t.includes("Unexpected token 'A',")||(t=(null==G?void 0:G["high-traffic-try-again-later"])||"Oops! We're experiencing high traffic at the moment. Please try again later."),Nt(t)||be(t)}}finally{Ie(),me("idle"),Ne(),ze.current=null,yield Et()}}));return Ct?null:t.jsx("div",Object.assign({className:C.default("flex w-full flex-shrink-0 flex-col items-center",!kt&&"px-4 pb-8"),dir:ee?"rtl":"ltr"},{children:t.jsxs("div",Object.assign({className:"flex w-full max-w-[800px] flex-col"},{children:[t.jsxs("div",Object.assign({ref:Ye,className:C.default("relative flex flex-col w-full justify-end gap-y-3 py-[3px]","block"===J.formFieldStyle&&"shadow"),style:Object.assign(Object.assign({},bt),{maxHeight:`${et}px`,overflowY:"auto"})},{children:[Ut&&t.jsxs("div",Object.assign({className:"sticky top-0 z-10 flex w-full items-center justify-between border-b px-4 py-2.5 shadow-sm backdrop-blur-md",style:{backgroundColor:bt.backgroundColor?`${bt.backgroundColor}E6`:void 0,borderColor:z.text+"20",color:z.text,borderTopRightRadius:J.cornerRadius+"px",borderTopLeftRadius:J.cornerRadius+"px"}},{children:[t.jsx("div",Object.assign({className:"flex items-center gap-2 text-sm font-medium"},{children:t.jsxs("span",{children:[Rt," ",qt?(null==G?void 0:G.credits)||"Credits":(null==G?void 0:G.uses)||"Uses"," ",(null==G?void 0:G.remaining)||"remaining"]})})),t.jsxs("div",Object.assign({className:"flex items-center gap-3"},{children:[t.jsx("button",Object.assign({className:"rounded-md px-3 py-1.5 text-xs font-semibold transition-opacity hover:opacity-90",style:{backgroundColor:z.accent,color:z.accentText},onClick:e=>{e.preventDefault(),e.stopPropagation();const t=N.buildUpgradeUrl({baseUrl:He,accessGroupId:null==se?void 0:se.accessGroupId});t&&(N.isInIframe()?window.open(t):location.href=t)}},{children:(null==G?void 0:G.upgrade)||"Upgrade"})),t.jsx("button",Object.assign({className:"flex h-6 w-6 items-center justify-center rounded-full opacity-60 transition-opacity hover:opacity-100",onClick:()=>Ke(!0)},{children:t.jsx("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",strokeWidth:2,stroke:"currentColor",className:"h-4 w-4"},{children:t.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M6 18L18 6M6 6l12 12"})}))}))]}))]})),!ge&&xe.length>0&&t.jsx(j.default,{className:"p-4 pb-0",isDisabled:ge}),t.jsxs("div",Object.assign({className:"relative flex w-full flex-col"},{children:[st&&t.jsxs("div",Object.assign({className:"absolute left-4 top-1/2 flex -translate-y-1/2 select-none items-center gap-x-2"},{children:[t.jsx("span",{className:"h-2 w-2 animate-pulse rounded-full bg-c-secondary",style:{backgroundColor:null!==(L=z.accent)&&void 0!==L?L:"#ff0000"}}),t.jsx("span",Object.assign({className:"text-sm text-c-secondary font-semilight",style:{color:z.text+"90"}},{children:(null==G?void 0:G.listening)||"Listening..."}))]})),t.jsx(w.default,Object.assign({ref:Ge,className:C.default(vt.i1,"py-3.5 max-h-60 px-4 w-full border-transparent bg-transparent",!Re.trim()&&!Re.includes("\n")&&"overflow-hidden text-ellipsis whitespace-nowrap placeholder:whitespace-normal placeholder:overflow-visible",ee?"text-right":"text-left",_t&&"mb-12",st&&"text-transparent"),value:Re,placeholder:It,onChange:e=>{Ue(e)},onKeyDown:e=>{Y||at||"Enter"===e.key&&(e.shiftKey||(e.preventDefault(),ye||ge||Mt()))},onPaste:t=>e.__awaiter(void 0,void 0,void 0,(function*(){const e=Array.from(t.clipboardData.files||[]);e.length>0&&(t.preventDefault(),ne(!1),yield we(e))}))},T&&{onFocus:T},A&&{onBlur:A},{dir:ee?"rtl":"ltr"})),t.jsx("div",Object.assign({ref:Qe,className:C.default("flex items-center gap-2 absolute right-0 z-2 transition-all duration-200 ease-in-out",_t?"bottom-0 mb-2.5":"top-1/2 -translate-y-1/2"),style:Object.assign(Object.assign({},!_t&&bt.backgroundColor&&{backgroundColor:bt.backgroundColor}),{borderTopRightRadius:J.cornerRadius+"px",borderBottomRightRadius:J.cornerRadius+"px"})},{children:ge?t.jsx("button",Object.assign({className:"flex h-8 w-8 items-center mr-2 justify-center rounded-full outline-none transition-colors duration-200 ease-in-out",onClick:()=>{Ze.current&&(Ze.current.abort(),Ze.current=null),ze.current&&(ze.current.cancel(),ze.current=null),me("idle")},style:{backgroundColor:z.accent,color:z.accentText}},{children:t.jsx(y.default,{className:"h-4 w-4 shrink-0"})})):st?t.jsx("button",Object.assign({className:"flex h-8 w-8 items-center mr-2 justify-center rounded-full outline-none transition-colors duration-200 ease-in-out",onClick:rt,style:{backgroundColor:z.accent,color:z.accentText}},{children:t.jsx(y.default,{className:"h-4 w-4 shrink-0"})})):t.jsxs(t.Fragment,{children:[Ot&&t.jsxs("button",Object.assign({className:"flex h-8 w-8 items-center justify-center rounded-full outline-none transition-colors duration-200 ease-in-out disabled:cursor-default",style:{backgroundColor:pt?z.accent+"10":void 0,color:pt?z.accent:z.accent+"80"},disabled:ye||ge,onClick:()=>{var e;return null===(e=We.current)||void 0===e?void 0:e.click()}},ft,{children:[t.jsx("input",{id:"file-upload",ref:We,type:"file",accept:[...h.allowedFileMimeTypes,...h.allowedImageMimeTypes,...h.additionalAllowedFileExtensions].join(", "),multiple:!0,hidden:!0,className:"hidden",onChange:t=>e.__awaiter(void 0,void 0,void 0,(function*(){ne(!1),yield we(Array.from(t.target.files||[])),t.target.value=""}))}),t.jsx(v.default,{className:"h-6 w-6 shrink-0"})]})),St&&t.jsx("button",Object.assign({className:"disabled:cursor-default flex h-8 w-8 items-center justify-center rounded-full outline-none transition-colors duration-200 ease-in-out",style:{backgroundColor:st?z.accent:ht?z.accent+"10":void 0,color:st?z.accentText:ht?z.accent:z.accent+"80"},disabled:ye||ge||nt,onClick:()=>{st?rt():(Je.current=Re,ot(Q||"en-US"))}},mt,{children:t.jsx(x.default,{className:"h-5 w-5 shrink-0"})})),t.jsx("button",Object.assign({className:"flex h-8 w-8 items-center mr-2 justify-center rounded-full outline-none transition-colors duration-200 ease-in-out disabled:cursor-default",style:{backgroundColor:ct||Lt?z.accent:z.accent+"10",color:ct||Lt?z.accentText:z.accent+"80"},disabled:!Lt,onClick:()=>Mt()},dt,{children:t.jsx(b.default,{className:C.default("h-6 w-6 shrink-0",ee&&"scale-x-[-1] transform")})}))]})}))]}))]})),je&&t.jsx(O.default,{error:je,className:"mt-3"})]}))}))}));E.displayName="Input",exports.default=E;
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("../../../_virtual/_tslib.js"),t=require("react/jsx-runtime"),s=require("react"),n=require("../../../hooks/pickaxe/usePickaxeContext.js"),i=require("../../../hooks/pickaxe/useResponseContext.js"),r=require("../../../hooks/studio/useStyleInput.js"),o=require("../../../hooks/studio/useStyleFontSize.js"),a=require("../../../hooks/pickaxe/useConversation.js"),l=require("../../../hooks/pickaxe/useDimensionContext.js"),c=require("../Addons/Auth/hooks/useAuthContext.js"),d=require("../Addons/Document/hooks/useDocument.js"),u=require("../Addons/Scroll/hooks/useScroll.js"),p=require("../Addons/Artifact/hooks/useArtifactContext.js"),f=require("../../../hooks/core/useHover.js"),m=require("../../../hooks/core/useMediaQuery.js"),h=require("../../../common/documents.js"),g=require("eventsource-parser"),v=require("../../Icons/attach-vertical.svg.js"),x=require("../../Icons/arrow-right.svg.js"),b=require("../../Icons/microphone.svg.js"),y=require("../../Icons/stop.svg.js"),I=require("../Addons/Document/List.js"),j=require("../../Core/Textarea.js"),w=require("../../Core/ErrorAlert.js"),N=require("../../../common/error.js"),O=require("../../../common/api/pickaxe.js"),S=require("../../../common/validation.js"),_=require("../../../common/cn.js"),k=require("../../../common/utils.js"),U=require("../../../hooks/studio/useStudio.js"),C=require("../../../hooks/pickaxe/useSpeech.js"),E=require("../common/PickaxeCommon.js");const T=e=>"string"==typeof e&&e.trim().length>0,A=(e,t)=>{if(e&&"object"==typeof e)return e[t]},D=e=>{const t=Number(e);return Number.isFinite(t)?t:void 0},L=({studioUser:e,deploymentId:t,portalId:s})=>{var n,i;const r=Array.isArray(A(e,"uses"))?A(e,"uses"):[],o=(({deploymentId:e,portalId:t})=>T(e)?{type:"deployment",id:e}:T(t)?{type:"portal",id:t}:null)({deploymentId:t,portalId:s});if(!o)return{scope:o,record:null};const a=null!==(i=null!==(n=r.find((e=>e.id===o.id&&e.type===o.type)))&&void 0!==n?n:r.find((e=>e.id===o.id)))&&void 0!==i?i:null;return{scope:o,record:a}},P=s.forwardRef((({resubmitPrompt:T,onFocus:A,onBlur:P,onInputHeightChange:q,initSmitheryAuthData:R},F)=>{var M,V,$,B,H,X,Y,K,W;const{origin:J,pickaxeId:z,sessionId:G,sender:Q,senderType:Z,portalId:ee,deploymentId:te,deploymentType:se,pickaxe:ne,styles:ie,colors:re,translations:oe,locale:ae,forceMobile:le,isNewChat:ce,isRtl:de,isShowFeedbackMessage:ue,accessGroup:pe,setIsNewChat:fe,setIsShowIceBreaker:me,setValidationStatus:he,setValidationUpgradeGroups:ge,setValidationUpgradeUrl:ve,onGenerateComplete:xe}=n.usePickaxeContext(),{token:be,isLoggedOut:ye,isSent:Ie,isPricingAuth:je}=c.useAuthContext(),{messages:we,isGenerating:Ne,setMessages:Oe,setStatus:Se,setLimitData:_e,setError:ke}=i.useResponseContext(),{documents:Ue,isUploading:Ce,documentError:Ee,onFileUpload:Te,setDocuments:Ae,setDocumentError:De}=d.useDocument(),{studio:Le}=U.useStudio(),{scrollStartSession:Pe,scrollEndSession:qe,scrollToBottom:Re}=u.useScroll({auto:!0}),{artifacts:Fe,currentPopupType:Me,setArtifacts:Ve,setCurrentArtifact:$e}=p.useArtifactContext(),{height:Be}=l.useDimensionContext(),He=a.useConversation(),[Xe,Ye]=s.useState(""),[Ke,We]=s.useState(!1),[Je,ze]=s.useState(!1),[Ge,Qe]=s.useState(null),[Ze,et]=s.useState(null),[tt,st]=s.useState(!1),[nt,it]=s.useState(0),rt=s.useRef(null),ot=s.useRef(""),at=s.useRef(null),lt=s.useRef(null),ct=s.useRef(null),dt=s.useRef(null),ut=s.useRef(null),pt=Math.max(.4*Be,100),{speechTranscript:ft,isSpeechListening:mt,isSpeechProcessing:ht,isSpeechSupported:gt,onStartListening:vt,onStopListening:xt}=C.useSpeech(),[bt]=m.useMediaQuery("(max-width: 480px)"),yt=f.useHover(),{isHover:It}=yt,jt=e.__rest(yt,["isHover"]),wt=f.useHover(),{isHover:Nt}=wt,Ot=e.__rest(wt,["isHover"]),St=f.useHover(),{isHover:_t}=St,kt=e.__rest(St,["isHover"]),Ut=o.useStyleFontSize(),Ct=r.useStyleInput(),Et="undefined"!=typeof window?window.location.hostname:"",Tt="undefined"!=typeof window?window.location.href:"",At="undefined"!=typeof window&&window.self!==window.top,Dt=Et.includes("pickaxe.co")&&!Tt.includes("https://studio.pickaxe.co/_embed")&&!At,Lt=null===(M=null==ne?void 0:ne.documentuploadtype)||void 0===M?void 0:M.startsWith("enduserupload"),Pt=gt&&(null==ne?void 0:ne.enablevoicetotext),qt="chat-input"===se&&ce&&!Ie,Rt="chat-input"===se&&je&&ye&&Ie,Ft=s.useCallback((e=>{const t=S.getValidationFailure(e);return!!t&&(ke(""),_e(null),he(t.status),ge(t.upgradeGroups),ve(t.upgradeUrl),!0)}),[ke,_e,he,ge,ve]),Mt=null!==(V=null==ne?void 0:ne.placeholdertext)&&void 0!==V?V:de?"بماذا تريد أن تتحدث؟":(null==oe?void 0:oe["what-do-you-want-to-talk-about"])||"What do you want to talk about?",Vt=Ke||Je,$t=s.useCallback((()=>e.__awaiter(void 0,void 0,void 0,(function*(){try{const e=yield fetch(`${process.env.NEXT_PUBLIC_PICKAXE_API_URL}/get_user`,Object.assign(Object.assign({method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(Object.assign(Object.assign(Object.assign({studioId:null==ne?void 0:ne.studioid},Q&&{sender:Q}),be&&{studioSessionToken:be}),!be&&!Q&&{sender:k.initializeEmbedUserId()}))},(!process.env.NODE_ENV||"development"===process.env.NODE_ENV)&&Object.assign({},process.env.NEXT_PUBLIC_PICKAXE_SESSION_TOKEN&&{headers:{"Content-Type":"application/json","x-pickaxe-session-token":process.env.NEXT_PUBLIC_PICKAXE_SESSION_TOKEN}})),Dt&&{credentials:"include"})),t=yield e.json();(null==t?void 0:t.studioUser)&&(Qe(t.studioUser),et(t.url))}catch(e){console.error("Failed to fetch studio user:",e)}}))),[J,z,G,Z,Q,be,ee,te,Dt]);s.useEffect((()=>{$t()}),[$t]);const Bt=Number(null!==($=null==pe?void 0:pe.limit)&&void 0!==$?$:0),Ht="string"==typeof(null==pe?void 0:pe.limitInterval)?pe.limitInterval:null,Xt=!!(null==Le?void 0:Le.data.usage)&&Le.data.usage.isCredits,Yt=s.useMemo((()=>L({studioUser:Ge,deploymentId:te,portalId:ee})),[te,ee,Ge]),Kt={currentUses:D(null==Ge?void 0:Ge.currentUses),extraUses:D(null==Ge?void 0:Ge.extraUses)},Wt=Yt.scope?{currentUses:null!==(H=D(null===(B=Yt.record)||void 0===B?void 0:B.currentUses))&&void 0!==H?H:0,extraUses:null!==(Y=D(null===(X=Yt.record)||void 0===X?void 0:X.extraUses))&&void 0!==Y?Y:0}:{currentUses:0,extraUses:0},Jt=ye?Wt:Kt;s.useEffect((()=>{let t=!0;return e.__awaiter(void 0,void 0,void 0,(function*(){var e;if(Xt&&(null===(e=null==Le?void 0:Le.data)||void 0===e?void 0:e.workspaceId))try{const e=yield O.default.get(`/cost_per_run?workspaceId=${Le.data.workspaceId}`,{withCredentials:!1});t&&it(1e4*(Number(e.data.costPerRun)||0))}catch(e){console.error("Failed to fetch average cost per run:",e),t&&it(0)}else t&&it(0)})),()=>{t=!1}}),[Xt,null===(K=null==Le?void 0:Le.data)||void 0===K?void 0:K.workspaceId]);const zt=(({currentUses:e,extraUses:t,limit:s,limitInterval:n})=>{const i=Number(null!=e?e:0),r=Number(null!=t?t:0);return s===E.STUDIO_INFINITY_VALUE||r===E.STUDIO_INFINITY_VALUE?E.STUDIO_INFINITY_VALUE:"one_time"===n?Math.max(0,r-i):Math.max(0,s-i)+r})({currentUses:Jt.currentUses,extraUses:Jt.extraUses,limit:Bt,limitInterval:Ht}),Gt=zt===E.STUDIO_INFINITY_VALUE?E.STUDIO_INFINITY_VALUE:Math.max(0,Math.ceil(zt)),Qt=(({extraUses:e,limit:t,limitInterval:s})=>{const n=Number(null!=e?e:0);return t===E.STUDIO_INFINITY_VALUE||n===E.STUDIO_INFINITY_VALUE?E.STUDIO_INFINITY_VALUE:"one_time"===s?Math.max(0,n):Math.max(0,t)+Math.max(0,n)})({extraUses:Jt.extraUses,limit:Bt,limitInterval:Ht}),Zt=Qt===E.STUDIO_INFINITY_VALUE?E.STUDIO_INFINITY_VALUE:Math.ceil(.05*Qt),es=Xt?Math.ceil(5*nt):5,ts=Zt===E.STUDIO_INFINITY_VALUE?E.STUDIO_INFINITY_VALUE:Math.max(Zt,es);console.log("Usage and Limits Debug:",{remaining:Gt,notificationThreshold:ts,studioUser:Ge});const ss=s.useMemo((()=>!!Ge&&(!tt&&(Gt!==E.STUDIO_INFINITY_VALUE&&(!(Gt<=0)&&Gt<=ts)))),[tt,ts,Gt,Ge]),ns=s.useMemo((()=>{var e,t,s;return!!ce&&(!!ne&&(!He.isLoading&&(!((null!==(t=null===(e=He.data)||void 0===e?void 0:e.messages.length)&&void 0!==t?t:0)>1)&&(!!(null===(s=ne.icebreakers)||void 0===s?void 0:s.length)&&(!ue&&!qt)))))}),[ne,ce,ue,qt,He.data,He.isLoading]),is=s.useMemo((()=>{if(Ne||Ce)return!1;const e=Ue.length>0&&Ue.every((e=>"finished"===e.status));return!(!Xe.trim()&&!e)&&Ue.every((e=>"finished"===e.status||e.isInsertedAsRaw))}),[Ne,Ce,Xe,Ue]);s.useImperativeHandle(F,(()=>({onSubmit:rs}))),s.useEffect((()=>{me(ns)}),[ns]),s.useEffect((()=>{var e;if(T){const t=Array.from(we),s=null===(e=t[t.length-2].parts.find((e=>"text"===e.type)))||void 0===e?void 0:e.content;rs(s,!0)}}),[T]),s.useEffect((()=>{if(!dt.current||!q)return;const e=new ResizeObserver((e=>{for(const t of e)q(t.contentRect.height)}));return e.observe(dt.current),()=>{e.disconnect()}}),[q]),s.useEffect((()=>{if(!mt)return;const e=ot.current?`${ot.current} `:"";Ye(`${e}${ft}`)}),[ft,mt]),s.useEffect((()=>{if(!lt.current)return;(()=>{if(!lt.current)return;let e=lt.current.scrollHeight>52;Xe.includes("\n")||Ue.length?e=!0:Xe.trim()||(e=!1),We(e)})()}),[Xe,Ue]),s.useEffect((()=>{const e=lt.current,t=ct.current;if(!e||!t||Ke||Xe.includes("\n"))return void ze(!1);const s=window.getComputedStyle(e),n=`${s.fontStyle} ${s.fontVariant} ${s.fontWeight} ${s.fontSize} / ${s.lineHeight} ${s.fontFamily}`,i=document.createElement("span");Object.assign(i.style,{font:n,letterSpacing:s.letterSpacing,position:"absolute",visibility:"hidden",whiteSpace:"nowrap",top:"0",left:"0"}),i.textContent=Xe||Mt,document.body.appendChild(i);const r=i.offsetWidth;i.remove();const o=parseFloat(s.paddingLeft)||0,a=parseFloat(s.paddingRight)||0,l=e.clientWidth-o-a-t.offsetWidth;ze(r>l)}),[Xe,Ke,Mt]);const rs=(t,s=!1)=>e.__awaiter(void 0,void 0,void 0,(function*(){var e,n,i;try{if(Ne||Ce)return;const r=Ue.filter((e=>"finished"===e.status&&!e.isInsertedAsRaw)),o=r.map((e=>e.documentId)).filter(Boolean),a=r.filter((e=>"image"===e.type)).map((e=>{const t=e.name.split(".").pop()||"";return{documentId:e.documentId,extension:t}})),l=o.length>0,c=null!=t?t:Xe;if(!c&&!l)return;ke(""),De(""),_e(null),Ye(""),fe(!1),Se("fetching"),Pe(),Re();const d=null!==(n=null===(e=null==ne?void 0:ne.documentuploadtype)||void 0===e?void 0:e.startsWith("enduserupload"))&&void 0!==n&&n&&o.length>0,u=[...s?Array.from(we.slice(0,we.length-1)):Array.from(we),...s?[]:[{id:we.length+1,role:"user",parts:[{type:"text",content:c,isVisible:!0}],documentIds:d?o:[]}],{id:we.length+(s?0:2),role:"assistant",parts:[],documentIds:[]}];Oe(u),Re(),d&&Ae([]);const p=yield fetch(`${process.env.NEXT_PUBLIC_PICKAXE_API_URL}/submit`,Object.assign({method:"POST",body:JSON.stringify(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({origin:J,pickaxeId:z,sessionId:G,senderType:Z,value:c},d&&{documentIds:o}),Q&&{sender:Q}),be&&{studioSessionToken:be}),!be&&!Q&&{sender:k.initializeEmbedUserId()}),ee&&{portalId:ee}),te&&{deploymentId:te}),a.length>0&&{uploadedModelImages:a})),headers:Object.assign(Object.assign({},(!process.env.NODE_ENV||"development"===process.env.NODE_ENV)&&Object.assign({},process.env.NEXT_PUBLIC_PICKAXE_SESSION_TOKEN&&{"x-pickaxe-session-token":process.env.NEXT_PUBLIC_PICKAXE_SESSION_TOKEN})),{"x-request-sent-at":(new Date).toISOString()})},Dt&&{credentials:"include"})),f=yield p.json();if(!f.success){if(Ft(f))return;const e=new Error(f.error||f.message||(null==oe?void 0:oe["failed-to-start-generation"])||"Failed to start generation");throw f.limitData&&(e.limitData=f.limitData),e}const m=f.submissionId;Se("streaming"),ut.current=new AbortController;const h=u.length-1,v=[];let x=[...null!=Fe?Fe:[]],b=0,y=!1,I="";for(;!y;)try{const e=yield fetch(`${process.env.NEXT_PUBLIC_PICKAXE_API_URL}/stream/${m}?index=${b}`,{signal:null===(i=ut.current)||void 0===i?void 0:i.signal,headers:{"Cache-Control":"no-cache",Connection:"keep-alive"}});if(!e.body)throw new Error("No response body");const t=e.body.getReader();at.current=t;const s=new TextDecoder,n=g.createParser({onEvent:e=>{var t,s;if(e.event&&"ping"!==e.event&&b++,"stop"!==e.event){if("error"===e.event){const t=JSON.parse(e.data),s=t.error||t.message||(null==oe?void 0:oe["something-went-wrong"])||"Something went wrong.";return Ft(t)||ke(s),void(y=!0)}if("delta"===e.event){const n=JSON.parse(e.data);if("data-error"===n.type&&R){const e=n.data.error;if("string"==typeof e){if(/['"]type['"]\s*:\s*['"]unauthorized_smithery['"]/.test(e)){const t=e.match(/['"]qualifiedName['"]\s*:\s*['"]([^'"]+)['"]/),s=e.match(/['"]serverId['"]\s*:\s*['"]([^'"]+)['"]/),n=e.match(/['"]name['"]\s*:\s*['"]([^'"]+)['"]/);if(t&&t[1]&&s&&s[1]&&n&&n[1])throw y=!0,R({smitheryId:t[1],serverId:s[1],name:n[1]}),new Error("STOP_STREAM")}}else if("object"==typeof e&&null!==e){const t=e;if("unauthorized_smithery"===t.type&&t.qualifiedName&&t.serverId&&t.name)throw y=!0,R({smitheryId:t.qualifiedName,serverId:t.serverId,name:t.name}),new Error("STOP_STREAM")}}else if("text-start"===n.type)I="",v.push({type:"text",content:"",isVisible:null===(t=n.isVisible)||void 0===t||t});else if("text-delta"===n.type)I+=n.delta,v[v.length-1].content=I;else if("text-end"===n.type)I="";else if("reasoning-start"===n.type)I="",v.push({type:"reasoning",content:"",isVisible:null===(s=n.isVisible)||void 0===s||s});else if("reasoning-delta"===n.type)I+=n.delta,v[v.length-1].content=I;else if("reasoning-end"===n.type)I="";else if(n.type.startsWith("data-")){const e=n;v.push({type:e.type,content:JSON.stringify(e.data),isVisible:!0})}Oe([...u.slice(0,h),Object.assign(Object.assign({},u[u.length-1]),{id:we.length+1,role:"assistant",parts:v})])}else if("artifact_created"===e.event){const t=JSON.parse(e.data);x=x.filter((e=>!(e.id===t.id&&e.version===t.version))),x.push(Object.assign(Object.assign({},t),{content:"",status:"streaming"})),Ve([...x]),Me.startsWith("inline")||$e({id:t.id,version:t.version})}else if("artifact_updated"===e.event){const t=JSON.parse(e.data);x=x.filter((e=>!(e.id===t.id&&e.version===t.version))),x.push(Object.assign(Object.assign({},t),{content:"",status:"updating"})),Ve(x),Me.startsWith("inline")||$e({id:t.id,version:t.version})}else if("artifact_rewrite"===e.event){const t=JSON.parse(e.data);x=x.filter((e=>!(e.id===t.id&&e.version===t.version))),x.push(Object.assign(Object.assign({},t),{content:"",status:"streaming"})),Ve(x),Me.startsWith("inline")||$e({id:t.id,version:t.version})}else if("artifact_content"===e.event){const t=JSON.parse(e.data),s=t.token.replace(/\u200B/g,"");x=x.map((e=>e.id===t.id&&e.version===t.version?Object.assign(Object.assign({},e),{content:e.content+s,status:"streaming"}):e)),Ve(x)}else if("artifact_finished"===e.event){const t=JSON.parse(e.data);Ve(x.map((e=>e.id===t.id?Object.assign(Object.assign({},e),{status:"finished"}):e)))}else if("error"===e.event){const t=JSON.parse(e.data),s=t.error||t.message||(null==oe?void 0:oe["something-went-wrong-try-again"])||"Something went wrong, please try again.";if(Ft(t))return void(y=!0);ke(s)}else"stop"===e.event&&(y=!0)}else y=!0}});for(;;){const{value:e,done:i}=yield t.read();if(i)break;n.feed(s.decode(e))}y||(yield new Promise((e=>setTimeout(e,1e3))))}catch(e){if("STOP_STREAM"===e.message||"AbortError"===e.name)return void(y=!0);console.warn("Stream connection lost, retrying...",e),yield new Promise((e=>setTimeout(e,1e3)))}null==xe||xe(G)}catch(e){if(e.limitData)_e(e.limitData),ke("");else{let t=N.default(e)||"";t&&!t.includes("Unexpected token 'A',")||(t=(null==oe?void 0:oe["high-traffic-try-again-later"])||"Oops! We're experiencing high traffic at the moment. Please try again later."),Ft(t)||ke(t)}}finally{Re(),Se("idle"),qe(),at.current=null,yield $t()}}));return Rt?null:t.jsx("div",Object.assign({className:_.default("flex w-full flex-shrink-0 flex-col items-center",!qt&&"px-4 pb-8"),dir:de?"rtl":"ltr"},{children:t.jsxs("div",Object.assign({className:"flex w-full max-w-[800px] flex-col"},{children:[t.jsxs("div",Object.assign({ref:dt,className:_.default("relative flex flex-col w-full justify-end gap-y-3 py-[3px]","block"===ie.formFieldStyle&&"shadow"),style:Object.assign(Object.assign({},Ct),{maxHeight:`${pt}px`,overflowY:"auto"})},{children:[ss&&t.jsxs("div",Object.assign({className:"sticky top-0 z-10 flex w-full items-center justify-between border-b px-4 py-2.5 shadow-sm backdrop-blur-md",style:{backgroundColor:Ct.backgroundColor?`${Ct.backgroundColor}E6`:void 0,borderColor:re.text+"20",color:re.text,borderTopRightRadius:ie.cornerRadius+"px",borderTopLeftRadius:ie.cornerRadius+"px"}},{children:[t.jsx("div",Object.assign({className:"flex items-center gap-2 text-sm font-medium"},{children:t.jsxs("span",{children:[Gt.toLocaleString()," ",Xt?(null==oe?void 0:oe.credits)||"Credits":(null==oe?void 0:oe.uses)||"Uses"," ",(null==oe?void 0:oe.remaining)||"remaining"]})})),t.jsxs("div",Object.assign({className:"flex items-center gap-3"},{children:[t.jsx("button",Object.assign({className:"rounded-md px-3 py-1.5 text-xs font-semibold transition-opacity hover:opacity-90",style:{backgroundColor:re.accent,color:re.accentText},onClick:e=>{e.preventDefault(),e.stopPropagation();const t=k.buildUpgradeUrl({baseUrl:Ze,accessGroupId:null==pe?void 0:pe.accessGroupId});t&&(k.isInIframe()?window.open(t):location.href=t)}},{children:(null==oe?void 0:oe.upgrade)||"Upgrade"})),t.jsx("button",Object.assign({className:"flex h-6 w-6 items-center justify-center rounded-full opacity-60 transition-opacity hover:opacity-100",onClick:()=>st(!0)},{children:t.jsx("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",strokeWidth:2,stroke:"currentColor",className:"h-4 w-4"},{children:t.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M6 18L18 6M6 6l12 12"})}))}))]}))]})),!Ne&&Ue.length>0&&t.jsx(I.default,{className:"p-4 pb-0",isDisabled:Ne}),t.jsxs("div",Object.assign({className:"relative flex w-full flex-col"},{children:[mt&&t.jsxs("div",Object.assign({className:"absolute left-4 top-1/2 flex -translate-y-1/2 select-none items-center gap-x-2"},{children:[t.jsx("span",{className:"h-2 w-2 animate-pulse rounded-full bg-c-secondary",style:{backgroundColor:null!==(W=re.accent)&&void 0!==W?W:"#ff0000"}}),t.jsx("span",Object.assign({className:"text-sm text-c-secondary font-semilight",style:{color:re.text+"90"}},{children:(null==oe?void 0:oe.listening)||"Listening..."}))]})),t.jsx(j.default,Object.assign({ref:lt,className:_.default(Ut.i1,"py-3.5 max-h-60 px-4 w-full border-transparent bg-transparent",!Xe.trim()&&!Xe.includes("\n")&&"overflow-hidden text-ellipsis whitespace-nowrap placeholder:whitespace-normal placeholder:overflow-visible",de?"text-right":"text-left",Vt&&"mb-12",mt&&"text-transparent"),value:Xe,placeholder:Mt,onChange:e=>{Ye(e)},onKeyDown:e=>{le||bt||"Enter"===e.key&&(e.shiftKey||(e.preventDefault(),Ce||Ne||rs()))},onPaste:t=>e.__awaiter(void 0,void 0,void 0,(function*(){const e=Array.from(t.clipboardData.files||[]);e.length>0&&(t.preventDefault(),fe(!1),yield Te(e))}))},A&&{onFocus:A},P&&{onBlur:P},{dir:de?"rtl":"ltr"})),t.jsx("div",Object.assign({ref:ct,className:_.default("flex items-center gap-2 absolute right-0 z-2 transition-all duration-200 ease-in-out",Vt?"bottom-0 mb-2.5":"top-1/2 -translate-y-1/2"),style:Object.assign(Object.assign({},!Vt&&Ct.backgroundColor&&{backgroundColor:Ct.backgroundColor}),{borderTopRightRadius:ie.cornerRadius+"px",borderBottomRightRadius:ie.cornerRadius+"px"})},{children:Ne?t.jsx("button",Object.assign({className:"flex h-8 w-8 items-center mr-2 justify-center rounded-full outline-none transition-colors duration-200 ease-in-out",onClick:()=>{ut.current&&(ut.current.abort(),ut.current=null),at.current&&(at.current.cancel(),at.current=null),Se("idle")},style:{backgroundColor:re.accent,color:re.accentText}},{children:t.jsx(y.default,{className:"h-4 w-4 shrink-0"})})):mt?t.jsx("button",Object.assign({className:"flex h-8 w-8 items-center mr-2 justify-center rounded-full outline-none transition-colors duration-200 ease-in-out",onClick:xt,style:{backgroundColor:re.accent,color:re.accentText}},{children:t.jsx(y.default,{className:"h-4 w-4 shrink-0"})})):t.jsxs(t.Fragment,{children:[Lt&&t.jsxs("button",Object.assign({className:"flex h-8 w-8 items-center justify-center rounded-full outline-none transition-colors duration-200 ease-in-out disabled:cursor-default",style:{backgroundColor:Nt?re.accent+"10":void 0,color:Nt?re.accent:re.accent+"80"},disabled:Ce||Ne,onClick:()=>{var e;return null===(e=rt.current)||void 0===e?void 0:e.click()}},Ot,{children:[t.jsx("input",{id:"file-upload",ref:rt,type:"file",accept:[...h.allowedFileMimeTypes,...h.allowedImageMimeTypes,...h.additionalAllowedFileExtensions].join(", "),multiple:!0,hidden:!0,className:"hidden",onChange:t=>e.__awaiter(void 0,void 0,void 0,(function*(){fe(!1),yield Te(Array.from(t.target.files||[])),t.target.value=""}))}),t.jsx(v.default,{className:"h-6 w-6 shrink-0"})]})),Pt&&t.jsx("button",Object.assign({className:"disabled:cursor-default flex h-8 w-8 items-center justify-center rounded-full outline-none transition-colors duration-200 ease-in-out",style:{backgroundColor:mt?re.accent:_t?re.accent+"10":void 0,color:mt?re.accentText:_t?re.accent:re.accent+"80"},disabled:Ce||Ne||ht,onClick:()=>{mt?xt():(ot.current=Xe,vt(ae||"en-US"))}},kt,{children:t.jsx(b.default,{className:"h-5 w-5 shrink-0"})})),t.jsx("button",Object.assign({className:"flex h-8 w-8 items-center mr-2 justify-center rounded-full outline-none transition-colors duration-200 ease-in-out disabled:cursor-default",style:{backgroundColor:It||is?re.accent:re.accent+"10",color:It||is?re.accentText:re.accent+"80"},disabled:!is,onClick:()=>rs()},jt,{children:t.jsx(x.default,{className:_.default("h-6 w-6 shrink-0",de&&"scale-x-[-1] transform")})}))]})}))]}))]})),Ee&&t.jsx(w.default,{error:Ee,className:"mt-3"})]}))}))}));P.displayName="Input",exports.default=P;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{__rest as e,__awaiter as t}from"../../../_virtual/_tslib.js";import{jsx as s,jsxs as n,Fragment as o}from"react/jsx-runtime";import{forwardRef as i,useState as r,useRef as a,useCallback as l,useEffect as c,useMemo as d,useImperativeHandle as u}from"react";import{usePickaxeContext as p}from"../../../hooks/pickaxe/usePickaxeContext.js";import{useResponseContext as m}from"../../../hooks/pickaxe/useResponseContext.js";import{useStyleInput as f}from"../../../hooks/studio/useStyleInput.js";import{useStyleFontSize as g}from"../../../hooks/studio/useStyleFontSize.js";import{useConversation as h}from"../../../hooks/pickaxe/useConversation.js";import{useDimensionContext as v}from"../../../hooks/pickaxe/useDimensionContext.js";import{useAuthContext as b}from"../Addons/Auth/hooks/useAuthContext.js";import{useDocument as y}from"../Addons/Document/hooks/useDocument.js";import{useScroll as x}from"../Addons/Scroll/hooks/useScroll.js";import{useArtifactContext as j}from"../Addons/Artifact/hooks/useArtifactContext.js";import{useHover as w}from"../../../hooks/core/useHover.js";import{useMediaQuery as O}from"../../../hooks/core/useMediaQuery.js";import{allowedFileMimeTypes as k,allowedImageMimeTypes as N,additionalAllowedFileExtensions as S}from"../../../common/documents.js";import{createParser as C}from"eventsource-parser";import I from"../../Icons/attach-vertical.svg.js";import E from"../../Icons/arrow-right.svg.js";import _ from"../../Icons/microphone.svg.js";import T from"../../Icons/stop.svg.js";import A from"../Addons/Document/List.js";import P from"../../Core/Textarea.js";import D from"../../Core/ErrorAlert.js";import R from"../../../common/error.js";import{getValidationFailure as U}from"../../../common/validation.js";import L from"../../../common/cn.js";import{buildUpgradeUrl as $,isInIframe as B,initializeEmbedUserId as V}from"../../../common/utils.js";import{useStudio as X}from"../../../hooks/studio/useStudio.js";import{useSpeech as K}from"../../../hooks/pickaxe/useSpeech.js";const W=i((({resubmitPrompt:i,onFocus:W,onBlur:F,onInputHeightChange:H,initSmitheryAuthData:J},M)=>{var z,G,q;const{origin:Q,pickaxeId:Y,sessionId:Z,sender:ee,senderType:te,portalId:se,deploymentId:ne,deploymentType:oe,pickaxe:ie,styles:re,colors:ae,translations:le,locale:ce,forceMobile:de,isNewChat:ue,isRtl:pe,isShowFeedbackMessage:me,accessGroup:fe,setIsNewChat:ge,setIsShowIceBreaker:he,setValidationStatus:ve,setValidationUpgradeGroups:be,setValidationUpgradeUrl:ye,onGenerateComplete:xe}=p(),{token:je,isLoggedOut:we,isSent:Oe,isPricingAuth:ke}=b(),{messages:Ne,isGenerating:Se,setMessages:Ce,setStatus:Ie,setLimitData:Ee,setError:_e}=m(),{documents:Te,isUploading:Ae,documentError:Pe,onFileUpload:De,setDocuments:Re,setDocumentError:Ue}=y(),{studio:Le}=X(),{scrollStartSession:$e,scrollEndSession:Be,scrollToBottom:Ve}=x({auto:!0}),{artifacts:Xe,currentPopupType:Ke,setArtifacts:We,setCurrentArtifact:Fe}=j(),{height:He}=v(),Je=h(),[Me,ze]=r(""),[Ge,qe]=r(!1),[Qe,Ye]=r(!1),[Ze,et]=r(null),[tt,st]=r(null),[nt,ot]=r(!1),it=a(null),rt=a(""),at=a(null),lt=a(null),ct=a(null),dt=a(null),ut=a(null),pt=Math.max(.4*He,100),{speechTranscript:mt,isSpeechListening:ft,isSpeechProcessing:gt,isSpeechSupported:ht,onStartListening:vt,onStopListening:bt}=K(),[yt]=O("(max-width: 480px)"),xt=w(),{isHover:jt}=xt,wt=e(xt,["isHover"]),Ot=w(),{isHover:kt}=Ot,Nt=e(Ot,["isHover"]),St=w(),{isHover:Ct}=St,It=e(St,["isHover"]),Et=g(),_t=f(),Tt="undefined"!=typeof window?window.location.hostname:"",At="undefined"!=typeof window?window.location.href:"",Pt="undefined"!=typeof window&&window.self!==window.top,Dt=Tt.includes("pickaxe.co")&&!At.includes("https://studio.pickaxe.co/_embed")&&!Pt,Rt=null===(z=null==ie?void 0:ie.documentuploadtype)||void 0===z?void 0:z.startsWith("enduserupload"),Ut=ht&&(null==ie?void 0:ie.enablevoicetotext),Lt="chat-input"===oe&&ue&&!Oe,$t="chat-input"===oe&&ke&&we&&Oe,Bt=l((e=>{const t=U(e);return!!t&&(_e(""),Ee(null),ve(t.status),be(t.upgradeGroups),ye(t.upgradeUrl),!0)}),[_e,Ee,ve,be,ye]),Vt=null!==(G=null==ie?void 0:ie.placeholdertext)&&void 0!==G?G:pe?"بماذا تريد أن تتحدث؟":(null==le?void 0:le["what-do-you-want-to-talk-about"])||"What do you want to talk about?",Xt=Ge||Qe,Kt=l((()=>t(void 0,void 0,void 0,(function*(){try{const e=yield fetch(`${process.env.NEXT_PUBLIC_PICKAXE_API_URL}/get_user`,Object.assign(Object.assign({method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(Object.assign(Object.assign(Object.assign({studioId:null==ie?void 0:ie.studioid},ee&&{sender:ee}),je&&{studioSessionToken:je}),!je&&!ee&&{sender:V()}))},(!process.env.NODE_ENV||"development"===process.env.NODE_ENV)&&Object.assign({},process.env.NEXT_PUBLIC_PICKAXE_SESSION_TOKEN&&{headers:{"Content-Type":"application/json","x-pickaxe-session-token":process.env.NEXT_PUBLIC_PICKAXE_SESSION_TOKEN}})),Dt&&{credentials:"include"})),t=yield e.json();(null==t?void 0:t.studioUser)&&(et(t.studioUser),st(t.url))}catch(e){console.error("Failed to fetch studio user:",e)}}))),[Q,Y,Z,te,ee,je,se,ne,Dt]);c((()=>{Kt()}),[Kt]);const Wt=(null==fe?void 0:fe.limit)||0,Ft=(null==Ze?void 0:Ze.currentUses)||0,Ht=(null==Ze?void 0:Ze.extraUses)||0,Jt=!!(null==Le?void 0:Le.data.usage)&&Le.data.usage.isCredits,Mt=Wt>Ft?Wt-Ft+Ht:Ht,zt=d((()=>!!Ze&&(!nt&&(!(Wt<=0)&&Mt<=.05*Wt))),[Ze,nt,Mt,Wt]),Gt=d((()=>{var e,t,s;return!!ue&&(!!ie&&(!Je.isLoading&&(!((null!==(t=null===(e=Je.data)||void 0===e?void 0:e.messages.length)&&void 0!==t?t:0)>1)&&(!!(null===(s=ie.icebreakers)||void 0===s?void 0:s.length)&&(!me&&!Lt)))))}),[ie,ue,me,Lt,Je.data,Je.isLoading]),qt=d((()=>{if(Se||Ae)return!1;const e=Te.length>0&&Te.every((e=>"finished"===e.status));return!(!Me.trim()&&!e)&&Te.every((e=>"finished"===e.status||e.isInsertedAsRaw))}),[Se,Ae,Me,Te]);u(M,(()=>({onSubmit:Qt}))),c((()=>{he(Gt)}),[Gt]),c((()=>{var e;if(i){const t=Array.from(Ne),s=null===(e=t[t.length-2].parts.find((e=>"text"===e.type)))||void 0===e?void 0:e.content;Qt(s,!0)}}),[i]),c((()=>{if(!dt.current||!H)return;const e=new ResizeObserver((e=>{for(const t of e)H(t.contentRect.height)}));return e.observe(dt.current),()=>{e.disconnect()}}),[H]),c((()=>{if(!ft)return;const e=rt.current?`${rt.current} `:"";ze(`${e}${mt}`)}),[mt,ft]),c((()=>{if(!lt.current)return;(()=>{if(!lt.current)return;let e=lt.current.scrollHeight>52;Me.includes("\n")||Te.length?e=!0:Me.trim()||(e=!1),qe(e)})()}),[Me,Te]),c((()=>{const e=lt.current,t=ct.current;if(!e||!t||Ge||Me.includes("\n"))return void Ye(!1);const s=window.getComputedStyle(e),n=`${s.fontStyle} ${s.fontVariant} ${s.fontWeight} ${s.fontSize} / ${s.lineHeight} ${s.fontFamily}`,o=document.createElement("span");Object.assign(o.style,{font:n,letterSpacing:s.letterSpacing,position:"absolute",visibility:"hidden",whiteSpace:"nowrap",top:"0",left:"0"}),o.textContent=Me||Vt,document.body.appendChild(o);const i=o.offsetWidth;o.remove();const r=parseFloat(s.paddingLeft)||0,a=parseFloat(s.paddingRight)||0,l=e.clientWidth-r-a-t.offsetWidth;Ye(i>l)}),[Me,Ge,Vt]);const Qt=(e,s=!1)=>t(void 0,void 0,void 0,(function*(){var t,n,o;try{if(Se||Ae)return;const i=Te.filter((e=>"finished"===e.status&&!e.isInsertedAsRaw)),r=i.map((e=>e.documentId)).filter(Boolean),a=i.filter((e=>"image"===e.type)).map((e=>{const t=e.name.split(".").pop()||"";return{documentId:e.documentId,extension:t}})),l=r.length>0,c=null!=e?e:Me;if(!c&&!l)return;_e(""),Ue(""),Ee(null),ze(""),ge(!1),Ie("fetching"),$e(),Ve();const d=null!==(n=null===(t=null==ie?void 0:ie.documentuploadtype)||void 0===t?void 0:t.startsWith("enduserupload"))&&void 0!==n&&n&&r.length>0,u=[...s?Array.from(Ne.slice(0,Ne.length-1)):Array.from(Ne),...s?[]:[{id:Ne.length+1,role:"user",parts:[{type:"text",content:c,isVisible:!0}],documentIds:d?r:[]}],{id:Ne.length+(s?0:2),role:"assistant",parts:[],documentIds:[]}];Ce(u),Ve(),d&&Re([]);const p=yield fetch(`${process.env.NEXT_PUBLIC_PICKAXE_API_URL}/submit`,Object.assign({method:"POST",body:JSON.stringify(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({origin:Q,pickaxeId:Y,sessionId:Z,senderType:te,value:c},d&&{documentIds:r}),ee&&{sender:ee}),je&&{studioSessionToken:je}),!je&&!ee&&{sender:V()}),se&&{portalId:se}),ne&&{deploymentId:ne}),a.length>0&&{uploadedModelImages:a})),headers:Object.assign(Object.assign({},(!process.env.NODE_ENV||"development"===process.env.NODE_ENV)&&Object.assign({},process.env.NEXT_PUBLIC_PICKAXE_SESSION_TOKEN&&{"x-pickaxe-session-token":process.env.NEXT_PUBLIC_PICKAXE_SESSION_TOKEN})),{"x-request-sent-at":(new Date).toISOString()})},Dt&&{credentials:"include"})),m=yield p.json();if(!m.success){if(Bt(m))return;const e=new Error(m.error||m.message||(null==le?void 0:le["failed-to-start-generation"])||"Failed to start generation");throw m.limitData&&(e.limitData=m.limitData),e}const f=m.submissionId;Ie("streaming"),ut.current=new AbortController;const g=u.length-1,h=[];let v=[...null!=Xe?Xe:[]],b=0,y=!1,x="";for(;!y;)try{const e=yield fetch(`${process.env.NEXT_PUBLIC_PICKAXE_API_URL}/stream/${f}?index=${b}`,{signal:null===(o=ut.current)||void 0===o?void 0:o.signal,headers:{"Cache-Control":"no-cache",Connection:"keep-alive"}});if(!e.body)throw new Error("No response body");const t=e.body.getReader();at.current=t;const s=new TextDecoder,n=C({onEvent:e=>{var t,s;if(e.event&&"ping"!==e.event&&b++,"stop"!==e.event){if("error"===e.event){const t=JSON.parse(e.data),s=t.error||t.message||(null==le?void 0:le["something-went-wrong"])||"Something went wrong.";return Bt(t)||_e(s),void(y=!0)}if("delta"===e.event){const n=JSON.parse(e.data);if("data-error"===n.type&&J){const e=n.data.error;if("string"==typeof e){if(/['"]type['"]\s*:\s*['"]unauthorized_smithery['"]/.test(e)){const t=e.match(/['"]qualifiedName['"]\s*:\s*['"]([^'"]+)['"]/),s=e.match(/['"]serverId['"]\s*:\s*['"]([^'"]+)['"]/),n=e.match(/['"]name['"]\s*:\s*['"]([^'"]+)['"]/);if(t&&t[1]&&s&&s[1]&&n&&n[1])throw y=!0,J({smitheryId:t[1],serverId:s[1],name:n[1]}),new Error("STOP_STREAM")}}else if("object"==typeof e&&null!==e){const t=e;if("unauthorized_smithery"===t.type&&t.qualifiedName&&t.serverId&&t.name)throw y=!0,J({smitheryId:t.qualifiedName,serverId:t.serverId,name:t.name}),new Error("STOP_STREAM")}}else if("text-start"===n.type)x="",h.push({type:"text",content:"",isVisible:null===(t=n.isVisible)||void 0===t||t});else if("text-delta"===n.type)x+=n.delta,h[h.length-1].content=x;else if("text-end"===n.type)x="";else if("reasoning-start"===n.type)x="",h.push({type:"reasoning",content:"",isVisible:null===(s=n.isVisible)||void 0===s||s});else if("reasoning-delta"===n.type)x+=n.delta,h[h.length-1].content=x;else if("reasoning-end"===n.type)x="";else if(n.type.startsWith("data-")){const e=n;h.push({type:e.type,content:JSON.stringify(e.data),isVisible:!0})}Ce([...u.slice(0,g),Object.assign(Object.assign({},u[u.length-1]),{id:Ne.length+1,role:"assistant",parts:h})])}else if("artifact_created"===e.event){const t=JSON.parse(e.data);v=v.filter((e=>!(e.id===t.id&&e.version===t.version))),v.push(Object.assign(Object.assign({},t),{content:"",status:"streaming"})),We([...v]),Ke.startsWith("inline")||Fe({id:t.id,version:t.version})}else if("artifact_updated"===e.event){const t=JSON.parse(e.data);v=v.filter((e=>!(e.id===t.id&&e.version===t.version))),v.push(Object.assign(Object.assign({},t),{content:"",status:"updating"})),We(v),Ke.startsWith("inline")||Fe({id:t.id,version:t.version})}else if("artifact_rewrite"===e.event){const t=JSON.parse(e.data);v=v.filter((e=>!(e.id===t.id&&e.version===t.version))),v.push(Object.assign(Object.assign({},t),{content:"",status:"streaming"})),We(v),Ke.startsWith("inline")||Fe({id:t.id,version:t.version})}else if("artifact_content"===e.event){const t=JSON.parse(e.data),s=t.token.replace(/\u200B/g,"");v=v.map((e=>e.id===t.id&&e.version===t.version?Object.assign(Object.assign({},e),{content:e.content+s,status:"streaming"}):e)),We(v)}else if("artifact_finished"===e.event){const t=JSON.parse(e.data);We(v.map((e=>e.id===t.id?Object.assign(Object.assign({},e),{status:"finished"}):e)))}else if("error"===e.event){const t=JSON.parse(e.data),s=t.error||t.message||(null==le?void 0:le["something-went-wrong-try-again"])||"Something went wrong, please try again.";if(Bt(t))return void(y=!0);_e(s)}else"stop"===e.event&&(y=!0)}else y=!0}});for(;;){const{value:e,done:o}=yield t.read();if(o)break;n.feed(s.decode(e))}y||(yield new Promise((e=>setTimeout(e,1e3))))}catch(e){if("STOP_STREAM"===e.message||"AbortError"===e.name)return void(y=!0);console.warn("Stream connection lost, retrying...",e),yield new Promise((e=>setTimeout(e,1e3)))}null==xe||xe(Z)}catch(e){if(e.limitData)Ee(e.limitData),_e("");else{let t=R(e)||"";t&&!t.includes("Unexpected token 'A',")||(t=(null==le?void 0:le["high-traffic-try-again-later"])||"Oops! We're experiencing high traffic at the moment. Please try again later."),Bt(t)||_e(t)}}finally{Ve(),Ie("idle"),Be(),at.current=null,yield Kt()}}));return $t?null:s("div",Object.assign({className:L("flex w-full flex-shrink-0 flex-col items-center",!Lt&&"px-4 pb-8"),dir:pe?"rtl":"ltr"},{children:n("div",Object.assign({className:"flex w-full max-w-[800px] flex-col"},{children:[n("div",Object.assign({ref:dt,className:L("relative flex flex-col w-full justify-end gap-y-3 py-[3px]","block"===re.formFieldStyle&&"shadow"),style:Object.assign(Object.assign({},_t),{maxHeight:`${pt}px`,overflowY:"auto"})},{children:[zt&&n("div",Object.assign({className:"sticky top-0 z-10 flex w-full items-center justify-between border-b px-4 py-2.5 shadow-sm backdrop-blur-md",style:{backgroundColor:_t.backgroundColor?`${_t.backgroundColor}E6`:void 0,borderColor:ae.text+"20",color:ae.text,borderTopRightRadius:re.cornerRadius+"px",borderTopLeftRadius:re.cornerRadius+"px"}},{children:[s("div",Object.assign({className:"flex items-center gap-2 text-sm font-medium"},{children:n("span",{children:[Mt," ",Jt?(null==le?void 0:le.credits)||"Credits":(null==le?void 0:le.uses)||"Uses"," ",(null==le?void 0:le.remaining)||"remaining"]})})),n("div",Object.assign({className:"flex items-center gap-3"},{children:[s("button",Object.assign({className:"rounded-md px-3 py-1.5 text-xs font-semibold transition-opacity hover:opacity-90",style:{backgroundColor:ae.accent,color:ae.accentText},onClick:e=>{e.preventDefault(),e.stopPropagation();const t=$({baseUrl:tt,accessGroupId:null==fe?void 0:fe.accessGroupId});t&&(B()?window.open(t):location.href=t)}},{children:(null==le?void 0:le.upgrade)||"Upgrade"})),s("button",Object.assign({className:"flex h-6 w-6 items-center justify-center rounded-full opacity-60 transition-opacity hover:opacity-100",onClick:()=>ot(!0)},{children:s("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",strokeWidth:2,stroke:"currentColor",className:"h-4 w-4"},{children:s("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M6 18L18 6M6 6l12 12"})}))}))]}))]})),!Se&&Te.length>0&&s(A,{className:"p-4 pb-0",isDisabled:Se}),n("div",Object.assign({className:"relative flex w-full flex-col"},{children:[ft&&n("div",Object.assign({className:"absolute left-4 top-1/2 flex -translate-y-1/2 select-none items-center gap-x-2"},{children:[s("span",{className:"h-2 w-2 animate-pulse rounded-full bg-c-secondary",style:{backgroundColor:null!==(q=ae.accent)&&void 0!==q?q:"#ff0000"}}),s("span",Object.assign({className:"text-sm text-c-secondary font-semilight",style:{color:ae.text+"90"}},{children:(null==le?void 0:le.listening)||"Listening..."}))]})),s(P,Object.assign({ref:lt,className:L(Et.i1,"py-3.5 max-h-60 px-4 w-full border-transparent bg-transparent",!Me.trim()&&!Me.includes("\n")&&"overflow-hidden text-ellipsis whitespace-nowrap placeholder:whitespace-normal placeholder:overflow-visible",pe?"text-right":"text-left",Xt&&"mb-12",ft&&"text-transparent"),value:Me,placeholder:Vt,onChange:e=>{ze(e)},onKeyDown:e=>{de||yt||"Enter"===e.key&&(e.shiftKey||(e.preventDefault(),Ae||Se||Qt()))},onPaste:e=>t(void 0,void 0,void 0,(function*(){const t=Array.from(e.clipboardData.files||[]);t.length>0&&(e.preventDefault(),ge(!1),yield De(t))}))},W&&{onFocus:W},F&&{onBlur:F},{dir:pe?"rtl":"ltr"})),s("div",Object.assign({ref:ct,className:L("flex items-center gap-2 absolute right-0 z-2 transition-all duration-200 ease-in-out",Xt?"bottom-0 mb-2.5":"top-1/2 -translate-y-1/2"),style:Object.assign(Object.assign({},!Xt&&_t.backgroundColor&&{backgroundColor:_t.backgroundColor}),{borderTopRightRadius:re.cornerRadius+"px",borderBottomRightRadius:re.cornerRadius+"px"})},{children:Se?s("button",Object.assign({className:"flex h-8 w-8 items-center mr-2 justify-center rounded-full outline-none transition-colors duration-200 ease-in-out",onClick:()=>{ut.current&&(ut.current.abort(),ut.current=null),at.current&&(at.current.cancel(),at.current=null),Ie("idle")},style:{backgroundColor:ae.accent,color:ae.accentText}},{children:s(T,{className:"h-4 w-4 shrink-0"})})):ft?s("button",Object.assign({className:"flex h-8 w-8 items-center mr-2 justify-center rounded-full outline-none transition-colors duration-200 ease-in-out",onClick:bt,style:{backgroundColor:ae.accent,color:ae.accentText}},{children:s(T,{className:"h-4 w-4 shrink-0"})})):n(o,{children:[Rt&&n("button",Object.assign({className:"flex h-8 w-8 items-center justify-center rounded-full outline-none transition-colors duration-200 ease-in-out disabled:cursor-default",style:{backgroundColor:kt?ae.accent+"10":void 0,color:kt?ae.accent:ae.accent+"80"},disabled:Ae||Se,onClick:()=>{var e;return null===(e=it.current)||void 0===e?void 0:e.click()}},Nt,{children:[s("input",{id:"file-upload",ref:it,type:"file",accept:[...k,...N,...S].join(", "),multiple:!0,hidden:!0,className:"hidden",onChange:e=>t(void 0,void 0,void 0,(function*(){ge(!1),yield De(Array.from(e.target.files||[])),e.target.value=""}))}),s(I,{className:"h-6 w-6 shrink-0"})]})),Ut&&s("button",Object.assign({className:"disabled:cursor-default flex h-8 w-8 items-center justify-center rounded-full outline-none transition-colors duration-200 ease-in-out",style:{backgroundColor:ft?ae.accent:Ct?ae.accent+"10":void 0,color:ft?ae.accentText:Ct?ae.accent:ae.accent+"80"},disabled:Ae||Se||gt,onClick:()=>{ft?bt():(rt.current=Me,vt(ce||"en-US"))}},It,{children:s(_,{className:"h-5 w-5 shrink-0"})})),s("button",Object.assign({className:"flex h-8 w-8 items-center mr-2 justify-center rounded-full outline-none transition-colors duration-200 ease-in-out disabled:cursor-default",style:{backgroundColor:jt||qt?ae.accent:ae.accent+"10",color:jt||qt?ae.accentText:ae.accent+"80"},disabled:!qt,onClick:()=>Qt()},wt,{children:s(E,{className:L("h-6 w-6 shrink-0",pe&&"scale-x-[-1] transform")})}))]})}))]}))]})),Pe&&s(D,{error:Pe,className:"mt-3"})]}))}))}));W.displayName="Input";export{W as default};
|
|
1
|
+
import{__rest as e,__awaiter as t}from"../../../_virtual/_tslib.js";import{jsx as s,jsxs as n,Fragment as o}from"react/jsx-runtime";import{forwardRef as i,useState as r,useRef as a,useCallback as l,useEffect as c,useMemo as d,useImperativeHandle as u}from"react";import{usePickaxeContext as m}from"../../../hooks/pickaxe/usePickaxeContext.js";import{useResponseContext as p}from"../../../hooks/pickaxe/useResponseContext.js";import{useStyleInput as f}from"../../../hooks/studio/useStyleInput.js";import{useStyleFontSize as h}from"../../../hooks/studio/useStyleFontSize.js";import{useConversation as g}from"../../../hooks/pickaxe/useConversation.js";import{useDimensionContext as v}from"../../../hooks/pickaxe/useDimensionContext.js";import{useAuthContext as b}from"../Addons/Auth/hooks/useAuthContext.js";import{useDocument as y}from"../Addons/Document/hooks/useDocument.js";import{useScroll as x}from"../Addons/Scroll/hooks/useScroll.js";import{useArtifactContext as j}from"../Addons/Artifact/hooks/useArtifactContext.js";import{useHover as w}from"../../../hooks/core/useHover.js";import{useMediaQuery as O}from"../../../hooks/core/useMediaQuery.js";import{allowedFileMimeTypes as k,allowedImageMimeTypes as I,additionalAllowedFileExtensions as N}from"../../../common/documents.js";import{createParser as S}from"eventsource-parser";import C from"../../Icons/attach-vertical.svg.js";import _ from"../../Icons/arrow-right.svg.js";import E from"../../Icons/microphone.svg.js";import U from"../../Icons/stop.svg.js";import T from"../Addons/Document/List.js";import A from"../../Core/Textarea.js";import P from"../../Core/ErrorAlert.js";import D from"../../../common/error.js";import L from"../../../common/api/pickaxe.js";import{getValidationFailure as R}from"../../../common/validation.js";import M from"../../../common/cn.js";import{buildUpgradeUrl as $,isInIframe as B,initializeEmbedUserId as V}from"../../../common/utils.js";import{useStudio as X}from"../../../hooks/studio/useStudio.js";import{useSpeech as F}from"../../../hooks/pickaxe/useSpeech.js";import{STUDIO_INFINITY_VALUE as K}from"../common/PickaxeCommon.js";const W=e=>"string"==typeof e&&e.trim().length>0,H=(e,t)=>{if(e&&"object"==typeof e)return e[t]},J=e=>{const t=Number(e);return Number.isFinite(t)?t:void 0},z=({studioUser:e,deploymentId:t,portalId:s})=>{var n,o;const i=Array.isArray(H(e,"uses"))?H(e,"uses"):[],r=(({deploymentId:e,portalId:t})=>W(e)?{type:"deployment",id:e}:W(t)?{type:"portal",id:t}:null)({deploymentId:t,portalId:s});if(!r)return{scope:r,record:null};const a=null!==(o=null!==(n=i.find((e=>e.id===r.id&&e.type===r.type)))&&void 0!==n?n:i.find((e=>e.id===r.id)))&&void 0!==o?o:null;return{scope:r,record:a}},G=i((({resubmitPrompt:i,onFocus:W,onBlur:H,onInputHeightChange:G,initSmitheryAuthData:q},Q)=>{var Y,Z,ee,te,se,ne,oe,ie,re;const{origin:ae,pickaxeId:le,sessionId:ce,sender:de,senderType:ue,portalId:me,deploymentId:pe,deploymentType:fe,pickaxe:he,styles:ge,colors:ve,translations:be,locale:ye,forceMobile:xe,isNewChat:je,isRtl:we,isShowFeedbackMessage:Oe,accessGroup:ke,setIsNewChat:Ie,setIsShowIceBreaker:Ne,setValidationStatus:Se,setValidationUpgradeGroups:Ce,setValidationUpgradeUrl:_e,onGenerateComplete:Ee}=m(),{token:Ue,isLoggedOut:Te,isSent:Ae,isPricingAuth:Pe}=b(),{messages:De,isGenerating:Le,setMessages:Re,setStatus:Me,setLimitData:$e,setError:Be}=p(),{documents:Ve,isUploading:Xe,documentError:Fe,onFileUpload:Ke,setDocuments:We,setDocumentError:He}=y(),{studio:Je}=X(),{scrollStartSession:ze,scrollEndSession:Ge,scrollToBottom:qe}=x({auto:!0}),{artifacts:Qe,currentPopupType:Ye,setArtifacts:Ze,setCurrentArtifact:et}=j(),{height:tt}=v(),st=g(),[nt,ot]=r(""),[it,rt]=r(!1),[at,lt]=r(!1),[ct,dt]=r(null),[ut,mt]=r(null),[pt,ft]=r(!1),[ht,gt]=r(0),vt=a(null),bt=a(""),yt=a(null),xt=a(null),jt=a(null),wt=a(null),Ot=a(null),kt=Math.max(.4*tt,100),{speechTranscript:It,isSpeechListening:Nt,isSpeechProcessing:St,isSpeechSupported:Ct,onStartListening:_t,onStopListening:Et}=F(),[Ut]=O("(max-width: 480px)"),Tt=w(),{isHover:At}=Tt,Pt=e(Tt,["isHover"]),Dt=w(),{isHover:Lt}=Dt,Rt=e(Dt,["isHover"]),Mt=w(),{isHover:$t}=Mt,Bt=e(Mt,["isHover"]),Vt=h(),Xt=f(),Ft="undefined"!=typeof window?window.location.hostname:"",Kt="undefined"!=typeof window?window.location.href:"",Wt="undefined"!=typeof window&&window.self!==window.top,Ht=Ft.includes("pickaxe.co")&&!Kt.includes("https://studio.pickaxe.co/_embed")&&!Wt,Jt=null===(Y=null==he?void 0:he.documentuploadtype)||void 0===Y?void 0:Y.startsWith("enduserupload"),zt=Ct&&(null==he?void 0:he.enablevoicetotext),Gt="chat-input"===fe&&je&&!Ae,qt="chat-input"===fe&&Pe&&Te&&Ae,Qt=l((e=>{const t=R(e);return!!t&&(Be(""),$e(null),Se(t.status),Ce(t.upgradeGroups),_e(t.upgradeUrl),!0)}),[Be,$e,Se,Ce,_e]),Yt=null!==(Z=null==he?void 0:he.placeholdertext)&&void 0!==Z?Z:we?"بماذا تريد أن تتحدث؟":(null==be?void 0:be["what-do-you-want-to-talk-about"])||"What do you want to talk about?",Zt=it||at,es=l((()=>t(void 0,void 0,void 0,(function*(){try{const e=yield fetch(`${process.env.NEXT_PUBLIC_PICKAXE_API_URL}/get_user`,Object.assign(Object.assign({method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(Object.assign(Object.assign(Object.assign({studioId:null==he?void 0:he.studioid},de&&{sender:de}),Ue&&{studioSessionToken:Ue}),!Ue&&!de&&{sender:V()}))},(!process.env.NODE_ENV||"development"===process.env.NODE_ENV)&&Object.assign({},process.env.NEXT_PUBLIC_PICKAXE_SESSION_TOKEN&&{headers:{"Content-Type":"application/json","x-pickaxe-session-token":process.env.NEXT_PUBLIC_PICKAXE_SESSION_TOKEN}})),Ht&&{credentials:"include"})),t=yield e.json();(null==t?void 0:t.studioUser)&&(dt(t.studioUser),mt(t.url))}catch(e){console.error("Failed to fetch studio user:",e)}}))),[ae,le,ce,ue,de,Ue,me,pe,Ht]);c((()=>{es()}),[es]);const ts=Number(null!==(ee=null==ke?void 0:ke.limit)&&void 0!==ee?ee:0),ss="string"==typeof(null==ke?void 0:ke.limitInterval)?ke.limitInterval:null,ns=!!(null==Je?void 0:Je.data.usage)&&Je.data.usage.isCredits,os=d((()=>z({studioUser:ct,deploymentId:pe,portalId:me})),[pe,me,ct]),is={currentUses:J(null==ct?void 0:ct.currentUses),extraUses:J(null==ct?void 0:ct.extraUses)},rs=os.scope?{currentUses:null!==(se=J(null===(te=os.record)||void 0===te?void 0:te.currentUses))&&void 0!==se?se:0,extraUses:null!==(oe=J(null===(ne=os.record)||void 0===ne?void 0:ne.extraUses))&&void 0!==oe?oe:0}:{currentUses:0,extraUses:0},as=Te?rs:is;c((()=>{let e=!0;return t(void 0,void 0,void 0,(function*(){var t;if(ns&&(null===(t=null==Je?void 0:Je.data)||void 0===t?void 0:t.workspaceId))try{const t=yield L.get(`/cost_per_run?workspaceId=${Je.data.workspaceId}`,{withCredentials:!1});e&>(1e4*(Number(t.data.costPerRun)||0))}catch(t){console.error("Failed to fetch average cost per run:",t),e&>(0)}else e&>(0)})),()=>{e=!1}}),[ns,null===(ie=null==Je?void 0:Je.data)||void 0===ie?void 0:ie.workspaceId]);const ls=(({currentUses:e,extraUses:t,limit:s,limitInterval:n})=>{const o=Number(null!=e?e:0),i=Number(null!=t?t:0);return s===K||i===K?K:"one_time"===n?Math.max(0,i-o):Math.max(0,s-o)+i})({currentUses:as.currentUses,extraUses:as.extraUses,limit:ts,limitInterval:ss}),cs=ls===K?K:Math.max(0,Math.ceil(ls)),ds=(({extraUses:e,limit:t,limitInterval:s})=>{const n=Number(null!=e?e:0);return t===K||n===K?K:"one_time"===s?Math.max(0,n):Math.max(0,t)+Math.max(0,n)})({extraUses:as.extraUses,limit:ts,limitInterval:ss}),us=ds===K?K:Math.ceil(.05*ds),ms=ns?Math.ceil(5*ht):5,ps=us===K?K:Math.max(us,ms);console.log("Usage and Limits Debug:",{remaining:cs,notificationThreshold:ps,studioUser:ct});const fs=d((()=>!!ct&&(!pt&&(cs!==K&&(!(cs<=0)&&cs<=ps)))),[pt,ps,cs,ct]),hs=d((()=>{var e,t,s;return!!je&&(!!he&&(!st.isLoading&&(!((null!==(t=null===(e=st.data)||void 0===e?void 0:e.messages.length)&&void 0!==t?t:0)>1)&&(!!(null===(s=he.icebreakers)||void 0===s?void 0:s.length)&&(!Oe&&!Gt)))))}),[he,je,Oe,Gt,st.data,st.isLoading]),gs=d((()=>{if(Le||Xe)return!1;const e=Ve.length>0&&Ve.every((e=>"finished"===e.status));return!(!nt.trim()&&!e)&&Ve.every((e=>"finished"===e.status||e.isInsertedAsRaw))}),[Le,Xe,nt,Ve]);u(Q,(()=>({onSubmit:vs}))),c((()=>{Ne(hs)}),[hs]),c((()=>{var e;if(i){const t=Array.from(De),s=null===(e=t[t.length-2].parts.find((e=>"text"===e.type)))||void 0===e?void 0:e.content;vs(s,!0)}}),[i]),c((()=>{if(!wt.current||!G)return;const e=new ResizeObserver((e=>{for(const t of e)G(t.contentRect.height)}));return e.observe(wt.current),()=>{e.disconnect()}}),[G]),c((()=>{if(!Nt)return;const e=bt.current?`${bt.current} `:"";ot(`${e}${It}`)}),[It,Nt]),c((()=>{if(!xt.current)return;(()=>{if(!xt.current)return;let e=xt.current.scrollHeight>52;nt.includes("\n")||Ve.length?e=!0:nt.trim()||(e=!1),rt(e)})()}),[nt,Ve]),c((()=>{const e=xt.current,t=jt.current;if(!e||!t||it||nt.includes("\n"))return void lt(!1);const s=window.getComputedStyle(e),n=`${s.fontStyle} ${s.fontVariant} ${s.fontWeight} ${s.fontSize} / ${s.lineHeight} ${s.fontFamily}`,o=document.createElement("span");Object.assign(o.style,{font:n,letterSpacing:s.letterSpacing,position:"absolute",visibility:"hidden",whiteSpace:"nowrap",top:"0",left:"0"}),o.textContent=nt||Yt,document.body.appendChild(o);const i=o.offsetWidth;o.remove();const r=parseFloat(s.paddingLeft)||0,a=parseFloat(s.paddingRight)||0,l=e.clientWidth-r-a-t.offsetWidth;lt(i>l)}),[nt,it,Yt]);const vs=(e,s=!1)=>t(void 0,void 0,void 0,(function*(){var t,n,o;try{if(Le||Xe)return;const i=Ve.filter((e=>"finished"===e.status&&!e.isInsertedAsRaw)),r=i.map((e=>e.documentId)).filter(Boolean),a=i.filter((e=>"image"===e.type)).map((e=>{const t=e.name.split(".").pop()||"";return{documentId:e.documentId,extension:t}})),l=r.length>0,c=null!=e?e:nt;if(!c&&!l)return;Be(""),He(""),$e(null),ot(""),Ie(!1),Me("fetching"),ze(),qe();const d=null!==(n=null===(t=null==he?void 0:he.documentuploadtype)||void 0===t?void 0:t.startsWith("enduserupload"))&&void 0!==n&&n&&r.length>0,u=[...s?Array.from(De.slice(0,De.length-1)):Array.from(De),...s?[]:[{id:De.length+1,role:"user",parts:[{type:"text",content:c,isVisible:!0}],documentIds:d?r:[]}],{id:De.length+(s?0:2),role:"assistant",parts:[],documentIds:[]}];Re(u),qe(),d&&We([]);const m=yield fetch(`${process.env.NEXT_PUBLIC_PICKAXE_API_URL}/submit`,Object.assign({method:"POST",body:JSON.stringify(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({origin:ae,pickaxeId:le,sessionId:ce,senderType:ue,value:c},d&&{documentIds:r}),de&&{sender:de}),Ue&&{studioSessionToken:Ue}),!Ue&&!de&&{sender:V()}),me&&{portalId:me}),pe&&{deploymentId:pe}),a.length>0&&{uploadedModelImages:a})),headers:Object.assign(Object.assign({},(!process.env.NODE_ENV||"development"===process.env.NODE_ENV)&&Object.assign({},process.env.NEXT_PUBLIC_PICKAXE_SESSION_TOKEN&&{"x-pickaxe-session-token":process.env.NEXT_PUBLIC_PICKAXE_SESSION_TOKEN})),{"x-request-sent-at":(new Date).toISOString()})},Ht&&{credentials:"include"})),p=yield m.json();if(!p.success){if(Qt(p))return;const e=new Error(p.error||p.message||(null==be?void 0:be["failed-to-start-generation"])||"Failed to start generation");throw p.limitData&&(e.limitData=p.limitData),e}const f=p.submissionId;Me("streaming"),Ot.current=new AbortController;const h=u.length-1,g=[];let v=[...null!=Qe?Qe:[]],b=0,y=!1,x="";for(;!y;)try{const e=yield fetch(`${process.env.NEXT_PUBLIC_PICKAXE_API_URL}/stream/${f}?index=${b}`,{signal:null===(o=Ot.current)||void 0===o?void 0:o.signal,headers:{"Cache-Control":"no-cache",Connection:"keep-alive"}});if(!e.body)throw new Error("No response body");const t=e.body.getReader();yt.current=t;const s=new TextDecoder,n=S({onEvent:e=>{var t,s;if(e.event&&"ping"!==e.event&&b++,"stop"!==e.event){if("error"===e.event){const t=JSON.parse(e.data),s=t.error||t.message||(null==be?void 0:be["something-went-wrong"])||"Something went wrong.";return Qt(t)||Be(s),void(y=!0)}if("delta"===e.event){const n=JSON.parse(e.data);if("data-error"===n.type&&q){const e=n.data.error;if("string"==typeof e){if(/['"]type['"]\s*:\s*['"]unauthorized_smithery['"]/.test(e)){const t=e.match(/['"]qualifiedName['"]\s*:\s*['"]([^'"]+)['"]/),s=e.match(/['"]serverId['"]\s*:\s*['"]([^'"]+)['"]/),n=e.match(/['"]name['"]\s*:\s*['"]([^'"]+)['"]/);if(t&&t[1]&&s&&s[1]&&n&&n[1])throw y=!0,q({smitheryId:t[1],serverId:s[1],name:n[1]}),new Error("STOP_STREAM")}}else if("object"==typeof e&&null!==e){const t=e;if("unauthorized_smithery"===t.type&&t.qualifiedName&&t.serverId&&t.name)throw y=!0,q({smitheryId:t.qualifiedName,serverId:t.serverId,name:t.name}),new Error("STOP_STREAM")}}else if("text-start"===n.type)x="",g.push({type:"text",content:"",isVisible:null===(t=n.isVisible)||void 0===t||t});else if("text-delta"===n.type)x+=n.delta,g[g.length-1].content=x;else if("text-end"===n.type)x="";else if("reasoning-start"===n.type)x="",g.push({type:"reasoning",content:"",isVisible:null===(s=n.isVisible)||void 0===s||s});else if("reasoning-delta"===n.type)x+=n.delta,g[g.length-1].content=x;else if("reasoning-end"===n.type)x="";else if(n.type.startsWith("data-")){const e=n;g.push({type:e.type,content:JSON.stringify(e.data),isVisible:!0})}Re([...u.slice(0,h),Object.assign(Object.assign({},u[u.length-1]),{id:De.length+1,role:"assistant",parts:g})])}else if("artifact_created"===e.event){const t=JSON.parse(e.data);v=v.filter((e=>!(e.id===t.id&&e.version===t.version))),v.push(Object.assign(Object.assign({},t),{content:"",status:"streaming"})),Ze([...v]),Ye.startsWith("inline")||et({id:t.id,version:t.version})}else if("artifact_updated"===e.event){const t=JSON.parse(e.data);v=v.filter((e=>!(e.id===t.id&&e.version===t.version))),v.push(Object.assign(Object.assign({},t),{content:"",status:"updating"})),Ze(v),Ye.startsWith("inline")||et({id:t.id,version:t.version})}else if("artifact_rewrite"===e.event){const t=JSON.parse(e.data);v=v.filter((e=>!(e.id===t.id&&e.version===t.version))),v.push(Object.assign(Object.assign({},t),{content:"",status:"streaming"})),Ze(v),Ye.startsWith("inline")||et({id:t.id,version:t.version})}else if("artifact_content"===e.event){const t=JSON.parse(e.data),s=t.token.replace(/\u200B/g,"");v=v.map((e=>e.id===t.id&&e.version===t.version?Object.assign(Object.assign({},e),{content:e.content+s,status:"streaming"}):e)),Ze(v)}else if("artifact_finished"===e.event){const t=JSON.parse(e.data);Ze(v.map((e=>e.id===t.id?Object.assign(Object.assign({},e),{status:"finished"}):e)))}else if("error"===e.event){const t=JSON.parse(e.data),s=t.error||t.message||(null==be?void 0:be["something-went-wrong-try-again"])||"Something went wrong, please try again.";if(Qt(t))return void(y=!0);Be(s)}else"stop"===e.event&&(y=!0)}else y=!0}});for(;;){const{value:e,done:o}=yield t.read();if(o)break;n.feed(s.decode(e))}y||(yield new Promise((e=>setTimeout(e,1e3))))}catch(e){if("STOP_STREAM"===e.message||"AbortError"===e.name)return void(y=!0);console.warn("Stream connection lost, retrying...",e),yield new Promise((e=>setTimeout(e,1e3)))}null==Ee||Ee(ce)}catch(e){if(e.limitData)$e(e.limitData),Be("");else{let t=D(e)||"";t&&!t.includes("Unexpected token 'A',")||(t=(null==be?void 0:be["high-traffic-try-again-later"])||"Oops! We're experiencing high traffic at the moment. Please try again later."),Qt(t)||Be(t)}}finally{qe(),Me("idle"),Ge(),yt.current=null,yield es()}}));return qt?null:s("div",Object.assign({className:M("flex w-full flex-shrink-0 flex-col items-center",!Gt&&"px-4 pb-8"),dir:we?"rtl":"ltr"},{children:n("div",Object.assign({className:"flex w-full max-w-[800px] flex-col"},{children:[n("div",Object.assign({ref:wt,className:M("relative flex flex-col w-full justify-end gap-y-3 py-[3px]","block"===ge.formFieldStyle&&"shadow"),style:Object.assign(Object.assign({},Xt),{maxHeight:`${kt}px`,overflowY:"auto"})},{children:[fs&&n("div",Object.assign({className:"sticky top-0 z-10 flex w-full items-center justify-between border-b px-4 py-2.5 shadow-sm backdrop-blur-md",style:{backgroundColor:Xt.backgroundColor?`${Xt.backgroundColor}E6`:void 0,borderColor:ve.text+"20",color:ve.text,borderTopRightRadius:ge.cornerRadius+"px",borderTopLeftRadius:ge.cornerRadius+"px"}},{children:[s("div",Object.assign({className:"flex items-center gap-2 text-sm font-medium"},{children:n("span",{children:[cs.toLocaleString()," ",ns?(null==be?void 0:be.credits)||"Credits":(null==be?void 0:be.uses)||"Uses"," ",(null==be?void 0:be.remaining)||"remaining"]})})),n("div",Object.assign({className:"flex items-center gap-3"},{children:[s("button",Object.assign({className:"rounded-md px-3 py-1.5 text-xs font-semibold transition-opacity hover:opacity-90",style:{backgroundColor:ve.accent,color:ve.accentText},onClick:e=>{e.preventDefault(),e.stopPropagation();const t=$({baseUrl:ut,accessGroupId:null==ke?void 0:ke.accessGroupId});t&&(B()?window.open(t):location.href=t)}},{children:(null==be?void 0:be.upgrade)||"Upgrade"})),s("button",Object.assign({className:"flex h-6 w-6 items-center justify-center rounded-full opacity-60 transition-opacity hover:opacity-100",onClick:()=>ft(!0)},{children:s("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",strokeWidth:2,stroke:"currentColor",className:"h-4 w-4"},{children:s("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M6 18L18 6M6 6l12 12"})}))}))]}))]})),!Le&&Ve.length>0&&s(T,{className:"p-4 pb-0",isDisabled:Le}),n("div",Object.assign({className:"relative flex w-full flex-col"},{children:[Nt&&n("div",Object.assign({className:"absolute left-4 top-1/2 flex -translate-y-1/2 select-none items-center gap-x-2"},{children:[s("span",{className:"h-2 w-2 animate-pulse rounded-full bg-c-secondary",style:{backgroundColor:null!==(re=ve.accent)&&void 0!==re?re:"#ff0000"}}),s("span",Object.assign({className:"text-sm text-c-secondary font-semilight",style:{color:ve.text+"90"}},{children:(null==be?void 0:be.listening)||"Listening..."}))]})),s(A,Object.assign({ref:xt,className:M(Vt.i1,"py-3.5 max-h-60 px-4 w-full border-transparent bg-transparent",!nt.trim()&&!nt.includes("\n")&&"overflow-hidden text-ellipsis whitespace-nowrap placeholder:whitespace-normal placeholder:overflow-visible",we?"text-right":"text-left",Zt&&"mb-12",Nt&&"text-transparent"),value:nt,placeholder:Yt,onChange:e=>{ot(e)},onKeyDown:e=>{xe||Ut||"Enter"===e.key&&(e.shiftKey||(e.preventDefault(),Xe||Le||vs()))},onPaste:e=>t(void 0,void 0,void 0,(function*(){const t=Array.from(e.clipboardData.files||[]);t.length>0&&(e.preventDefault(),Ie(!1),yield Ke(t))}))},W&&{onFocus:W},H&&{onBlur:H},{dir:we?"rtl":"ltr"})),s("div",Object.assign({ref:jt,className:M("flex items-center gap-2 absolute right-0 z-2 transition-all duration-200 ease-in-out",Zt?"bottom-0 mb-2.5":"top-1/2 -translate-y-1/2"),style:Object.assign(Object.assign({},!Zt&&Xt.backgroundColor&&{backgroundColor:Xt.backgroundColor}),{borderTopRightRadius:ge.cornerRadius+"px",borderBottomRightRadius:ge.cornerRadius+"px"})},{children:Le?s("button",Object.assign({className:"flex h-8 w-8 items-center mr-2 justify-center rounded-full outline-none transition-colors duration-200 ease-in-out",onClick:()=>{Ot.current&&(Ot.current.abort(),Ot.current=null),yt.current&&(yt.current.cancel(),yt.current=null),Me("idle")},style:{backgroundColor:ve.accent,color:ve.accentText}},{children:s(U,{className:"h-4 w-4 shrink-0"})})):Nt?s("button",Object.assign({className:"flex h-8 w-8 items-center mr-2 justify-center rounded-full outline-none transition-colors duration-200 ease-in-out",onClick:Et,style:{backgroundColor:ve.accent,color:ve.accentText}},{children:s(U,{className:"h-4 w-4 shrink-0"})})):n(o,{children:[Jt&&n("button",Object.assign({className:"flex h-8 w-8 items-center justify-center rounded-full outline-none transition-colors duration-200 ease-in-out disabled:cursor-default",style:{backgroundColor:Lt?ve.accent+"10":void 0,color:Lt?ve.accent:ve.accent+"80"},disabled:Xe||Le,onClick:()=>{var e;return null===(e=vt.current)||void 0===e?void 0:e.click()}},Rt,{children:[s("input",{id:"file-upload",ref:vt,type:"file",accept:[...k,...I,...N].join(", "),multiple:!0,hidden:!0,className:"hidden",onChange:e=>t(void 0,void 0,void 0,(function*(){Ie(!1),yield Ke(Array.from(e.target.files||[])),e.target.value=""}))}),s(C,{className:"h-6 w-6 shrink-0"})]})),zt&&s("button",Object.assign({className:"disabled:cursor-default flex h-8 w-8 items-center justify-center rounded-full outline-none transition-colors duration-200 ease-in-out",style:{backgroundColor:Nt?ve.accent:$t?ve.accent+"10":void 0,color:Nt?ve.accentText:$t?ve.accent:ve.accent+"80"},disabled:Xe||Le||St,onClick:()=>{Nt?Et():(bt.current=nt,_t(ye||"en-US"))}},Bt,{children:s(E,{className:"h-5 w-5 shrink-0"})})),s("button",Object.assign({className:"flex h-8 w-8 items-center mr-2 justify-center rounded-full outline-none transition-colors duration-200 ease-in-out disabled:cursor-default",style:{backgroundColor:At||gs?ve.accent:ve.accent+"10",color:At||gs?ve.accentText:ve.accent+"80"},disabled:!gs,onClick:()=>vs()},Pt,{children:s(_,{className:M("h-6 w-6 shrink-0",we&&"scale-x-[-1] transform")})}))]})}))]}))]})),Fe&&s(P,{error:Fe,className:"mt-3"})]}))}))}));G.displayName="Input";export{G as default};
|