@pickaxeproject/react 6.24.4 → 6.24.6
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/cjs/common/speechTranscript.js +1 -0
- package/dist/cjs/components/Pickaxe/Addons/Artifact/Renderer/index.js +1 -1
- package/dist/cjs/components/Pickaxe/Addons/Artifact/index.js +1 -1
- package/dist/cjs/components/Pickaxe/Addons/Scroll/Provider.js +1 -1
- package/dist/cjs/components/Pickaxe/Addons/Scroll/hooks/useScroll.js +1 -1
- package/dist/cjs/components/Pickaxe/Chat/Input.js +1 -1
- package/dist/cjs/components/Pickaxe/Chat/index.js +1 -1
- package/dist/cjs/hooks/pickaxe/useSpeechToText.js +1 -1
- package/dist/cjs/node_modules/.pnpm/cose-base@1.0.3/node_modules/cose-base/cose-base.js +1 -1
- package/dist/cjs/node_modules/.pnpm/cose-base@2.2.0/node_modules/cose-base/cose-base.js +1 -1
- package/dist/cjs/node_modules/.pnpm/layout-base@1.0.2/node_modules/layout-base/layout-base.js +1 -1
- package/dist/cjs/node_modules/.pnpm/layout-base@2.0.1/node_modules/layout-base/layout-base.js +1 -1
- package/dist/cjs/src/common/speechTranscript.d.ts +20 -0
- package/dist/cjs/src/components/Pickaxe/Addons/Artifact/Renderer/index.d.ts +1 -1
- package/dist/cjs/src/components/Pickaxe/Addons/Scroll/Provider.d.ts +3 -0
- package/dist/cjs/src/components/Pickaxe/Addons/Scroll/hooks/useScroll.d.ts +2 -1
- package/dist/cjs/src/components/Pickaxe/Addons/Scroll/hooks/useScrollContext.d.ts +4 -0
- package/dist/cjs/src/hooks/pickaxe/useSpeechToText.d.ts +5 -0
- package/dist/esm/common/speechTranscript.js +1 -0
- package/dist/esm/components/Pickaxe/Addons/Artifact/Renderer/index.js +1 -1
- package/dist/esm/components/Pickaxe/Addons/Artifact/index.js +1 -1
- package/dist/esm/components/Pickaxe/Addons/Scroll/Provider.js +1 -1
- package/dist/esm/components/Pickaxe/Addons/Scroll/hooks/useScroll.js +1 -1
- package/dist/esm/components/Pickaxe/Chat/Input.js +1 -1
- package/dist/esm/components/Pickaxe/Chat/index.js +1 -1
- package/dist/esm/hooks/pickaxe/useSpeechToText.js +1 -1
- package/dist/esm/node_modules/.pnpm/cose-base@1.0.3/node_modules/cose-base/cose-base.js +1 -1
- package/dist/esm/node_modules/.pnpm/cose-base@2.2.0/node_modules/cose-base/cose-base.js +1 -1
- package/dist/esm/node_modules/.pnpm/layout-base@1.0.2/node_modules/layout-base/layout-base.js +1 -1
- package/dist/esm/node_modules/.pnpm/layout-base@2.0.1/node_modules/layout-base/layout-base.js +1 -1
- package/dist/esm/src/common/speechTranscript.d.ts +20 -0
- package/dist/esm/src/components/Pickaxe/Addons/Artifact/Renderer/index.d.ts +1 -1
- package/dist/esm/src/components/Pickaxe/Addons/Scroll/Provider.d.ts +3 -0
- package/dist/esm/src/components/Pickaxe/Addons/Scroll/hooks/useScroll.d.ts +2 -1
- package/dist/esm/src/components/Pickaxe/Addons/Scroll/hooks/useScrollContext.d.ts +4 -0
- package/dist/esm/src/hooks/pickaxe/useSpeechToText.d.ts +5 -0
- package/package.json +2 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
import{__rest as e,__awaiter as t}from"../../../_virtual/_tslib.js";import{jsx as n,jsxs as o,Fragment as s}from"react/jsx-runtime";import{canChat as i}from"../../../common/canChat.js";import{useEndUserModel as r}from"../../../hooks/pickaxe/useEndUserModel.js";import a from"../common/EndUserModelPicker.js";import{updateStreamTextPart as l,upsertActionApprovalPart as d}from"../../../common/actionApproval.js";import{forwardRef as c,useState as u,useRef as p,useCallback as m,useEffect as g,useMemo as f,useImperativeHandle as v}from"react";import{usePickaxeContext as h}from"../../../hooks/pickaxe/usePickaxeContext.js";import{useResponseContext as b}from"../../../hooks/pickaxe/useResponseContext.js";import{useStyleInput as y}from"../../../hooks/studio/useStyleInput.js";import{useStyleFontSize as x}from"../../../hooks/studio/useStyleFontSize.js";import{useConversation as j}from"../../../hooks/pickaxe/useConversation.js";import{useDimensionContext as I}from"../../../hooks/pickaxe/useDimensionContext.js";import{useAuthContext as w}from"../Addons/Auth/hooks/useAuthContext.js";import{useDocument as k}from"../Addons/Document/hooks/useDocument.js";import{useScroll as O}from"../Addons/Scroll/hooks/useScroll.js";import{useArtifactContext as N}from"../Addons/Artifact/hooks/useArtifactContext.js";import{useHover as S}from"../../../hooks/core/useHover.js";import{useMediaQuery as C}from"../../../hooks/core/useMediaQuery.js";import{allowedFileMimeTypes as E,allowedImageMimeTypes as _,additionalAllowedFileExtensions as T}from"../../../common/documents.js";import{createParser as U}from"eventsource-parser";import A from"../../Icons/attach-vertical.svg.js";import P from"../../Icons/arrow-right.svg.js";import D from"../../Icons/microphone.svg.js";import L from"../../Icons/message-clock.svg.js";import M from"../../Icons/stop.svg.js";import R from"../../Icons/trash.svg.js";import $ from"../../Icons/pencil.svg.js";import B from"../Addons/Document/List.js";import X from"../../Core/Textarea.js";import K from"../../Core/ErrorAlert.js";import F from"../../Core/Menu/index.js";import G from"../../Core/Menu/Button.js";import V from"../../Core/Menu/List.js";import H from"../../../common/error.js";import{pickaxeApi2 as W}from"../../../common/api/pickaxe.js";import{getValidationFailure as q}from"../../../common/validation.js";import J from"../../../common/cn.js";import{buildUpgradeUrl as z,openAuthenticatedPricingUrl as Q,initializeEmbedUserId as Y}from"../../../common/utils.js";import{getPickaxeConfigMetadata as Z}from"../../../common/pickaxeConfig.js";import{readAgentPrefill as ee}from"../../../common/agentPrefill.js";import{fireDeploymentSessionInitializedWebhook as te,fireDeploymentFirstMessageSubmittedWebhook as ne}from"../../../common/deploymentWebhooks.js";import{useStudio as oe}from"../../../hooks/studio/useStudio.js";import{useSpeechToText as se}from"../../../hooks/pickaxe/useSpeechToText.js";import{STUDIO_INFINITY_VALUE as ie}from"../common/PickaxeCommon.js";const re=(e,t)=>{const n=e.find((e=>e.id===t));return n?e.filter((e=>e.id!==t)).map((e=>e.predecessorSubmissionId===t?Object.assign(Object.assign({},e),{predecessorSubmissionId:n.predecessorSubmissionId}):e)):e},ae=e=>"string"==typeof e&&e.trim().length>0,le=()=>"undefined"!=typeof crypto&&"randomUUID"in crypto?crypto.randomUUID():`submission-${Date.now()}-${Math.random().toString(36).slice(2)}`,de=e=>e.map((e=>Object.assign({},e))),ce=e=>e instanceof Error&&("AbortError"===e.name||"BodyStreamBuffer was aborted"===e.message),ue=(e,t)=>{if(e&&"object"==typeof e)return e[t]},pe=(e,t)=>{const n=ue(e,t);return ae(n)?n:null},me=e=>{const t=Number(e);return Number.isFinite(t)?t:void 0},ge=({studioUser:e,deploymentId:t,portalId:n})=>{var o,s;const i=Array.isArray(ue(e,"uses"))?ue(e,"uses"):[],r=(({deploymentId:e,portalId:t})=>ae(e)?{type:"deployment",id:e}:ae(t)?{type:"portal",id:t}:null)({deploymentId:t,portalId:n});if(!r)return{scope:r,record:null};const a=null!==(s=null!==(o=i.find((e=>e.id===r.id&&e.type===r.type)))&&void 0!==o?o:i.find((e=>e.id===r.id)))&&void 0!==s?s:null;return{scope:r,record:a}},fe=c((({resubmitPrompt:c,onFocus:ue,onBlur:fe,onInputHeightChange:ve,initSmitheryAuthData:he},be)=>{var ye,xe,je,Ie,we,ke,Oe,Ne,Se,Ce,Ee,_e,Te,Ue,Ae,Pe,De,Le;const{origin:Me,pickaxeId:Re,sessionId:$e,sender:Be,senderType:Xe,portalId:Ke,deploymentId:Fe,deploymentType:Ge,pickaxe:Ve,styles:He,colors:We,translations:qe,locale:Je,forceMobile:ze,isNewChat:Qe,isRtl:Ye,isEmbed:Ze,isShowFeedbackMessage:et,accessGroup:tt,setIsNewChat:nt,setIsShowIceBreaker:ot,setValidationStatus:st,setValidationUpgradeGroups:it,setValidationUpgradeUrl:rt,setAccessGroup:at,onUpgrade:lt,onGenerateComplete:dt}=h(),{value:ct,enabled:ut}=r(),{token:pt,isLoggedOut:mt,isSent:gt,isPricingAuth:ft}=w(),{messages:vt,isGenerating:ht,setMessages:bt,setStatus:yt,setLimitData:xt,setError:jt,setActionApprovalToken:It}=b(),{documents:wt,isUploading:kt,documentError:Ot,onFileUpload:Nt,setDocuments:St,setDocumentError:Ct}=k(),{studio:Et}=oe(),[_t]=C("(max-width: 480px)"),{scrollStartSession:Tt,scrollEndSession:Ut,scrollToBottom:At}=O({auto:!0,smooth:!(ze||_t)}),{artifacts:Pt,currentPopupType:Dt,setArtifacts:Lt,setCurrentArtifact:Mt}=N(),{height:Rt}=I(),$t=j(),[Bt,Xt]=u((()=>ee([Fe,Re]).chatInput)),[Kt,Ft]=u(!1),[Gt,Vt]=u(!1),[Ht,Wt]=u(!1),[qt,Jt]=u(!1),[zt,Qt]=u([]),[Yt,Zt]=u(!1),[en,tn]=u(null),[nn,on]=u(null),[sn,rn]=u(null),[an,ln]=u(null),[dn,cn]=u(!1),[un,pn]=u(!1),[mn,gn]=u(0),fn=p(null),vn=p(""),hn=p(null),bn=p(null),yn=p(null),xn=p([]),jn=p(null),In=p(null),wn=p(null),kn=p(null),On=p(new Set),Nn=p(null),Sn=Math.max(.4*Rt,100),{speechTranscript:Cn,isSpeechListening:En,isSpeechProcessing:_n,isSpeechSupported:Tn,onStartListening:Un,onStopListening:An}=se(),Pn=S(),{isHover:Dn}=Pn,Ln=e(Pn,["isHover"]),Mn=S(),{isHover:Rn}=Mn,$n=e(Mn,["isHover"]),Bn=S(),{isHover:Xn}=Bn,Kn=e(Bn,["isHover"]),Fn=x(),Gn=y(),Vn="undefined"!=typeof window?window.location.hostname:"",Hn="undefined"!=typeof window?window.location.href:"",Wn="undefined"!=typeof window&&window.self!==window.top,qn=Vn.includes("pickaxe.co")&&!Hn.includes("https://studio.pickaxe.co/_embed")&&!Wn,Jn=null!==(xe=null===(ye=null==Ve?void 0:Ve.documentuploadtype)||void 0===ye?void 0:ye.startsWith("enduserupload"))&&void 0!==xe&&xe,zn=Tn&&(null==Ve?void 0:Ve.enablevoicetotext),Qn=En&&!Bt.trim(),Yn=ae(Fe),Zn="chat-input"===Ge&&Qe&&!gt,eo="chat-input"===Ge&&ft&&mt&>,to=m((e=>{const t=q(e);return!!t&&(jt(""),xt(null),st(t.status),at(t.accessGroup),it(t.upgradeGroups),rt(t.upgradeUrl),!0)}),[jt,It,xt,st,it,rt,at]),no=null!==(je=null==Ve?void 0:Ve.placeholdertext)&&void 0!==je?je:Ye?"بماذا تريد أن تتحدث؟":(null==qe?void 0:qe["what-do-you-want-to-talk-about"])||"What do you want to talk about?",oo=Kt||Gt,so=m((()=>t(void 0,void 0,void 0,(function*(){cn(!1);try{const e=yield fetch(`${process.env.NEXT_PUBLIC_PICKAXE_API2_URL}/user`,Object.assign(Object.assign({method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(Object.assign({studioId:null==Ve?void 0:Ve.studioid},pt?{studioSessionToken:pt}:Be?{sender:Be}:{sender:Y()}))},(!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}})),qn&&{credentials:"include"})),t=yield e.json();(null==t?void 0:t.studioUser)&&(rn(t.studioUser),ln(t.url))}catch(e){console.error("Failed to fetch studio user:",e)}finally{cn(!0)}}))),[qn,null==Ve?void 0:Ve.studioid,Be,pt]);g((()=>{so()}),[so]);const io=Number(null!==(Ie=null==tt?void 0:tt.limit)&&void 0!==Ie?Ie:0),ro="string"==typeof(null==tt?void 0:tt.limitInterval)?tt.limitInterval:null,ao=!!(null==Et?void 0:Et.data.usage)&&Et.data.usage.isCredits,lo=f((()=>{var e,t,n,o,s;return null!==(s=null!==(o=null!==(n=null!==(t=null!==(e=null!=Ke?Ke:pe(sn,"portalId"))&&void 0!==e?e:pe(sn,"portalid"))&&void 0!==t?t:pe(tt,"portalId"))&&void 0!==n?n:pe(tt,"portalid"))&&void 0!==o?o:pe(Ve,"portalId"))&&void 0!==s?s:pe(Ve,"portalid")}),[tt,Ke,Ve,sn]),co=f((()=>ge({studioUser:sn,deploymentId:Fe,portalId:lo})),[Fe,lo,sn]);g((()=>{Yn&&Qe&&$e&&On.current.add($e)}),[Qe,$e,Yn]);const uo=m((()=>{var e,t,n;return{studioId:null==Ve?void 0:Ve.studioid,userEmail:pe(sn,"email"),userId:null!==(e=pe(sn,"userId"))&&void 0!==e?e:pe(sn,"userid"),sessionId:$e,deploymentId:Fe,deploymentType:Ge,portalId:lo,accessGroupId:null!==(t=null==tt?void 0:tt.accessGroupId)&&void 0!==t?t:null,pickaxeId:Re,sender:Be,senderType:Xe,origin:Me,metadata:null!==(n=Z(Fe))&&void 0!==n?n:null}}),[null==tt?void 0:tt.accessGroupId,Fe,Ge,Me,null==Ve?void 0:Ve.studioid,Re,lo,Be,Xe,$e,sn]),po=m((()=>!!(Yn&&dn&&$e)&&(!!On.current.has($e)&&(te(uo()),On.current.delete($e),!0))),[uo,dn,$e,Yn]);g((()=>{if(!dn||!$e)return;po();const e=Nn.current;(null==e?void 0:e.sessionId)===$e&&(ne(Object.assign(Object.assign(Object.assign({},e),uo()),{message:e.message,documentIds:e.documentIds,uploadedModelImages:e.uploadedModelImages,hasUploadedDocuments:e.hasUploadedDocuments,isHidden:e.isHidden})),Nn.current=null)}),[po,uo,dn,$e]);const mo={currentUses:me(null==sn?void 0:sn.currentUses),extraUses:me(null==sn?void 0:sn.extraUses)},go=co.scope?{currentUses:null!==(ke=me(null===(we=co.record)||void 0===we?void 0:we.currentUses))&&void 0!==ke?ke:0,extraUses:null!==(Ne=me(null===(Oe=co.record)||void 0===Oe?void 0:Oe.extraUses))&&void 0!==Ne?Ne:0}:{currentUses:0,extraUses:0},fo=pe(sn,"type"),vo="guest"===fo||!fo&&mt?go:mo;g((()=>{let e=!0;return t(void 0,void 0,void 0,(function*(){var t;if(ao&&(null===(t=null==Et?void 0:Et.data)||void 0===t?void 0:t.workspaceId))try{const t=yield W.get(`/cost_per_run?workspaceId=${Et.data.workspaceId}`,{withCredentials:!1});e&&gn(1e4*(Number(t.data.costPerRun)||0))}catch(t){console.error("Failed to fetch average cost per run:",t),e&&gn(0)}else e&&gn(0)})),()=>{e=!1}}),[ao,null===(Se=null==Et?void 0:Et.data)||void 0===Se?void 0:Se.workspaceId]);const ho=(({accessGroupType:e,currentUses:t,extraUses:n,limit:o,limitInterval:s})=>{const i=Number(null!=t?t:0),r=Number(null!=n?n:0);return"public"===e&&"one_time"===s?o===ie?ie:Math.max(0,o-i):o===ie||r===ie?ie:"one_time"===s?Math.max(0,r):Math.max(0,o-i)+r})({accessGroupType:null==tt?void 0:tt.type,currentUses:vo.currentUses,extraUses:vo.extraUses,limit:io,limitInterval:ro}),bo=ho===ie?ie:Math.max(0,Math.ceil(ho)),yo=(({accessGroupType:e,extraUses:t,limit:n,limitInterval:o})=>{const s=Number(null!=t?t:0);return"public"===e&&"one_time"===o?n===ie?ie:Math.max(0,n):n===ie||s===ie?ie:"one_time"===o?Math.max(0,s):Math.max(0,n)+Math.max(0,s)})({accessGroupType:null==tt?void 0:tt.type,extraUses:vo.extraUses,limit:io,limitInterval:ro}),xo=yo===ie?ie:Math.ceil(.05*yo),jo=ao?Math.ceil(5*mn):5,Io=xo===ie?ie:Math.max(xo,jo),wo=f((()=>!!sn&&(!un&&(bo!==ie&&(!(yo<=0||bo>=yo)&&bo<=Io)))),[un,Io,bo,sn,yo]),ko=Boolean(null==tt?void 0:tt.hideUpgradeOptions),Oo=Boolean(!ko&&((null===(Ce=null==tt?void 0:tt.upgrade)||void 0===Ce?void 0:Ce.isBuyMoreUses)||(null===(Ee=null==tt?void 0:tt.upgrade)||void 0===Ee?void 0:Ee.isLinkToCustomURL)||(null===(_e=null==tt?void 0:tt.upgrade)||void 0===_e?void 0:_e.isUpgradeToAnotherGroup)&&(null===(Te=tt.upgrade.accessGroupIds)||void 0===Te?void 0:Te.length))),No=!ko&&(null===(Ue=null==tt?void 0:tt.upgrade)||void 0===Ue?void 0:Ue.isLinkToCustomURL)&&"string"==typeof tt.upgrade.limitLink&&tt.upgrade.limitLink.trim().length>0?tt.upgrade.limitLink.trim():null,So=No&&"string"==typeof(null===(Ae=null==tt?void 0:tt.upgrade)||void 0===Ae?void 0:Ae.limitCTA)&&tt.upgrade.limitCTA.trim().length>0?tt.upgrade.limitCTA:(null==qe?void 0:qe["pricing.upgrade"])||(null==qe?void 0:qe.upgrade)||"Upgrade",Co=f((()=>{var e,t,n;return!!Qe&&(!!Ve&&(!$t.isLoading&&(!((null!==(t=null===(e=$t.data)||void 0===e?void 0:e.messages.length)&&void 0!==t?t:0)>1)&&(!!(null===(n=Ve.icebreakers)||void 0===n?void 0:n.length)&&(!et&&!Zn)))))}),[Ve,Qe,et,Zn,$t.data,$t.isLoading]),Eo=f((()=>{if(kt||Ht)return!1;const e=Jn&&wt.length>0&&wt.every((e=>"finished"===e.status));return!(!Bt.trim()&&!e)&&wt.every((e=>"finished"===e.status||e.isInsertedAsRaw))}),[Jn,kt,Ht,Bt,wt]);v(be,(()=>({onSubmit:Po}))),g((()=>{ot(Co)}),[Co]),g((()=>{var e;if(c){const t=Array.from(vt),n=null===(e=t[t.length-2].parts.find((e=>"text"===e.type)))||void 0===e?void 0:e.content;Po(n,!0)}}),[c]),g((()=>{if(!wn.current||!ve)return;const e=new ResizeObserver((e=>{for(const t of e)ve(t.contentRect.height)}));return e.observe(wn.current),()=>{e.disconnect()}}),[ve]),g((()=>{if(!En)return;const e=vn.current?`${vn.current} `:"";Xt(`${e}${Cn}`)}),[Cn,En]),g((()=>{if(!jn.current)return;(()=>{if(!jn.current)return;let e=jn.current.scrollHeight>52;Bt.includes("\n")||wt.length?e=!0:Bt.trim()||(e=!1),Ft(e)})()}),[Bt,wt]),g((()=>{const e=jn.current,t=In.current;if(!e||!t||ut||Kt||Bt.includes("\n"))return void Vt(!1);const n=window.getComputedStyle(e),o=`${n.fontStyle} ${n.fontVariant} ${n.fontWeight} ${n.fontSize} / ${n.lineHeight} ${n.fontFamily}`,s=document.createElement("span");Object.assign(s.style,{font:o,letterSpacing:n.letterSpacing,position:"absolute",visibility:"hidden",whiteSpace:"nowrap",top:"0",left:"0"}),s.textContent=Bt||no,document.body.appendChild(s);const i=s.offsetWidth;s.remove();const r=parseFloat(n.paddingLeft)||0,a=parseFloat(n.paddingRight)||0,l=e.clientWidth-r-a-t.offsetWidth;Vt(i>l)}),[Bt,Kt,no,ut]);const _o=e=>t(void 0,void 0,void 0,(function*(){if(!(e=null!=e?e:bn.current))return!1;const t=de(xn.current);try{return(yield fetch(`${process.env.NEXT_PUBLIC_PICKAXE_API2_URL}/response/cancel/${e}`,Object.assign({method:"POST",headers:Object.assign(Object.assign({"Content-Type":"application/json"},(!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()}),body:JSON.stringify({outputMessageParts:t})},qn&&{credentials:"include"}))).ok}catch(e){return console.warn("Failed to cancel submission",e),!1}})),To=e=>{yn.current=e,kn.current&&(kn.current.abort(),kn.current=null),hn.current&&(hn.current.cancel().catch((()=>{})),hn.current=null)},Uo=e=>t(void 0,void 0,void 0,(function*(){const t=Date.now()+3e4;for(;Date.now()<t;){try{const t=yield fetch(`${process.env.NEXT_PUBLIC_PICKAXE_API2_URL}/response/status/${e}`,Object.assign({headers:Object.assign({"Cache-Control":"no-cache"},(!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}))},qn&&{credentials:"include"}));if(t.ok){if((yield t.json()).terminal)return!0}}catch(e){console.warn("Failed to read submission status",e)}yield new Promise((e=>setTimeout(e,250)))}return!1})),Ao=()=>{const e=bn.current;e&&!Ht&&!kt&&Bt.trim()&&(Qt((t=>{var n,o;return[...t,{id:le(),message:Bt,predecessorSubmissionId:null!==(o=null===(n=t[t.length-1])||void 0===n?void 0:n.id)&&void 0!==o?o:e}]})),Xt(""))},Po=(e,n=!1,o=!1,s,r=!1)=>t(void 0,void 0,void 0,(function*(){var t,a,c,u,p;if(!i(Ve))return;let m=null;try{if(ht&&!o||kt||En||_n)return;const i=wt.filter((e=>"finished"===e.status&&!e.isInsertedAsRaw)),g=i.map((e=>e.documentId)).filter(Boolean),f=i.filter((e=>"image"===e.type)).map((e=>{const t=e.name.split(".").pop()||"";return{documentId:e.documentId,extension:t}})),v=null!=e?e:Bt,h=null!==(a=null===(t=null==Ve?void 0:Ve.documentuploadtype)||void 0===t?void 0:t.startsWith("enduserupload"))&&void 0!==a&&a&&g.length>0;if(!v&&!h)return;jt(""),Ct(""),xt(null),Xt(""),nt(!1),Jt(!1),yt("fetching"),Tt(),At();const b=n?vt.slice(0,vt.length-1):vt,y=(e=>e.reduce(((e,t)=>Math.max(e,t.id)),0)+1)(b),x=y+(n?0:1),j={id:x,role:"assistant",parts:[],documentIds:[]},I=[...b,...n?[]:[{id:y,role:"user",parts:[{type:"text",content:v,isVisible:!0}],documentIds:h?g:[]}],j];bt(I),At(),h&&St([]);const w=Z(Fe),k=null!=s?s:le();m=k,bn.current=k,yn.current=null,xn.current=[];const O=yield fetch(`${process.env.NEXT_PUBLIC_PICKAXE_API2_URL}/response/submit`,Object.assign({method:"POST",body:JSON.stringify(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({supportsActionConfirmation:!0,selectedModel:ct||void 0,origin:Me,pickaxeId:Re,sessionId:$e,submissionId:k},r&&{interactionType:"steer"}),{senderType:Xe,value:v}),h&&{documentIds:g}),Be&&{sender:Be}),pt&&{studioSessionToken:pt}),!pt&&!Be&&{sender:Y()}),lo&&{portalId:lo}),Fe&&{deploymentId:Fe}),w&&{metadata:w}),h&&f.length>0?{uploadedModelImages:f}:{})),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()})},qn&&{credentials:"include"})),N=yield O.json();if(!N.success){if(N.limitData){const e=new Error(N.error||N.message||(null==qe?void 0:qe["failed-to-start-generation"])||"Failed to start generation");throw e.limitData=N.limitData,e}if(to(N))return;throw new Error(N.error||N.message||(null==qe?void 0:qe["failed-to-start-generation"])||"Failed to start generation")}It(null!==(c=N.actionApprovalToken)&&void 0!==c?c:null);const S=null!==(u=N.submissionId)&&void 0!==u?u:k;m=S,bn.current=S;const C=()=>yn.current===S;if(C())return;Yn&&Qe&&$e&&On.current.add($e);const E=Object.assign(Object.assign({},uo()),{message:v,documentIds:h?g:[],uploadedModelImages:h?f:[],hasUploadedDocuments:h,isHidden:n,metadata:null!=w?w:null});dn?(po(),ne(E)):Nn.current=E,yt("streaming"),kn.current=new AbortController;const _=[];let T=[...null!=Pt?Pt:[]],A=0,P=!1,D="";for(;!P;)try{const e=yield fetch(`${process.env.NEXT_PUBLIC_PICKAXE_API2_URL}/response/stream/${S}?index=${A}`,{signal:null===(p=kn.current)||void 0===p?void 0:p.signal,headers:{"Cache-Control":"no-cache",Connection:"keep-alive"}});if(!e.body)throw new Error("No response body");const t=e.body.getReader();hn.current=t;const n=new TextDecoder,o=U({onEvent:e=>{var t,n;if(C())P=!0;else if(e.event&&"ping"!==e.event&&A++,"stop"!==e.event){if("error"===e.event){const t=JSON.parse(e.data);if(t.limitData)return xt(t.limitData),jt(""),void(P=!0);const n=t.error||t.message||(null==qe?void 0:qe["something-went-wrong"])||"Something went wrong.";return to(t)||jt(n),void(P=!0)}if("delta"===e.event){const o=JSON.parse(e.data);if("finish"===o.type)return void Jt(!0);if("data-error"===o.type&&he){const e=o.data.error;if("string"==typeof e){const t=/['"]type['"]\s*:\s*['"]unauthorized_smithery['"]/.test(e),n=/['"]type['"]\s*:\s*['"]unauthorized_composio['"]/.test(e);if(t){const t=e.match(/['"]qualifiedName['"]\s*:\s*['"]([^'"]+)['"]/),n=e.match(/['"]serverId['"]\s*:\s*['"]([^'"]+)['"]/),o=e.match(/['"]name['"]\s*:\s*['"]([^'"]+)['"]/);if(t&&t[1]&&n&&n[1]&&o&&o[1])throw P=!0,he({provider:"smithery",smitheryId:t[1],serverId:n[1],name:o[1]}),new Error("STOP_STREAM")}else if(n){const t=e.match(/['"]toolkitSlug['"]\s*:\s*['"]([^'"]+)['"]/),n=e.match(/['"]serverId['"]\s*:\s*['"]([^'"]+)['"]/),o=e.match(/['"]name['"]\s*:\s*['"]([^'"]+)['"]/);if(t&&t[1]&&n&&n[1]&&o&&o[1])throw P=!0,he({provider:"composio",toolkitSlug:t[1],serverId:n[1],name:o[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 P=!0,he({provider:"smithery",smitheryId:t.qualifiedName,serverId:t.serverId,name:t.name}),new Error("STOP_STREAM");if("unauthorized_composio"===t.type&&t.toolkitSlug&&t.serverId&&t.name)throw P=!0,he({provider:"composio",toolkitSlug:t.toolkitSlug,serverId:t.serverId,name:t.name}),new Error("STOP_STREAM")}}else if("text-start"===o.type)D="",_.push({type:"text",content:"",isVisible:null===(t=o.isVisible)||void 0===t||t});else if("text-delta"===o.type)D+=o.delta,l(_,"text",D);else if("text-end"===o.type)D="";else if("reasoning-start"===o.type)D="",_.push({type:"reasoning",content:"",isVisible:null===(n=o.isVisible)||void 0===n||n});else if("reasoning-delta"===o.type)D+=o.delta,l(_,"reasoning",D);else if("reasoning-end"===o.type)D="";else if(o.type.startsWith("data-")){const e=o;"data-action-approval"===e.type?d(_,e.data):_.push({type:e.type,content:JSON.stringify(e.data),isVisible:!0})}xn.current=de(_);const s=de(_);bt((e=>{const t=e.findIndex((e=>e.id===x)),n=Object.assign(Object.assign({},j),{parts:s});return-1===t?[...e,n]:e.map(((e,o)=>o===t?n:e))}))}else if("artifact_created"===e.event){const t=JSON.parse(e.data);T=T.filter((e=>!(e.id===t.id&&e.version===t.version))),T.push(Object.assign(Object.assign({},t),{content:"",status:"streaming"})),Lt([...T]),Dt.startsWith("inline")||Mt({id:t.id,version:t.version})}else if("artifact_updated"===e.event){const t=JSON.parse(e.data);T=T.filter((e=>!(e.id===t.id&&e.version===t.version))),T.push(Object.assign(Object.assign({},t),{content:"",status:"updating"})),Lt(T),Dt.startsWith("inline")||Mt({id:t.id,version:t.version})}else if("artifact_rewrite"===e.event){const t=JSON.parse(e.data);T=T.filter((e=>!(e.id===t.id&&e.version===t.version))),T.push(Object.assign(Object.assign({},t),{content:"",status:"streaming"})),Lt(T),Dt.startsWith("inline")||Mt({id:t.id,version:t.version})}else if("artifact_content"===e.event){const t=JSON.parse(e.data),n=t.token.replace(/\u200B/g,"");T=T.map((e=>e.id===t.id&&e.version===t.version?Object.assign(Object.assign({},e),{content:e.content+n,status:"streaming"}):e)),Lt(T)}else if("artifact_finished"===e.event){const t=JSON.parse(e.data);Lt(T.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);if(t.limitData)return xt(t.limitData),jt(""),void(P=!0);const n=t.error||t.message||(null==qe?void 0:qe["something-went-wrong-try-again"])||"Something went wrong, please try again.";if(to(t))return void(P=!0);jt(n)}else"stop"===e.event&&(P=!0)}else P=!0}});for(;;){if(C()){P=!0,t.cancel().catch((()=>{}));break}const{value:e,done:s}=yield t.read();if(C()){P=!0,t.cancel().catch((()=>{}));break}if(s)break;o.feed(n.decode(e))}P||C()||(yield new Promise((e=>setTimeout(e,1e3))))}catch(e){if("STOP_STREAM"===e.message||ce(e)||C())return void(P=!0);console.warn("Stream connection lost, retrying...",e),yield new Promise((e=>setTimeout(e,1e3)))}null==dt||dt($e)}catch(e){if(ce(e))return;if(e.limitData)xt(e.limitData),jt("");else{let t=H(e)||"";t&&!t.includes("Unexpected token 'A',")||(t=(null==qe?void 0:qe["high-traffic-try-again-later"])||"Oops! We're experiencing high traffic at the moment. Please try again later."),to(t)||jt(t)}}finally{const e=!m||bn.current===m;At(),e&&(yt("idle"),Ut(),hn.current=null),m&&e&&(bn.current=null,xn.current=[]),yield so()}}));return g((()=>{if(ht||Ht||Yt||0===zt.length)return;const e=zt[0];Zt(!0),tn(e.id),t(void 0,void 0,void 0,(function*(){try{if(!(yield Uo(e.predecessorSubmissionId)))return void jt((null==qe?void 0:qe["queued-message-waiting"])||"A queued message is waiting for the previous response to finish.");Qt((t=>t.filter((t=>t.id!==e.id)))),yield Po(e.message,!1,!0,e.id)}finally{Zt(!1),tn(null)}}))}),[ht,Yt,Ht,zt]),eo?null:n("div",Object.assign({className:J("flex w-full flex-shrink-0 flex-col items-center",!Zn&&"px-4 pb-8"),dir:Ye?"rtl":"ltr"},{children:o("div",Object.assign({className:"flex w-full max-w-[800px] flex-col"},{children:[zt.length>0&&n("div",Object.assign({className:"mx-3 -mb-3 overflow-hidden border pb-3",style:{borderColor:We.text+"18",backgroundColor:null!==(Pe=Gn.backgroundColor)&&void 0!==Pe?Pe:We.text+"08",color:We.text,borderTopLeftRadius:Math.max(He.cornerRadius-4,12),borderTopRightRadius:Math.max(He.cornerRadius-4,12)}},{children:zt.map(((e,i)=>{var r;return o("div",Object.assign({className:"flex min-h-10 items-center gap-2 px-3 py-2",style:i<zt.length-1?{borderBottom:`1px solid ${We.text}12`}:void 0},{children:[n(L,{className:"h-4 w-4 shrink-0 opacity-50","aria-hidden":"true"}),n("span",Object.assign({className:"min-w-0 flex-1 truncate text-sm",title:e.message},{children:e.message})),nn===e.id||en===e.id?o("span",Object.assign({className:"flex shrink-0 items-center gap-1.5 px-2 py-1 text-xs opacity-60","aria-live":"polite"},{children:[n("span",{className:"h-3 w-3 animate-spin rounded-full border border-current border-r-transparent","aria-hidden":"true"}),nn===e.id?(null==qe?void 0:qe.steering)||"Steering...":(null==qe?void 0:qe.starting)||"Starting..."]})):o(s,{children:[o("button",Object.assign({type:"button",className:"shrink-0 rounded-md px-2 py-1 text-xs font-medium opacity-70 transition-opacity hover:opacity-100 disabled:cursor-default disabled:opacity-40",disabled:Ht||!ht,onClick:()=>{(e=>{t(void 0,void 0,void 0,(function*(){const t=bn.current;if(!t||Ht)return;const n=zt.findIndex((t=>t.id===e.id));if(-1===n)return;Wt(!0),on(e.id),jt(""),To(t);let o=!1;try{if(!(yield _o(t)))throw new Error((null==qe?void 0:qe["failed-to-interrupt-current-response"])||"Failed to interrupt the current response.");if(!(yield Uo(t)))throw new Error((null==qe?void 0:qe["current-response-still-stopping"])||"The current response is still stopping. Please send your message again in a moment.");yt("idle"),Qt((t=>t.filter((t=>t.id!==e.id)))),o=!0,Wt(!1),on(null),yield Po(e.message,!1,!0,e.id,!0)}catch(t){yt("idle"),o&&Qt((t=>{if(t.some((t=>t.id===e.id)))return t;const o=[...t];return o.splice(n,0,e),o})),jt(H(t))}finally{Wt(!1),on(null)}}))})(e)},"aria-label":`${(null==qe?void 0:qe["steer-with"])||"Steer with"}: ${e.message}`},{children:[n("span",Object.assign({"aria-hidden":"true"},{children:"↳ "})),(null==qe?void 0:qe.steer)||"Steer"]})),n("button",Object.assign({type:"button",className:"flex h-7 w-7 shrink-0 items-center justify-center rounded-md opacity-50 transition-opacity hover:opacity-100 disabled:cursor-default disabled:opacity-30",disabled:Ht,onClick:()=>{return t=e.id,void Qt((e=>re(e,t)));var t},"aria-label":`${(null==qe?void 0:qe["remove-queued-message"])||"Remove queued message"}: ${e.message}`},{children:n(R,{className:"h-4 w-4","aria-hidden":"true"})})),o(F,Object.assign({id:`queued-message-menu-${e.id}`,className:"shrink-0"},{children:[n(G,Object.assign({className:"flex h-7 w-7 items-center justify-center rounded-md opacity-50 transition-opacity hover:opacity-100",isDisabled:Ht,role:"button",tabIndex:Ht?-1:0,"aria-haspopup":"menu","aria-label":(null==qe?void 0:qe["more-options"])||"More options",onKeyDown:e=>{"Enter"!==e.key&&" "!==e.key||(e.preventDefault(),e.currentTarget.click())}},{children:o("svg",Object.assign({viewBox:"0 0 24 24",className:"h-4 w-4",fill:"currentColor","aria-hidden":"true"},{children:[n("circle",{cx:"5",cy:"12",r:"1.6"}),n("circle",{cx:"12",cy:"12",r:"1.6"}),n("circle",{cx:"19",cy:"12",r:"1.6"})]}))})),n(V,Object.assign({role:"menu",align:Ye?"bottom-start":"bottom-end",positionStrategy:Ze?"absolute":"fixed",width:"auto",className:"p-1 text-sm shadow-xl",style:{backgroundColor:null!==(r=Gn.backgroundColor)&&void 0!==r?r:We.primary,color:We.text,borderRadius:"12px"},border:`1px solid ${We.text}20`},{children:o("button",Object.assign({type:"button",role:"menuitem",className:"flex min-w-36 items-center gap-2 rounded-lg px-3 py-2 text-left transition-colors hover:bg-black/5 dark:hover:bg-white/10",onClick:()=>(e=>{Qt((t=>re(t,e.id))),Xt(e.message),requestAnimationFrame((()=>{const t=jn.current;t&&(t.focus(),t.setSelectionRange(e.message.length,e.message.length))}))})(e)},{children:[n($,{className:"h-4 w-4 shrink-0"}),(null==qe?void 0:qe["edit-message"])||"Edit message"]}))}))]}))]})]}),e.id)}))})),o("div",Object.assign({ref:wn,className:J("relative z-10 flex flex-col w-full justify-end gap-y-3 py-[3px]","block"===He.formFieldStyle&&"shadow"),style:Object.assign(Object.assign({},Gn),{maxHeight:`${Sn}px`,overflowY:"auto"})},{children:[wo&&o("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:Gn.backgroundColor?`${Gn.backgroundColor}E6`:void 0,borderColor:We.text+"20",color:We.text,borderTopRightRadius:He.cornerRadius+"px",borderTopLeftRadius:He.cornerRadius+"px"}},{children:[n("div",Object.assign({className:"flex items-center gap-2 text-sm font-medium"},{children:o("span",{children:[bo.toLocaleString()," ",ao?(null==qe?void 0:qe.credits)||"Credits":(null==qe?void 0:qe.uses)||"Uses"," ",(null==qe?void 0:qe.remaining)||"remaining"]})})),o("div",Object.assign({className:"flex items-center gap-3"},{children:[Oo&&n("button",Object.assign({className:"rounded-md px-3 py-1.5 text-xs font-semibold transition-opacity hover:opacity-90",style:{backgroundColor:We.accent,color:We.accentText},onClick:e=>{if(e.preventDefault(),e.stopPropagation(),No)return void window.open(No,"_blank","noopener,noreferrer");if(lt)return void lt();const t=z({baseUrl:an,accessGroupId:null==tt?void 0:tt.accessGroupId});t&&Q({deploymentId:Fe,pricingUrl:t,studioId:null==Ve?void 0:Ve.studioid,studioSessionToken:pt})}},{children:So})),n("button",Object.assign({className:"flex h-6 w-6 items-center justify-center rounded-full opacity-60 transition-opacity hover:opacity-100",onClick:()=>pn(!0)},{children:n("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:n("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M6 18L18 6M6 6l12 12"})}))}))]}))]})),!ht&&wt.length>0&&n(B,{className:"p-4 pb-0",isDisabled:ht}),o("div",Object.assign({className:"relative flex w-full flex-col"},{children:[Qn&&o("div",Object.assign({className:J(ut?"top-6":"top-1/2","pointer-events-none absolute z-10 flex -translate-y-1/2 select-none items-center gap-x-2",Ye?"right-4":"left-4")},{children:[n("span",{className:"h-2 w-2 animate-pulse rounded-full bg-c-secondary",style:{backgroundColor:null!==(De=We.accent)&&void 0!==De?De:"#ff0000"}}),n("span",Object.assign({className:"text-sm text-c-secondary font-semilight",style:{color:We.text+"90"}},{children:(null==qe?void 0:qe.listening)||"Listening..."}))]})),n(X,Object.assign({ref:jn,className:J(Fn.i1,"py-3.5 max-h-60 px-4 w-full border-transparent bg-transparent",!Bt.trim()&&!Bt.includes("\n")&&"overflow-hidden text-ellipsis whitespace-nowrap placeholder:whitespace-normal placeholder:overflow-visible",Ye?"text-right":"text-left",!ut&&oo&&"mb-12"),value:Bt,placeholder:Qn?"":no,onChange:e=>{Xt(e)},onKeyDown:e=>{ze||_t||"Enter"===e.key&&(e.shiftKey||(e.preventDefault(),kt||Ht||(ht?Ao():Po())))},onPaste:e=>t(void 0,void 0,void 0,(function*(){const t=Array.from(e.clipboardData.files||[]);if(t.length>0){if(!Jn)return;e.preventDefault(),nt(!1),yield Nt(t)}}))},ue&&{onFocus:ue},fe&&{onBlur:fe},{dir:Ye?"rtl":"ltr"})),o("div",Object.assign({ref:In,className:ut?"relative flex w-full items-center gap-2 px-3 pb-2 [&>button]:shrink-0 [&>button]:mr-0":J("flex items-center gap-2 absolute z-2 transition-all duration-200 ease-in-out",oo?"bottom-3 right-2":"right-0 top-1/2 -translate-y-1/2"),style:Object.assign(Object.assign({},!oo&&Gn.backgroundColor&&{backgroundColor:Gn.backgroundColor}),{borderTopRightRadius:He.cornerRadius+"px",borderBottomRightRadius:He.cornerRadius+"px"})},{children:[!ht&&!En&&Jn&&o("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:Rn?We.accent+"10":void 0,color:Rn?We.accent:We.accent+"80"},disabled:kt||ht,"aria-label":null!==(Le=null==qe?void 0:qe["attach-files"])&&void 0!==Le?Le:"Attach files",onClick:()=>{var e;return null===(e=fn.current)||void 0===e?void 0:e.click()}},$n,{children:[n("input",{id:"file-upload",ref:fn,type:"file",accept:[...E,..._,...T].join(", "),multiple:!0,hidden:!0,className:"hidden",onChange:e=>t(void 0,void 0,void 0,(function*(){nt(!1),yield Nt(Array.from(e.target.files||[])),e.target.value=""}))}),n(A,{className:"h-6 w-6 shrink-0"})]})),n(a,{compact:!0}),ht&&!qt?o(s,{children:[n("button",Object.assign({"aria-label":(null==qe?void 0:qe["stop-response"])||"Stop response",className:"flex h-8 w-8 items-center justify-center rounded-full outline-none transition-colors duration-200 ease-in-out",onClick:()=>{const e=bn.current;e&&(To(e),_o(e)),yt("idle")},style:{backgroundColor:We.accent+"10",color:We.accent}},{children:n(M,{className:"h-4 w-4 shrink-0"})})),n("button",Object.assign({"aria-label":(null==qe?void 0:qe["queue-message"])||"Queue message",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",disabled:Ht||kt||!Bt.trim(),onClick:Ao,style:{backgroundColor:Bt.trim()?We.accent:We.accent+"10",color:Bt.trim()?We.accentText:We.accent+"80"}},{children:n(P,{className:J("h-6 w-6 shrink-0",Ye&&"scale-x-[-1] transform")})}))]}):En||_n?n("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:()=>{An()},disabled:_n,style:{backgroundColor:We.accent,color:We.accentText}},{children:n(M,{className:"h-4 w-4 shrink-0"})})):o(s,{children:[zn&&n("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:En?We.accent:Xn?We.accent+"10":void 0,color:En?We.accentText:Xn?We.accent:We.accent+"80"},disabled:kt||ht||_n,onClick:()=>{En?An():(vn.current=Bt,Un(Je||"en-US"))}},Kn,{children:n(D,{className:"h-5 w-5 shrink-0"})})),n("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:Dn||Eo?We.accent:We.accent+"10",color:Dn||Eo?We.accentText:We.accent+"80"},disabled:!Eo,onClick:()=>Po()},Ln,{children:n(P,{className:J("h-6 w-6 shrink-0",Ye&&"scale-x-[-1] transform")})}))]})]}))]}))]})),Ot&&n(K,{error:Ot,className:"mt-3"})]}))}))}));fe.displayName="Input";export{fe as default};
|
|
1
|
+
import{__rest as e,__awaiter as t}from"../../../_virtual/_tslib.js";import{jsx as n,jsxs as s,Fragment as o}from"react/jsx-runtime";import{canChat as i}from"../../../common/canChat.js";import{useEndUserModel as r}from"../../../hooks/pickaxe/useEndUserModel.js";import a from"../common/EndUserModelPicker.js";import{updateStreamTextPart as l,upsertActionApprovalPart as d}from"../../../common/actionApproval.js";import{forwardRef as c,useState as u,useRef as p,useCallback as m,useEffect as g,useMemo as f,useImperativeHandle as v}from"react";import{usePickaxeContext as h}from"../../../hooks/pickaxe/usePickaxeContext.js";import{useResponseContext as b}from"../../../hooks/pickaxe/useResponseContext.js";import{useStyleInput as y}from"../../../hooks/studio/useStyleInput.js";import{useStyleFontSize as x}from"../../../hooks/studio/useStyleFontSize.js";import{useConversation as j}from"../../../hooks/pickaxe/useConversation.js";import{useDimensionContext as w}from"../../../hooks/pickaxe/useDimensionContext.js";import{useAuthContext as I}from"../Addons/Auth/hooks/useAuthContext.js";import{useDocument as k}from"../Addons/Document/hooks/useDocument.js";import{useScroll as O}from"../Addons/Scroll/hooks/useScroll.js";import{useArtifactContext as N}from"../Addons/Artifact/hooks/useArtifactContext.js";import{useHover as S}from"../../../hooks/core/useHover.js";import{useMediaQuery as C}from"../../../hooks/core/useMediaQuery.js";import{allowedFileMimeTypes as E,allowedImageMimeTypes as T,additionalAllowedFileExtensions as _}from"../../../common/documents.js";import{createParser as U}from"eventsource-parser";import A from"../../Icons/attach-vertical.svg.js";import P from"../../Icons/arrow-right.svg.js";import D from"../../Icons/microphone.svg.js";import L from"../../Icons/message-clock.svg.js";import M from"../../Icons/stop.svg.js";import R from"../../Icons/trash.svg.js";import $ from"../../Icons/pencil.svg.js";import B from"../Addons/Document/List.js";import X from"../../Core/Textarea.js";import K from"../../Core/ErrorAlert.js";import F from"../../Core/Menu/index.js";import G from"../../Core/Menu/Button.js";import V from"../../Core/Menu/List.js";import H from"../../../common/error.js";import{pickaxeApi2 as W}from"../../../common/api/pickaxe.js";import{getValidationFailure as q}from"../../../common/validation.js";import J from"../../../common/cn.js";import{buildUpgradeUrl as z,openAuthenticatedPricingUrl as Q,initializeEmbedUserId as Y}from"../../../common/utils.js";import{getPickaxeConfigMetadata as Z}from"../../../common/pickaxeConfig.js";import{readAgentPrefill as ee}from"../../../common/agentPrefill.js";import{fireDeploymentSessionInitializedWebhook as te,fireDeploymentFirstMessageSubmittedWebhook as ne}from"../../../common/deploymentWebhooks.js";import{useStudio as se}from"../../../hooks/studio/useStudio.js";import{useSpeechToText as oe}from"../../../hooks/pickaxe/useSpeechToText.js";import{STUDIO_INFINITY_VALUE as ie}from"../common/PickaxeCommon.js";const re=(e,t)=>{const n=e.find((e=>e.id===t));return n?e.filter((e=>e.id!==t)).map((e=>e.predecessorSubmissionId===t?Object.assign(Object.assign({},e),{predecessorSubmissionId:n.predecessorSubmissionId}):e)):e},ae=e=>"string"==typeof e&&e.trim().length>0,le=()=>"undefined"!=typeof crypto&&"randomUUID"in crypto?crypto.randomUUID():`submission-${Date.now()}-${Math.random().toString(36).slice(2)}`,de=e=>e.map((e=>Object.assign({},e))),ce=e=>e instanceof Error&&("AbortError"===e.name||"BodyStreamBuffer was aborted"===e.message),ue=(e,t)=>{if(e&&"object"==typeof e)return e[t]},pe=(e,t)=>{const n=ue(e,t);return ae(n)?n:null},me=e=>{const t=Number(e);return Number.isFinite(t)?t:void 0},ge=({studioUser:e,deploymentId:t,portalId:n})=>{var s,o;const i=Array.isArray(ue(e,"uses"))?ue(e,"uses"):[],r=(({deploymentId:e,portalId:t})=>ae(e)?{type:"deployment",id:e}:ae(t)?{type:"portal",id:t}:null)({deploymentId:t,portalId:n});if(!r)return{scope:r,record:null};const a=null!==(o=null!==(s=i.find((e=>e.id===r.id&&e.type===r.type)))&&void 0!==s?s:i.find((e=>e.id===r.id)))&&void 0!==o?o:null;return{scope:r,record:a}},fe=c((({resubmitPrompt:c,onFocus:ue,onBlur:fe,onInputHeightChange:ve,initSmitheryAuthData:he},be)=>{var ye,xe,je,we,Ie,ke,Oe,Ne,Se,Ce,Ee,Te,_e,Ue,Ae,Pe,De,Le;const{origin:Me,pickaxeId:Re,sessionId:$e,sender:Be,senderType:Xe,portalId:Ke,deploymentId:Fe,deploymentType:Ge,pickaxe:Ve,styles:He,colors:We,translations:qe,locale:Je,forceMobile:ze,isNewChat:Qe,isRtl:Ye,isEmbed:Ze,isShowFeedbackMessage:et,accessGroup:tt,setIsNewChat:nt,setIsShowIceBreaker:st,setValidationStatus:ot,setValidationUpgradeGroups:it,setValidationUpgradeUrl:rt,setAccessGroup:at,onUpgrade:lt,onGenerateComplete:dt}=h(),{value:ct,enabled:ut}=r(),{token:pt,isLoggedOut:mt,isSent:gt,isPricingAuth:ft}=I(),{messages:vt,isGenerating:ht,setMessages:bt,setStatus:yt,setLimitData:xt,setError:jt,setActionApprovalToken:wt}=b(),{documents:It,isUploading:kt,documentError:Ot,onFileUpload:Nt,setDocuments:St,setDocumentError:Ct}=k(),{studio:Et}=se(),[Tt]=C("(max-width: 480px)"),{scrollStartSession:_t,scrollEndSession:Ut,scrollToBottom:At}=O({auto:!0,smooth:!(ze||Tt)}),{artifacts:Pt,currentPopupType:Dt,setArtifacts:Lt,setCurrentArtifact:Mt}=N(),{height:Rt}=w(),$t=j(),[Bt,Xt]=u((()=>ee([Fe,Re]).chatInput)),[Kt,Ft]=u(null),[Gt,Vt]=u(!1),[Ht,Wt]=u(!1),[qt,Jt]=u(!1),[zt,Qt]=u(!1),[Yt,Zt]=u([]),[en,tn]=u(!1),[nn,sn]=u(null),[on,rn]=u(null),[an,ln]=u(null),[dn,cn]=u(null),[un,pn]=u(!1),[mn,gn]=u(!1),[fn,vn]=u(0),hn=p(null),bn=p(""),yn=p(null),xn=p(null),jn=p(null),wn=p([]),In=p(null),kn=p(null),On=p(null),Nn=p(null),Sn=p(new Set),Cn=p(null),En=Math.max(.4*Rt,100),{speechTranscript:Tn,isSpeechListening:_n,isSpeechProcessing:Un,isSpeechSupported:An,getSpeechTranscriptSnapshot:Pn,speechTranscriptRevision:Dn,resetSpeechTranscript:Ln,onStartListening:Mn,onStopListening:Rn}=oe(),$n=S(),{isHover:Bn}=$n,Xn=e($n,["isHover"]),Kn=S(),{isHover:Fn}=Kn,Gn=e(Kn,["isHover"]),Vn=S(),{isHover:Hn}=Vn,Wn=e(Vn,["isHover"]),qn=x(),Jn=y(),zn="undefined"!=typeof window?window.location.hostname:"",Qn="undefined"!=typeof window?window.location.href:"",Yn="undefined"!=typeof window&&window.self!==window.top,Zn=zn.includes("pickaxe.co")&&!Qn.includes("https://studio.pickaxe.co/_embed")&&!Yn,es=null!==(xe=null===(ye=null==Ve?void 0:Ve.documentuploadtype)||void 0===ye?void 0:ye.startsWith("enduserupload"))&&void 0!==xe&&xe,ts=An&&(null==Ve?void 0:Ve.enablevoicetotext),ns=_n&&!Bt.trim(),ss=ae(Fe),os="chat-input"===Ge&&Qe&&!gt,is="chat-input"===Ge&&ft&&mt&>,rs=m((e=>{const t=q(e);return!!t&&(jt(""),xt(null),ot(t.status),at(t.accessGroup),it(t.upgradeGroups),rt(t.upgradeUrl),!0)}),[jt,wt,xt,ot,it,rt,at]),as=null!==(je=null==Ve?void 0:Ve.placeholdertext)&&void 0!==je?je:Ye?"بماذا تريد أن تتحدث؟":(null==qe?void 0:qe["what-do-you-want-to-talk-about"])||"What do you want to talk about?",ls=Gt||Ht,ds=m((()=>t(void 0,void 0,void 0,(function*(){pn(!1);try{const e=yield fetch(`${process.env.NEXT_PUBLIC_PICKAXE_API2_URL}/user`,Object.assign(Object.assign({method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(Object.assign({studioId:null==Ve?void 0:Ve.studioid},pt?{studioSessionToken:pt}:Be?{sender:Be}:{sender:Y()}))},(!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}})),Zn&&{credentials:"include"})),t=yield e.json();(null==t?void 0:t.studioUser)&&(ln(t.studioUser),cn(t.url))}catch(e){console.error("Failed to fetch studio user:",e)}finally{pn(!0)}}))),[Zn,null==Ve?void 0:Ve.studioid,Be,pt]);g((()=>{ds()}),[ds]);const cs=Number(null!==(we=null==tt?void 0:tt.limit)&&void 0!==we?we:0),us="string"==typeof(null==tt?void 0:tt.limitInterval)?tt.limitInterval:null,ps=!!(null==Et?void 0:Et.data.usage)&&Et.data.usage.isCredits,ms=f((()=>{var e,t,n,s,o;return null!==(o=null!==(s=null!==(n=null!==(t=null!==(e=null!=Ke?Ke:pe(an,"portalId"))&&void 0!==e?e:pe(an,"portalid"))&&void 0!==t?t:pe(tt,"portalId"))&&void 0!==n?n:pe(tt,"portalid"))&&void 0!==s?s:pe(Ve,"portalId"))&&void 0!==o?o:pe(Ve,"portalid")}),[tt,Ke,Ve,an]),gs=f((()=>ge({studioUser:an,deploymentId:Fe,portalId:ms})),[Fe,ms,an]);g((()=>{ss&&Qe&&$e&&Sn.current.add($e)}),[Qe,$e,ss]);const fs=m((()=>{var e,t,n;return{studioId:null==Ve?void 0:Ve.studioid,userEmail:pe(an,"email"),userId:null!==(e=pe(an,"userId"))&&void 0!==e?e:pe(an,"userid"),sessionId:$e,deploymentId:Fe,deploymentType:Ge,portalId:ms,accessGroupId:null!==(t=null==tt?void 0:tt.accessGroupId)&&void 0!==t?t:null,pickaxeId:Re,sender:Be,senderType:Xe,origin:Me,metadata:null!==(n=Z(Fe))&&void 0!==n?n:null}}),[null==tt?void 0:tt.accessGroupId,Fe,Ge,Me,null==Ve?void 0:Ve.studioid,Re,ms,Be,Xe,$e,an]),vs=m((()=>!!(ss&&un&&$e)&&(!!Sn.current.has($e)&&(te(fs()),Sn.current.delete($e),!0))),[fs,un,$e,ss]);g((()=>{if(!un||!$e)return;vs();const e=Cn.current;(null==e?void 0:e.sessionId)===$e&&(ne(Object.assign(Object.assign(Object.assign({},e),fs()),{message:e.message,documentIds:e.documentIds,uploadedModelImages:e.uploadedModelImages,hasUploadedDocuments:e.hasUploadedDocuments,isHidden:e.isHidden})),Cn.current=null)}),[vs,fs,un,$e]);const hs={currentUses:me(null==an?void 0:an.currentUses),extraUses:me(null==an?void 0:an.extraUses)},bs=gs.scope?{currentUses:null!==(ke=me(null===(Ie=gs.record)||void 0===Ie?void 0:Ie.currentUses))&&void 0!==ke?ke:0,extraUses:null!==(Ne=me(null===(Oe=gs.record)||void 0===Oe?void 0:Oe.extraUses))&&void 0!==Ne?Ne:0}:{currentUses:0,extraUses:0},ys=pe(an,"type"),xs="guest"===ys||!ys&&mt?bs:hs;g((()=>{let e=!0;return t(void 0,void 0,void 0,(function*(){var t;if(ps&&(null===(t=null==Et?void 0:Et.data)||void 0===t?void 0:t.workspaceId))try{const t=yield W.get(`/cost_per_run?workspaceId=${Et.data.workspaceId}`,{withCredentials:!1});e&&vn(1e4*(Number(t.data.costPerRun)||0))}catch(t){console.error("Failed to fetch average cost per run:",t),e&&vn(0)}else e&&vn(0)})),()=>{e=!1}}),[ps,null===(Se=null==Et?void 0:Et.data)||void 0===Se?void 0:Se.workspaceId]);const js=(({accessGroupType:e,currentUses:t,extraUses:n,limit:s,limitInterval:o})=>{const i=Number(null!=t?t:0),r=Number(null!=n?n:0);return"public"===e&&"one_time"===o?s===ie?ie:Math.max(0,s-i):s===ie||r===ie?ie:"one_time"===o?Math.max(0,r):Math.max(0,s-i)+r})({accessGroupType:null==tt?void 0:tt.type,currentUses:xs.currentUses,extraUses:xs.extraUses,limit:cs,limitInterval:us}),ws=js===ie?ie:Math.max(0,Math.ceil(js)),Is=(({accessGroupType:e,extraUses:t,limit:n,limitInterval:s})=>{const o=Number(null!=t?t:0);return"public"===e&&"one_time"===s?n===ie?ie:Math.max(0,n):n===ie||o===ie?ie:"one_time"===s?Math.max(0,o):Math.max(0,n)+Math.max(0,o)})({accessGroupType:null==tt?void 0:tt.type,extraUses:xs.extraUses,limit:cs,limitInterval:us}),ks=Is===ie?ie:Math.ceil(.05*Is),Os=ps?Math.ceil(5*fn):5,Ns=ks===ie?ie:Math.max(ks,Os),Ss=f((()=>!!an&&(!mn&&(ws!==ie&&(!(Is<=0||ws>=Is)&&ws<=Ns)))),[mn,Ns,ws,an,Is]),Cs=Boolean(null==tt?void 0:tt.hideUpgradeOptions),Es=Boolean(!Cs&&((null===(Ce=null==tt?void 0:tt.upgrade)||void 0===Ce?void 0:Ce.isBuyMoreUses)||(null===(Ee=null==tt?void 0:tt.upgrade)||void 0===Ee?void 0:Ee.isLinkToCustomURL)||(null===(Te=null==tt?void 0:tt.upgrade)||void 0===Te?void 0:Te.isUpgradeToAnotherGroup)&&(null===(_e=tt.upgrade.accessGroupIds)||void 0===_e?void 0:_e.length))),Ts=!Cs&&(null===(Ue=null==tt?void 0:tt.upgrade)||void 0===Ue?void 0:Ue.isLinkToCustomURL)&&"string"==typeof tt.upgrade.limitLink&&tt.upgrade.limitLink.trim().length>0?tt.upgrade.limitLink.trim():null,_s=Ts&&"string"==typeof(null===(Ae=null==tt?void 0:tt.upgrade)||void 0===Ae?void 0:Ae.limitCTA)&&tt.upgrade.limitCTA.trim().length>0?tt.upgrade.limitCTA:(null==qe?void 0:qe["pricing.upgrade"])||(null==qe?void 0:qe.upgrade)||"Upgrade",Us=f((()=>{var e,t,n;return!!Qe&&(!!Ve&&(!$t.isLoading&&(!((null!==(t=null===(e=$t.data)||void 0===e?void 0:e.messages.length)&&void 0!==t?t:0)>1)&&(!!(null===(n=Ve.icebreakers)||void 0===n?void 0:n.length)&&(!et&&!os)))))}),[Ve,Qe,et,os,$t.data,$t.isLoading]),As=f((()=>{if(kt||qt)return!1;const e=es&&It.length>0&&It.every((e=>"finished"===e.status));return!(!Bt.trim()&&!e)&&It.every((e=>"finished"===e.status||e.isInsertedAsRaw))}),[es,kt,qt,Bt,It]);v(be,(()=>({onSubmit:$s}))),g((()=>{st(Us)}),[Us]),g((()=>{var e;if(c){const t=Array.from(vt),n=null===(e=t[t.length-2].parts.find((e=>"text"===e.type)))||void 0===e?void 0:e.content;$s(n,!0)}}),[c]),g((()=>{if(!On.current||!ve)return;const e=new ResizeObserver((e=>{for(const t of e)ve(t.contentRect.height)}));return e.observe(On.current),()=>{e.disconnect()}}),[ve]),g((()=>{if(!_n)return;const e=bn.current?`${bn.current} `:"",t=Pn();Ft(t),Xt(`${e}${t.text}`)}),[Tn,Dn,_n,Pn]);const Ps=()=>{bn.current="",Ln(Kt),Ft(null)};g((()=>{if(!In.current)return;(()=>{if(!In.current)return;let e=In.current.scrollHeight>52;Bt.includes("\n")||It.length?e=!0:Bt.trim()||(e=!1),Vt(e)})()}),[Bt,It]),g((()=>{const e=In.current,t=kn.current;if(!e||!t||ut||Gt||Bt.includes("\n"))return void Wt(!1);const n=window.getComputedStyle(e),s=`${n.fontStyle} ${n.fontVariant} ${n.fontWeight} ${n.fontSize} / ${n.lineHeight} ${n.fontFamily}`,o=document.createElement("span");Object.assign(o.style,{font:s,letterSpacing:n.letterSpacing,position:"absolute",visibility:"hidden",whiteSpace:"nowrap",top:"0",left:"0"}),o.textContent=Bt||as,document.body.appendChild(o);const i=o.offsetWidth;o.remove();const r=parseFloat(n.paddingLeft)||0,a=parseFloat(n.paddingRight)||0,l=e.clientWidth-r-a-t.offsetWidth;Wt(i>l)}),[Bt,Gt,as,ut]);const Ds=e=>t(void 0,void 0,void 0,(function*(){if(!(e=null!=e?e:xn.current))return!1;const t=de(wn.current);try{return(yield fetch(`${process.env.NEXT_PUBLIC_PICKAXE_API2_URL}/response/cancel/${e}`,Object.assign({method:"POST",headers:Object.assign(Object.assign({"Content-Type":"application/json"},(!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()}),body:JSON.stringify({outputMessageParts:t})},Zn&&{credentials:"include"}))).ok}catch(e){return console.warn("Failed to cancel submission",e),!1}})),Ls=e=>{jn.current=e,Nn.current&&(Nn.current.abort(),Nn.current=null),yn.current&&(yn.current.cancel().catch((()=>{})),yn.current=null)},Ms=e=>t(void 0,void 0,void 0,(function*(){const t=Date.now()+3e4;for(;Date.now()<t;){try{const t=yield fetch(`${process.env.NEXT_PUBLIC_PICKAXE_API2_URL}/response/status/${e}`,Object.assign({headers:Object.assign({"Cache-Control":"no-cache"},(!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}))},Zn&&{credentials:"include"}));if(t.ok){if((yield t.json()).terminal)return!0}}catch(e){console.warn("Failed to read submission status",e)}yield new Promise((e=>setTimeout(e,250)))}return!1})),Rs=()=>{const e=xn.current;e&&!qt&&!kt&&Bt.trim()&&(Ps(),Zt((t=>{var n,s;return[...t,{id:le(),message:Bt,predecessorSubmissionId:null!==(s=null===(n=t[t.length-1])||void 0===n?void 0:n.id)&&void 0!==s?s:e}]})),Xt(""))},$s=(e,n=!1,s=!1,o,r=!1)=>t(void 0,void 0,void 0,(function*(){var t,a,c,u,p;if(!i(Ve))return;let m=null;try{if(ht&&!s||kt)return;const i=It.filter((e=>"finished"===e.status&&!e.isInsertedAsRaw)),g=i.map((e=>e.documentId)).filter(Boolean),f=i.filter((e=>"image"===e.type)).map((e=>{const t=e.name.split(".").pop()||"";return{documentId:e.documentId,extension:t}})),v=null!=e?e:Bt,h=null!==(a=null===(t=null==Ve?void 0:Ve.documentuploadtype)||void 0===t?void 0:t.startsWith("enduserupload"))&&void 0!==a&&a&&g.length>0;if(!v.trim()&&!h)return;if((_n||Un)&&!v.trim())return;o||(Ps(),Xt("")),jt(""),Ct(""),xt(null),nt(!1),Qt(!1),yt("fetching"),_t(),At();const b=n?vt.slice(0,vt.length-1):vt,y=(e=>e.reduce(((e,t)=>Math.max(e,t.id)),0)+1)(b),x=y+(n?0:1),j={id:x,role:"assistant",parts:[],documentIds:[]},w=[...b,...n?[]:[{id:y,role:"user",parts:[{type:"text",content:v,isVisible:!0}],documentIds:h?g:[]}],j];bt(w),At(),h&&St([]);const I=Z(Fe),k=null!=o?o:le();m=k,xn.current=k,jn.current=null,wn.current=[];const O=yield fetch(`${process.env.NEXT_PUBLIC_PICKAXE_API2_URL}/response/submit`,Object.assign({method:"POST",body:JSON.stringify(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({supportsActionConfirmation:!0,selectedModel:ct||void 0,origin:Me,pickaxeId:Re,sessionId:$e,submissionId:k},r&&{interactionType:"steer"}),{senderType:Xe,value:v}),h&&{documentIds:g}),Be&&{sender:Be}),pt&&{studioSessionToken:pt}),!pt&&!Be&&{sender:Y()}),ms&&{portalId:ms}),Fe&&{deploymentId:Fe}),I&&{metadata:I}),h&&f.length>0?{uploadedModelImages:f}:{})),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()})},Zn&&{credentials:"include"})),N=yield O.json();if(!N.success){if(N.limitData){const e=new Error(N.error||N.message||(null==qe?void 0:qe["failed-to-start-generation"])||"Failed to start generation");throw e.limitData=N.limitData,e}if(rs(N))return;throw new Error(N.error||N.message||(null==qe?void 0:qe["failed-to-start-generation"])||"Failed to start generation")}wt(null!==(c=N.actionApprovalToken)&&void 0!==c?c:null);const S=null!==(u=N.submissionId)&&void 0!==u?u:k;m=S,xn.current=S;const C=()=>jn.current===S;if(C())return;ss&&Qe&&$e&&Sn.current.add($e);const E=Object.assign(Object.assign({},fs()),{message:v,documentIds:h?g:[],uploadedModelImages:h?f:[],hasUploadedDocuments:h,isHidden:n,metadata:null!=I?I:null});un?(vs(),ne(E)):Cn.current=E,yt("streaming"),Nn.current=new AbortController;const T=[];let _=[...null!=Pt?Pt:[]],A=0,P=!1,D="";for(;!P;)try{const e=yield fetch(`${process.env.NEXT_PUBLIC_PICKAXE_API2_URL}/response/stream/${S}?index=${A}`,{signal:null===(p=Nn.current)||void 0===p?void 0:p.signal,headers:{"Cache-Control":"no-cache",Connection:"keep-alive"}});if(!e.body)throw new Error("No response body");const t=e.body.getReader();yn.current=t;const n=new TextDecoder,s=U({onEvent:e=>{var t,n;if(C())P=!0;else if(e.event&&"ping"!==e.event&&A++,"stop"!==e.event){if("error"===e.event){const t=JSON.parse(e.data);if(t.limitData)return xt(t.limitData),jt(""),void(P=!0);const n=t.error||t.message||(null==qe?void 0:qe["something-went-wrong"])||"Something went wrong.";return rs(t)||jt(n),void(P=!0)}if("delta"===e.event){const s=JSON.parse(e.data);if("finish"===s.type)return void Qt(!0);if("data-error"===s.type&&he){const e=s.data.error;if("string"==typeof e){const t=/['"]type['"]\s*:\s*['"]unauthorized_smithery['"]/.test(e),n=/['"]type['"]\s*:\s*['"]unauthorized_composio['"]/.test(e);if(t){const t=e.match(/['"]qualifiedName['"]\s*:\s*['"]([^'"]+)['"]/),n=e.match(/['"]serverId['"]\s*:\s*['"]([^'"]+)['"]/),s=e.match(/['"]name['"]\s*:\s*['"]([^'"]+)['"]/);if(t&&t[1]&&n&&n[1]&&s&&s[1])throw P=!0,he({provider:"smithery",smitheryId:t[1],serverId:n[1],name:s[1]}),new Error("STOP_STREAM")}else if(n){const t=e.match(/['"]toolkitSlug['"]\s*:\s*['"]([^'"]+)['"]/),n=e.match(/['"]serverId['"]\s*:\s*['"]([^'"]+)['"]/),s=e.match(/['"]name['"]\s*:\s*['"]([^'"]+)['"]/);if(t&&t[1]&&n&&n[1]&&s&&s[1])throw P=!0,he({provider:"composio",toolkitSlug:t[1],serverId:n[1],name:s[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 P=!0,he({provider:"smithery",smitheryId:t.qualifiedName,serverId:t.serverId,name:t.name}),new Error("STOP_STREAM");if("unauthorized_composio"===t.type&&t.toolkitSlug&&t.serverId&&t.name)throw P=!0,he({provider:"composio",toolkitSlug:t.toolkitSlug,serverId:t.serverId,name:t.name}),new Error("STOP_STREAM")}}else if("text-start"===s.type)D="",T.push({type:"text",content:"",isVisible:null===(t=s.isVisible)||void 0===t||t});else if("text-delta"===s.type)D+=s.delta,l(T,"text",D);else if("text-end"===s.type)D="";else if("reasoning-start"===s.type)D="",T.push({type:"reasoning",content:"",isVisible:null===(n=s.isVisible)||void 0===n||n});else if("reasoning-delta"===s.type)D+=s.delta,l(T,"reasoning",D);else if("reasoning-end"===s.type)D="";else if(s.type.startsWith("data-")){const e=s;"data-action-approval"===e.type?d(T,e.data):T.push({type:e.type,content:JSON.stringify(e.data),isVisible:!0})}wn.current=de(T);const o=de(T);bt((e=>{const t=e.findIndex((e=>e.id===x)),n=Object.assign(Object.assign({},j),{parts:o});return-1===t?[...e,n]:e.map(((e,s)=>s===t?n:e))}))}else if("artifact_created"===e.event){const t=JSON.parse(e.data);_=_.filter((e=>!(e.id===t.id&&e.version===t.version))),_.push(Object.assign(Object.assign({},t),{content:"",status:"streaming"})),Lt([..._]),Dt.startsWith("inline")||Mt({id:t.id,version:t.version})}else if("artifact_updated"===e.event){const t=JSON.parse(e.data);_=_.filter((e=>!(e.id===t.id&&e.version===t.version))),_.push(Object.assign(Object.assign({},t),{content:"",status:"updating"})),Lt(_),Dt.startsWith("inline")||Mt({id:t.id,version:t.version})}else if("artifact_rewrite"===e.event){const t=JSON.parse(e.data);_=_.filter((e=>!(e.id===t.id&&e.version===t.version))),_.push(Object.assign(Object.assign({},t),{content:"",status:"streaming"})),Lt(_),Dt.startsWith("inline")||Mt({id:t.id,version:t.version})}else if("artifact_content"===e.event){const t=JSON.parse(e.data),n=t.token.replace(/\u200B/g,"");_=_.map((e=>e.id===t.id&&e.version===t.version?Object.assign(Object.assign({},e),{content:e.content+n,status:"streaming"}):e)),Lt(_)}else if("artifact_finished"===e.event){const t=JSON.parse(e.data);Lt(_.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);if(t.limitData)return xt(t.limitData),jt(""),void(P=!0);const n=t.error||t.message||(null==qe?void 0:qe["something-went-wrong-try-again"])||"Something went wrong, please try again.";if(rs(t))return void(P=!0);jt(n)}else"stop"===e.event&&(P=!0)}else P=!0}});for(;;){if(C()){P=!0,t.cancel().catch((()=>{}));break}const{value:e,done:o}=yield t.read();if(C()){P=!0,t.cancel().catch((()=>{}));break}if(o)break;s.feed(n.decode(e))}P||C()||(yield new Promise((e=>setTimeout(e,1e3))))}catch(e){if("STOP_STREAM"===e.message||ce(e)||C())return void(P=!0);console.warn("Stream connection lost, retrying...",e),yield new Promise((e=>setTimeout(e,1e3)))}null==dt||dt($e)}catch(e){if(ce(e))return;if(e.limitData)xt(e.limitData),jt("");else{let t=H(e)||"";t&&!t.includes("Unexpected token 'A',")||(t=(null==qe?void 0:qe["high-traffic-try-again-later"])||"Oops! We're experiencing high traffic at the moment. Please try again later."),rs(t)||jt(t)}}finally{const e=!m||xn.current===m;At(),e&&(yt("idle"),Ut(),yn.current=null),m&&e&&(xn.current=null,wn.current=[]),yield ds()}}));return g((()=>{if(ht||qt||en||0===Yt.length)return;const e=Yt[0];tn(!0),sn(e.id),t(void 0,void 0,void 0,(function*(){try{if(!(yield Ms(e.predecessorSubmissionId)))return void jt((null==qe?void 0:qe["queued-message-waiting"])||"A queued message is waiting for the previous response to finish.");Zt((t=>t.filter((t=>t.id!==e.id)))),yield $s(e.message,!1,!0,e.id)}finally{tn(!1),sn(null)}}))}),[ht,en,qt,Yt]),is?null:n("div",Object.assign({className:J("flex w-full flex-shrink-0 flex-col items-center",!os&&"px-4 pb-8"),dir:Ye?"rtl":"ltr"},{children:s("div",Object.assign({className:"flex w-full max-w-[800px] flex-col"},{children:[Yt.length>0&&n("div",Object.assign({className:"mx-3 -mb-3 overflow-hidden border pb-3",style:{borderColor:We.text+"18",backgroundColor:null!==(Pe=Jn.backgroundColor)&&void 0!==Pe?Pe:We.text+"08",color:We.text,borderTopLeftRadius:Math.max(He.cornerRadius-4,12),borderTopRightRadius:Math.max(He.cornerRadius-4,12)}},{children:Yt.map(((e,i)=>{var r;return s("div",Object.assign({className:"flex min-h-10 items-center gap-2 px-3 py-2",style:i<Yt.length-1?{borderBottom:`1px solid ${We.text}12`}:void 0},{children:[n(L,{className:"h-4 w-4 shrink-0 opacity-50","aria-hidden":"true"}),n("span",Object.assign({className:"min-w-0 flex-1 truncate text-sm",title:e.message},{children:e.message})),on===e.id||nn===e.id?s("span",Object.assign({className:"flex shrink-0 items-center gap-1.5 px-2 py-1 text-xs opacity-60","aria-live":"polite"},{children:[n("span",{className:"h-3 w-3 animate-spin rounded-full border border-current border-r-transparent","aria-hidden":"true"}),on===e.id?(null==qe?void 0:qe.steering)||"Steering...":(null==qe?void 0:qe.starting)||"Starting..."]})):s(o,{children:[s("button",Object.assign({type:"button",className:"shrink-0 rounded-md px-2 py-1 text-xs font-medium opacity-70 transition-opacity hover:opacity-100 disabled:cursor-default disabled:opacity-40",disabled:qt||!ht,onClick:()=>{(e=>{t(void 0,void 0,void 0,(function*(){const t=xn.current;if(!t||qt)return;const n=Yt.findIndex((t=>t.id===e.id));if(-1===n)return;Jt(!0),rn(e.id),jt(""),Ls(t);let s=!1;try{if(!(yield Ds(t)))throw new Error((null==qe?void 0:qe["failed-to-interrupt-current-response"])||"Failed to interrupt the current response.");if(!(yield Ms(t)))throw new Error((null==qe?void 0:qe["current-response-still-stopping"])||"The current response is still stopping. Please send your message again in a moment.");yt("idle"),Zt((t=>t.filter((t=>t.id!==e.id)))),s=!0,Jt(!1),rn(null),yield $s(e.message,!1,!0,e.id,!0)}catch(t){yt("idle"),s&&Zt((t=>{if(t.some((t=>t.id===e.id)))return t;const s=[...t];return s.splice(n,0,e),s})),jt(H(t))}finally{Jt(!1),rn(null)}}))})(e)},"aria-label":`${(null==qe?void 0:qe["steer-with"])||"Steer with"}: ${e.message}`},{children:[n("span",Object.assign({"aria-hidden":"true"},{children:"↳ "})),(null==qe?void 0:qe.steer)||"Steer"]})),n("button",Object.assign({type:"button",className:"flex h-7 w-7 shrink-0 items-center justify-center rounded-md opacity-50 transition-opacity hover:opacity-100 disabled:cursor-default disabled:opacity-30",disabled:qt,onClick:()=>{return t=e.id,void Zt((e=>re(e,t)));var t},"aria-label":`${(null==qe?void 0:qe["remove-queued-message"])||"Remove queued message"}: ${e.message}`},{children:n(R,{className:"h-4 w-4","aria-hidden":"true"})})),s(F,Object.assign({id:`queued-message-menu-${e.id}`,className:"shrink-0"},{children:[n(G,Object.assign({className:"flex h-7 w-7 items-center justify-center rounded-md opacity-50 transition-opacity hover:opacity-100",isDisabled:qt,role:"button",tabIndex:qt?-1:0,"aria-haspopup":"menu","aria-label":(null==qe?void 0:qe["more-options"])||"More options",onKeyDown:e=>{"Enter"!==e.key&&" "!==e.key||(e.preventDefault(),e.currentTarget.click())}},{children:s("svg",Object.assign({viewBox:"0 0 24 24",className:"h-4 w-4",fill:"currentColor","aria-hidden":"true"},{children:[n("circle",{cx:"5",cy:"12",r:"1.6"}),n("circle",{cx:"12",cy:"12",r:"1.6"}),n("circle",{cx:"19",cy:"12",r:"1.6"})]}))})),n(V,Object.assign({role:"menu",align:Ye?"bottom-start":"bottom-end",positionStrategy:Ze?"absolute":"fixed",width:"auto",className:"p-1 text-sm shadow-xl",style:{backgroundColor:null!==(r=Jn.backgroundColor)&&void 0!==r?r:We.primary,color:We.text,borderRadius:"12px"},border:`1px solid ${We.text}20`},{children:s("button",Object.assign({type:"button",role:"menuitem",className:"flex min-w-36 items-center gap-2 rounded-lg px-3 py-2 text-left transition-colors hover:bg-black/5 dark:hover:bg-white/10",onClick:()=>(e=>{Zt((t=>re(t,e.id))),Xt(e.message),requestAnimationFrame((()=>{const t=In.current;t&&(t.focus(),t.setSelectionRange(e.message.length,e.message.length))}))})(e)},{children:[n($,{className:"h-4 w-4 shrink-0"}),(null==qe?void 0:qe["edit-message"])||"Edit message"]}))}))]}))]})]}),e.id)}))})),s("div",Object.assign({ref:On,className:J("relative z-10 flex flex-col w-full justify-end gap-y-3 py-[3px]","block"===He.formFieldStyle&&"shadow"),style:Object.assign(Object.assign({},Jn),{maxHeight:`${En}px`,overflowY:"auto"})},{children:[Ss&&s("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:Jn.backgroundColor?`${Jn.backgroundColor}E6`:void 0,borderColor:We.text+"20",color:We.text,borderTopRightRadius:He.cornerRadius+"px",borderTopLeftRadius:He.cornerRadius+"px"}},{children:[n("div",Object.assign({className:"flex items-center gap-2 text-sm font-medium"},{children:s("span",{children:[ws.toLocaleString()," ",ps?(null==qe?void 0:qe.credits)||"Credits":(null==qe?void 0:qe.uses)||"Uses"," ",(null==qe?void 0:qe.remaining)||"remaining"]})})),s("div",Object.assign({className:"flex items-center gap-3"},{children:[Es&&n("button",Object.assign({className:"rounded-md px-3 py-1.5 text-xs font-semibold transition-opacity hover:opacity-90",style:{backgroundColor:We.accent,color:We.accentText},onClick:e=>{if(e.preventDefault(),e.stopPropagation(),Ts)return void window.open(Ts,"_blank","noopener,noreferrer");if(lt)return void lt();const t=z({baseUrl:dn,accessGroupId:null==tt?void 0:tt.accessGroupId});t&&Q({deploymentId:Fe,pricingUrl:t,studioId:null==Ve?void 0:Ve.studioid,studioSessionToken:pt})}},{children:_s})),n("button",Object.assign({className:"flex h-6 w-6 items-center justify-center rounded-full opacity-60 transition-opacity hover:opacity-100",onClick:()=>gn(!0)},{children:n("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:n("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M6 18L18 6M6 6l12 12"})}))}))]}))]})),!ht&&It.length>0&&n(B,{className:"p-4 pb-0",isDisabled:ht}),s("div",Object.assign({className:"relative flex w-full flex-col"},{children:[ns&&s("div",Object.assign({className:J(ut?"top-6":"top-1/2","pointer-events-none absolute z-10 flex -translate-y-1/2 select-none items-center gap-x-2",Ye?"right-4":"left-4")},{children:[n("span",{className:"h-2 w-2 animate-pulse rounded-full bg-c-secondary",style:{backgroundColor:null!==(De=We.accent)&&void 0!==De?De:"#ff0000"}}),n("span",Object.assign({className:"text-sm text-c-secondary font-semilight",style:{color:We.text+"90"}},{children:(null==qe?void 0:qe.listening)||"Listening..."}))]})),n(X,Object.assign({ref:In,className:J(qn.i1,"py-3.5 max-h-60 px-4 w-full border-transparent bg-transparent",!Bt.trim()&&!Bt.includes("\n")&&"overflow-hidden text-ellipsis whitespace-nowrap placeholder:whitespace-normal placeholder:overflow-visible",Ye?"text-right":"text-left",!ut&&ls&&"mb-12"),value:Bt,placeholder:ns?"":as,onChange:e=>{Xt(e)},onKeyDown:e=>{ze||Tt||"Enter"===e.key&&(e.shiftKey||(e.preventDefault(),kt||qt||(ht?Rs():$s())))},onPaste:e=>t(void 0,void 0,void 0,(function*(){const t=Array.from(e.clipboardData.files||[]);if(t.length>0){if(!es)return;e.preventDefault(),nt(!1),yield Nt(t)}}))},ue&&{onFocus:ue},fe&&{onBlur:fe},{dir:Ye?"rtl":"ltr"})),s("div",Object.assign({ref:kn,className:ut?"relative flex w-full items-center gap-2 px-3 pb-2 [&>button]:shrink-0 [&>button]:mr-0":J("flex items-center gap-2 absolute z-2 transition-all duration-200 ease-in-out",ls?"bottom-3 right-2":"right-0 top-1/2 -translate-y-1/2"),style:Object.assign(Object.assign({},!ls&&Jn.backgroundColor&&{backgroundColor:Jn.backgroundColor}),{borderTopRightRadius:He.cornerRadius+"px",borderBottomRightRadius:He.cornerRadius+"px"})},{children:[!ht&&!_n&&es&&s("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:Fn?We.accent+"10":void 0,color:Fn?We.accent:We.accent+"80"},disabled:kt||ht,"aria-label":null!==(Le=null==qe?void 0:qe["attach-files"])&&void 0!==Le?Le:"Attach files",onClick:()=>{var e;return null===(e=hn.current)||void 0===e?void 0:e.click()}},Gn,{children:[n("input",{id:"file-upload",ref:hn,type:"file",accept:[...E,...T,..._].join(", "),multiple:!0,hidden:!0,className:"hidden",onChange:e=>t(void 0,void 0,void 0,(function*(){nt(!1),yield Nt(Array.from(e.target.files||[])),e.target.value=""}))}),n(A,{className:"h-6 w-6 shrink-0"})]})),n(a,{compact:!0}),s(o,ht&&!zt?{children:[(_n||Un)&&n("button",Object.assign({"aria-label":(null==qe?void 0:qe["stop-listening"])||"Stop listening",title:(null==qe?void 0:qe["stop-listening"])||"Stop listening",className:"flex h-8 w-8 items-center justify-center rounded-full outline-none transition-colors duration-200 ease-in-out",onClick:()=>{Rn()},disabled:Un,style:{backgroundColor:We.accent,color:We.accentText}},{children:n(D,{className:"h-5 w-5 shrink-0"})})),n("button",Object.assign({"aria-label":(null==qe?void 0:qe["stop-response"])||"Stop response",className:"flex h-8 w-8 items-center justify-center rounded-full outline-none transition-colors duration-200 ease-in-out",onClick:()=>{const e=xn.current;e&&(Ls(e),Ds(e)),yt("idle")},style:{backgroundColor:We.accent+"10",color:We.accent}},{children:n(M,{className:"h-4 w-4 shrink-0"})})),n("button",Object.assign({"aria-label":(null==qe?void 0:qe["queue-message"])||"Queue message",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",disabled:qt||kt||!Bt.trim(),onClick:Rs,style:{backgroundColor:Bt.trim()?We.accent:We.accent+"10",color:Bt.trim()?We.accentText:We.accent+"80"}},{children:n(P,{className:J("h-6 w-6 shrink-0",Ye&&"scale-x-[-1] transform")})}))]}:_n||Un?{children:[n("button",Object.assign({"aria-label":(null==qe?void 0:qe["stop-listening"])||"Stop listening",className:"flex h-8 w-8 items-center mr-2 justify-center rounded-full outline-none transition-colors duration-200 ease-in-out",onClick:()=>{Rn()},disabled:Un,style:{backgroundColor:We.accent,color:We.accentText}},{children:n(M,{className:"h-4 w-4 shrink-0"})})),Bt.trim()&&n("button",Object.assign({"aria-label":(null==qe?void 0:qe["send-message"])||"Send message",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",disabled:!As,onClick:()=>{$s()},style:{backgroundColor:We.accent,color:We.accentText}},{children:n(P,{className:J("h-6 w-6 shrink-0",Ye&&"scale-x-[-1] transform")})}))]}:{children:[ts&&n("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:_n?We.accent:Hn?We.accent+"10":void 0,color:_n?We.accentText:Hn?We.accent:We.accent+"80"},disabled:kt||ht||Un,onClick:()=>{_n?Rn():(Ft(null),bn.current=Bt,Mn(Je||"en-US"))}},Wn,{children:n(D,{className:"h-5 w-5 shrink-0"})})),n("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:Bn||As?We.accent:We.accent+"10",color:Bn||As?We.accentText:We.accent+"80"},disabled:!As,onClick:()=>$s()},Xn,{children:n(P,{className:J("h-6 w-6 shrink-0",Ye&&"scale-x-[-1] transform")})}))]})]}))]}))]})),Ot&&n(K,{error:Ot,className:"mt-3"})]}))}))}));fe.displayName="Input";export{fe as default};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{__awaiter as e}from"../../../_virtual/_tslib.js";import{jsxs as t,jsx as o,Fragment as i}from"react/jsx-runtime";import{canChat as n}from"../../../common/canChat.js";import{useState as s,useRef as r,useEffect as a,useCallback as l}from"react";import{usePickaxeContext as c}from"../../../hooks/pickaxe/usePickaxeContext.js";import{useAuthContext as d}from"../Addons/Auth/hooks/useAuthContext.js";import{useDimensionContext as m}from"../../../hooks/pickaxe/useDimensionContext.js";import{useDocument as u}from"../Addons/Document/hooks/useDocument.js";import{
|
|
1
|
+
import{__awaiter as e}from"../../../_virtual/_tslib.js";import{jsxs as t,jsx as o,Fragment as i}from"react/jsx-runtime";import{canChat as n}from"../../../common/canChat.js";import{useState as s,useRef as r,useEffect as a,useCallback as l}from"react";import{usePickaxeContext as c}from"../../../hooks/pickaxe/usePickaxeContext.js";import{useAuthContext as d}from"../Addons/Auth/hooks/useAuthContext.js";import{useDimensionContext as m}from"../../../hooks/pickaxe/useDimensionContext.js";import{useDocument as u}from"../Addons/Document/hooks/useDocument.js";import{useScroll as p}from"../Addons/Scroll/hooks/useScroll.js";import{useStyleFontSize as f}from"../../../hooks/studio/useStyleFontSize.js";import h from"../../../hooks/core/useScrollToBottomVisibility.js";import v from"./History/index.js";import g from"./Input.js";import b from"../../Icons/attach-vertical.svg.js";import x from"../../../common/cn.js";import{pickaxeApi2 as j}from"../../../common/api/pickaxe.js";import{v4 as k}from"uuid";import{StudioTip as y}from"../../Core/StudioTip.js";import w from"../common/ScrollToBottomButton.js";import I from"../common/PickaxeMCPButton.js";import{useResponseContext as D}from"../../../hooks/pickaxe/useResponseContext.js";import{NavPill as S,EditableNavPill as C,HistoryPill as T}from"../Addons/Navbar/NavPill.js";import N from"../../Icons/history.svg.js";const O=()=>{var O,A;const{deploymentType:P,isNewChat:F,setIsNewChat:B,sessionId:z,setSessionId:E,setLastSessionId:H,pickaxeId:R,sender:G,pickaxe:L,styles:V,isEmbed:_,mcpEnabled:M,translations:U}=c(),{isSent:W,token:q}=d(),{width:J,height:K,setDimension:Q}=m(),{setDocuments:X,onFileUpload:Y}=u(),{scrollContainerRef:Z,scrollToBottom:$}=p({listen:!1}),{isGenerating:ee,messages:te}=D(),oe=f(),[ie,ne]=s(0),[se,re]=s(!1),[ae,le]=s(!1),ce=r(null),de=r(null),me=r(0),[ue,pe]=s(null),[fe,he]=s(!1),ve=(null==U?void 0:U["new-chat"])||"New chat",ge=n(L),be=ge&&"chat-input"===P&&F&&!W,xe=ge&&null!==(A=null===(O=null==L?void 0:L.documentuploadtype)||void 0===O?void 0:O.startsWith("enduserupload"))&&void 0!==A&&A,{hasScrollableContent:je,isNearBottom:ke}=h(Z,{},[be]);a((()=>()=>{X([])}),[]);const ye=l((()=>{if(!R||!G&&!q)return;const t=(o=0)=>e(void 0,void 0,void 0,(function*(){var e;try{const t=yield j.post("/conversation/title",Object.assign({sessionId:z},q?{studioSessionToken:q}:G?{userId:G}:{}));if(t.data&&t.data.success){const e=t.data.title;if(e&&"Conversation Title"!==e)return void Ie(e)}else console.error("Failed to load conversation:",null===(e=t.data)||void 0===e?void 0:e.error)}catch(e){console.error("Error fetching conversation:",e)}o<20&&setTimeout((()=>t(o+1)),3e3)}));t()}),[R,G,z,q]);a((()=>{ee||F||!z||ye()}),[ee,F,z,ye]),a((()=>{if(!ce.current)return;const e=new ResizeObserver((e=>{for(const t of e){const{width:e,height:o}=t.contentRect;Q(parseInt(e.toFixed(0)),parseInt(o.toFixed(0)))}}));return e.observe(ce.current),()=>{e.disconnect()}}),[Q]);const[we,Ie]=s(ve),De=(null==L?void 0:L.formtitle)||"Pickaxe",Se=(null==L?void 0:L.coverphoto)||void 0,[Ce,Te]=s(!1);a((()=>{const e=!be&&!_&&V.portalTheme&&(te.filter((e=>"user"===e.role)).length>0||se||!F);Te(null!=e&&e)}),[be,_,se,F,te,V.portalTheme]);const Ne=l((()=>{$({force:!0,behavior:"auto"})}),[$]);return t("div",Object.assign({ref:ce,className:"relative flex h-full w-full flex-col items-center overflow-hidden",onDragEnter:e=>{e.preventDefault(),e.stopPropagation(),xe&&(me.current+=1,e.dataTransfer.items&&e.dataTransfer.items.length>0&&le(!0))},onDragLeave:e=>{e.preventDefault(),e.stopPropagation(),xe&&(me.current-=1,0===me.current&&le(!1))},onDragOver:e=>{e.preventDefault(),e.stopPropagation()},onDrop:t=>e(void 0,void 0,void 0,(function*(){if(t.preventDefault(),t.stopPropagation(),le(!1),me.current=0,!xe)return;const e=Array.from(t.dataTransfer.files||[]);e.length>0&&(B(!1),yield Y(e))}))},{children:[ae&&t("div",Object.assign({className:"absolute inset-0 z-50 flex flex-col items-center justify-center rounded-lg bg-white/80 backdrop-blur-sm transition-all duration-300"},{children:[o("div",Object.assign({className:"flex h-24 w-24 items-center justify-center rounded-full bg-white shadow-lg animate-bounce text-black"},{children:o(b,{className:"h-10 w-10"})})),o("h3",Object.assign({className:x(oe.h3,"mt-6 font-semibold text-c-primary text-black")},{children:(null==U?void 0:U["drop-files-to-upload"])||"Drop files to upload"})),o("p",Object.assign({className:x(oe.b2,"mt-2 opacity-60 text-black")},{children:(null==U?void 0:U["add-anything-to-the-conversation"])||"Add anything to the conversation"}))]})),!_&&M?o("div",Object.assign({className:"pointer-events-none absolute left-1/2 top-4 z-40 flex w-full max-w-[800px] -translate-x-1/2 justify-end px-4"},{children:o("div",Object.assign({className:"pointer-events-auto"},{children:o(I,{})}))})):null,be?o(g,{}):t(i,{children:[Ce&&t("div",Object.assign({className:x("direct-link"===P?"absolute top-4 left-4 md:top-6 md:left-6 z-40 flex items-center gap-2 animate-in fade-in slide-in-from-top-4 duration-500":"w-full max-w-3xl mt-6 px-4 md:px-0 flex justify-start z-30 mb-4 animate-in fade-in slide-in-from-top-4 duration-500 gap-2","dark"===V.portalTheme?"glass-dark ":"")},{children:[o(S,{text:De,icon:Se}),F||we===ve?o(S,{text:we}):o(C,{text:we,sessionId:z,onRename:t=>e(void 0,void 0,void 0,(function*(){if(z)try{yield j.patch("/conversation/title",Object.assign({sessionId:z,name:t},q?{studioSessionToken:q}:G?{userId:G}:{})),Ie(t)}catch(e){console.error("Error renaming chat:",e),alert((null==U?void 0:U["failed-rename-chat"])||"Failed to rename chat.")}})),onDelete:()=>e(void 0,void 0,void 0,(function*(){if(z&&window.confirm((null==U?void 0:U["delete-confirm"])||"Are you sure you want to delete this conversation?"))try{yield j.delete("/conversation",{data:Object.assign({sessionId:z},q?{studioSessionToken:q}:G?{userId:G}:{})}),B(!0),E(ge?k():""),Ie(ve)}catch(e){console.error("Error deleting chat:",e),alert((null==U?void 0:U["failed-delete-chat"])||"Failed to delete chat.")}})),isDarkGlass:"dark"===V.portalTheme}),o(y,Object.assign({content:U["chat-history"]||"Chat History",align:"bottom",containerClassName:"inline-flex shrink-0"},{children:o(T,{icon:o(N,{}),onClick:()=>{E(""),H(z)}})}))]})),o(v,{additionalScrollHeight:ie,isForceHideInfo:K<=545||J<=350||se,isInputFocused:se,onSubmit:t=>e(void 0,void 0,void 0,(function*(){ge&&de.current&&de.current.onSubmit(t)})),smitheryAuthData:ue,resubmitPrompt:()=>{pe(null),he(!0)}}),o(w,{isVisible:je&&!ke,bottom:ie+65,onClick:Ne}),ge&&o(g,{ref:de,onFocus:()=>re(!0),onBlur:()=>re(!1),onInputHeightChange:ne,initSmitheryAuthData:e=>pe(e),resubmitPrompt:fe})]})]}))};export{O as default};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{__awaiter as e}from"../../_virtual/_tslib.js";import{useState as t,useRef as r,useEffect as o}from"react";import{pickaxeApi2 as
|
|
1
|
+
import{__awaiter as e}from"../../_virtual/_tslib.js";import{useState as t,useRef as r,useCallback as n,useEffect as o}from"react";import{pickaxeApi2 as s}from"../../common/api/pickaxe.js";import{getUnconsumedSpeech as c,consumeSpeechTurn as i}from"../../common/speechTranscript.js";const a=e=>{var t,r;for(const n of null!==(r=null===(t=null==e?void 0:e.stream)||void 0===t?void 0:t.getTracks())&&void 0!==r?r:[])n.stop();(null==e?void 0:e.audioContext)&&"closed"!==e.audioContext.state&&e.audioContext.close()},u=()=>{if("undefined"!=typeof window)return window.AudioContext||window.webkitAudioContext},l=e=>{var t,r;e.processor&&(e.processor.onaudioprocess=null,e.processor.disconnect()),null===(t=e.source)||void 0===t||t.disconnect(),null===(r=e.silentGain)||void 0===r||r.disconnect(),e.processor=void 0,e.source=void 0,e.silentGain=void 0;for(const t of e.stream.getTracks())t.stop();"closed"!==e.audioContext.state&&e.audioContext.close()},d=()=>{var d;const[m,p]=t(""),[f,v]=t(0),[w,y]=t(!1),[g,h]=t(!1),k=r(!0),S=r(0),C=r(null),b=r(null),x=r(new Map),A=r(new Map),T=r(-1),M=r(""),E=r(0),P=n((()=>M.current),[]),I=n((()=>({sessionId:E.current,text:M.current,turns:new Map(x.current)})),[]),N=n((()=>Array.from(x.current.entries()).sort((([e],[t])=>e-t)).map((([e,t])=>{const r=A.current.get(e);return!r&&e<=T.current?"":c(t,r)})).filter(Boolean).join(" ").trim()),[]),O=n((e=>{if(e&&e.sessionId===E.current){const t=T.current;for(const[r,n]of e.turns)r<=t&&!A.current.has(r)||(A.current.set(r,i(n,A.current.get(r))),T.current=Math.max(T.current,r))}const t=N();M.current=t,p(t),v((e=>e+1))}),[N]),W=e=>{l(e),e.socket.readyState!==WebSocket.OPEN&&e.socket.readyState!==WebSocket.CONNECTING||e.socket.close(),C.current===e&&(C.current=null)};o((()=>(k.current=!0,()=>{k.current=!1,S.current+=1,a(b.current),b.current=null;const e=C.current;e&&(e.socket.readyState===WebSocket.OPEN&&e.socket.send(JSON.stringify({type:"Terminate"})),W(e))})),[]);return{speechTranscript:m,speechTranscriptRevision:f,getSpeechTranscript:P,getSpeechTranscriptSnapshot:I,resetSpeechTranscript:O,isSpeechSupported:"undefined"!=typeof window&&Boolean(u())&&Boolean(null===(d=navigator.mediaDevices)||void 0===d?void 0:d.getUserMedia)&&"WebSocket"in window,isSpeechProcessing:g,isSpeechListening:w,onStartListening:t=>e(void 0,void 0,void 0,(function*(){var e;const t=++S.current,r=u();if(!r||!(null===(e=navigator.mediaDevices)||void 0===e?void 0:e.getUserMedia))return;const n=C.current;n&&W(n),a(b.current);const o={};let c;b.current=o;try{if(E.current+=1,h(!0),y(!1),p(""),M.current="",x.current.clear(),A.current.clear(),T.current=-1,o.stream=yield navigator.mediaDevices.getUserMedia({audio:{autoGainControl:!0,channelCount:1,echoCancellation:!0,noiseSuppression:!0}}),!k.current||t!==S.current)return;o.audioContext=new r;const{data:e}=yield s.post("/speech/assemblyai");if(!k.current||t!==S.current)return;if(!e.success||!e.token)throw new Error(e.error||"AssemblyAI streaming token was not returned");const n=new URL("wss://streaming.assemblyai.com/v3/ws");n.searchParams.set("sample_rate",String(16e3)),n.searchParams.set("speech_model","whisper-rt"),n.searchParams.set("language_detection","true"),n.searchParams.set("format_turns","true"),n.searchParams.set("token",e.token),c={socket:new WebSocket(n),stream:o.stream,audioContext:o.audioContext,started:!1},o.stream=void 0,o.audioContext=void 0,b.current=null,C.current=c;const i=c;yield new Promise(((e,r)=>{const n=window.setTimeout((()=>{r(new Error("AssemblyAI streaming session timed out"))}),1e4),o=e=>{s.started||(window.clearTimeout(n),r(e))},s=i;s.socket.binaryType="arraybuffer",s.socket.onmessage=r=>{if(C.current===s&&k.current&&(s.started||t===S.current))try{const o=JSON.parse(String(r.data));if("Begin"!==o.type||s.started){if("Turn"===o.type)(e=>{var t;const r=(e=>{var t,r;const n=null===(t=e.transcript)||void 0===t?void 0:t.trim();if(n)return n;const o=null===(r=e.utterance)||void 0===r?void 0:r.trim();return o&&!/^(?:\[[^\]]+\]\s*)+$/.test(o)?o:""})(e),n=null!==(t=e.turn_order)&&void 0!==t?t:0;r?x.current.set(n,{text:r,words:e.words}):x.current.delete(n);const o=N();k.current&&(M.current=o,p(o))})(o);else if("Termination"===o.type)s.socket.close();else if("Error"===o.type)throw new Error(o.error||"AssemblyAI streaming failed")}else{s.started=!0,window.clearTimeout(n);const r=s.audioContext.createMediaStreamSource(s.stream),o=s.audioContext.createScriptProcessor(4096,1,1),c=s.audioContext.createGain();c.gain.value=0,o.onaudioprocess=({inputBuffer:e})=>{if(s.socket.readyState!==WebSocket.OPEN)return;const t=((e,t)=>{const r=t/16e3,n=Math.max(1,Math.round(e.length/r)),o=new Int16Array(n);let s=0;for(let t=0;t<n;t+=1){const n=Math.min(e.length,Math.round((t+1)*r));let c=0,i=0;for(;s<n;s+=1)c+=e[s],i+=1;const a=Math.max(-1,Math.min(1,i?c/i:0));o[t]=a<0?32768*a:32767*a}return o})(e.getChannelData(0),e.sampleRate);s.socket.send(t.buffer)},r.connect(o),o.connect(c),c.connect(s.audioContext.destination),s.source=r,s.processor=o,s.silentGain=c,s.audioContext.resume(),k.current&&t===S.current&&y(!0),e()}}catch(e){console.error("Could not process AssemblyAI message",e),o(e instanceof Error?e:new Error(String(e))),s.socket.close()}},s.socket.onerror=()=>{const e=new Error("Could not connect to AssemblyAI streaming");o(e),s.started&&console.error(e),s.socket.close()},s.socket.onclose=()=>{o(new Error("AssemblyAI streaming closed before it started")),(e=>{l(e),C.current===e&&(C.current=null,k.current&&y(!1))})(s)}})),k.current&&t===S.current||W(c)}catch(e){c&&C.current===c&&W(c),k.current&&t===S.current&&console.error("Could not start AssemblyAI speech recognition",e)}finally{a(o),b.current===o&&(b.current=null),k.current&&t===S.current&&h(!1)}})),onStopListening:()=>e(void 0,void 0,void 0,(function*(){const e=++S.current;a(b.current),b.current=null;const t=C.current;if(!t)return y(!1),void h(!1);try{h(!0),l(t),yield new Promise((e=>{const r=window.setTimeout(e,2e3),n=t.socket.onclose;t.socket.onclose=o=>{window.clearTimeout(r),null==n||n.call(t.socket,o),e()},t.socket.readyState===WebSocket.OPEN?t.socket.send(JSON.stringify({type:"Terminate"})):e()}))}catch(e){console.error("Could not stop AssemblyAI speech recognition",e)}finally{W(t),k.current&&e===S.current&&(y(!1),h(!1))}}))}};export{d as useSpeechToText};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{commonjsGlobal as t}from"../../../../../_virtual/_commonjsHelpers.js";import{__module as e}from"../../../../../_virtual/cose-base2.js";import{__require as r}from"../../../layout-base@1.0.2/node_modules/layout-base/layout-base.js";var i;function o(){return i||(i=1,t=e,e.exports,o=function(t){return function(t){var e={};function r(i){if(e[i])return e[i].exports;var o=e[i]={i:i,l:!1,exports:{}};return t[i].call(o.exports,o,o.exports,r),o.l=!0,o.exports}return r.m=t,r.c=e,r.i=function(t){return t},r.d=function(t,e,i){r.o(t,e)||Object.defineProperty(t,e,{configurable:!1,enumerable:!0,get:i})},r.n=function(t){var e=t&&t.__esModule?function(){return t.default}:function(){return t};return r.d(e,"a",e),e},r.o=function(t,e){return Object.prototype.hasOwnProperty.call(t,e)},r.p="",r(r.s=7)}([function(e,r){e.exports=t},function(t,e,r){var i=r(0).FDLayoutConstants;function o(){}for(var n in i)o[n]=i[n];o.DEFAULT_USE_MULTI_LEVEL_SCALING=!1,o.DEFAULT_RADIAL_SEPARATION=i.DEFAULT_EDGE_LENGTH,o.DEFAULT_COMPONENT_SEPERATION=60,o.TILE=!0,o.TILING_PADDING_VERTICAL=10,o.TILING_PADDING_HORIZONTAL=10,o.TREE_REDUCTION_ON_INCREMENTAL=!1,t.exports=o},function(t,e,r){var i=r(0).FDLayoutEdge;function o(t,e,r){i.call(this,t,e,r)}for(var n in o.prototype=Object.create(i.prototype),i)o[n]=i[n];t.exports=o},function(t,e,r){var i=r(0).LGraph;function o(t,e,r){i.call(this,t,e,r)}for(var n in o.prototype=Object.create(i.prototype),i)o[n]=i[n];t.exports=o},function(t,e,r){var i=r(0).LGraphManager;function o(t){i.call(this,t)}for(var n in o.prototype=Object.create(i.prototype),i)o[n]=i[n];t.exports=o},function(t,e,r){var i=r(0).FDLayoutNode,o=r(0).IMath;function n(t,e,r,o){i.call(this,t,e,r,o)}for(var a in n.prototype=Object.create(i.prototype),i)n[a]=i[a];n.prototype.move=function(){var t=this.graphManager.getLayout();this.displacementX=t.coolingFactor*(this.springForceX+this.repulsionForceX+this.gravitationForceX)/this.noOfChildren,this.displacementY=t.coolingFactor*(this.springForceY+this.repulsionForceY+this.gravitationForceY)/this.noOfChildren,Math.abs(this.displacementX)>t.coolingFactor*t.maxNodeDisplacement&&(this.displacementX=t.coolingFactor*t.maxNodeDisplacement*o.sign(this.displacementX)),Math.abs(this.displacementY)>t.coolingFactor*t.maxNodeDisplacement&&(this.displacementY=t.coolingFactor*t.maxNodeDisplacement*o.sign(this.displacementY)),null==this.child||0==this.child.getNodes().length?this.moveBy(this.displacementX,this.displacementY):this.propogateDisplacementToChildren(this.displacementX,this.displacementY),t.totalDisplacement+=Math.abs(this.displacementX)+Math.abs(this.displacementY),this.springForceX=0,this.springForceY=0,this.repulsionForceX=0,this.repulsionForceY=0,this.gravitationForceX=0,this.gravitationForceY=0,this.displacementX=0,this.displacementY=0},n.prototype.propogateDisplacementToChildren=function(t,e){for(var r,i=this.getChild().getNodes(),o=0;o<i.length;o++)null==(r=i[o]).getChild()?(r.moveBy(t,e),r.displacementX+=t,r.displacementY+=e):r.propogateDisplacementToChildren(t,e)},n.prototype.setPred1=function(t){this.pred1=t},n.prototype.getPred1=function(){return pred1},n.prototype.getPred2=function(){return pred2},n.prototype.setNext=function(t){this.next=t},n.prototype.getNext=function(){return next},n.prototype.setProcessed=function(t){this.processed=t},n.prototype.isProcessed=function(){return processed},t.exports=n},function(t,e,r){var i=r(0).FDLayout,o=r(4),n=r(3),a=r(5),s=r(2),h=r(1),d=r(0).FDLayoutConstants,g=r(0).LayoutConstants,l=r(0).Point,p=r(0).PointD,c=r(0).Layout,u=r(0).Integer,f=r(0).IGeometry,v=r(0).LGraph,T=r(0).Transform;function E(){i.call(this),this.toBeTiled={}}for(var m in E.prototype=Object.create(i.prototype),i)E[m]=i[m];E.prototype.newGraphManager=function(){var t=new o(this);return this.graphManager=t,t},E.prototype.newGraph=function(t){return new n(null,this.graphManager,t)},E.prototype.newNode=function(t){return new a(this.graphManager,t)},E.prototype.newEdge=function(t){return new s(null,null,t)},E.prototype.initParameters=function(){i.prototype.initParameters.call(this,arguments),this.isSubLayout||(h.DEFAULT_EDGE_LENGTH<10?this.idealEdgeLength=10:this.idealEdgeLength=h.DEFAULT_EDGE_LENGTH,this.useSmartIdealEdgeLengthCalculation=h.DEFAULT_USE_SMART_IDEAL_EDGE_LENGTH_CALCULATION,this.springConstant=d.DEFAULT_SPRING_STRENGTH,this.repulsionConstant=d.DEFAULT_REPULSION_STRENGTH,this.gravityConstant=d.DEFAULT_GRAVITY_STRENGTH,this.compoundGravityConstant=d.DEFAULT_COMPOUND_GRAVITY_STRENGTH,this.gravityRangeFactor=d.DEFAULT_GRAVITY_RANGE_FACTOR,this.compoundGravityRangeFactor=d.DEFAULT_COMPOUND_GRAVITY_RANGE_FACTOR,this.prunedNodesAll=[],this.growTreeIterations=0,this.afterGrowthIterations=0,this.isTreeGrowing=!1,this.isGrowthFinished=!1,this.coolingCycle=0,this.maxCoolingCycle=this.maxIterations/d.CONVERGENCE_CHECK_PERIOD,this.finalTemperature=d.CONVERGENCE_CHECK_PERIOD/this.maxIterations,this.coolingAdjuster=1)},E.prototype.layout=function(){return g.DEFAULT_CREATE_BENDS_AS_NEEDED&&(this.createBendpoints(),this.graphManager.resetAllEdges()),this.level=0,this.classicLayout()},E.prototype.classicLayout=function(){if(this.nodesWithGravity=this.calculateNodesToApplyGravitationTo(),this.graphManager.setAllNodesToApplyGravitation(this.nodesWithGravity),this.calcNoOfChildrenForAllNodes(),this.graphManager.calcLowestCommonAncestors(),this.graphManager.calcInclusionTreeDepths(),this.graphManager.getRoot().calcEstimatedSize(),this.calcIdealEdgeLengths(),this.incremental)h.TREE_REDUCTION_ON_INCREMENTAL&&(this.reduceTrees(),this.graphManager.resetAllNodesToApplyGravitation(),e=new Set(this.getAllNodes()),r=this.nodesWithGravity.filter((function(t){return e.has(t)})),this.graphManager.setAllNodesToApplyGravitation(r));else{var t=this.getFlatForest();if(t.length>0)this.positionNodesRadially(t);else{this.reduceTrees(),this.graphManager.resetAllNodesToApplyGravitation();var e=new Set(this.getAllNodes()),r=this.nodesWithGravity.filter((function(t){return e.has(t)}));this.graphManager.setAllNodesToApplyGravitation(r),this.positionNodesRandomly()}}return this.initSpringEmbedder(),this.runSpringEmbedder(),!0},E.prototype.tick=function(){if(this.totalIterations++,this.totalIterations===this.maxIterations&&!this.isTreeGrowing&&!this.isGrowthFinished){if(!(this.prunedNodesAll.length>0))return!0;this.isTreeGrowing=!0}if(this.totalIterations%d.CONVERGENCE_CHECK_PERIOD==0&&!this.isTreeGrowing&&!this.isGrowthFinished){if(this.isConverged()){if(!(this.prunedNodesAll.length>0))return!0;this.isTreeGrowing=!0}this.coolingCycle++,0==this.layoutQuality?this.coolingAdjuster=this.coolingCycle:1==this.layoutQuality&&(this.coolingAdjuster=this.coolingCycle/3),this.coolingFactor=Math.max(this.initialCoolingFactor-Math.pow(this.coolingCycle,Math.log(100*(this.initialCoolingFactor-this.finalTemperature))/Math.log(this.maxCoolingCycle))/100*this.coolingAdjuster,this.finalTemperature),this.animationPeriod=Math.ceil(this.initialAnimationPeriod*Math.sqrt(this.coolingFactor))}if(this.isTreeGrowing){if(this.growTreeIterations%10==0)if(this.prunedNodesAll.length>0){this.graphManager.updateBounds(),this.updateGrid(),this.growTree(this.prunedNodesAll),this.graphManager.resetAllNodesToApplyGravitation();var t=new Set(this.getAllNodes()),e=this.nodesWithGravity.filter((function(e){return t.has(e)}));this.graphManager.setAllNodesToApplyGravitation(e),this.graphManager.updateBounds(),this.updateGrid(),this.coolingFactor=d.DEFAULT_COOLING_FACTOR_INCREMENTAL}else this.isTreeGrowing=!1,this.isGrowthFinished=!0;this.growTreeIterations++}if(this.isGrowthFinished){if(this.isConverged())return!0;this.afterGrowthIterations%10==0&&(this.graphManager.updateBounds(),this.updateGrid()),this.coolingFactor=d.DEFAULT_COOLING_FACTOR_INCREMENTAL*((100-this.afterGrowthIterations)/100),this.afterGrowthIterations++}var r=!this.isTreeGrowing&&!this.isGrowthFinished,i=this.growTreeIterations%10==1&&this.isTreeGrowing||this.afterGrowthIterations%10==1&&this.isGrowthFinished;return this.totalDisplacement=0,this.graphManager.updateBounds(),this.calcSpringForces(),this.calcRepulsionForces(r,i),this.calcGravitationalForces(),this.moveNodes(),this.animate(),!1},E.prototype.getPositionsData=function(){for(var t=this.graphManager.getAllNodes(),e={},r=0;r<t.length;r++){var i=t[r].rect,o=t[r].id;e[o]={id:o,x:i.getCenterX(),y:i.getCenterY(),w:i.width,h:i.height}}return e},E.prototype.runSpringEmbedder=function(){this.initialAnimationPeriod=25,this.animationPeriod=this.initialAnimationPeriod;var t=!1;if("during"===d.ANIMATE)this.emit("layoutstarted");else{for(;!t;)t=this.tick();this.graphManager.updateBounds()}},E.prototype.calculateNodesToApplyGravitationTo=function(){var t,e,r=[],i=this.graphManager.getGraphs(),o=i.length;for(e=0;e<o;e++)(t=i[e]).updateConnected(),t.isConnected||(r=r.concat(t.getNodes()));return r},E.prototype.createBendpoints=function(){var t=[];t=t.concat(this.graphManager.getAllEdges());var e,r=new Set;for(e=0;e<t.length;e++){var i=t[e];if(!r.has(i)){var o=i.getSource(),n=i.getTarget();if(o==n)i.getBendpoints().push(new p),i.getBendpoints().push(new p),this.createDummyNodesForBendpoints(i),r.add(i);else{var a=[];if(a=(a=a.concat(o.getEdgeListToNode(n))).concat(n.getEdgeListToNode(o)),!r.has(a[0])){var s;if(a.length>1)for(s=0;s<a.length;s++){var h=a[s];h.getBendpoints().push(new p),this.createDummyNodesForBendpoints(h)}a.forEach((function(t){r.add(t)}))}}}if(r.size==t.length)break}},E.prototype.positionNodesRadially=function(t){for(var e=new l(0,0),r=Math.ceil(Math.sqrt(t.length)),i=0,o=0,n=0,a=new p(0,0),s=0;s<t.length;s++){s%r==0&&(n=0,o=i,0!=s&&(o+=h.DEFAULT_COMPONENT_SEPERATION),i=0);var d=t[s],u=c.findCenterOfTree(d);e.x=n,e.y=o,(a=E.radialLayout(d,u,e)).y>i&&(i=Math.floor(a.y)),n=Math.floor(a.x+h.DEFAULT_COMPONENT_SEPERATION)}this.transform(new p(g.WORLD_CENTER_X-a.x/2,g.WORLD_CENTER_Y-a.y/2))},E.radialLayout=function(t,e,r){var i=Math.max(this.maxDiagonalInTree(t),h.DEFAULT_RADIAL_SEPARATION);E.branchRadialLayout(e,null,0,359,0,i);var o=v.calculateBounds(t),n=new T;n.setDeviceOrgX(o.getMinX()),n.setDeviceOrgY(o.getMinY()),n.setWorldOrgX(r.x),n.setWorldOrgY(r.y);for(var a=0;a<t.length;a++)t[a].transform(n);var s=new p(o.getMaxX(),o.getMaxY());return n.inverseTransformPoint(s)},E.branchRadialLayout=function(t,e,r,i,o,n){var a=(i-r+1)/2;a<0&&(a+=180);var s=(a+r)%360*f.TWO_PI/360,h=o*Math.cos(s),d=o*Math.sin(s);t.setCenter(h,d);var g=[],l=(g=g.concat(t.getEdges())).length;null!=e&&l--;for(var p,c=0,u=g.length,v=t.getEdgesBetween(e);v.length>1;){var T=v[0];v.splice(0,1);var m=g.indexOf(T);m>=0&&g.splice(m,1),u--,l--}p=null!=e?(g.indexOf(v[0])+1)%u:0;for(var y=Math.abs(i-r)/l,N=p;c!=l;N=++N%u){var w=g[N].getOtherEnd(t);if(w!=e){var A=(r+c*y)%360,C=(A+y)%360;E.branchRadialLayout(w,t,A,C,o+n,n),c++}}},E.maxDiagonalInTree=function(t){for(var e=u.MIN_VALUE,r=0;r<t.length;r++){var i=t[r].getDiagonal();i>e&&(e=i)}return e},E.prototype.calcRepulsionRange=function(){return 2*(this.level+1)*this.idealEdgeLength},E.prototype.groupZeroDegreeMembers=function(){var t=this,e={};this.memberGroups={},this.idToDummyNode={};for(var r=[],i=this.graphManager.getAllNodes(),o=0;o<i.length;o++){var n=(s=i[o]).getParent();0!==this.getNodeDegreeWithChildren(s)||null!=n.id&&this.getToBeTiled(n)||r.push(s)}for(o=0;o<r.length;o++){var s,h=(s=r[o]).getParent().id;void 0===e[h]&&(e[h]=[]),e[h]=e[h].concat(s)}Object.keys(e).forEach((function(r){if(e[r].length>1){var i="DummyCompound_"+r;t.memberGroups[i]=e[r];var o=e[r][0].getParent(),n=new a(t.graphManager);n.id=i,n.paddingLeft=o.paddingLeft||0,n.paddingRight=o.paddingRight||0,n.paddingBottom=o.paddingBottom||0,n.paddingTop=o.paddingTop||0,t.idToDummyNode[i]=n;var s=t.getGraphManager().add(t.newGraph(),n),h=o.getChild();h.add(n);for(var d=0;d<e[r].length;d++){var g=e[r][d];h.remove(g),s.add(g)}}}))},E.prototype.clearCompounds=function(){var t={},e={};this.performDFSOnCompounds();for(var r=0;r<this.compoundOrder.length;r++)e[this.compoundOrder[r].id]=this.compoundOrder[r],t[this.compoundOrder[r].id]=[].concat(this.compoundOrder[r].getChild().getNodes()),this.graphManager.remove(this.compoundOrder[r].getChild()),this.compoundOrder[r].child=null;this.graphManager.resetAllNodes(),this.tileCompoundMembers(t,e)},E.prototype.clearZeroDegreeMembers=function(){var t=this,e=this.tiledZeroDegreePack=[];Object.keys(this.memberGroups).forEach((function(r){var i=t.idToDummyNode[r];e[r]=t.tileNodes(t.memberGroups[r],i.paddingLeft+i.paddingRight),i.rect.width=e[r].width,i.rect.height=e[r].height}))},E.prototype.repopulateCompounds=function(){for(var t=this.compoundOrder.length-1;t>=0;t--){var e=this.compoundOrder[t],r=e.id,i=e.paddingLeft,o=e.paddingTop;this.adjustLocations(this.tiledMemberPack[r],e.rect.x,e.rect.y,i,o)}},E.prototype.repopulateZeroDegreeMembers=function(){var t=this,e=this.tiledZeroDegreePack;Object.keys(e).forEach((function(r){var i=t.idToDummyNode[r],o=i.paddingLeft,n=i.paddingTop;t.adjustLocations(e[r],i.rect.x,i.rect.y,o,n)}))},E.prototype.getToBeTiled=function(t){var e=t.id;if(null!=this.toBeTiled[e])return this.toBeTiled[e];var r=t.getChild();if(null==r)return this.toBeTiled[e]=!1,!1;for(var i=r.getNodes(),o=0;o<i.length;o++){var n=i[o];if(this.getNodeDegree(n)>0)return this.toBeTiled[e]=!1,!1;if(null!=n.getChild()){if(!this.getToBeTiled(n))return this.toBeTiled[e]=!1,!1}else this.toBeTiled[n.id]=!1}return this.toBeTiled[e]=!0,!0},E.prototype.getNodeDegree=function(t){t.id;for(var e=t.getEdges(),r=0,i=0;i<e.length;i++){var o=e[i];o.getSource().id!==o.getTarget().id&&(r+=1)}return r},E.prototype.getNodeDegreeWithChildren=function(t){var e=this.getNodeDegree(t);if(null==t.getChild())return e;for(var r=t.getChild().getNodes(),i=0;i<r.length;i++){var o=r[i];e+=this.getNodeDegreeWithChildren(o)}return e},E.prototype.performDFSOnCompounds=function(){this.compoundOrder=[],this.fillCompexOrderByDFS(this.graphManager.getRoot().getNodes())},E.prototype.fillCompexOrderByDFS=function(t){for(var e=0;e<t.length;e++){var r=t[e];null!=r.getChild()&&this.fillCompexOrderByDFS(r.getChild().getNodes()),this.getToBeTiled(r)&&this.compoundOrder.push(r)}},E.prototype.adjustLocations=function(t,e,r,i,o){r+=o;for(var n=e+=i,a=0;a<t.rows.length;a++){var s=t.rows[a];e=n;for(var h=0,d=0;d<s.length;d++){var g=s[d];g.rect.x=e,g.rect.y=r,e+=g.rect.width+t.horizontalPadding,g.rect.height>h&&(h=g.rect.height)}r+=h+t.verticalPadding}},E.prototype.tileCompoundMembers=function(t,e){var r=this;this.tiledMemberPack=[],Object.keys(t).forEach((function(i){var o=e[i];r.tiledMemberPack[i]=r.tileNodes(t[i],o.paddingLeft+o.paddingRight),o.rect.width=r.tiledMemberPack[i].width,o.rect.height=r.tiledMemberPack[i].height}))},E.prototype.tileNodes=function(t,e){var r={rows:[],rowWidth:[],rowHeight:[],width:0,height:e,verticalPadding:h.TILING_PADDING_VERTICAL,horizontalPadding:h.TILING_PADDING_HORIZONTAL};t.sort((function(t,e){return t.rect.width*t.rect.height>e.rect.width*e.rect.height?-1:t.rect.width*t.rect.height<e.rect.width*e.rect.height?1:0}));for(var i=0;i<t.length;i++){var o=t[i];0==r.rows.length?this.insertNodeToRow(r,o,0,e):this.canAddHorizontal(r,o.rect.width,o.rect.height)?this.insertNodeToRow(r,o,this.getShortestRowIndex(r),e):this.insertNodeToRow(r,o,r.rows.length,e),this.shiftToLastRow(r)}return r},E.prototype.insertNodeToRow=function(t,e,r,i){var o=i;r==t.rows.length&&(t.rows.push([]),t.rowWidth.push(o),t.rowHeight.push(0));var n=t.rowWidth[r]+e.rect.width;t.rows[r].length>0&&(n+=t.horizontalPadding),t.rowWidth[r]=n,t.width<n&&(t.width=n);var a=e.rect.height;r>0&&(a+=t.verticalPadding);var s=0;a>t.rowHeight[r]&&(s=t.rowHeight[r],t.rowHeight[r]=a,s=t.rowHeight[r]-s),t.height+=s,t.rows[r].push(e)},E.prototype.getShortestRowIndex=function(t){for(var e=-1,r=Number.MAX_VALUE,i=0;i<t.rows.length;i++)t.rowWidth[i]<r&&(e=i,r=t.rowWidth[i]);return e},E.prototype.getLongestRowIndex=function(t){for(var e=-1,r=Number.MIN_VALUE,i=0;i<t.rows.length;i++)t.rowWidth[i]>r&&(e=i,r=t.rowWidth[i]);return e},E.prototype.canAddHorizontal=function(t,e,r){var i=this.getShortestRowIndex(t);if(i<0)return!0;var o=t.rowWidth[i];if(o+t.horizontalPadding+e<=t.width)return!0;var n,a,s=0;return t.rowHeight[i]<r&&i>0&&(s=r+t.verticalPadding-t.rowHeight[i]),n=t.width-o>=e+t.horizontalPadding?(t.height+s)/(o+e+t.horizontalPadding):(t.height+s)/t.width,s=r+t.verticalPadding,(a=t.width<e?(t.height+s)/e:(t.height+s)/t.width)<1&&(a=1/a),n<1&&(n=1/n),n<a},E.prototype.shiftToLastRow=function(t){var e=this.getLongestRowIndex(t),r=t.rowWidth.length-1,i=t.rows[e],o=i[i.length-1],n=o.width+t.horizontalPadding;if(t.width-t.rowWidth[r]>n&&e!=r){i.splice(-1,1),t.rows[r].push(o),t.rowWidth[e]=t.rowWidth[e]-n,t.rowWidth[r]=t.rowWidth[r]+n,t.width=t.rowWidth[instance.getLongestRowIndex(t)];for(var a=Number.MIN_VALUE,s=0;s<i.length;s++)i[s].height>a&&(a=i[s].height);e>0&&(a+=t.verticalPadding);var h=t.rowHeight[e]+t.rowHeight[r];t.rowHeight[e]=a,t.rowHeight[r]<o.height+t.verticalPadding&&(t.rowHeight[r]=o.height+t.verticalPadding);var d=t.rowHeight[e]+t.rowHeight[r];t.height+=d-h,this.shiftToLastRow(t)}},E.prototype.tilingPreLayout=function(){h.TILE&&(this.groupZeroDegreeMembers(),this.clearCompounds(),this.clearZeroDegreeMembers())},E.prototype.tilingPostLayout=function(){h.TILE&&(this.repopulateZeroDegreeMembers(),this.repopulateCompounds())},E.prototype.reduceTrees=function(){for(var t,e=[],r=!0;r;){var i=this.graphManager.getAllNodes(),o=[];r=!1;for(var n=0;n<i.length;n++)1!=(t=i[n]).getEdges().length||t.getEdges()[0].isInterGraph||null!=t.getChild()||(o.push([t,t.getEdges()[0],t.getOwner()]),r=!0);if(1==r){for(var a=[],s=0;s<o.length;s++)1==o[s][0].getEdges().length&&(a.push(o[s]),o[s][0].getOwner().remove(o[s][0]));e.push(a),this.graphManager.resetAllNodes(),this.graphManager.resetAllEdges()}}this.prunedNodesAll=e},E.prototype.growTree=function(t){for(var e,r=t[t.length-1],i=0;i<r.length;i++)e=r[i],this.findPlaceforPrunedNode(e),e[2].add(e[0]),e[2].add(e[1],e[1].source,e[1].target);t.splice(t.length-1,1),this.graphManager.resetAllNodes(),this.graphManager.resetAllEdges()},E.prototype.findPlaceforPrunedNode=function(t){var e,r,i=t[0],o=(r=i==t[1].source?t[1].target:t[1].source).startX,n=r.finishX,a=r.startY,s=r.finishY,h=[0,0,0,0];if(a>0)for(var g=o;g<=n;g++)h[0]+=this.grid[g][a-1].length+this.grid[g][a].length-1;if(n<this.grid.length-1)for(g=a;g<=s;g++)h[1]+=this.grid[n+1][g].length+this.grid[n][g].length-1;if(s<this.grid[0].length-1)for(g=o;g<=n;g++)h[2]+=this.grid[g][s+1].length+this.grid[g][s].length-1;if(o>0)for(g=a;g<=s;g++)h[3]+=this.grid[o-1][g].length+this.grid[o][g].length-1;for(var l,p,c=u.MAX_VALUE,f=0;f<h.length;f++)h[f]<c?(c=h[f],l=1,p=f):h[f]==c&&l++;if(3==l&&0==c)0==h[0]&&0==h[1]&&0==h[2]?e=1:0==h[0]&&0==h[1]&&0==h[3]?e=0:0==h[0]&&0==h[2]&&0==h[3]?e=3:0==h[1]&&0==h[2]&&0==h[3]&&(e=2);else if(2==l&&0==c){var v=Math.floor(2*Math.random());e=0==h[0]&&0==h[1]?0==v?0:1:0==h[0]&&0==h[2]?0==v?0:2:0==h[0]&&0==h[3]?0==v?0:3:0==h[1]&&0==h[2]?0==v?1:2:0==h[1]&&0==h[3]?0==v?1:3:0==v?2:3}else e=4==l&&0==c?v=Math.floor(4*Math.random()):p;0==e?i.setCenter(r.getCenterX(),r.getCenterY()-r.getHeight()/2-d.DEFAULT_EDGE_LENGTH-i.getHeight()/2):1==e?i.setCenter(r.getCenterX()+r.getWidth()/2+d.DEFAULT_EDGE_LENGTH+i.getWidth()/2,r.getCenterY()):2==e?i.setCenter(r.getCenterX(),r.getCenterY()+r.getHeight()/2+d.DEFAULT_EDGE_LENGTH+i.getHeight()/2):i.setCenter(r.getCenterX()-r.getWidth()/2-d.DEFAULT_EDGE_LENGTH-i.getWidth()/2,r.getCenterY())},t.exports=E},function(t,e,r){var i={};i.layoutBase=r(0),i.CoSEConstants=r(1),i.CoSEEdge=r(2),i.CoSEGraph=r(3),i.CoSEGraphManager=r(4),i.CoSELayout=r(6),i.CoSENode=r(5),t.exports=i}])},t.exports=o(r())),e.exports;var t,o}e.exports;export{o as __require};
|
|
1
|
+
import{commonjsGlobal as t}from"../../../../../_virtual/_commonjsHelpers.js";import{__module as e}from"../../../../../_virtual/cose-base.js";import{__require as r}from"../../../layout-base@1.0.2/node_modules/layout-base/layout-base.js";var i;function o(){return i||(i=1,t=e,e.exports,o=function(t){return function(t){var e={};function r(i){if(e[i])return e[i].exports;var o=e[i]={i:i,l:!1,exports:{}};return t[i].call(o.exports,o,o.exports,r),o.l=!0,o.exports}return r.m=t,r.c=e,r.i=function(t){return t},r.d=function(t,e,i){r.o(t,e)||Object.defineProperty(t,e,{configurable:!1,enumerable:!0,get:i})},r.n=function(t){var e=t&&t.__esModule?function(){return t.default}:function(){return t};return r.d(e,"a",e),e},r.o=function(t,e){return Object.prototype.hasOwnProperty.call(t,e)},r.p="",r(r.s=7)}([function(e,r){e.exports=t},function(t,e,r){var i=r(0).FDLayoutConstants;function o(){}for(var n in i)o[n]=i[n];o.DEFAULT_USE_MULTI_LEVEL_SCALING=!1,o.DEFAULT_RADIAL_SEPARATION=i.DEFAULT_EDGE_LENGTH,o.DEFAULT_COMPONENT_SEPERATION=60,o.TILE=!0,o.TILING_PADDING_VERTICAL=10,o.TILING_PADDING_HORIZONTAL=10,o.TREE_REDUCTION_ON_INCREMENTAL=!1,t.exports=o},function(t,e,r){var i=r(0).FDLayoutEdge;function o(t,e,r){i.call(this,t,e,r)}for(var n in o.prototype=Object.create(i.prototype),i)o[n]=i[n];t.exports=o},function(t,e,r){var i=r(0).LGraph;function o(t,e,r){i.call(this,t,e,r)}for(var n in o.prototype=Object.create(i.prototype),i)o[n]=i[n];t.exports=o},function(t,e,r){var i=r(0).LGraphManager;function o(t){i.call(this,t)}for(var n in o.prototype=Object.create(i.prototype),i)o[n]=i[n];t.exports=o},function(t,e,r){var i=r(0).FDLayoutNode,o=r(0).IMath;function n(t,e,r,o){i.call(this,t,e,r,o)}for(var a in n.prototype=Object.create(i.prototype),i)n[a]=i[a];n.prototype.move=function(){var t=this.graphManager.getLayout();this.displacementX=t.coolingFactor*(this.springForceX+this.repulsionForceX+this.gravitationForceX)/this.noOfChildren,this.displacementY=t.coolingFactor*(this.springForceY+this.repulsionForceY+this.gravitationForceY)/this.noOfChildren,Math.abs(this.displacementX)>t.coolingFactor*t.maxNodeDisplacement&&(this.displacementX=t.coolingFactor*t.maxNodeDisplacement*o.sign(this.displacementX)),Math.abs(this.displacementY)>t.coolingFactor*t.maxNodeDisplacement&&(this.displacementY=t.coolingFactor*t.maxNodeDisplacement*o.sign(this.displacementY)),null==this.child||0==this.child.getNodes().length?this.moveBy(this.displacementX,this.displacementY):this.propogateDisplacementToChildren(this.displacementX,this.displacementY),t.totalDisplacement+=Math.abs(this.displacementX)+Math.abs(this.displacementY),this.springForceX=0,this.springForceY=0,this.repulsionForceX=0,this.repulsionForceY=0,this.gravitationForceX=0,this.gravitationForceY=0,this.displacementX=0,this.displacementY=0},n.prototype.propogateDisplacementToChildren=function(t,e){for(var r,i=this.getChild().getNodes(),o=0;o<i.length;o++)null==(r=i[o]).getChild()?(r.moveBy(t,e),r.displacementX+=t,r.displacementY+=e):r.propogateDisplacementToChildren(t,e)},n.prototype.setPred1=function(t){this.pred1=t},n.prototype.getPred1=function(){return pred1},n.prototype.getPred2=function(){return pred2},n.prototype.setNext=function(t){this.next=t},n.prototype.getNext=function(){return next},n.prototype.setProcessed=function(t){this.processed=t},n.prototype.isProcessed=function(){return processed},t.exports=n},function(t,e,r){var i=r(0).FDLayout,o=r(4),n=r(3),a=r(5),s=r(2),h=r(1),d=r(0).FDLayoutConstants,g=r(0).LayoutConstants,l=r(0).Point,p=r(0).PointD,c=r(0).Layout,u=r(0).Integer,f=r(0).IGeometry,v=r(0).LGraph,T=r(0).Transform;function E(){i.call(this),this.toBeTiled={}}for(var m in E.prototype=Object.create(i.prototype),i)E[m]=i[m];E.prototype.newGraphManager=function(){var t=new o(this);return this.graphManager=t,t},E.prototype.newGraph=function(t){return new n(null,this.graphManager,t)},E.prototype.newNode=function(t){return new a(this.graphManager,t)},E.prototype.newEdge=function(t){return new s(null,null,t)},E.prototype.initParameters=function(){i.prototype.initParameters.call(this,arguments),this.isSubLayout||(h.DEFAULT_EDGE_LENGTH<10?this.idealEdgeLength=10:this.idealEdgeLength=h.DEFAULT_EDGE_LENGTH,this.useSmartIdealEdgeLengthCalculation=h.DEFAULT_USE_SMART_IDEAL_EDGE_LENGTH_CALCULATION,this.springConstant=d.DEFAULT_SPRING_STRENGTH,this.repulsionConstant=d.DEFAULT_REPULSION_STRENGTH,this.gravityConstant=d.DEFAULT_GRAVITY_STRENGTH,this.compoundGravityConstant=d.DEFAULT_COMPOUND_GRAVITY_STRENGTH,this.gravityRangeFactor=d.DEFAULT_GRAVITY_RANGE_FACTOR,this.compoundGravityRangeFactor=d.DEFAULT_COMPOUND_GRAVITY_RANGE_FACTOR,this.prunedNodesAll=[],this.growTreeIterations=0,this.afterGrowthIterations=0,this.isTreeGrowing=!1,this.isGrowthFinished=!1,this.coolingCycle=0,this.maxCoolingCycle=this.maxIterations/d.CONVERGENCE_CHECK_PERIOD,this.finalTemperature=d.CONVERGENCE_CHECK_PERIOD/this.maxIterations,this.coolingAdjuster=1)},E.prototype.layout=function(){return g.DEFAULT_CREATE_BENDS_AS_NEEDED&&(this.createBendpoints(),this.graphManager.resetAllEdges()),this.level=0,this.classicLayout()},E.prototype.classicLayout=function(){if(this.nodesWithGravity=this.calculateNodesToApplyGravitationTo(),this.graphManager.setAllNodesToApplyGravitation(this.nodesWithGravity),this.calcNoOfChildrenForAllNodes(),this.graphManager.calcLowestCommonAncestors(),this.graphManager.calcInclusionTreeDepths(),this.graphManager.getRoot().calcEstimatedSize(),this.calcIdealEdgeLengths(),this.incremental)h.TREE_REDUCTION_ON_INCREMENTAL&&(this.reduceTrees(),this.graphManager.resetAllNodesToApplyGravitation(),e=new Set(this.getAllNodes()),r=this.nodesWithGravity.filter((function(t){return e.has(t)})),this.graphManager.setAllNodesToApplyGravitation(r));else{var t=this.getFlatForest();if(t.length>0)this.positionNodesRadially(t);else{this.reduceTrees(),this.graphManager.resetAllNodesToApplyGravitation();var e=new Set(this.getAllNodes()),r=this.nodesWithGravity.filter((function(t){return e.has(t)}));this.graphManager.setAllNodesToApplyGravitation(r),this.positionNodesRandomly()}}return this.initSpringEmbedder(),this.runSpringEmbedder(),!0},E.prototype.tick=function(){if(this.totalIterations++,this.totalIterations===this.maxIterations&&!this.isTreeGrowing&&!this.isGrowthFinished){if(!(this.prunedNodesAll.length>0))return!0;this.isTreeGrowing=!0}if(this.totalIterations%d.CONVERGENCE_CHECK_PERIOD==0&&!this.isTreeGrowing&&!this.isGrowthFinished){if(this.isConverged()){if(!(this.prunedNodesAll.length>0))return!0;this.isTreeGrowing=!0}this.coolingCycle++,0==this.layoutQuality?this.coolingAdjuster=this.coolingCycle:1==this.layoutQuality&&(this.coolingAdjuster=this.coolingCycle/3),this.coolingFactor=Math.max(this.initialCoolingFactor-Math.pow(this.coolingCycle,Math.log(100*(this.initialCoolingFactor-this.finalTemperature))/Math.log(this.maxCoolingCycle))/100*this.coolingAdjuster,this.finalTemperature),this.animationPeriod=Math.ceil(this.initialAnimationPeriod*Math.sqrt(this.coolingFactor))}if(this.isTreeGrowing){if(this.growTreeIterations%10==0)if(this.prunedNodesAll.length>0){this.graphManager.updateBounds(),this.updateGrid(),this.growTree(this.prunedNodesAll),this.graphManager.resetAllNodesToApplyGravitation();var t=new Set(this.getAllNodes()),e=this.nodesWithGravity.filter((function(e){return t.has(e)}));this.graphManager.setAllNodesToApplyGravitation(e),this.graphManager.updateBounds(),this.updateGrid(),this.coolingFactor=d.DEFAULT_COOLING_FACTOR_INCREMENTAL}else this.isTreeGrowing=!1,this.isGrowthFinished=!0;this.growTreeIterations++}if(this.isGrowthFinished){if(this.isConverged())return!0;this.afterGrowthIterations%10==0&&(this.graphManager.updateBounds(),this.updateGrid()),this.coolingFactor=d.DEFAULT_COOLING_FACTOR_INCREMENTAL*((100-this.afterGrowthIterations)/100),this.afterGrowthIterations++}var r=!this.isTreeGrowing&&!this.isGrowthFinished,i=this.growTreeIterations%10==1&&this.isTreeGrowing||this.afterGrowthIterations%10==1&&this.isGrowthFinished;return this.totalDisplacement=0,this.graphManager.updateBounds(),this.calcSpringForces(),this.calcRepulsionForces(r,i),this.calcGravitationalForces(),this.moveNodes(),this.animate(),!1},E.prototype.getPositionsData=function(){for(var t=this.graphManager.getAllNodes(),e={},r=0;r<t.length;r++){var i=t[r].rect,o=t[r].id;e[o]={id:o,x:i.getCenterX(),y:i.getCenterY(),w:i.width,h:i.height}}return e},E.prototype.runSpringEmbedder=function(){this.initialAnimationPeriod=25,this.animationPeriod=this.initialAnimationPeriod;var t=!1;if("during"===d.ANIMATE)this.emit("layoutstarted");else{for(;!t;)t=this.tick();this.graphManager.updateBounds()}},E.prototype.calculateNodesToApplyGravitationTo=function(){var t,e,r=[],i=this.graphManager.getGraphs(),o=i.length;for(e=0;e<o;e++)(t=i[e]).updateConnected(),t.isConnected||(r=r.concat(t.getNodes()));return r},E.prototype.createBendpoints=function(){var t=[];t=t.concat(this.graphManager.getAllEdges());var e,r=new Set;for(e=0;e<t.length;e++){var i=t[e];if(!r.has(i)){var o=i.getSource(),n=i.getTarget();if(o==n)i.getBendpoints().push(new p),i.getBendpoints().push(new p),this.createDummyNodesForBendpoints(i),r.add(i);else{var a=[];if(a=(a=a.concat(o.getEdgeListToNode(n))).concat(n.getEdgeListToNode(o)),!r.has(a[0])){var s;if(a.length>1)for(s=0;s<a.length;s++){var h=a[s];h.getBendpoints().push(new p),this.createDummyNodesForBendpoints(h)}a.forEach((function(t){r.add(t)}))}}}if(r.size==t.length)break}},E.prototype.positionNodesRadially=function(t){for(var e=new l(0,0),r=Math.ceil(Math.sqrt(t.length)),i=0,o=0,n=0,a=new p(0,0),s=0;s<t.length;s++){s%r==0&&(n=0,o=i,0!=s&&(o+=h.DEFAULT_COMPONENT_SEPERATION),i=0);var d=t[s],u=c.findCenterOfTree(d);e.x=n,e.y=o,(a=E.radialLayout(d,u,e)).y>i&&(i=Math.floor(a.y)),n=Math.floor(a.x+h.DEFAULT_COMPONENT_SEPERATION)}this.transform(new p(g.WORLD_CENTER_X-a.x/2,g.WORLD_CENTER_Y-a.y/2))},E.radialLayout=function(t,e,r){var i=Math.max(this.maxDiagonalInTree(t),h.DEFAULT_RADIAL_SEPARATION);E.branchRadialLayout(e,null,0,359,0,i);var o=v.calculateBounds(t),n=new T;n.setDeviceOrgX(o.getMinX()),n.setDeviceOrgY(o.getMinY()),n.setWorldOrgX(r.x),n.setWorldOrgY(r.y);for(var a=0;a<t.length;a++)t[a].transform(n);var s=new p(o.getMaxX(),o.getMaxY());return n.inverseTransformPoint(s)},E.branchRadialLayout=function(t,e,r,i,o,n){var a=(i-r+1)/2;a<0&&(a+=180);var s=(a+r)%360*f.TWO_PI/360,h=o*Math.cos(s),d=o*Math.sin(s);t.setCenter(h,d);var g=[],l=(g=g.concat(t.getEdges())).length;null!=e&&l--;for(var p,c=0,u=g.length,v=t.getEdgesBetween(e);v.length>1;){var T=v[0];v.splice(0,1);var m=g.indexOf(T);m>=0&&g.splice(m,1),u--,l--}p=null!=e?(g.indexOf(v[0])+1)%u:0;for(var y=Math.abs(i-r)/l,N=p;c!=l;N=++N%u){var w=g[N].getOtherEnd(t);if(w!=e){var A=(r+c*y)%360,C=(A+y)%360;E.branchRadialLayout(w,t,A,C,o+n,n),c++}}},E.maxDiagonalInTree=function(t){for(var e=u.MIN_VALUE,r=0;r<t.length;r++){var i=t[r].getDiagonal();i>e&&(e=i)}return e},E.prototype.calcRepulsionRange=function(){return 2*(this.level+1)*this.idealEdgeLength},E.prototype.groupZeroDegreeMembers=function(){var t=this,e={};this.memberGroups={},this.idToDummyNode={};for(var r=[],i=this.graphManager.getAllNodes(),o=0;o<i.length;o++){var n=(s=i[o]).getParent();0!==this.getNodeDegreeWithChildren(s)||null!=n.id&&this.getToBeTiled(n)||r.push(s)}for(o=0;o<r.length;o++){var s,h=(s=r[o]).getParent().id;void 0===e[h]&&(e[h]=[]),e[h]=e[h].concat(s)}Object.keys(e).forEach((function(r){if(e[r].length>1){var i="DummyCompound_"+r;t.memberGroups[i]=e[r];var o=e[r][0].getParent(),n=new a(t.graphManager);n.id=i,n.paddingLeft=o.paddingLeft||0,n.paddingRight=o.paddingRight||0,n.paddingBottom=o.paddingBottom||0,n.paddingTop=o.paddingTop||0,t.idToDummyNode[i]=n;var s=t.getGraphManager().add(t.newGraph(),n),h=o.getChild();h.add(n);for(var d=0;d<e[r].length;d++){var g=e[r][d];h.remove(g),s.add(g)}}}))},E.prototype.clearCompounds=function(){var t={},e={};this.performDFSOnCompounds();for(var r=0;r<this.compoundOrder.length;r++)e[this.compoundOrder[r].id]=this.compoundOrder[r],t[this.compoundOrder[r].id]=[].concat(this.compoundOrder[r].getChild().getNodes()),this.graphManager.remove(this.compoundOrder[r].getChild()),this.compoundOrder[r].child=null;this.graphManager.resetAllNodes(),this.tileCompoundMembers(t,e)},E.prototype.clearZeroDegreeMembers=function(){var t=this,e=this.tiledZeroDegreePack=[];Object.keys(this.memberGroups).forEach((function(r){var i=t.idToDummyNode[r];e[r]=t.tileNodes(t.memberGroups[r],i.paddingLeft+i.paddingRight),i.rect.width=e[r].width,i.rect.height=e[r].height}))},E.prototype.repopulateCompounds=function(){for(var t=this.compoundOrder.length-1;t>=0;t--){var e=this.compoundOrder[t],r=e.id,i=e.paddingLeft,o=e.paddingTop;this.adjustLocations(this.tiledMemberPack[r],e.rect.x,e.rect.y,i,o)}},E.prototype.repopulateZeroDegreeMembers=function(){var t=this,e=this.tiledZeroDegreePack;Object.keys(e).forEach((function(r){var i=t.idToDummyNode[r],o=i.paddingLeft,n=i.paddingTop;t.adjustLocations(e[r],i.rect.x,i.rect.y,o,n)}))},E.prototype.getToBeTiled=function(t){var e=t.id;if(null!=this.toBeTiled[e])return this.toBeTiled[e];var r=t.getChild();if(null==r)return this.toBeTiled[e]=!1,!1;for(var i=r.getNodes(),o=0;o<i.length;o++){var n=i[o];if(this.getNodeDegree(n)>0)return this.toBeTiled[e]=!1,!1;if(null!=n.getChild()){if(!this.getToBeTiled(n))return this.toBeTiled[e]=!1,!1}else this.toBeTiled[n.id]=!1}return this.toBeTiled[e]=!0,!0},E.prototype.getNodeDegree=function(t){t.id;for(var e=t.getEdges(),r=0,i=0;i<e.length;i++){var o=e[i];o.getSource().id!==o.getTarget().id&&(r+=1)}return r},E.prototype.getNodeDegreeWithChildren=function(t){var e=this.getNodeDegree(t);if(null==t.getChild())return e;for(var r=t.getChild().getNodes(),i=0;i<r.length;i++){var o=r[i];e+=this.getNodeDegreeWithChildren(o)}return e},E.prototype.performDFSOnCompounds=function(){this.compoundOrder=[],this.fillCompexOrderByDFS(this.graphManager.getRoot().getNodes())},E.prototype.fillCompexOrderByDFS=function(t){for(var e=0;e<t.length;e++){var r=t[e];null!=r.getChild()&&this.fillCompexOrderByDFS(r.getChild().getNodes()),this.getToBeTiled(r)&&this.compoundOrder.push(r)}},E.prototype.adjustLocations=function(t,e,r,i,o){r+=o;for(var n=e+=i,a=0;a<t.rows.length;a++){var s=t.rows[a];e=n;for(var h=0,d=0;d<s.length;d++){var g=s[d];g.rect.x=e,g.rect.y=r,e+=g.rect.width+t.horizontalPadding,g.rect.height>h&&(h=g.rect.height)}r+=h+t.verticalPadding}},E.prototype.tileCompoundMembers=function(t,e){var r=this;this.tiledMemberPack=[],Object.keys(t).forEach((function(i){var o=e[i];r.tiledMemberPack[i]=r.tileNodes(t[i],o.paddingLeft+o.paddingRight),o.rect.width=r.tiledMemberPack[i].width,o.rect.height=r.tiledMemberPack[i].height}))},E.prototype.tileNodes=function(t,e){var r={rows:[],rowWidth:[],rowHeight:[],width:0,height:e,verticalPadding:h.TILING_PADDING_VERTICAL,horizontalPadding:h.TILING_PADDING_HORIZONTAL};t.sort((function(t,e){return t.rect.width*t.rect.height>e.rect.width*e.rect.height?-1:t.rect.width*t.rect.height<e.rect.width*e.rect.height?1:0}));for(var i=0;i<t.length;i++){var o=t[i];0==r.rows.length?this.insertNodeToRow(r,o,0,e):this.canAddHorizontal(r,o.rect.width,o.rect.height)?this.insertNodeToRow(r,o,this.getShortestRowIndex(r),e):this.insertNodeToRow(r,o,r.rows.length,e),this.shiftToLastRow(r)}return r},E.prototype.insertNodeToRow=function(t,e,r,i){var o=i;r==t.rows.length&&(t.rows.push([]),t.rowWidth.push(o),t.rowHeight.push(0));var n=t.rowWidth[r]+e.rect.width;t.rows[r].length>0&&(n+=t.horizontalPadding),t.rowWidth[r]=n,t.width<n&&(t.width=n);var a=e.rect.height;r>0&&(a+=t.verticalPadding);var s=0;a>t.rowHeight[r]&&(s=t.rowHeight[r],t.rowHeight[r]=a,s=t.rowHeight[r]-s),t.height+=s,t.rows[r].push(e)},E.prototype.getShortestRowIndex=function(t){for(var e=-1,r=Number.MAX_VALUE,i=0;i<t.rows.length;i++)t.rowWidth[i]<r&&(e=i,r=t.rowWidth[i]);return e},E.prototype.getLongestRowIndex=function(t){for(var e=-1,r=Number.MIN_VALUE,i=0;i<t.rows.length;i++)t.rowWidth[i]>r&&(e=i,r=t.rowWidth[i]);return e},E.prototype.canAddHorizontal=function(t,e,r){var i=this.getShortestRowIndex(t);if(i<0)return!0;var o=t.rowWidth[i];if(o+t.horizontalPadding+e<=t.width)return!0;var n,a,s=0;return t.rowHeight[i]<r&&i>0&&(s=r+t.verticalPadding-t.rowHeight[i]),n=t.width-o>=e+t.horizontalPadding?(t.height+s)/(o+e+t.horizontalPadding):(t.height+s)/t.width,s=r+t.verticalPadding,(a=t.width<e?(t.height+s)/e:(t.height+s)/t.width)<1&&(a=1/a),n<1&&(n=1/n),n<a},E.prototype.shiftToLastRow=function(t){var e=this.getLongestRowIndex(t),r=t.rowWidth.length-1,i=t.rows[e],o=i[i.length-1],n=o.width+t.horizontalPadding;if(t.width-t.rowWidth[r]>n&&e!=r){i.splice(-1,1),t.rows[r].push(o),t.rowWidth[e]=t.rowWidth[e]-n,t.rowWidth[r]=t.rowWidth[r]+n,t.width=t.rowWidth[instance.getLongestRowIndex(t)];for(var a=Number.MIN_VALUE,s=0;s<i.length;s++)i[s].height>a&&(a=i[s].height);e>0&&(a+=t.verticalPadding);var h=t.rowHeight[e]+t.rowHeight[r];t.rowHeight[e]=a,t.rowHeight[r]<o.height+t.verticalPadding&&(t.rowHeight[r]=o.height+t.verticalPadding);var d=t.rowHeight[e]+t.rowHeight[r];t.height+=d-h,this.shiftToLastRow(t)}},E.prototype.tilingPreLayout=function(){h.TILE&&(this.groupZeroDegreeMembers(),this.clearCompounds(),this.clearZeroDegreeMembers())},E.prototype.tilingPostLayout=function(){h.TILE&&(this.repopulateZeroDegreeMembers(),this.repopulateCompounds())},E.prototype.reduceTrees=function(){for(var t,e=[],r=!0;r;){var i=this.graphManager.getAllNodes(),o=[];r=!1;for(var n=0;n<i.length;n++)1!=(t=i[n]).getEdges().length||t.getEdges()[0].isInterGraph||null!=t.getChild()||(o.push([t,t.getEdges()[0],t.getOwner()]),r=!0);if(1==r){for(var a=[],s=0;s<o.length;s++)1==o[s][0].getEdges().length&&(a.push(o[s]),o[s][0].getOwner().remove(o[s][0]));e.push(a),this.graphManager.resetAllNodes(),this.graphManager.resetAllEdges()}}this.prunedNodesAll=e},E.prototype.growTree=function(t){for(var e,r=t[t.length-1],i=0;i<r.length;i++)e=r[i],this.findPlaceforPrunedNode(e),e[2].add(e[0]),e[2].add(e[1],e[1].source,e[1].target);t.splice(t.length-1,1),this.graphManager.resetAllNodes(),this.graphManager.resetAllEdges()},E.prototype.findPlaceforPrunedNode=function(t){var e,r,i=t[0],o=(r=i==t[1].source?t[1].target:t[1].source).startX,n=r.finishX,a=r.startY,s=r.finishY,h=[0,0,0,0];if(a>0)for(var g=o;g<=n;g++)h[0]+=this.grid[g][a-1].length+this.grid[g][a].length-1;if(n<this.grid.length-1)for(g=a;g<=s;g++)h[1]+=this.grid[n+1][g].length+this.grid[n][g].length-1;if(s<this.grid[0].length-1)for(g=o;g<=n;g++)h[2]+=this.grid[g][s+1].length+this.grid[g][s].length-1;if(o>0)for(g=a;g<=s;g++)h[3]+=this.grid[o-1][g].length+this.grid[o][g].length-1;for(var l,p,c=u.MAX_VALUE,f=0;f<h.length;f++)h[f]<c?(c=h[f],l=1,p=f):h[f]==c&&l++;if(3==l&&0==c)0==h[0]&&0==h[1]&&0==h[2]?e=1:0==h[0]&&0==h[1]&&0==h[3]?e=0:0==h[0]&&0==h[2]&&0==h[3]?e=3:0==h[1]&&0==h[2]&&0==h[3]&&(e=2);else if(2==l&&0==c){var v=Math.floor(2*Math.random());e=0==h[0]&&0==h[1]?0==v?0:1:0==h[0]&&0==h[2]?0==v?0:2:0==h[0]&&0==h[3]?0==v?0:3:0==h[1]&&0==h[2]?0==v?1:2:0==h[1]&&0==h[3]?0==v?1:3:0==v?2:3}else e=4==l&&0==c?v=Math.floor(4*Math.random()):p;0==e?i.setCenter(r.getCenterX(),r.getCenterY()-r.getHeight()/2-d.DEFAULT_EDGE_LENGTH-i.getHeight()/2):1==e?i.setCenter(r.getCenterX()+r.getWidth()/2+d.DEFAULT_EDGE_LENGTH+i.getWidth()/2,r.getCenterY()):2==e?i.setCenter(r.getCenterX(),r.getCenterY()+r.getHeight()/2+d.DEFAULT_EDGE_LENGTH+i.getHeight()/2):i.setCenter(r.getCenterX()-r.getWidth()/2-d.DEFAULT_EDGE_LENGTH-i.getWidth()/2,r.getCenterY())},t.exports=E},function(t,e,r){var i={};i.layoutBase=r(0),i.CoSEConstants=r(1),i.CoSEEdge=r(2),i.CoSEGraph=r(3),i.CoSEGraphManager=r(4),i.CoSELayout=r(6),i.CoSENode=r(5),t.exports=i}])},t.exports=o(r())),e.exports;var t,o}e.exports;export{o as __require};
|